text stringlengths 54 60.6k |
|---|
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/frame/browser_frame_chromeos.h"
#include "chrome/browser/chromeos/frame/normal_browser_frame_view.h"
#include "chrome/browser/views/frame/browser_view.h"
// static (Factory method.)
BrowserFrame* BrowserFrame::Create(BrowserView* browser_view,
Profile* profile) {
chromeos::BrowserFrameChromeos* frame =
new chromeos::BrowserFrameChromeos(browser_view, profile);
frame->Init();
return frame;
}
namespace chromeos {
BrowserFrameChromeos::BrowserFrameChromeos(
BrowserView* browser_view, Profile* profile)
: BrowserFrameGtk(browser_view, profile) {
}
BrowserFrameChromeos::~BrowserFrameChromeos() {
}
void BrowserFrameChromeos::Init() {
// TODO(oshima): handle app panels. This currently uses the default
// implementation, which opens Chrome's app panel instead of
// ChromeOS's panel.
if (!IsPanel()) {
set_browser_frame_view(new NormalBrowserFrameView(this, browser_view()));
}
BrowserFrameGtk::Init();
}
bool BrowserFrameChromeos::IsMaximized() const {
return !IsPanel() || WindowGtk::IsMaximized();
}
bool BrowserFrameChromeos::IsPanel() const {
return browser_view()->IsBrowserTypePanel() ||
browser_view()->IsBrowserTypePopup();
}
} // namespace chromeos
<commit_msg>This fixes the crash that happens when opening dev tools/javascript console.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/frame/browser_frame_chromeos.h"
#include "chrome/browser/chromeos/frame/normal_browser_frame_view.h"
#include "chrome/browser/views/frame/browser_view.h"
// static (Factory method.)
BrowserFrame* BrowserFrame::Create(BrowserView* browser_view,
Profile* profile) {
chromeos::BrowserFrameChromeos* frame =
new chromeos::BrowserFrameChromeos(browser_view, profile);
frame->Init();
return frame;
}
namespace chromeos {
BrowserFrameChromeos::BrowserFrameChromeos(
BrowserView* browser_view, Profile* profile)
: BrowserFrameGtk(browser_view, profile) {
}
BrowserFrameChromeos::~BrowserFrameChromeos() {
}
void BrowserFrameChromeos::Init() {
// Excludes a browser intance that requires icon/title. This is typically true
// for dev tools and javascript console.
// TODO(oshima): handle app panels. This currently uses the default
// implementation, which opens Chrome's app panel instead of
// ChromeOS's panel.
if (!IsPanel() &&
!browser_view()->ShouldShowWindowIcon() &&
!browser_view()->ShouldShowWindowTitle()) {
set_browser_frame_view(new NormalBrowserFrameView(this, browser_view()));
}
BrowserFrameGtk::Init();
}
bool BrowserFrameChromeos::IsMaximized() const {
return !IsPanel() || WindowGtk::IsMaximized();
}
bool BrowserFrameChromeos::IsPanel() const {
return browser_view()->IsBrowserTypePanel() ||
browser_view()->IsBrowserTypePopup();
}
} // namespace chromeos
<|endoftext|> |
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/ref_counted.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/extensions/autoupdate_interceptor.h"
#include "chrome/browser/extensions/extension_browsertest.h"
#include "chrome/browser/extensions/extension_host.h"
#include "chrome/browser/extensions/extensions_service.h"
#include "chrome/browser/extensions/extension_updater.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/notification_service.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/ui_test_utils.h"
class ExtensionManagementTest : public ExtensionBrowserTest {
protected:
// Helper method that returns whether the extension is at the given version.
// This calls version(), which must be defined in the extension's bg page,
// as well as asking the extension itself.
bool IsExtensionAtVersion(Extension* extension,
const std::string& expected_version) {
// Test that the extension's version from the manifest and reported by the
// background page is correct. This is to ensure that the processes are in
// sync with the Extension.
ExtensionProcessManager* manager = browser()->profile()->
GetExtensionProcessManager();
ExtensionHost* ext_host = manager->GetBackgroundHostForExtension(extension);
EXPECT_TRUE(ext_host);
if (!ext_host)
return false;
std::string version_from_bg;
bool exec = ui_test_utils::ExecuteJavaScriptAndExtractString(
ext_host->render_view_host(), L"", L"version()", &version_from_bg);
EXPECT_TRUE(exec);
if (!exec)
return false;
if (version_from_bg != expected_version ||
extension->VersionString() != expected_version)
return false;
return true;
}
// Helper method that installs a low permission extension then updates
// to the second version requiring increased permissions. Returns whether
// the operation was completed successfully.
bool InstallAndUpdateIncreasingPermissionsExtension() {
ExtensionsService* service = browser()->profile()->GetExtensionsService();
TabContents* contents = browser()->GetSelectedTabContents();
if (service->HasInstalledExtensions() || !contents)
return false;
// Install the initial version, which should happen just fine.
if (!InstallExtension(
test_data_dir_.AppendASCII("permissions-low-v1.crx"), 1))
return false;
EXPECT_EQ(0, contents->infobar_delegate_count());
// Upgrade to a version that wants more permissions. We should disable the
// extension and prompt the user to reenable.
if (service->extensions()->size() != 1u)
return false;
if (!UpdateExtension(
service->extensions()->at(0)->id(),
test_data_dir_.AppendASCII("permissions-high-v2.crx"), -1))
return false;
EXPECT_EQ(1, contents->infobar_delegate_count());
EXPECT_EQ(0u, service->extensions()->size());
if (service->disabled_extensions()->size() != 1u)
return false;
return true;
}
};
// Tests that installing the same version does not overwrite.
IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, InstallSameVersion) {
ExtensionsService* service = browser()->profile()->GetExtensionsService();
ASSERT_FALSE(service->HasInstalledExtensions());
ASSERT_TRUE(InstallExtension(
test_data_dir_.AppendASCII("install/install.crx"), 1));
// Install an extension with the same version. The previous install should
// be kept.
ASSERT_TRUE(InstallExtension(
test_data_dir_.AppendASCII("install/install_same_version.crx"), 0));
EXPECT_TRUE(IsExtensionAtVersion(service->extensions()->at(0), "1.0"));
}
IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, InstallOlderVersion) {
ExtensionsService* service = browser()->profile()->GetExtensionsService();
ASSERT_FALSE(service->HasInstalledExtensions());
ASSERT_TRUE(InstallExtension(
test_data_dir_.AppendASCII("install/install.crx"), 1));
ASSERT_TRUE(InstallExtension(
test_data_dir_.AppendASCII("install/install_older_version.crx"), 0));
EXPECT_TRUE(IsExtensionAtVersion(service->extensions()->at(0), "1.0"));
}
IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, InstallThenCancel) {
ExtensionsService* service = browser()->profile()->GetExtensionsService();
ASSERT_FALSE(service->HasInstalledExtensions());
ASSERT_TRUE(InstallExtension(
test_data_dir_.AppendASCII("install/install.crx"), 1));
// Cancel this install.
StartInstallButCancel(test_data_dir_.AppendASCII("install/install_v2.crx"));
EXPECT_TRUE(IsExtensionAtVersion(service->extensions()->at(0), "1.0"));
}
// Tests that installing and uninstalling extensions don't crash with an
// incognito window open.
IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, Incognito) {
// Open an incognito window to the extensions management page. We just
// want to make sure that we don't crash while playing with extensions when
// this guy is around.
ui_test_utils::OpenURLOffTheRecord(browser()->profile(),
GURL(chrome::kChromeUIExtensionsURL));
ASSERT_TRUE(InstallExtension(test_data_dir_.AppendASCII("good.crx"), 1));
UninstallExtension("ldnnhddmnhbkjipkidpdiheffobcpfmf");
}
// Tests the process of updating an extension to one that requires higher
// permissions.
IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, UpdatePermissions) {
ExtensionsService* service = browser()->profile()->GetExtensionsService();
ASSERT_TRUE(InstallAndUpdateIncreasingPermissionsExtension());
// Now try reenabling it, which should also dismiss the infobar.
service->EnableExtension(service->disabled_extensions()->at(0)->id());
TabContents* contents = browser()->GetSelectedTabContents();
ASSERT_TRUE(contents);
EXPECT_EQ(0, contents->infobar_delegate_count());
EXPECT_EQ(1u, service->extensions()->size());
EXPECT_EQ(0u, service->disabled_extensions()->size());
}
// Tests that we can uninstall a disabled extension.
IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, UninstallDisabled) {
ExtensionsService* service = browser()->profile()->GetExtensionsService();
ASSERT_TRUE(InstallAndUpdateIncreasingPermissionsExtension());
// Now try uninstalling it.
UninstallExtension(service->disabled_extensions()->at(0)->id());
EXPECT_EQ(0u, service->extensions()->size());
EXPECT_EQ(0u, service->disabled_extensions()->size());
ASSERT_FALSE(service->HasInstalledExtensions());
}
// Tests that disabling and re-enabling an extension works.
IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, DisableEnable) {
ExtensionProcessManager* manager = browser()->profile()->
GetExtensionProcessManager();
ExtensionsService* service = browser()->profile()->GetExtensionsService();
// Load an extension, expect the background page to be available.
ASSERT_FALSE(service->HasInstalledExtensions());
ASSERT_TRUE(LoadExtension(
test_data_dir_.AppendASCII("good").AppendASCII("Extensions")
.AppendASCII("bjafgdebaacbbbecmhlhpofkepfkgcpa")
.AppendASCII("1.0")));
ASSERT_EQ(1u, service->extensions()->size());
EXPECT_EQ(0u, service->disabled_extensions()->size());
Extension* extension = service->extensions()->at(0);
EXPECT_TRUE(manager->GetBackgroundHostForExtension(extension));
ASSERT_TRUE(service->HasInstalledExtensions());
// After disabling, the background page should go away.
service->DisableExtension("bjafgdebaacbbbecmhlhpofkepfkgcpa");
EXPECT_EQ(0u, service->extensions()->size());
EXPECT_EQ(1u, service->disabled_extensions()->size());
EXPECT_FALSE(manager->GetBackgroundHostForExtension(extension));
ASSERT_TRUE(service->HasInstalledExtensions());
// And bring it back.
service->EnableExtension("bjafgdebaacbbbecmhlhpofkepfkgcpa");
EXPECT_EQ(1u, service->extensions()->size());
EXPECT_EQ(0u, service->disabled_extensions()->size());
EXPECT_TRUE(manager->GetBackgroundHostForExtension(extension));
ASSERT_TRUE(service->HasInstalledExtensions());
}
// TODO(asargent): This test seems to crash on linux buildbots.
// (http://crbug.com/31737)
#if !defined(OS_LINUX)
// Tests extension autoupdate.
IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, AutoUpdate) {
FilePath basedir = test_data_dir_.AppendASCII("autoupdate");
// Note: This interceptor gets requests on the IO thread.
scoped_refptr<AutoUpdateInterceptor> interceptor(new AutoUpdateInterceptor());
URLFetcher::enable_interception_for_tests(true);
interceptor->SetResponseOnIOThread("http://localhost/autoupdate/manifest",
basedir.AppendASCII("manifest_v2.xml"));
interceptor->SetResponseOnIOThread("http://localhost/autoupdate/v2.crx",
basedir.AppendASCII("v2.crx"));
// Install version 1 of the extension.
ExtensionsService* service = browser()->profile()->GetExtensionsService();
ASSERT_FALSE(service->HasInstalledExtensions());
ASSERT_TRUE(InstallExtension(basedir.AppendASCII("v1.crx"), 1));
const ExtensionList* extensions = service->extensions();
ASSERT_TRUE(service->HasInstalledExtensions());
ASSERT_EQ(1u, extensions->size());
ASSERT_EQ("ogjcoiohnmldgjemafoockdghcjciccf", extensions->at(0)->id());
ASSERT_EQ("1.0", extensions->at(0)->VersionString());
// We don't want autoupdate blacklist checks.
service->updater()->set_blacklist_checks_enabled(false);
// Run autoupdate and make sure version 2 of the extension was installed.
service->updater()->CheckNow();
ASSERT_TRUE(WaitForExtensionInstall());
extensions = service->extensions();
ASSERT_EQ(1u, extensions->size());
ASSERT_EQ("ogjcoiohnmldgjemafoockdghcjciccf", extensions->at(0)->id());
ASSERT_EQ("2.0", extensions->at(0)->VersionString());
// Now try doing an update to version 3, which has been incorrectly
// signed. This should fail.
interceptor->SetResponseOnIOThread("http://localhost/autoupdate/manifest",
basedir.AppendASCII("manifest_v3.xml"));
interceptor->SetResponseOnIOThread("http://localhost/autoupdate/v3.crx",
basedir.AppendASCII("v3.crx"));
service->updater()->CheckNow();
ASSERT_TRUE(WaitForExtensionInstallError());
// Make sure the extension state is the same as before.
extensions = service->extensions();
ASSERT_EQ(1u, extensions->size());
ASSERT_EQ("ogjcoiohnmldgjemafoockdghcjciccf", extensions->at(0)->id());
ASSERT_EQ("2.0", extensions->at(0)->VersionString());
}
#endif // !defined(OS_LINUX)
<commit_msg>Disable UninstallDisabled and UpdatePermissions temporarily. BUG=none TEST=none TBR=asargent Review URL: http://codereview.chromium.org/552077<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/ref_counted.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/extensions/autoupdate_interceptor.h"
#include "chrome/browser/extensions/extension_browsertest.h"
#include "chrome/browser/extensions/extension_host.h"
#include "chrome/browser/extensions/extensions_service.h"
#include "chrome/browser/extensions/extension_updater.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/notification_service.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/ui_test_utils.h"
class ExtensionManagementTest : public ExtensionBrowserTest {
protected:
// Helper method that returns whether the extension is at the given version.
// This calls version(), which must be defined in the extension's bg page,
// as well as asking the extension itself.
bool IsExtensionAtVersion(Extension* extension,
const std::string& expected_version) {
// Test that the extension's version from the manifest and reported by the
// background page is correct. This is to ensure that the processes are in
// sync with the Extension.
ExtensionProcessManager* manager = browser()->profile()->
GetExtensionProcessManager();
ExtensionHost* ext_host = manager->GetBackgroundHostForExtension(extension);
EXPECT_TRUE(ext_host);
if (!ext_host)
return false;
std::string version_from_bg;
bool exec = ui_test_utils::ExecuteJavaScriptAndExtractString(
ext_host->render_view_host(), L"", L"version()", &version_from_bg);
EXPECT_TRUE(exec);
if (!exec)
return false;
if (version_from_bg != expected_version ||
extension->VersionString() != expected_version)
return false;
return true;
}
// Helper method that installs a low permission extension then updates
// to the second version requiring increased permissions. Returns whether
// the operation was completed successfully.
bool InstallAndUpdateIncreasingPermissionsExtension() {
ExtensionsService* service = browser()->profile()->GetExtensionsService();
TabContents* contents = browser()->GetSelectedTabContents();
if (service->HasInstalledExtensions() || !contents)
return false;
// Install the initial version, which should happen just fine.
if (!InstallExtension(
test_data_dir_.AppendASCII("permissions-low-v1.crx"), 1))
return false;
EXPECT_EQ(0, contents->infobar_delegate_count());
// Upgrade to a version that wants more permissions. We should disable the
// extension and prompt the user to reenable.
if (service->extensions()->size() != 1u)
return false;
if (!UpdateExtension(
service->extensions()->at(0)->id(),
test_data_dir_.AppendASCII("permissions-high-v2.crx"), -1))
return false;
EXPECT_EQ(1, contents->infobar_delegate_count());
EXPECT_EQ(0u, service->extensions()->size());
if (service->disabled_extensions()->size() != 1u)
return false;
return true;
}
};
// Tests that installing the same version does not overwrite.
IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, InstallSameVersion) {
ExtensionsService* service = browser()->profile()->GetExtensionsService();
ASSERT_FALSE(service->HasInstalledExtensions());
ASSERT_TRUE(InstallExtension(
test_data_dir_.AppendASCII("install/install.crx"), 1));
// Install an extension with the same version. The previous install should
// be kept.
ASSERT_TRUE(InstallExtension(
test_data_dir_.AppendASCII("install/install_same_version.crx"), 0));
EXPECT_TRUE(IsExtensionAtVersion(service->extensions()->at(0), "1.0"));
}
IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, InstallOlderVersion) {
ExtensionsService* service = browser()->profile()->GetExtensionsService();
ASSERT_FALSE(service->HasInstalledExtensions());
ASSERT_TRUE(InstallExtension(
test_data_dir_.AppendASCII("install/install.crx"), 1));
ASSERT_TRUE(InstallExtension(
test_data_dir_.AppendASCII("install/install_older_version.crx"), 0));
EXPECT_TRUE(IsExtensionAtVersion(service->extensions()->at(0), "1.0"));
}
IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, InstallThenCancel) {
ExtensionsService* service = browser()->profile()->GetExtensionsService();
ASSERT_FALSE(service->HasInstalledExtensions());
ASSERT_TRUE(InstallExtension(
test_data_dir_.AppendASCII("install/install.crx"), 1));
// Cancel this install.
StartInstallButCancel(test_data_dir_.AppendASCII("install/install_v2.crx"));
EXPECT_TRUE(IsExtensionAtVersion(service->extensions()->at(0), "1.0"));
}
// Tests that installing and uninstalling extensions don't crash with an
// incognito window open.
IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, Incognito) {
// Open an incognito window to the extensions management page. We just
// want to make sure that we don't crash while playing with extensions when
// this guy is around.
ui_test_utils::OpenURLOffTheRecord(browser()->profile(),
GURL(chrome::kChromeUIExtensionsURL));
ASSERT_TRUE(InstallExtension(test_data_dir_.AppendASCII("good.crx"), 1));
UninstallExtension("ldnnhddmnhbkjipkidpdiheffobcpfmf");
}
// Tests the process of updating an extension to one that requires higher
// permissions.
IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, DISABLED_UpdatePermissions) {
ExtensionsService* service = browser()->profile()->GetExtensionsService();
ASSERT_TRUE(InstallAndUpdateIncreasingPermissionsExtension());
// Now try reenabling it, which should also dismiss the infobar.
service->EnableExtension(service->disabled_extensions()->at(0)->id());
TabContents* contents = browser()->GetSelectedTabContents();
ASSERT_TRUE(contents);
EXPECT_EQ(0, contents->infobar_delegate_count());
EXPECT_EQ(1u, service->extensions()->size());
EXPECT_EQ(0u, service->disabled_extensions()->size());
}
// Tests that we can uninstall a disabled extension.
IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, DISABLED_UninstallDisabled) {
ExtensionsService* service = browser()->profile()->GetExtensionsService();
ASSERT_TRUE(InstallAndUpdateIncreasingPermissionsExtension());
// Now try uninstalling it.
UninstallExtension(service->disabled_extensions()->at(0)->id());
EXPECT_EQ(0u, service->extensions()->size());
EXPECT_EQ(0u, service->disabled_extensions()->size());
ASSERT_FALSE(service->HasInstalledExtensions());
}
// Tests that disabling and re-enabling an extension works.
IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, DisableEnable) {
ExtensionProcessManager* manager = browser()->profile()->
GetExtensionProcessManager();
ExtensionsService* service = browser()->profile()->GetExtensionsService();
// Load an extension, expect the background page to be available.
ASSERT_FALSE(service->HasInstalledExtensions());
ASSERT_TRUE(LoadExtension(
test_data_dir_.AppendASCII("good").AppendASCII("Extensions")
.AppendASCII("bjafgdebaacbbbecmhlhpofkepfkgcpa")
.AppendASCII("1.0")));
ASSERT_EQ(1u, service->extensions()->size());
EXPECT_EQ(0u, service->disabled_extensions()->size());
Extension* extension = service->extensions()->at(0);
EXPECT_TRUE(manager->GetBackgroundHostForExtension(extension));
ASSERT_TRUE(service->HasInstalledExtensions());
// After disabling, the background page should go away.
service->DisableExtension("bjafgdebaacbbbecmhlhpofkepfkgcpa");
EXPECT_EQ(0u, service->extensions()->size());
EXPECT_EQ(1u, service->disabled_extensions()->size());
EXPECT_FALSE(manager->GetBackgroundHostForExtension(extension));
ASSERT_TRUE(service->HasInstalledExtensions());
// And bring it back.
service->EnableExtension("bjafgdebaacbbbecmhlhpofkepfkgcpa");
EXPECT_EQ(1u, service->extensions()->size());
EXPECT_EQ(0u, service->disabled_extensions()->size());
EXPECT_TRUE(manager->GetBackgroundHostForExtension(extension));
ASSERT_TRUE(service->HasInstalledExtensions());
}
// TODO(asargent): This test seems to crash on linux buildbots.
// (http://crbug.com/31737)
#if !defined(OS_LINUX)
// Tests extension autoupdate.
IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, AutoUpdate) {
FilePath basedir = test_data_dir_.AppendASCII("autoupdate");
// Note: This interceptor gets requests on the IO thread.
scoped_refptr<AutoUpdateInterceptor> interceptor(new AutoUpdateInterceptor());
URLFetcher::enable_interception_for_tests(true);
interceptor->SetResponseOnIOThread("http://localhost/autoupdate/manifest",
basedir.AppendASCII("manifest_v2.xml"));
interceptor->SetResponseOnIOThread("http://localhost/autoupdate/v2.crx",
basedir.AppendASCII("v2.crx"));
// Install version 1 of the extension.
ExtensionsService* service = browser()->profile()->GetExtensionsService();
ASSERT_FALSE(service->HasInstalledExtensions());
ASSERT_TRUE(InstallExtension(basedir.AppendASCII("v1.crx"), 1));
const ExtensionList* extensions = service->extensions();
ASSERT_TRUE(service->HasInstalledExtensions());
ASSERT_EQ(1u, extensions->size());
ASSERT_EQ("ogjcoiohnmldgjemafoockdghcjciccf", extensions->at(0)->id());
ASSERT_EQ("1.0", extensions->at(0)->VersionString());
// We don't want autoupdate blacklist checks.
service->updater()->set_blacklist_checks_enabled(false);
// Run autoupdate and make sure version 2 of the extension was installed.
service->updater()->CheckNow();
ASSERT_TRUE(WaitForExtensionInstall());
extensions = service->extensions();
ASSERT_EQ(1u, extensions->size());
ASSERT_EQ("ogjcoiohnmldgjemafoockdghcjciccf", extensions->at(0)->id());
ASSERT_EQ("2.0", extensions->at(0)->VersionString());
// Now try doing an update to version 3, which has been incorrectly
// signed. This should fail.
interceptor->SetResponseOnIOThread("http://localhost/autoupdate/manifest",
basedir.AppendASCII("manifest_v3.xml"));
interceptor->SetResponseOnIOThread("http://localhost/autoupdate/v3.crx",
basedir.AppendASCII("v3.crx"));
service->updater()->CheckNow();
ASSERT_TRUE(WaitForExtensionInstallError());
// Make sure the extension state is the same as before.
extensions = service->extensions();
ASSERT_EQ(1u, extensions->size());
ASSERT_EQ("ogjcoiohnmldgjemafoockdghcjciccf", extensions->at(0)->id());
ASSERT_EQ("2.0", extensions->at(0)->VersionString());
}
#endif // !defined(OS_LINUX)
<|endoftext|> |
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/net/resolve_proxy_msg_helper.h"
#include "base/waitable_event.h"
#include "net/base/net_errors.h"
#include "testing/gtest/include/gtest/gtest.h"
// This ProxyConfigService always returns "http://pac" as the PAC url to use.
class MockProxyConfigService: public net::ProxyConfigService {
public:
virtual int GetProxyConfig(net::ProxyConfig* results) {
results->pac_url = GURL("http://pac");
return net::OK;
}
};
// This PAC resolver always returns the hostname of the query URL as the
// proxy to use. The Block() method will make GetProxyForURL() hang until
// Unblock() is called.
class MockProxyResolver : public net::ProxyResolver {
public:
explicit MockProxyResolver() : event_(false, false), is_blocked_(false) {
}
virtual int GetProxyForURL(const GURL& query_url,
const GURL& /*pac_url*/,
net::ProxyInfo* results) {
if (is_blocked_)
event_.Wait();
results->UseNamedProxy(query_url.host());
return net::OK;
}
void Block() {
is_blocked_ = true;
event_.Reset();
}
void Unblock() {
is_blocked_ = false;
event_.Signal();
}
private:
base::WaitableEvent event_;
bool is_blocked_;
};
// This struct holds the values that were passed to
// Delegate::OnResolveProxyCompleted(). The caller should use WaitUntilDone()
// to block until the result has been populated.
struct ResultFuture {
public:
ResultFuture()
: reply_msg(NULL),
error_code(0),
started_(false, false),
completed_(false, false) {
}
// Wait until the request has completed. In other words we have invoked:
// ResolveProxyMsgHelper::Delegate::OnResolveProxyCompleted.
void WaitUntilDone() {
completed_.Wait();
}
// Wait until the request has been sent to ResolveProxyMsgHelper.
void WaitUntilStarted() {
started_.Wait();
}
bool TimedWaitUntilDone(const base::TimeDelta& max_time) {
return completed_.TimedWait(max_time);
}
// These fields are only valid after returning from WaitUntilDone().
IPC::Message* reply_msg;
int error_code;
std::string proxy_list;
private:
friend class AsyncRequestRunner;
base::WaitableEvent started_;
base::WaitableEvent completed_;
};
// This class lives on the io thread. It starts async requests using the
// class under test (ResolveProxyMsgHelper), and signals the result future on
// completion.
class AsyncRequestRunner : public ResolveProxyMsgHelper::Delegate {
public:
AsyncRequestRunner(net::ProxyService* proxy_service) {
resolve_proxy_msg_helper_.reset(
new ResolveProxyMsgHelper(this, proxy_service));
}
void Start(ResultFuture* future, const GURL& url, IPC::Message* reply_msg) {
futures_.push_back(future);
resolve_proxy_msg_helper_->Start(url, reply_msg);
// Notify of request start.
future->started_.Signal();
}
virtual void OnResolveProxyCompleted(IPC::Message* reply_msg,
int error_code,
const std::string& proxy_list) {
// Update the result future for this request (top of queue), and signal it.
ResultFuture* future = futures_.front();
futures_.pop_front();
future->reply_msg = reply_msg;
future->error_code = error_code;
future->proxy_list = proxy_list;
// Notify of request completion.
future->completed_.Signal();
}
private:
std::deque<ResultFuture*> futures_;
scoped_ptr<ResolveProxyMsgHelper> resolve_proxy_msg_helper_;
};
// Helper class to start async requests on an io thread, and return a
// result future. The caller then uses ResultFuture::WaitUntilDone() to
// get at the results. It "bridges" the originating thread with the helper
// io thread.
class RunnerBridge {
public:
RunnerBridge() : io_thread_("io_thread"), done_(true, false) {
// Start an io thread where we will run the async requests.
base::Thread::Options options;
options.message_loop_type = MessageLoop::TYPE_IO;
io_thread_.StartWithOptions(options);
// Construct the state that lives on io thread.
io_thread_.message_loop()->PostTask(FROM_HERE, NewRunnableMethod(
this, &RunnerBridge::DoConstruct));
done_.Wait();
}
// Start an async request on the io thread.
ResultFuture* Start(const GURL& url, IPC::Message* reply_msg) {
ResultFuture* future = new ResultFuture();
io_thread_.message_loop()->PostTask(FROM_HERE, NewRunnableMethod(
async_runner_, &AsyncRequestRunner::Start, future, url, reply_msg));
return future;
}
void DestroyAsyncRunner() {
io_thread_.message_loop()->PostTask(FROM_HERE, NewRunnableMethod(
this, &RunnerBridge::DoDestroyAsyncRunner));
done_.Wait();
}
~RunnerBridge() {
io_thread_.message_loop()->PostTask(FROM_HERE, NewRunnableMethod(
this, &RunnerBridge::DoDestroy));
done_.Wait();
}
MockProxyResolver* proxy_resolver() {
return proxy_resolver_;
}
// Called from io thread.
void DoConstruct() {
proxy_resolver_ = new MockProxyResolver();
proxy_service_ = new net::ProxyService(new MockProxyConfigService(),
proxy_resolver_);
async_runner_ = new AsyncRequestRunner(proxy_service_);
done_.Signal();
}
// Called from io thread.
void DoDestroy() {
delete async_runner_;
delete proxy_service_;
done_.Signal();
}
// Called from io thread.
void DoDestroyAsyncRunner() {
delete async_runner_;
async_runner_ = NULL;
done_.Signal();
}
private:
base::Thread io_thread_;
base::WaitableEvent done_;
net::ProxyService* proxy_service_;
MockProxyResolver* proxy_resolver_; // Owned by proxy_service_.
AsyncRequestRunner* async_runner_;
};
// Avoid the need to have an AddRef / Release
template<>
void RunnableMethodTraits<RunnerBridge>::RetainCallee(RunnerBridge*) {}
template<>
void RunnableMethodTraits<RunnerBridge>::ReleaseCallee(RunnerBridge*) {}
template<>
void RunnableMethodTraits<AsyncRequestRunner>::RetainCallee(AsyncRequestRunner*) {}
template<>
void RunnableMethodTraits<AsyncRequestRunner>::ReleaseCallee(AsyncRequestRunner*) {}
// Issue three sequential requests -- each should succeed.
TEST(ResolveProxyMsgHelperTest, Sequential) {
RunnerBridge runner;
GURL url1("http://www.google1.com/");
GURL url2("http://www.google2.com/");
GURL url3("http://www.google3.com/");
scoped_ptr<IPC::Message> msg1(new IPC::Message());
scoped_ptr<IPC::Message> msg2(new IPC::Message());
scoped_ptr<IPC::Message> msg3(new IPC::Message());
// Execute each request sequentially (so there are never 2 requests
// outstanding at the same time).
scoped_ptr<ResultFuture> result1(runner.Start(url1, msg1.get()));
result1->WaitUntilDone();
scoped_ptr<ResultFuture> result2(runner.Start(url2, msg2.get()));
result2->WaitUntilDone();
scoped_ptr<ResultFuture> result3(runner.Start(url3, msg3.get()));
result3->WaitUntilDone();
// Check that each request gave the expected result.
EXPECT_EQ(msg1.get(), result1->reply_msg);
EXPECT_EQ(net::OK, result1->error_code);
EXPECT_EQ("PROXY www.google1.com", result1->proxy_list);
EXPECT_EQ(msg2.get(), result2->reply_msg);
EXPECT_EQ(net::OK, result2->error_code);
EXPECT_EQ("PROXY www.google2.com", result2->proxy_list);
EXPECT_EQ(msg3.get(), result3->reply_msg);
EXPECT_EQ(net::OK, result3->error_code);
EXPECT_EQ("PROXY www.google3.com", result3->proxy_list);
}
// Issue a request while one is already in progress -- should be queued.
TEST(ResolveProxyMsgHelperTest, QueueRequests) {
RunnerBridge runner;
GURL url1("http://www.google1.com/");
GURL url2("http://www.google2.com/");
GURL url3("http://www.google3.com/");
scoped_ptr<IPC::Message> msg1(new IPC::Message());
scoped_ptr<IPC::Message> msg2(new IPC::Message());
scoped_ptr<IPC::Message> msg3(new IPC::Message());
// Make the proxy resolver hang on the next request.
runner.proxy_resolver()->Block();
// Start three requests. Since the proxy resolver is hung, the second two
// will be pending.
scoped_ptr<ResultFuture> result1(runner.Start(url1, msg1.get()));
scoped_ptr<ResultFuture> result2(runner.Start(url2, msg2.get()));
scoped_ptr<ResultFuture> result3(runner.Start(url3, msg3.get()));
// Wait for the final request to have been scheduled. Otherwise we may rush
// to calling Unblock() without actually having blocked anything.
result3->WaitUntilStarted();
// Unblock the proxy service so requests 1-3 can complete.
runner.proxy_resolver()->Unblock();
// Wait for all the requests to finish (they run in FIFO order).
result3->WaitUntilDone();
// Check that each call invoked the callback with the right parameters.
EXPECT_EQ(msg1.get(), result1->reply_msg);
EXPECT_EQ(net::OK, result1->error_code);
EXPECT_EQ("PROXY www.google1.com:80", result1->proxy_list);
EXPECT_EQ(msg2.get(), result2->reply_msg);
EXPECT_EQ(net::OK, result2->error_code);
EXPECT_EQ("PROXY www.google2.com:80", result2->proxy_list);
EXPECT_EQ(msg3.get(), result3->reply_msg);
EXPECT_EQ(net::OK, result3->error_code);
EXPECT_EQ("PROXY www.google3.com:80", result3->proxy_list);
}
// Delete the helper while a request is in progress, and others are pending.
TEST(ResolveProxyMsgHelperTest, CancelPendingRequests) {
RunnerBridge runner;
GURL url1("http://www.google1.com/");
GURL url2("http://www.google2.com/");
GURL url3("http://www.google3.com/");
// NOTE: these are not scoped ptr, since they will be deleted by the
// request's cancellation.
IPC::Message* msg1 = new IPC::Message();
IPC::Message* msg2 = new IPC::Message();
IPC::Message* msg3 = new IPC::Message();
// Make the next request block.
runner.proxy_resolver()->Block();
// Start three requests; since the first one blocked, the other two should
// be pending.
scoped_ptr<ResultFuture> result1(runner.Start(url1, msg1));
scoped_ptr<ResultFuture> result2(runner.Start(url2, msg2));
scoped_ptr<ResultFuture> result3(runner.Start(url3, msg3));
result3->WaitUntilStarted();
// Delete the underlying ResolveProxyMsgHelper -- this should cancel all
// the requests which are outstanding.
runner.DestroyAsyncRunner();
// Unblocking the proxy resolver means the three requests can complete --
// however they should not try to notify the delegate since we have already
// deleted the helper.
runner.proxy_resolver()->Unblock();
// Check that none of the requests were sent to the delegate.
EXPECT_FALSE(
result1->TimedWaitUntilDone(base::TimeDelta::FromMilliseconds(2)));
EXPECT_FALSE(
result2->TimedWaitUntilDone(base::TimeDelta::FromMilliseconds(2)));
EXPECT_FALSE(
result3->TimedWaitUntilDone(base::TimeDelta::FromMilliseconds(2)));
// It should also be the case that msg1, msg2, msg3 were deleted by the
// cancellation. (Else will show up as a leak in Purify).
}
<commit_msg>Update test expectation. This needs the port numbers, since they now get properly inferred.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/net/resolve_proxy_msg_helper.h"
#include "base/waitable_event.h"
#include "net/base/net_errors.h"
#include "testing/gtest/include/gtest/gtest.h"
// This ProxyConfigService always returns "http://pac" as the PAC url to use.
class MockProxyConfigService: public net::ProxyConfigService {
public:
virtual int GetProxyConfig(net::ProxyConfig* results) {
results->pac_url = GURL("http://pac");
return net::OK;
}
};
// This PAC resolver always returns the hostname of the query URL as the
// proxy to use. The Block() method will make GetProxyForURL() hang until
// Unblock() is called.
class MockProxyResolver : public net::ProxyResolver {
public:
explicit MockProxyResolver() : event_(false, false), is_blocked_(false) {
}
virtual int GetProxyForURL(const GURL& query_url,
const GURL& /*pac_url*/,
net::ProxyInfo* results) {
if (is_blocked_)
event_.Wait();
results->UseNamedProxy(query_url.host());
return net::OK;
}
void Block() {
is_blocked_ = true;
event_.Reset();
}
void Unblock() {
is_blocked_ = false;
event_.Signal();
}
private:
base::WaitableEvent event_;
bool is_blocked_;
};
// This struct holds the values that were passed to
// Delegate::OnResolveProxyCompleted(). The caller should use WaitUntilDone()
// to block until the result has been populated.
struct ResultFuture {
public:
ResultFuture()
: reply_msg(NULL),
error_code(0),
started_(false, false),
completed_(false, false) {
}
// Wait until the request has completed. In other words we have invoked:
// ResolveProxyMsgHelper::Delegate::OnResolveProxyCompleted.
void WaitUntilDone() {
completed_.Wait();
}
// Wait until the request has been sent to ResolveProxyMsgHelper.
void WaitUntilStarted() {
started_.Wait();
}
bool TimedWaitUntilDone(const base::TimeDelta& max_time) {
return completed_.TimedWait(max_time);
}
// These fields are only valid after returning from WaitUntilDone().
IPC::Message* reply_msg;
int error_code;
std::string proxy_list;
private:
friend class AsyncRequestRunner;
base::WaitableEvent started_;
base::WaitableEvent completed_;
};
// This class lives on the io thread. It starts async requests using the
// class under test (ResolveProxyMsgHelper), and signals the result future on
// completion.
class AsyncRequestRunner : public ResolveProxyMsgHelper::Delegate {
public:
AsyncRequestRunner(net::ProxyService* proxy_service) {
resolve_proxy_msg_helper_.reset(
new ResolveProxyMsgHelper(this, proxy_service));
}
void Start(ResultFuture* future, const GURL& url, IPC::Message* reply_msg) {
futures_.push_back(future);
resolve_proxy_msg_helper_->Start(url, reply_msg);
// Notify of request start.
future->started_.Signal();
}
virtual void OnResolveProxyCompleted(IPC::Message* reply_msg,
int error_code,
const std::string& proxy_list) {
// Update the result future for this request (top of queue), and signal it.
ResultFuture* future = futures_.front();
futures_.pop_front();
future->reply_msg = reply_msg;
future->error_code = error_code;
future->proxy_list = proxy_list;
// Notify of request completion.
future->completed_.Signal();
}
private:
std::deque<ResultFuture*> futures_;
scoped_ptr<ResolveProxyMsgHelper> resolve_proxy_msg_helper_;
};
// Helper class to start async requests on an io thread, and return a
// result future. The caller then uses ResultFuture::WaitUntilDone() to
// get at the results. It "bridges" the originating thread with the helper
// io thread.
class RunnerBridge {
public:
RunnerBridge() : io_thread_("io_thread"), done_(true, false) {
// Start an io thread where we will run the async requests.
base::Thread::Options options;
options.message_loop_type = MessageLoop::TYPE_IO;
io_thread_.StartWithOptions(options);
// Construct the state that lives on io thread.
io_thread_.message_loop()->PostTask(FROM_HERE, NewRunnableMethod(
this, &RunnerBridge::DoConstruct));
done_.Wait();
}
// Start an async request on the io thread.
ResultFuture* Start(const GURL& url, IPC::Message* reply_msg) {
ResultFuture* future = new ResultFuture();
io_thread_.message_loop()->PostTask(FROM_HERE, NewRunnableMethod(
async_runner_, &AsyncRequestRunner::Start, future, url, reply_msg));
return future;
}
void DestroyAsyncRunner() {
io_thread_.message_loop()->PostTask(FROM_HERE, NewRunnableMethod(
this, &RunnerBridge::DoDestroyAsyncRunner));
done_.Wait();
}
~RunnerBridge() {
io_thread_.message_loop()->PostTask(FROM_HERE, NewRunnableMethod(
this, &RunnerBridge::DoDestroy));
done_.Wait();
}
MockProxyResolver* proxy_resolver() {
return proxy_resolver_;
}
// Called from io thread.
void DoConstruct() {
proxy_resolver_ = new MockProxyResolver();
proxy_service_ = new net::ProxyService(new MockProxyConfigService(),
proxy_resolver_);
async_runner_ = new AsyncRequestRunner(proxy_service_);
done_.Signal();
}
// Called from io thread.
void DoDestroy() {
delete async_runner_;
delete proxy_service_;
done_.Signal();
}
// Called from io thread.
void DoDestroyAsyncRunner() {
delete async_runner_;
async_runner_ = NULL;
done_.Signal();
}
private:
base::Thread io_thread_;
base::WaitableEvent done_;
net::ProxyService* proxy_service_;
MockProxyResolver* proxy_resolver_; // Owned by proxy_service_.
AsyncRequestRunner* async_runner_;
};
// Avoid the need to have an AddRef / Release
template<>
void RunnableMethodTraits<RunnerBridge>::RetainCallee(RunnerBridge*) {}
template<>
void RunnableMethodTraits<RunnerBridge>::ReleaseCallee(RunnerBridge*) {}
template<>
void RunnableMethodTraits<AsyncRequestRunner>::RetainCallee(AsyncRequestRunner*) {}
template<>
void RunnableMethodTraits<AsyncRequestRunner>::ReleaseCallee(AsyncRequestRunner*) {}
// Issue three sequential requests -- each should succeed.
TEST(ResolveProxyMsgHelperTest, Sequential) {
RunnerBridge runner;
GURL url1("http://www.google1.com/");
GURL url2("http://www.google2.com/");
GURL url3("http://www.google3.com/");
scoped_ptr<IPC::Message> msg1(new IPC::Message());
scoped_ptr<IPC::Message> msg2(new IPC::Message());
scoped_ptr<IPC::Message> msg3(new IPC::Message());
// Execute each request sequentially (so there are never 2 requests
// outstanding at the same time).
scoped_ptr<ResultFuture> result1(runner.Start(url1, msg1.get()));
result1->WaitUntilDone();
scoped_ptr<ResultFuture> result2(runner.Start(url2, msg2.get()));
result2->WaitUntilDone();
scoped_ptr<ResultFuture> result3(runner.Start(url3, msg3.get()));
result3->WaitUntilDone();
// Check that each request gave the expected result.
EXPECT_EQ(msg1.get(), result1->reply_msg);
EXPECT_EQ(net::OK, result1->error_code);
EXPECT_EQ("PROXY www.google1.com:80", result1->proxy_list);
EXPECT_EQ(msg2.get(), result2->reply_msg);
EXPECT_EQ(net::OK, result2->error_code);
EXPECT_EQ("PROXY www.google2.com:80", result2->proxy_list);
EXPECT_EQ(msg3.get(), result3->reply_msg);
EXPECT_EQ(net::OK, result3->error_code);
EXPECT_EQ("PROXY www.google3.com:80", result3->proxy_list);
}
// Issue a request while one is already in progress -- should be queued.
TEST(ResolveProxyMsgHelperTest, QueueRequests) {
RunnerBridge runner;
GURL url1("http://www.google1.com/");
GURL url2("http://www.google2.com/");
GURL url3("http://www.google3.com/");
scoped_ptr<IPC::Message> msg1(new IPC::Message());
scoped_ptr<IPC::Message> msg2(new IPC::Message());
scoped_ptr<IPC::Message> msg3(new IPC::Message());
// Make the proxy resolver hang on the next request.
runner.proxy_resolver()->Block();
// Start three requests. Since the proxy resolver is hung, the second two
// will be pending.
scoped_ptr<ResultFuture> result1(runner.Start(url1, msg1.get()));
scoped_ptr<ResultFuture> result2(runner.Start(url2, msg2.get()));
scoped_ptr<ResultFuture> result3(runner.Start(url3, msg3.get()));
// Wait for the final request to have been scheduled. Otherwise we may rush
// to calling Unblock() without actually having blocked anything.
result3->WaitUntilStarted();
// Unblock the proxy service so requests 1-3 can complete.
runner.proxy_resolver()->Unblock();
// Wait for all the requests to finish (they run in FIFO order).
result3->WaitUntilDone();
// Check that each call invoked the callback with the right parameters.
EXPECT_EQ(msg1.get(), result1->reply_msg);
EXPECT_EQ(net::OK, result1->error_code);
EXPECT_EQ("PROXY www.google1.com:80", result1->proxy_list);
EXPECT_EQ(msg2.get(), result2->reply_msg);
EXPECT_EQ(net::OK, result2->error_code);
EXPECT_EQ("PROXY www.google2.com:80", result2->proxy_list);
EXPECT_EQ(msg3.get(), result3->reply_msg);
EXPECT_EQ(net::OK, result3->error_code);
EXPECT_EQ("PROXY www.google3.com:80", result3->proxy_list);
}
// Delete the helper while a request is in progress, and others are pending.
TEST(ResolveProxyMsgHelperTest, CancelPendingRequests) {
RunnerBridge runner;
GURL url1("http://www.google1.com/");
GURL url2("http://www.google2.com/");
GURL url3("http://www.google3.com/");
// NOTE: these are not scoped ptr, since they will be deleted by the
// request's cancellation.
IPC::Message* msg1 = new IPC::Message();
IPC::Message* msg2 = new IPC::Message();
IPC::Message* msg3 = new IPC::Message();
// Make the next request block.
runner.proxy_resolver()->Block();
// Start three requests; since the first one blocked, the other two should
// be pending.
scoped_ptr<ResultFuture> result1(runner.Start(url1, msg1));
scoped_ptr<ResultFuture> result2(runner.Start(url2, msg2));
scoped_ptr<ResultFuture> result3(runner.Start(url3, msg3));
result3->WaitUntilStarted();
// Delete the underlying ResolveProxyMsgHelper -- this should cancel all
// the requests which are outstanding.
runner.DestroyAsyncRunner();
// Unblocking the proxy resolver means the three requests can complete --
// however they should not try to notify the delegate since we have already
// deleted the helper.
runner.proxy_resolver()->Unblock();
// Check that none of the requests were sent to the delegate.
EXPECT_FALSE(
result1->TimedWaitUntilDone(base::TimeDelta::FromMilliseconds(2)));
EXPECT_FALSE(
result2->TimedWaitUntilDone(base::TimeDelta::FromMilliseconds(2)));
EXPECT_FALSE(
result3->TimedWaitUntilDone(base::TimeDelta::FromMilliseconds(2)));
// It should also be the case that msg1, msg2, msg3 were deleted by the
// cancellation. (Else will show up as a leak in Purify).
}
<|endoftext|> |
<commit_before>/* Sirikata
* SingleMaterialGeometryFilter.cpp
*
* Copyright (c) 2010, Ewen Cheslack-Postava
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Sirikata nor the names of its contributors may
* be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "SingleMaterialGeometryFilter.hpp"
#include <sirikata/mesh/Meshdata.hpp>
namespace Sirikata {
namespace Mesh {
SingleMaterialGeometryFilter::SingleMaterialGeometryFilter(const String& args) {
}
FilterDataPtr SingleMaterialGeometryFilter::apply(FilterDataPtr input) {
for(FilterData::const_iterator md_it = input->begin(); md_it != input->end(); md_it++) {
VisualPtr vis = *md_it;
// Meshdata only currently
MeshdataPtr md( std::tr1::dynamic_pointer_cast<Meshdata>(vis) );
if (!md) continue;
// Our approach is to run through all SubMeshGeometries generating
// versions that are split. By maintaining a map from old indices to a
// list of new indices, we can then run through all GeometryInstances,
// duplicating them for each part of the original instance.
// This map stores geometryIndex -> list of new geometry indices,
// allowing the old instances to be split into a set of new instances
typedef std::map<uint32, std::vector<uint32> > OldToNewIndexMap;
OldToNewIndexMap new_geo_indices;
// Our output should be a new set of SubMeshGeometries and a new set of
// GeometryInstances referring to them.
SubMeshGeometryList new_geometry;
GeometryInstanceList new_instances;
for(uint32 geo_idx = 0; geo_idx < md->geometry.size(); geo_idx++) {
SubMeshGeometry& geo = md->geometry[geo_idx];
// This mesh needs to be split into several new meshes, by material.
typedef std::map<SubMeshGeometry::Primitive::MaterialId, SubMeshGeometry> SingleMatMeshMap;
SingleMatMeshMap new_meshes;
for(uint32 pi = 0; pi < geo.primitives.size(); pi++) {
SubMeshGeometry::Primitive& prim = geo.primitives[pi];
// Create new submesh if there isn't one for this material id yet
if (new_meshes.find(prim.materialId) == new_meshes.end()) {
// Copy all data
new_meshes[prim.materialId] = geo;
// And clear the prim list
new_meshes[prim.materialId].primitives.clear();
}
// Add this primitive
new_meshes[prim.materialId].primitives.push_back(prim);
// Reset material id -- all should be 0 since all will only have
// 1 material id
new_meshes[prim.materialId].primitives.back().materialId = 0;
}
// Recompute summary info for these new submeshes, add them to the
// new set, and store their indices for use by the instance
// geometries
typedef std::map<SubMeshGeometry::Primitive::MaterialId, uint32> NewSubMeshIndexMap;
NewSubMeshIndexMap new_indices_by_material;
for(SingleMatMeshMap::iterator nm_it = new_meshes.begin(); nm_it != new_meshes.end(); nm_it++) {
nm_it->second.recomputeBounds();
uint32 new_index = new_geometry.size();
new_geometry.push_back(nm_it->second);
new_indices_by_material[nm_it->first] = new_index;
}
// Now, run through and find GeometryInstances which are using the
// original mesh and make new ones using all the split ones
for(uint32 ii = 0; ii < md->instances.size(); ii++) {
GeometryInstance& geo_inst = md->instances[ii];
if (geo_inst.geometryIndex != geo_idx) continue;
for(NewSubMeshIndexMap::iterator sm_it = new_indices_by_material.begin(); sm_it != new_indices_by_material.end(); sm_it++) {
new_instances.push_back(geo_inst);
// Point to new index
new_instances.back().geometryIndex = sm_it->second;
// Reset material binding map, using only the material bound
// for this material from the earlier version.
new_instances.back().materialBindingMap.clear();
new_instances.back().materialBindingMap[0] = geo_inst.materialBindingMap[sm_it->first];
}
}
}
// After all the translation, just swapping out the list of
// SubMeshGeometries and GeometryInstances should be safe
md->geometry = new_geometry;
md->instances = new_instances;
}
return input;
}
} // namespace Mesh
} // namespace Sirikata
<commit_msg>Make SingleMaterialGeometryFilter use much less memory.<commit_after>/* Sirikata
* SingleMaterialGeometryFilter.cpp
*
* Copyright (c) 2010, Ewen Cheslack-Postava
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Sirikata nor the names of its contributors may
* be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "SingleMaterialGeometryFilter.hpp"
#include <sirikata/mesh/Meshdata.hpp>
namespace Sirikata {
namespace Mesh {
SingleMaterialGeometryFilter::SingleMaterialGeometryFilter(const String& args) {
}
namespace {
/** Clone this SubMeshGeometry, taking only a subset of its elements. Because
* copying requires duplicating the underlying data, this also removes
* now-unused data from the underlying vertex data in the copy. NOTE: Currently
* only supports a single material, i.e. all copied primitives should use the
* same material. Also, it *doesn't* recompute bounds.
*
* \param prims the indices of the primitives to keep
* \param output a bare SubMeshGeometry to output to
*/
// This would be nice to put into SubMeshGeometry directly, but right now it
// doesn't handle all cases well enough to do that -- multiple materials,
// animations, etc.
void copySubset(const SubMeshGeometry& orig, const std::vector<int>& prims, SubMeshGeometry* output) {
// Make sure we have a fresh start
*output = SubMeshGeometry();
output->name = orig.name;
// Initialize texUVs for new mesh. Faster to initialize once here than check
// every time through one of the data copying loops belo
for(std::vector<SubMeshGeometry::TextureSet>::const_iterator tex_set_it = orig.texUVs.begin(); tex_set_it != orig.texUVs.end(); tex_set_it++) {
output->texUVs.push_back(SubMeshGeometry::TextureSet());
output->texUVs.back().stride = tex_set_it->stride;
}
// Keep track of which data is referenced
std::vector<bool> referenced_indices(orig.positions.size(), false);
// Iterate through all copied prims, marking indices as used
for(std::vector<int>::const_iterator prim_it = prims.begin(); prim_it != prims.end(); prim_it++) {
const SubMeshGeometry::Primitive& prim = orig.primitives[*prim_it];
for(std::vector<unsigned short>::const_iterator ind_it = prim.indices.begin(); ind_it != prim.indices.end(); ind_it++)
referenced_indices[*ind_it] = true;
}
// With them all marked, form a map to translate from old indices -> new
// indices. Copy data over as we go.
std::map<unsigned short, unsigned short> index_map;
uint new_index_source = 0;
for(int orig_index = 0; orig_index < (int)referenced_indices.size(); orig_index++) {
if (referenced_indices[orig_index] == false) continue;
index_map[orig_index] = new_index_source;
new_index_source++;
output->positions.push_back( orig.positions[orig_index] );
if ((int)orig.normals.size() > orig_index)
output->normals.push_back( orig.normals[orig_index] );
if ((int)orig.tangents.size() > orig_index)
output->tangents.push_back( orig.tangents[orig_index] );
if ((int)orig.colors.size() > orig_index)
output->colors.push_back( orig.colors[orig_index] );
for(int tex_idx = 0; tex_idx < (int)orig.texUVs.size(); tex_idx++) {
for(int stride_i = 0; stride_i < (int)orig.texUVs[tex_idx].stride; stride_i++)
output->texUVs[tex_idx].uvs.push_back(
orig.texUVs[tex_idx].uvs[orig_index*orig.texUVs[tex_idx].stride + stride_i]
);
}
}
// Copy primitives over, adjusting indices
for(std::vector<int>::const_iterator prim_it = prims.begin(); prim_it != prims.end(); prim_it++) {
output->primitives.push_back(SubMeshGeometry::Primitive());
const SubMeshGeometry::Primitive& orig_prim = orig.primitives[*prim_it];
SubMeshGeometry::Primitive& new_prim = output->primitives.back();
// NOTE: This is a special case for the transformation we want -- there
// should only be one material so they all get mapped to 0.
new_prim.materialId = 0;
// Resize appropriately and copy new indices
new_prim.indices.resize(orig_prim.indices.size());
for(int ind = 0; ind < (int)orig_prim.indices.size(); ind++)
new_prim.indices[ind] = index_map[ orig_prim.indices[ind] ];
}
// Copy animations
for(SkinControllerList::const_iterator skin_it = orig.skinControllers.begin(); skin_it != orig.skinControllers.end(); skin_it++) {
const SkinController& orig_skin = *skin_it;
output->skinControllers.push_back(SkinController());
SkinController& new_skin = output->skinControllers.back();
// Some things aren't affected by the vertex data reduction
new_skin.joints = orig_skin.joints;
new_skin.bindShapeMatrix = orig_skin.bindShapeMatrix;
new_skin.inverseBindMatrices = orig_skin.inverseBindMatrices;
// weightStartIndices, weights, and jointIndices need to be
// decimated based on the reduced set of vertices
for(int orig_vert_idx = 0; orig_vert_idx < (int)referenced_indices.size(); orig_vert_idx++) {
if (referenced_indices[orig_vert_idx] == false) continue;
new_skin.weightStartIndices.push_back( new_skin.weights.size() );
for(int influence_idx = orig_skin.weightStartIndices[orig_vert_idx];
influence_idx < (int)orig_skin.weightStartIndices[orig_vert_idx+1];
influence_idx++) {
new_skin.weights.push_back( orig_skin.weights[influence_idx] );
new_skin.jointIndices.push_back( orig_skin.jointIndices[influence_idx] );
}
}
// One last entry in weightStartIndices because the extra
// entry allows simple subtraction to determine #influences
new_skin.weightStartIndices.push_back( new_skin.weights.size() );
}
}
} // namespace
FilterDataPtr SingleMaterialGeometryFilter::apply(FilterDataPtr input) {
for(FilterData::const_iterator md_it = input->begin(); md_it != input->end(); md_it++) {
VisualPtr vis = *md_it;
// Meshdata only currently
MeshdataPtr md( std::tr1::dynamic_pointer_cast<Meshdata>(vis) );
if (!md) continue;
// Our approach is to run through all SubMeshGeometries generating
// versions that are split. By maintaining a map from old indices to a
// list of new indices, we can then run through all GeometryInstances,
// duplicating them for each part of the original instance.
// This map stores geometryIndex -> list of new geometry indices,
// allowing the old instances to be split into a set of new instances
typedef std::map<uint32, std::vector<uint32> > OldToNewIndexMap;
OldToNewIndexMap new_geo_indices;
// Our output should be a new set of SubMeshGeometries and a new set of
// GeometryInstances referring to them.
SubMeshGeometryList new_geometry;
GeometryInstanceList new_instances;
for(uint32 geo_idx = 0; geo_idx < md->geometry.size(); geo_idx++) {
SubMeshGeometry& geo = md->geometry[geo_idx];
// This mesh needs to be split into several new meshes, by
// material. First, collect the primitives to be put under the copy
// for each material.
typedef std::map<SubMeshGeometry::Primitive::MaterialId, std::vector<int> > SingleMatPrimSetMap;
SingleMatPrimSetMap new_meshes_prims;
for(uint32 pi = 0; pi < geo.primitives.size(); pi++) {
SubMeshGeometry::Primitive& prim = geo.primitives[pi];
// Add this primitive
new_meshes_prims[prim.materialId].push_back(pi);
}
// Then copy the submesh, using only the primitives for each item.
typedef std::map<SubMeshGeometry::Primitive::MaterialId, SubMeshGeometry> SingleMatMeshMap;
SingleMatMeshMap new_meshes;
for(SingleMatPrimSetMap::iterator mat_it = new_meshes_prims.begin(); mat_it != new_meshes_prims.end(); mat_it++)
copySubset(geo, mat_it->second, &new_meshes[mat_it->first]);
new_meshes_prims.clear();
// Recompute summary info for these new submeshes, add them to the
// new set, and store their indices for use by the instance
// geometries
typedef std::map<SubMeshGeometry::Primitive::MaterialId, uint32> NewSubMeshIndexMap;
NewSubMeshIndexMap new_indices_by_material;
for(SingleMatMeshMap::iterator nm_it = new_meshes.begin(); nm_it != new_meshes.end(); nm_it++) {
nm_it->second.recomputeBounds();
uint32 new_index = new_geometry.size();
new_geometry.push_back(nm_it->second);
new_indices_by_material[nm_it->first] = new_index;
}
// Now, run through and find GeometryInstances which are using the
// original mesh and make new ones using all the split ones
for(uint32 ii = 0; ii < md->instances.size(); ii++) {
GeometryInstance& geo_inst = md->instances[ii];
if (geo_inst.geometryIndex != geo_idx) continue;
for(NewSubMeshIndexMap::iterator sm_it = new_indices_by_material.begin(); sm_it != new_indices_by_material.end(); sm_it++) {
new_instances.push_back(geo_inst);
// Point to new index
new_instances.back().geometryIndex = sm_it->second;
// Reset material binding map, using only the material bound
// for this material from the earlier version.
new_instances.back().materialBindingMap.clear();
new_instances.back().materialBindingMap[0] = geo_inst.materialBindingMap[sm_it->first];
}
}
}
// After all the translation, just swapping out the list of
// SubMeshGeometries and GeometryInstances should be safe
md->geometry = new_geometry;
md->instances = new_instances;
}
return input;
}
} // namespace Mesh
} // namespace Sirikata
<|endoftext|> |
<commit_before>/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/core/kernels/sendrecv_ops.h"
#include "tensorflow/core/framework/op.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/lib/strings/numbers.h"
#include "tensorflow/core/lib/strings/strcat.h"
#include "tensorflow/core/platform/logging.h"
namespace tensorflow {
static string GetRendezvousKeyPrefix(const string& send_device,
const string& recv_device,
const uint64 send_device_incarnation,
const string& tensor_name) {
return strings::StrCat(send_device, ";",
strings::FpToString(send_device_incarnation), ";",
recv_device, ";", tensor_name);
}
static void GetRendezvousKey(const string& key_prefix,
const FrameAndIter& frame_iter, string* key) {
key->clear();
strings::StrAppend(key, key_prefix, ";", frame_iter.frame_id, ":",
frame_iter.iter_id);
}
static FrameAndIter GetFrameAndIter(OpKernelContext* ctx,
bool hostmem_sendrecv) {
if (hostmem_sendrecv && ctx->call_frame() != nullptr) {
// Host memory send/recv pairs are added by
// common_runtime/memory_types.cc. When the pair of nodes are
// added inside a function, we need to use the function call frame
// to formulate the unique rendezvous key.
return FrameAndIter(reinterpret_cast<uint64>(ctx->call_frame()), 0);
} else {
return ctx->frame_iter();
}
}
SendOp::SendOp(OpKernelConstruction* ctx) : OpKernel(ctx) {
string send_device;
OP_REQUIRES_OK(ctx, ctx->GetAttr("send_device", &send_device));
string recv_device;
OP_REQUIRES_OK(ctx, ctx->GetAttr("recv_device", &recv_device));
uint64 send_device_incarnation;
OP_REQUIRES_OK(
ctx, ctx->GetAttr("send_device_incarnation",
reinterpret_cast<int64*>(&send_device_incarnation)));
string tensor_name;
OP_REQUIRES_OK(ctx, ctx->GetAttr("tensor_name", &tensor_name));
key_prefix_ = GetRendezvousKeyPrefix(send_device, recv_device,
send_device_incarnation, tensor_name);
// The vast majority of Send nodes are outside any loop context, so
// proactively cache the rendezvous key for the top-level.
GetRendezvousKey(key_prefix_, {0, 0}, &parsed_key_.buf_);
OP_REQUIRES_OK(ctx, Rendezvous::ParseKey(parsed_key_.buf_, &parsed_key_));
if (!ctx->GetAttr("_hostmem_sendrecv", &hostmem_sendrecv_).ok()) {
hostmem_sendrecv_ = false;
}
}
void SendOp::Compute(OpKernelContext* ctx) {
OP_REQUIRES(
ctx, ctx->rendezvous() != nullptr,
errors::Internal("Op kernel context needs to provide a rendezvous."));
// The device context may be passed between the Send/Recv
// boundary, so that the device context used to produce the Tensor
// is used when performing the copy on the recv side (which may be
// a different device).
Rendezvous::Args args;
args.device_context = ctx->op_device_context();
args.alloc_attrs = ctx->input_alloc_attr(0);
FrameAndIter frame_iter = GetFrameAndIter(ctx, hostmem_sendrecv_);
if (frame_iter == FrameAndIter(0, 0)) {
// Use the cached rendezvous key.
VLOG(2) << "Send " << parsed_key_.buf_;
OP_REQUIRES_OK(ctx,
ctx->rendezvous()->Send(parsed_key_, args, ctx->input(0),
ctx->is_input_dead()));
} else {
Rendezvous::ParsedKey in_loop_parsed;
GetRendezvousKey(key_prefix_, frame_iter, &in_loop_parsed.buf_);
VLOG(2) << "Send " << in_loop_parsed.buf_;
OP_REQUIRES_OK(ctx,
Rendezvous::ParseKey(in_loop_parsed.buf_, &in_loop_parsed));
OP_REQUIRES_OK(ctx,
ctx->rendezvous()->Send(in_loop_parsed, args, ctx->input(0),
ctx->is_input_dead()));
}
}
REGISTER_KERNEL_BUILDER(Name("_Send").Device(DEVICE_CPU), SendOp);
REGISTER_KERNEL_BUILDER(Name("_Send").Device(DEVICE_GPU), SendOp);
#ifdef TENSORFLOW_USE_SYCL
REGISTER_KERNEL_BUILDER(Name("_Send").Device(DEVICE_SYCL), SendOp);
REGISTER_KERNEL_BUILDER(
Name("_HostSend").Device(DEVICE_SYCL).HostMemory("tensor"), SendOp);
#endif // TENSORFLOW_USE_SYCL
REGISTER_KERNEL_BUILDER(Name("_HostSend").Device(DEVICE_CPU), SendOp);
REGISTER_KERNEL_BUILDER(
Name("_HostSend").Device(DEVICE_GPU).HostMemory("tensor"), SendOp);
RecvOp::RecvOp(OpKernelConstruction* ctx) : AsyncOpKernel(ctx) {
string send_device;
OP_REQUIRES_OK(ctx, ctx->GetAttr("send_device", &send_device));
string recv_device;
OP_REQUIRES_OK(ctx, ctx->GetAttr("recv_device", &recv_device));
uint64 send_device_incarnation;
OP_REQUIRES_OK(
ctx, ctx->GetAttr("send_device_incarnation",
reinterpret_cast<int64*>(&send_device_incarnation)));
string tensor_name;
OP_REQUIRES_OK(ctx, ctx->GetAttr("tensor_name", &tensor_name));
key_prefix_ = GetRendezvousKeyPrefix(send_device, recv_device,
send_device_incarnation, tensor_name);
// The vast majority of Recv nodes are outside any loop context, so
// proactively cache the rendezvous key for the top-level.
GetRendezvousKey(key_prefix_, {0, 0}, &parsed_key_.buf_);
OP_REQUIRES_OK(ctx, Rendezvous::ParseKey(parsed_key_.buf_, &parsed_key_));
if (!ctx->GetAttr("_hostmem_sendrecv", &hostmem_sendrecv_).ok()) {
hostmem_sendrecv_ = false;
}
}
void RecvOp::ComputeAsync(OpKernelContext* ctx, DoneCallback done) {
OP_REQUIRES(
ctx, ctx->rendezvous() != nullptr,
errors::Internal("Op kernel context needs to provide a rendezvous."));
Rendezvous::Args args;
args.device_context = ctx->op_device_context();
args.alloc_attrs = ctx->output_alloc_attr(0);
using namespace std::placeholders;
Rendezvous::DoneCallback done_cb = std::bind(
[ctx](DoneCallback done,
// Begin unbound arguments.
const Status& s, const Rendezvous::Args& send_args,
const Rendezvous::Args& recv_args, const Tensor& val,
bool is_dead) {
ctx->SetStatus(s);
if (s.ok()) {
// 'ctx' allocates the output tensor of the expected type.
// The runtime checks whether the tensor received here is
// the same type.
if (!is_dead) {
ctx->set_output(0, val);
}
*ctx->is_output_dead() = is_dead;
}
done();
},
std::move(done), _1, _2, _3, _4, _5);
FrameAndIter frame_iter = GetFrameAndIter(ctx, hostmem_sendrecv_);
if (frame_iter == FrameAndIter(0, 0)) {
VLOG(2) << "Recv " << parsed_key_.buf_;
ctx->rendezvous()->RecvAsync(parsed_key_, args, std::move(done_cb));
} else {
Rendezvous::ParsedKey in_loop_parsed;
GetRendezvousKey(key_prefix_, frame_iter, &in_loop_parsed.buf_);
VLOG(2) << "Recv " << in_loop_parsed.buf_;
OP_REQUIRES_OK_ASYNC(
ctx, Rendezvous::ParseKey(in_loop_parsed.buf_, &in_loop_parsed), done);
ctx->rendezvous()->RecvAsync(in_loop_parsed, args, std::move(done_cb));
}
}
REGISTER_KERNEL_BUILDER(Name("_Recv").Device(DEVICE_CPU), RecvOp);
REGISTER_KERNEL_BUILDER(Name("_Recv").Device(DEVICE_GPU), RecvOp);
#ifdef TENSORFLOW_USE_SYCL
REGISTER_KERNEL_BUILDER(Name("_Recv").Device(DEVICE_SYCL), RecvOp);
#endif // TENSORFLOW_USE_SYCL
REGISTER_KERNEL_BUILDER(Name("_HostRecv").Device(DEVICE_CPU), RecvOp);
REGISTER_KERNEL_BUILDER(
Name("_HostRecv").Device(DEVICE_GPU).HostMemory("tensor"), RecvOp);
#ifdef TENSORFLOW_USE_SYCL
REGISTER_KERNEL_BUILDER(
Name("_HostRecv").Device(DEVICE_SYCL).HostMemory("tensor"), RecvOp);
#endif // TENSORFLOW_USE_SYCL
} // end namespace tensorflow
<commit_msg>Do not log a warning when `Rendezvous::Send()` fails in the Send op kernel.<commit_after>/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/core/kernels/sendrecv_ops.h"
#include "tensorflow/core/framework/op.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/lib/strings/numbers.h"
#include "tensorflow/core/lib/strings/strcat.h"
#include "tensorflow/core/platform/logging.h"
namespace tensorflow {
static string GetRendezvousKeyPrefix(const string& send_device,
const string& recv_device,
const uint64 send_device_incarnation,
const string& tensor_name) {
return strings::StrCat(send_device, ";",
strings::FpToString(send_device_incarnation), ";",
recv_device, ";", tensor_name);
}
static void GetRendezvousKey(const string& key_prefix,
const FrameAndIter& frame_iter, string* key) {
key->clear();
strings::StrAppend(key, key_prefix, ";", frame_iter.frame_id, ":",
frame_iter.iter_id);
}
static FrameAndIter GetFrameAndIter(OpKernelContext* ctx,
bool hostmem_sendrecv) {
if (hostmem_sendrecv && ctx->call_frame() != nullptr) {
// Host memory send/recv pairs are added by
// common_runtime/memory_types.cc. When the pair of nodes are
// added inside a function, we need to use the function call frame
// to formulate the unique rendezvous key.
return FrameAndIter(reinterpret_cast<uint64>(ctx->call_frame()), 0);
} else {
return ctx->frame_iter();
}
}
SendOp::SendOp(OpKernelConstruction* ctx) : OpKernel(ctx) {
string send_device;
OP_REQUIRES_OK(ctx, ctx->GetAttr("send_device", &send_device));
string recv_device;
OP_REQUIRES_OK(ctx, ctx->GetAttr("recv_device", &recv_device));
uint64 send_device_incarnation;
OP_REQUIRES_OK(
ctx, ctx->GetAttr("send_device_incarnation",
reinterpret_cast<int64*>(&send_device_incarnation)));
string tensor_name;
OP_REQUIRES_OK(ctx, ctx->GetAttr("tensor_name", &tensor_name));
key_prefix_ = GetRendezvousKeyPrefix(send_device, recv_device,
send_device_incarnation, tensor_name);
// The vast majority of Send nodes are outside any loop context, so
// proactively cache the rendezvous key for the top-level.
GetRendezvousKey(key_prefix_, {0, 0}, &parsed_key_.buf_);
OP_REQUIRES_OK(ctx, Rendezvous::ParseKey(parsed_key_.buf_, &parsed_key_));
if (!ctx->GetAttr("_hostmem_sendrecv", &hostmem_sendrecv_).ok()) {
hostmem_sendrecv_ = false;
}
}
void SendOp::Compute(OpKernelContext* ctx) {
OP_REQUIRES(
ctx, ctx->rendezvous() != nullptr,
errors::Internal("Op kernel context needs to provide a rendezvous."));
// The device context may be passed between the Send/Recv
// boundary, so that the device context used to produce the Tensor
// is used when performing the copy on the recv side (which may be
// a different device).
Rendezvous::Args args;
args.device_context = ctx->op_device_context();
args.alloc_attrs = ctx->input_alloc_attr(0);
FrameAndIter frame_iter = GetFrameAndIter(ctx, hostmem_sendrecv_);
if (frame_iter == FrameAndIter(0, 0)) {
// Use the cached rendezvous key.
VLOG(2) << "Send " << parsed_key_.buf_;
ctx->SetStatus(ctx->rendezvous()->Send(parsed_key_, args, ctx->input(0),
ctx->is_input_dead()));
return;
} else {
Rendezvous::ParsedKey in_loop_parsed;
GetRendezvousKey(key_prefix_, frame_iter, &in_loop_parsed.buf_);
VLOG(2) << "Send " << in_loop_parsed.buf_;
OP_REQUIRES_OK(ctx,
Rendezvous::ParseKey(in_loop_parsed.buf_, &in_loop_parsed));
ctx->SetStatus(ctx->rendezvous()->Send(in_loop_parsed, args, ctx->input(0),
ctx->is_input_dead()));
return;
}
}
REGISTER_KERNEL_BUILDER(Name("_Send").Device(DEVICE_CPU), SendOp);
REGISTER_KERNEL_BUILDER(Name("_Send").Device(DEVICE_GPU), SendOp);
#ifdef TENSORFLOW_USE_SYCL
REGISTER_KERNEL_BUILDER(Name("_Send").Device(DEVICE_SYCL), SendOp);
REGISTER_KERNEL_BUILDER(
Name("_HostSend").Device(DEVICE_SYCL).HostMemory("tensor"), SendOp);
#endif // TENSORFLOW_USE_SYCL
REGISTER_KERNEL_BUILDER(Name("_HostSend").Device(DEVICE_CPU), SendOp);
REGISTER_KERNEL_BUILDER(
Name("_HostSend").Device(DEVICE_GPU).HostMemory("tensor"), SendOp);
RecvOp::RecvOp(OpKernelConstruction* ctx) : AsyncOpKernel(ctx) {
string send_device;
OP_REQUIRES_OK(ctx, ctx->GetAttr("send_device", &send_device));
string recv_device;
OP_REQUIRES_OK(ctx, ctx->GetAttr("recv_device", &recv_device));
uint64 send_device_incarnation;
OP_REQUIRES_OK(
ctx, ctx->GetAttr("send_device_incarnation",
reinterpret_cast<int64*>(&send_device_incarnation)));
string tensor_name;
OP_REQUIRES_OK(ctx, ctx->GetAttr("tensor_name", &tensor_name));
key_prefix_ = GetRendezvousKeyPrefix(send_device, recv_device,
send_device_incarnation, tensor_name);
// The vast majority of Recv nodes are outside any loop context, so
// proactively cache the rendezvous key for the top-level.
GetRendezvousKey(key_prefix_, {0, 0}, &parsed_key_.buf_);
OP_REQUIRES_OK(ctx, Rendezvous::ParseKey(parsed_key_.buf_, &parsed_key_));
if (!ctx->GetAttr("_hostmem_sendrecv", &hostmem_sendrecv_).ok()) {
hostmem_sendrecv_ = false;
}
}
void RecvOp::ComputeAsync(OpKernelContext* ctx, DoneCallback done) {
OP_REQUIRES(
ctx, ctx->rendezvous() != nullptr,
errors::Internal("Op kernel context needs to provide a rendezvous."));
Rendezvous::Args args;
args.device_context = ctx->op_device_context();
args.alloc_attrs = ctx->output_alloc_attr(0);
using namespace std::placeholders;
Rendezvous::DoneCallback done_cb = std::bind(
[ctx](DoneCallback done,
// Begin unbound arguments.
const Status& s, const Rendezvous::Args& send_args,
const Rendezvous::Args& recv_args, const Tensor& val,
bool is_dead) {
ctx->SetStatus(s);
if (s.ok()) {
// 'ctx' allocates the output tensor of the expected type.
// The runtime checks whether the tensor received here is
// the same type.
if (!is_dead) {
ctx->set_output(0, val);
}
*ctx->is_output_dead() = is_dead;
}
done();
},
std::move(done), _1, _2, _3, _4, _5);
FrameAndIter frame_iter = GetFrameAndIter(ctx, hostmem_sendrecv_);
if (frame_iter == FrameAndIter(0, 0)) {
VLOG(2) << "Recv " << parsed_key_.buf_;
ctx->rendezvous()->RecvAsync(parsed_key_, args, std::move(done_cb));
} else {
Rendezvous::ParsedKey in_loop_parsed;
GetRendezvousKey(key_prefix_, frame_iter, &in_loop_parsed.buf_);
VLOG(2) << "Recv " << in_loop_parsed.buf_;
OP_REQUIRES_OK_ASYNC(
ctx, Rendezvous::ParseKey(in_loop_parsed.buf_, &in_loop_parsed), done);
ctx->rendezvous()->RecvAsync(in_loop_parsed, args, std::move(done_cb));
}
}
REGISTER_KERNEL_BUILDER(Name("_Recv").Device(DEVICE_CPU), RecvOp);
REGISTER_KERNEL_BUILDER(Name("_Recv").Device(DEVICE_GPU), RecvOp);
#ifdef TENSORFLOW_USE_SYCL
REGISTER_KERNEL_BUILDER(Name("_Recv").Device(DEVICE_SYCL), RecvOp);
#endif // TENSORFLOW_USE_SYCL
REGISTER_KERNEL_BUILDER(Name("_HostRecv").Device(DEVICE_CPU), RecvOp);
REGISTER_KERNEL_BUILDER(
Name("_HostRecv").Device(DEVICE_GPU).HostMemory("tensor"), RecvOp);
#ifdef TENSORFLOW_USE_SYCL
REGISTER_KERNEL_BUILDER(
Name("_HostRecv").Device(DEVICE_SYCL).HostMemory("tensor"), RecvOp);
#endif // TENSORFLOW_USE_SYCL
} // end namespace tensorflow
<|endoftext|> |
<commit_before>// Copyright (c) 2020 ASMlover. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list ofconditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in
// the documentation and/or other materialsprovided with the
// distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#include <tuple>
#include <iostream>
#include "common.hh"
namespace tree {
}
void test_tree() {
}
<commit_msg>:construction: chore(node): add base node for tree<commit_after>// Copyright (c) 2020 ASMlover. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list ofconditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in
// the documentation and/or other materialsprovided with the
// distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#include <tuple>
#include <iostream>
#include "common.hh"
namespace tree {
using ColorType = bool;
static constexpr ColorType kColorRed = false;
static constexpr ColorType kColorBlack = true;
static constexpr int kHeightMask = 0xff;
struct NodeBase;
using BasePtr = NodeBase*;
using ConstBasePtr = const NodeBase*;
struct NodeBase {
BasePtr parent;
BasePtr left;
BasePtr right;
static inline BasePtr minimum(BasePtr x) noexcept {
while (x->left != nullptr)
x = x->left;
return x;
}
static inline ConstBasePtr minimum(ConstBasePtr x) noexcept {
return minimum(const_cast<BasePtr>(x));
}
static inline BasePtr maximum(BasePtr x) noexcept {
while (x->right != nullptr)
x = x->right;
return x;
}
static inline ConstBasePtr maximum(ConstBasePtr x) noexcept {
return maximum(const_cast<BasePtr>(x));
}
static BasePtr successor(BasePtr x) noexcept {
if (x->right != nullptr) {
x = x->right;
while (x->left != nullptr)
x = x->left;
}
else {
BasePtr y = x->parent;
while (x == y->right) {
x = y;
y = y->parent;
}
if (x->right != y)
x = y;
}
return x;
}
static ConstBasePtr successor(ConstBasePtr x) noexcept {
return successor(const_cast<BasePtr>(x));
}
static BasePtr predecessor(BasePtr x) noexcept {
if (x->left != nullptr) {
x = x->left;
while (x->right != nullptr)
x = x->right;
}
else {
BasePtr y = x->parent;
while (x == y->left) {
x = y;
y = y->parent;
}
x = y;
}
return x;
}
static ConstBasePtr predecessor(ConstBasePtr x) noexcept {
return predecessor(const_cast<BasePtr>(x));
}
};
struct AVLNodeBase : public NodeBase {
using Ptr = AVLNodeBase*;
int height;
inline int lheight() const noexcept { return left ? Ptr(left)->height : 0; }
inline int rheight() const noexcept { return right ? Ptr(right)->height : 0; }
inline void update_height() noexcept { height = Xt::max(lheight(), rheight()) + 1; }
static BasePtr predecessor(BasePtr x) noexcept {
return (Ptr(x)->height == kHeightMask && x->parent->parent == x)
? x->right : NodeBase::predecessor(x);
}
static ConstBasePtr predecessor(ConstBasePtr x) noexcept {
return predecessor(const_cast<BasePtr>(x));
}
};
struct RBNodeBase : public NodeBase {
using Ptr = RBNodeBase*;
ColorType color;
inline bool is_red() const noexcept { return color == kColorRed; }
inline bool is_black() const noexcept { return color == kColorBlack; }
inline void set_red() noexcept { color = kColorRed; }
inline void set_black() noexcept { color = kColorBlack; }
static BasePtr predecessor(BasePtr x) noexcept {
return (Ptr(x)->is_red() && x->parent->parent == x)
? x->right : NodeBase::predecessor(x);
}
static ConstBasePtr predecessor(ConstBasePtr x) noexcept {
return predecessor(const_cast<BasePtr>(x));
}
};
}
void test_tree() {
}
<|endoftext|> |
<commit_before>#include <iostream>
#include "3.cpp"
using namespace std;
int main()
{
DoubleLinkedChain<int> ch;
DoubleLinkedList<int> L1, L2;
int a1[] = {1, 3, 5, 7, 9, 6};
int a2[] = {3, 4, 8, 5, 7};
for (size_t i = 0; i < 5; i++)
{
L1.insertEnd(a1[i]);
L2.insertEnd(a2[i]);
}
L1.insertEnd(a1[5]);
ch.join(L1, L2);
DoubleListElement<int> *front = ch.getFrontPtr(), *pn = front->prev;
cout << "First chain: (";
while (front && front->prev == pn)
{
cout << front->data << " ";
pn = front;
front = front->next;
}
cout << ")" << endl;
cout << "First link between chains: " << pn->data << " -> " <<
front->data << endl;
DoubleListElement<int> *back = ch.getBackPtr();
pn = back->next;
cout << "Second chain (reversed): (";
while (back && back->next == pn)
{
cout << back->data << " ";
pn = back;
back = back->prev;
}
cout << ")" << endl;
cout << "Second link between chains: " << pn->data << " -> " <<
back->data << endl;
cout << "Is joined: " << ch.isJoined() << endl;
cout << "Sum: " << ch.sum() << endl;
return 0;
}
<commit_msg>added missing header files<commit_after>#include <iostream>
#include "dllist.cpp"
#include "dlchain.cpp"
#include "3.cpp"
using namespace std;
int main()
{
DoubleLinkedChain<int> ch;
DoubleLinkedList<int> L1, L2;
int a1[] = {1, 3, 5, 7, 9, 6};
int a2[] = {3, 4, 8, 5, 7};
for (size_t i = 0; i < 5; i++)
{
L1.insertEnd(a1[i]);
L2.insertEnd(a2[i]);
}
L1.insertEnd(a1[5]);
ch.join(L1, L2);
DoubleListElement<int> *front = ch.getFrontPtr(), *pn = front->prev;
cout << "First chain: (";
while (front && front->prev == pn)
{
cout << front->data << " ";
pn = front;
front = front->next;
}
cout << ")" << endl;
cout << "First link between chains: " << pn->data << " -> " <<
front->data << endl;
DoubleListElement<int> *back = ch.getBackPtr();
pn = back->next;
cout << "Second chain (reversed): (";
while (back && back->next == pn)
{
cout << back->data << " ";
pn = back;
back = back->prev;
}
cout << ")" << endl;
cout << "Second link between chains: " << pn->data << " -> " <<
back->data << endl;
cout << "Is joined: " << ch.isJoined() << endl;
cout << "Sum: " << ch.sum() << endl;
return 0;
}
<|endoftext|> |
<commit_before>//==============================================================================
// Single cell simulation graph panels widget
//==============================================================================
#include "singlecellsimulationgraphpanel.h"
#include "singlecellsimulationgraphpanels.h"
//==============================================================================
#include <QSettings>
#include <QWheelEvent>
//==============================================================================
namespace OpenCOR {
namespace SingleCellSimulation {
//==============================================================================
SingleCellSimulationGraphPanels::SingleCellSimulationGraphPanels(const QString &pName,
QWidget *pParent) :
QSplitter(Qt::Vertical, pParent),
CommonWidget(pName, this, pParent)
{
}
//==============================================================================
static const QString SettingsGraphPanelsCount = "GraphPanelsCount";
//==============================================================================
void SingleCellSimulationGraphPanels::loadSettings(QSettings *pSettings)
{
// Let the user know of a few default things about ourselves by emitting a
// few signals
emit removeGraphPanelsEnabled(false);
// Retrieve the number of graph panels and create the corresponding number
// of graphs
int graphPanelsCount = pSettings->value(SettingsGraphPanelsCount, 1).toInt();
if (!graphPanelsCount)
// For some reason, the settings for the number of graph panels to be
// created got messed up, so...
graphPanelsCount = 1;
for (int i = 0; i < graphPanelsCount; ++i)
addGraphPanel();
// Select the first graph panel
qobject_cast<SingleCellSimulationGraphPanel *>(widget(0))->setActive(true);
}
//==============================================================================
void SingleCellSimulationGraphPanels::saveSettings(QSettings *pSettings) const
{
// Keep track of the number of graph panels
pSettings->setValue(SettingsGraphPanelsCount, count());
}
//==============================================================================
void SingleCellSimulationGraphPanels::wheelEvent(QWheelEvent *pEvent)
{
// Default handling of the event
QSplitter::wheelEvent(pEvent);
// Select the previous/next graph panel, if any
if (pEvent->delta())
for (int i = 0, iMax = count(); i < iMax; ++i) {
SingleCellSimulationGraphPanel *graphPanel = qobject_cast<SingleCellSimulationGraphPanel *>(widget(i));
if (graphPanel->isActive()) {
// We are dealing with the currently active graph panel, so
// inactivate it and activate either its predecessor or successor
graphPanel->setActive(false);
int shift = 1;
#ifdef Q_WS_MAC
#ifdef AVAILABLE_MAC_OS_X_VERSION_10_7_AND_LATER
// From version 10.7 of Mac OS X, the scrolling works the other way
// round, so...
shift = -1;
#endif
#endif
i += (pEvent->delta() < 0)?shift:-shift;
if (i < 0)
i = 0;
else if (i == iMax)
i = iMax-1;
qobject_cast<SingleCellSimulationGraphPanel *>(widget(i))->setActive(true);
break;
}
}
}
//==============================================================================
SingleCellSimulationGraphPanel * SingleCellSimulationGraphPanels::addGraphPanel()
{
// Keep track of the graph panels' original size
QList<int> origSizes = sizes();
// Create a new graph panel
SingleCellSimulationGraphPanel *res = new SingleCellSimulationGraphPanel(this);
// Add the graph panel to ourselves
addWidget(res);
// Resize the graph panels, thus making sure that their size is what it
// should be (see issue #58)
double scalingFactor = (double) (count()-1)/count();
for (int i = 0, iMax = origSizes.count(); i < iMax; ++i)
origSizes[i] *= scalingFactor;
setSizes(origSizes << height()/count());
// Create a connection to keep track of whenever the graph panel gets
// activated
connect(res, SIGNAL(activated(SingleCellSimulationGraphPanel *)),
this, SLOT(graphPanelActivated(SingleCellSimulationGraphPanel *)));
// Activate the graph panel
res->setActive(true);
// Let people know that we have added a graph panel
emit grapPanelAdded(res);
// Let people know whether graph panels can be removed
emit removeGraphPanelsEnabled(count() > 1);
// Return our newly created graph panel
return res;
}
//==============================================================================
void SingleCellSimulationGraphPanels::removeGraphPanel()
{
if (count() == 1)
// There is only one graph panel left, so...
return;
// Remove the current graph panel
for (int i = 0, iMax = count(); i < iMax; ++i) {
SingleCellSimulationGraphPanel *graphPanel = qobject_cast<SingleCellSimulationGraphPanel *>(widget(i));
if (graphPanel->isActive()) {
// We are dealing with the currently active graph panel, so remove
// it
graphPanel->hide();
delete graphPanel;
// Activate the next graph panel or the last one available, if any
if (i < count())
// There is a next graph panel, so activate it
qobject_cast<SingleCellSimulationGraphPanel *>(widget(i))->setActive(true);
else
// We were dealing with the last graph panel, so just activate
// the new last graph panel
qobject_cast<SingleCellSimulationGraphPanel *>(widget(count()-1))->setActive(true);
// We are all done, so...
break;
}
}
// Let people know that we have removed a graph panel
emit grapPanelRemoved();
// Let people know whether graph panels can be removed
emit removeGraphPanelsEnabled(count() > 1);
}
//==============================================================================
SingleCellSimulationGraphPanel * SingleCellSimulationGraphPanels::activeGraphPanel()
{
// Return the active graph panel
for (int i = 0, iMax = count(); i < iMax; ++i) {
SingleCellSimulationGraphPanel *graphPanel = qobject_cast<SingleCellSimulationGraphPanel *>(widget(i));
if (graphPanel->isActive())
// We found the active graph panel, so...
return graphPanel;
}
// There are no graph panels, so...
// Note: indeed, since if there is at least one graph panel, then we have an
// active graph panel...
return 0;
}
//==============================================================================
void SingleCellSimulationGraphPanels::graphPanelActivated(SingleCellSimulationGraphPanel *pGraphPanel)
{
// A graph panel has been activated, so inactivate all the others
for (int i = 0, iMax = count(); i < iMax; ++i) {
SingleCellSimulationGraphPanel *graphPanel = qobject_cast<SingleCellSimulationGraphPanel *>(widget(i));
if (graphPanel != pGraphPanel)
// We are not dealing with the graph panel that just got activated,
// so inactivate it
graphPanel->setActive(false);
}
}
//==============================================================================
} // namespace SingleCellSimulation
} // namespace OpenCOR
//==============================================================================
// End of file
//==============================================================================
<commit_msg>Keeps track of the active graph panel (closes #70).<commit_after>//==============================================================================
// Single cell simulation graph panels widget
//==============================================================================
#include "singlecellsimulationgraphpanel.h"
#include "singlecellsimulationgraphpanels.h"
//==============================================================================
#include <QSettings>
#include <QWheelEvent>
//==============================================================================
namespace OpenCOR {
namespace SingleCellSimulation {
//==============================================================================
SingleCellSimulationGraphPanels::SingleCellSimulationGraphPanels(const QString &pName,
QWidget *pParent) :
QSplitter(Qt::Vertical, pParent),
CommonWidget(pName, this, pParent)
{
}
//==============================================================================
static const QString SettingsGraphPanelsCount = "GraphPanelsCount";
static const QString SettingsActiveGraphPanel = "ActiveGraphPanel";
//==============================================================================
void SingleCellSimulationGraphPanels::loadSettings(QSettings *pSettings)
{
// Let the user know of a few default things about ourselves by emitting a
// few signals
emit removeGraphPanelsEnabled(false);
// Retrieve the number of graph panels and create the corresponding number
// of graphs
int graphPanelsCount = pSettings->value(SettingsGraphPanelsCount, 1).toInt();
if (!graphPanelsCount)
// For some reason, the settings for the number of graph panels to be
// created got messed up, so...
graphPanelsCount = 1;
for (int i = 0; i < graphPanelsCount; ++i)
addGraphPanel();
// Select the graph panel that used to be active
qobject_cast<SingleCellSimulationGraphPanel *>(widget(pSettings->value(SettingsActiveGraphPanel, 0).toInt()))->setActive(true);
}
//==============================================================================
void SingleCellSimulationGraphPanels::saveSettings(QSettings *pSettings) const
{
// Keep track of the number of graph panels and of which graph panel was the
// active one
pSettings->setValue(SettingsGraphPanelsCount, count());
for (int i = 0, iMax = count(); i < iMax; ++i)
if (qobject_cast<SingleCellSimulationGraphPanel *>(widget(i))->isActive()) {
// We found the active graph panel, so...
pSettings->setValue(SettingsActiveGraphPanel, i);
break;
}
}
//==============================================================================
void SingleCellSimulationGraphPanels::wheelEvent(QWheelEvent *pEvent)
{
// Default handling of the event
QSplitter::wheelEvent(pEvent);
// Select the previous/next graph panel, if any
if (pEvent->delta())
for (int i = 0, iMax = count(); i < iMax; ++i) {
SingleCellSimulationGraphPanel *graphPanel = qobject_cast<SingleCellSimulationGraphPanel *>(widget(i));
if (graphPanel->isActive()) {
// We are dealing with the currently active graph panel, so
// inactivate it and activate either its predecessor or successor
graphPanel->setActive(false);
int shift = 1;
#ifdef Q_WS_MAC
#ifdef AVAILABLE_MAC_OS_X_VERSION_10_7_AND_LATER
// From version 10.7 of Mac OS X, the scrolling works the other way
// round, so...
shift = -1;
#endif
#endif
i += (pEvent->delta() < 0)?shift:-shift;
if (i < 0)
i = 0;
else if (i == iMax)
i = iMax-1;
qobject_cast<SingleCellSimulationGraphPanel *>(widget(i))->setActive(true);
break;
}
}
}
//==============================================================================
SingleCellSimulationGraphPanel * SingleCellSimulationGraphPanels::addGraphPanel()
{
// Keep track of the graph panels' original size
QList<int> origSizes = sizes();
// Create a new graph panel
SingleCellSimulationGraphPanel *res = new SingleCellSimulationGraphPanel(this);
// Add the graph panel to ourselves
addWidget(res);
// Resize the graph panels, thus making sure that their size is what it
// should be (see issue #58)
double scalingFactor = (double) (count()-1)/count();
for (int i = 0, iMax = origSizes.count(); i < iMax; ++i)
origSizes[i] *= scalingFactor;
setSizes(origSizes << height()/count());
// Create a connection to keep track of whenever the graph panel gets
// activated
connect(res, SIGNAL(activated(SingleCellSimulationGraphPanel *)),
this, SLOT(graphPanelActivated(SingleCellSimulationGraphPanel *)));
// Activate the graph panel
res->setActive(true);
// Let people know that we have added a graph panel
emit grapPanelAdded(res);
// Let people know whether graph panels can be removed
emit removeGraphPanelsEnabled(count() > 1);
// Return our newly created graph panel
return res;
}
//==============================================================================
void SingleCellSimulationGraphPanels::removeGraphPanel()
{
if (count() == 1)
// There is only one graph panel left, so...
return;
// Remove the current graph panel
for (int i = 0, iMax = count(); i < iMax; ++i) {
SingleCellSimulationGraphPanel *graphPanel = qobject_cast<SingleCellSimulationGraphPanel *>(widget(i));
if (graphPanel->isActive()) {
// We are dealing with the currently active graph panel, so remove
// it
graphPanel->hide();
delete graphPanel;
// Activate the next graph panel or the last one available, if any
if (i < count())
// There is a next graph panel, so activate it
qobject_cast<SingleCellSimulationGraphPanel *>(widget(i))->setActive(true);
else
// We were dealing with the last graph panel, so just activate
// the new last graph panel
qobject_cast<SingleCellSimulationGraphPanel *>(widget(count()-1))->setActive(true);
// We are all done, so...
break;
}
}
// Let people know that we have removed a graph panel
emit grapPanelRemoved();
// Let people know whether graph panels can be removed
emit removeGraphPanelsEnabled(count() > 1);
}
//==============================================================================
SingleCellSimulationGraphPanel * SingleCellSimulationGraphPanels::activeGraphPanel()
{
// Return the active graph panel
for (int i = 0, iMax = count(); i < iMax; ++i) {
SingleCellSimulationGraphPanel *graphPanel = qobject_cast<SingleCellSimulationGraphPanel *>(widget(i));
if (graphPanel->isActive())
// We found the active graph panel, so...
return graphPanel;
}
// There are no graph panels, so...
// Note: indeed, since if there is at least one graph panel, then we have an
// active graph panel...
return 0;
}
//==============================================================================
void SingleCellSimulationGraphPanels::graphPanelActivated(SingleCellSimulationGraphPanel *pGraphPanel)
{
// A graph panel has been activated, so inactivate all the others
for (int i = 0, iMax = count(); i < iMax; ++i) {
SingleCellSimulationGraphPanel *graphPanel = qobject_cast<SingleCellSimulationGraphPanel *>(widget(i));
if (graphPanel != pGraphPanel)
// We are not dealing with the graph panel that just got activated,
// so inactivate it
graphPanel->setActive(false);
}
}
//==============================================================================
} // namespace SingleCellSimulation
} // namespace OpenCOR
//==============================================================================
// End of file
//==============================================================================
<|endoftext|> |
<commit_before>/*
* This file is part of openfx-arena <https://github.com/olear/openfx-arena>,
* Copyright (C) 2015, 2016 FxArena DA
* Copyright (C) 2016 INRIA
*
* openfx-arena is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation.
*
* openfx-arena is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with openfx-arena. If not, see <http://www.gnu.org/licenses/gpl-2.0.html>
*/
#include <librsvg/rsvg.h>
#ifdef LEGACY
#include "librsvg/rsvg-cairo.h"
#endif
#include "GenericReader.h"
#include "GenericOCIO.h"
#include "ofxsImageEffect.h"
#ifdef OFX_IO_USING_OCIO
#include <OpenColorIO/OpenColorIO.h>
#endif
#define kPluginName "ReadSVG"
#define kPluginGrouping "Image/Readers"
#define kPluginIdentifier "net.fxarena.openfx.ReadSVG"
#define kPluginVersionMajor 2
#define kPluginVersionMinor 0
#define kPluginEvaluation 50
#define kParamDpi "dpi"
#define kParamDpiLabel "DPI"
#define kParamDpiHint "Dots-per-inch (90 is default)"
#define kParamDpiDefault 90
#define kSupportsRGBA true
#define kSupportsRGB false
#define kSupportsAlpha false
#define kSupportsTiles false
class ReadSVGPlugin : public GenericReaderPlugin
{
public:
ReadSVGPlugin(OfxImageEffectHandle handle, const std::vector<std::string>& extensions);
virtual ~ReadSVGPlugin();
private:
virtual bool isVideoStream(const std::string& /*filename*/) OVERRIDE FINAL { return false; }
virtual void decode(const std::string& filename, OfxTime time, int view, bool isPlayback, const OfxRectI& renderWindow, float *pixelData, const OfxRectI& bounds, OFX::PixelComponentEnum pixelComponents, int pixelComponentCount, int rowBytes) OVERRIDE FINAL;
virtual bool getFrameBounds(const std::string& filename, OfxTime time, OfxRectI *bounds, double *par, std::string *error,int *tile_width, int *tile_height) OVERRIDE FINAL;
virtual void onInputFileChanged(const std::string& newFile, bool setColorSpace, OFX::PreMultiplicationEnum *premult, OFX::PixelComponentEnum *components, int *componentCount) OVERRIDE FINAL;
OFX::IntParam *_dpi;
};
ReadSVGPlugin::ReadSVGPlugin(OfxImageEffectHandle handle, const std::vector<std::string>& extensions)
: GenericReaderPlugin(handle, extensions, kSupportsRGBA, kSupportsRGB, kSupportsAlpha, kSupportsTiles, false)
,_dpi(0)
{
_dpi = fetchIntParam(kParamDpi);
assert(_dpi);
}
ReadSVGPlugin::~ReadSVGPlugin()
{
}
void
ReadSVGPlugin::decode(const std::string& filename,
OfxTime time,
int /*view*/,
bool /*isPlayback*/,
const OfxRectI& renderWindow,
float *pixelData,
const OfxRectI& /*bounds*/,
OFX::PixelComponentEnum /*pixelComponents*/,
int pixelComponentCount,
int /*rowBytes*/)
{
if (pixelComponentCount != 4) {
setPersistentMessage(OFX::Message::eMessageError, "", "Wrong pixel components");
OFX::throwSuiteStatusException(kOfxStatErrFormat);
}
if (filename.empty()) {
setPersistentMessage(OFX::Message::eMessageError, "", "No filename");
OFX::throwSuiteStatusException(kOfxStatErrFormat);
}
GError *error = NULL;
RsvgHandle *handle;
RsvgDimensionData dimension;
cairo_surface_t *surface;
cairo_t *cr;
cairo_status_t status;
double imageWidth, imageHeight, scaleWidth, scaleHeight;
int dpi, width, height, renderWidth, renderHeight;
_dpi->getValueAtTime(time, dpi);
rsvg_set_default_dpi_x_y(dpi, dpi);
handle=rsvg_handle_new_from_file(filename.c_str(), &error);
if (error != NULL) {
setPersistentMessage(OFX::Message::eMessageError, "", "Failed to read SVG");
OFX::throwSuiteStatusException(kOfxStatErrFormat);
}
rsvg_handle_get_dimensions(handle, &dimension);
imageWidth = dimension.width;
imageHeight = dimension.height;
renderWidth= renderWindow.x2 - renderWindow.x1;
renderHeight= renderWindow.y2 - renderWindow.y1;
if (dpi != kParamDpiDefault) {
width = imageWidth * dpi / kParamDpiDefault;
height = imageHeight * dpi / kParamDpiDefault;
}
else {
width = imageWidth;
height = imageHeight;
}
if (width != renderWidth || height != renderHeight) {
setPersistentMessage(OFX::Message::eMessageError, "", "Image don't match RenderWindow");
OFX::throwSuiteStatusException(kOfxStatErrFormat);
}
surface=cairo_image_surface_create(CAIRO_FORMAT_ARGB32, width, height);
cr=cairo_create(surface);
scaleWidth = width / imageWidth;
scaleHeight = height / imageHeight;
cairo_scale(cr, scaleWidth, scaleHeight);
rsvg_handle_render_cairo(handle, cr);
status = cairo_status(cr);
if (status) {
setPersistentMessage(OFX::Message::eMessageError, "", "Render failed");
OFX::throwSuiteStatusException(kOfxStatErrFormat);
}
cairo_surface_flush(surface);
unsigned char* cdata = cairo_image_surface_get_data(surface);
unsigned char* pixels = new unsigned char[width * height * pixelComponentCount];
for (int i = 0; i < width; ++i) {
for (int j = 0; j < height; ++j) {
for (int k = 0; k < pixelComponentCount; ++k)
pixels[(i + j * width) * pixelComponentCount + k] = cdata[(i + (height - 1 - j) * width) * pixelComponentCount + k];
}
}
int offset = 0;
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
pixelData[offset] = (float)pixels[offset + 2] / 255.f;
pixelData[offset + 1] = (float)pixels[offset + 1] / 255.f;
pixelData[offset + 2] = (float)pixels[offset] / 255.f;
pixelData[offset + 3] = (float)pixels[offset + 3] / 255.f;
offset += pixelComponentCount;
}
}
g_object_unref(handle);
cairo_destroy(cr);
cairo_surface_destroy(surface);
cdata = NULL;
error = NULL;
delete[] pixels;
}
bool ReadSVGPlugin::getFrameBounds(const std::string& filename,
OfxTime time,
OfxRectI *bounds,
double *par,
std::string* /*error*/,int *tile_width, int *tile_height)
{
if (filename.empty()) {
setPersistentMessage(OFX::Message::eMessageError, "", "No filename");
OFX::throwSuiteStatusException(kOfxStatErrFormat);
}
int dpi;
_dpi->getValueAtTime(time, dpi);
GError *error = NULL;
RsvgHandle *handle;
RsvgDimensionData dimension;
double imageWidth, imageHeight;
int width, height;
rsvg_set_default_dpi_x_y(dpi, dpi);
handle=rsvg_handle_new_from_file(filename.c_str(), &error);
if (error != NULL) {
setPersistentMessage(OFX::Message::eMessageError, "", "Failed to read SVG");
OFX::throwSuiteStatusException(kOfxStatErrFormat);
}
rsvg_handle_get_dimensions(handle, &dimension);
imageWidth = dimension.width;
imageHeight = dimension.height;
if (dpi != kParamDpiDefault) {
width = imageWidth * dpi / kParamDpiDefault;
height = imageHeight * dpi / kParamDpiDefault;
}
else {
width = imageWidth;
height = imageHeight;
}
g_object_unref(handle);
error = NULL;
if (width > 0 && height > 0) {
bounds->x1 = 0;
bounds->x2 = width;
bounds->y1 = 0;
bounds->y2 = height;
*par = 1.0;
}
*tile_width = *tile_height = 0;
return true;
}
void ReadSVGPlugin::onInputFileChanged(const std::string& newFile,
bool setColorSpace,
OFX::PreMultiplicationEnum *premult,
OFX::PixelComponentEnum *components,int */*componentCount*/)
{
assert(premult && components);
if (newFile.empty()) {
setPersistentMessage(OFX::Message::eMessageError, "", "No filename");
OFX::throwSuiteStatusException(kOfxStatErrFormat);
}
GError *error = NULL;
RsvgHandle *handle;
handle=rsvg_handle_new_from_file(newFile.c_str(), &error);
if (error != NULL) {
setPersistentMessage(OFX::Message::eMessageError, "", "Failed to read SVG");
OFX::throwSuiteStatusException(kOfxStatErrFormat);
}
g_object_unref(handle);
error = NULL;
if (setColorSpace) {
# ifdef OFX_IO_USING_OCIO
_ocio->setInputColorspace("sRGB");
# endif
}
*components = OFX::ePixelComponentRGBA;
*premult = OFX::eImagePreMultiplied;
}
using namespace OFX;
mDeclareReaderPluginFactory(ReadSVGPluginFactory, {}, false);
void
ReadSVGPluginFactory::load()
{
_extensions.clear();
_extensions.push_back("svg");
_extensions.push_back("svgz");
}
/** @brief The basic describe function, passed a plugin descriptor */
void ReadSVGPluginFactory::describe(OFX::ImageEffectDescriptor &desc)
{
GenericReaderDescribe(desc, _extensions, kPluginEvaluation, kSupportsTiles, false);
desc.setLabel(kPluginName);
desc.setPluginDescription("Fast SVG (Scalable Vector Graphics) reader using librsvg and Cairo.");
}
/** @brief The describe in context function, passed a plugin descriptor and a context */
void ReadSVGPluginFactory::describeInContext(OFX::ImageEffectDescriptor &desc, ContextEnum context)
{
PageParamDescriptor *page = GenericReaderDescribeInContextBegin(desc, context, isVideoStreamPlugin(), kSupportsRGBA, kSupportsRGB, kSupportsAlpha, kSupportsTiles, false);
{
IntParamDescriptor* param = desc.defineIntParam(kParamDpi);
param->setLabel(kParamDpiLabel);
param->setHint(kParamDpiHint);
param->setRange(1, 10000);
param->setDisplayRange(1, 500);
param->setDefault(kParamDpiDefault);
param->setAnimates(false);
param->setLayoutHint(OFX::eLayoutHintDivider);
page->addChild(*param);
}
GenericReaderDescribeInContextEnd(desc, context, page, "reference", "reference");
}
/** @brief The create instance function, the plugin must return an object derived from the \ref OFX::ImageEffect class */
ImageEffect* ReadSVGPluginFactory::createInstance(OfxImageEffectHandle handle,
ContextEnum /*context*/)
{
ReadSVGPlugin* ret = new ReadSVGPlugin(handle, _extensions);
ret->restoreStateFromParameters();
return ret;
}
static ReadSVGPluginFactory p(kPluginIdentifier, kPluginVersionMajor, kPluginVersionMinor);
mRegisterPluginFactoryInstance(p)
<commit_msg>ReadSVG: support multiplane (layers), #222<commit_after>/*
* This file is part of openfx-arena <https://github.com/olear/openfx-arena>,
* Copyright (C) 2015, 2016 FxArena DA
* Copyright (C) 2016 INRIA
*
* openfx-arena is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation.
*
* openfx-arena is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with openfx-arena. If not, see <http://www.gnu.org/licenses/gpl-2.0.html>
*/
#include <librsvg/rsvg.h>
#ifdef LEGACY
#include "librsvg/rsvg-cairo.h"
#endif
#include <libxml/xmlmemory.h>
#include <libxml/parser.h>
#include <iostream>
#include "ofxNatron.h"
#include "GenericReader.h"
#include "GenericOCIO.h"
#include "ofxsMacros.h"
#include "ofxsImageEffect.h"
#ifdef OFX_IO_USING_OCIO
#include <OpenColorIO/OpenColorIO.h>
#endif
#define kPluginName "ReadSVG"
#define kPluginGrouping "Image/Readers"
#define kPluginIdentifier "net.fxarena.openfx.ReadSVG"
#define kPluginVersionMajor 3
#define kPluginVersionMinor 0
#define kPluginEvaluation 50
#define kParamDpi "dpi"
#define kParamDpiLabel "DPI"
#define kParamDpiHint "Dots-per-inch (90 is default)"
#define kParamDpiDefault 90
#define kSupportsRGBA true
#define kSupportsRGB false
#define kSupportsAlpha false
#define kSupportsTiles false
#define kIsMultiPlanar true
static bool gHostIsNatron = false;
class ReadSVGPlugin : public GenericReaderPlugin
{
public:
ReadSVGPlugin(OfxImageEffectHandle handle, const std::vector<std::string>& extensions);
virtual ~ReadSVGPlugin();
private:
virtual bool isVideoStream(const std::string& /*filename*/) OVERRIDE FINAL { return false; }
virtual void decode(const std::string& filename, OfxTime time, int view, bool isPlayback, const OfxRectI& renderWindow, float *pixelData, const OfxRectI& bounds,
OFX::PixelComponentEnum pixelComponents, int pixelComponentCount, int rowBytes) OVERRIDE FINAL
{
std::string rawComps;
switch (pixelComponents) {
case OFX::ePixelComponentAlpha:
rawComps = kOfxImageComponentAlpha;
break;
case OFX::ePixelComponentRGB:
rawComps = kOfxImageComponentRGB;
break;
case OFX::ePixelComponentRGBA:
rawComps = kOfxImageComponentRGBA;
break;
default:
OFX::throwSuiteStatusException(kOfxStatFailed);
return;
}
decodePlane(filename, time, view, isPlayback, renderWindow, pixelData, bounds, pixelComponents, pixelComponentCount, rawComps, rowBytes);
}
virtual void decodePlane(const std::string& filename, OfxTime time, int view, bool isPlayback, const OfxRectI& renderWindow, float *pixelData, const OfxRectI& bounds, OFX::PixelComponentEnum pixelComponents, int pixelComponentCount, const std::string& rawComponents, int rowBytes) OVERRIDE FINAL;
virtual void getClipComponents(const OFX::ClipComponentsArguments& args, OFX::ClipComponentsSetter& clipComponents) OVERRIDE FINAL;
virtual bool getFrameBounds(const std::string& filename, OfxTime time, OfxRectI *bounds, double *par, std::string *error, int *tile_width, int *tile_height) OVERRIDE FINAL;
virtual void restoreState(const std::string& filename) OVERRIDE FINAL;
virtual void onInputFileChanged(const std::string& newFile, bool setColorSpace, OFX::PreMultiplicationEnum *premult, OFX::PixelComponentEnum *components, int *componentCount) OVERRIDE FINAL;
void getLayers(xmlNode *node, std::vector<std::string> *layers);
OFX::IntParam *_dpi;
std::vector<std::string> imageLayers;
};
ReadSVGPlugin::ReadSVGPlugin(OfxImageEffectHandle handle, const std::vector<std::string>& extensions)
: GenericReaderPlugin(handle, extensions, kSupportsRGBA, kSupportsRGB, kSupportsAlpha, kSupportsTiles,
#ifdef OFX_EXTENSIONS_NUKE
(OFX::getImageEffectHostDescription() && OFX::getImageEffectHostDescription()->isMultiPlanar) ? kIsMultiPlanar : false
#else
false
#endif
)
,_dpi(0)
{
_dpi = fetchIntParam(kParamDpi);
assert(_dpi);
}
ReadSVGPlugin::~ReadSVGPlugin()
{
}
void
ReadSVGPlugin::getLayers(xmlNode *node, std::vector<std::string> *layers)
{
xmlNode *cur_node = NULL;
for (cur_node = node; cur_node; cur_node = cur_node->next) {
if (cur_node->type == XML_ELEMENT_NODE) {
if ((!xmlStrcmp(cur_node->name, (const xmlChar *)"g"))) {
xmlChar *xmlID;
xmlID = xmlGetProp(cur_node, (const xmlChar *)"id");
if (xmlID!=NULL) {
std::string layerName;
layerName = (reinterpret_cast<char*>(xmlID));
layers->push_back(layerName);
}
xmlFree(xmlID);
}
}
getLayers(cur_node->children,layers);
}
}
void
ReadSVGPlugin::getClipComponents(const OFX::ClipComponentsArguments& args, OFX::ClipComponentsSetter& clipComponents)
{
assert(isMultiPlanar());
clipComponents.addClipComponents(*_outputClip, getOutputComponents());
clipComponents.setPassThroughClip(NULL, args.time, args.view);
if (imageLayers.size()>0 && gHostIsNatron) {
for (int i = 0; i < (int)imageLayers.size(); i++) {
if (!imageLayers[i].empty()) {
std::string component(kNatronOfxImageComponentsPlane);
component.append(imageLayers[i]);
component.append(kNatronOfxImageComponentsPlaneChannel);
component.append("R");
component.append(kNatronOfxImageComponentsPlaneChannel);
component.append("G");
component.append(kNatronOfxImageComponentsPlaneChannel);
component.append("B");
component.append(kNatronOfxImageComponentsPlaneChannel);
component.append("A");
clipComponents.addClipComponents(*_outputClip, component);
}
}
}
}
void
ReadSVGPlugin::decodePlane(const std::string& filename, OfxTime time, int /*view*/, bool /*isPlayback*/, const OfxRectI& renderWindow, float *pixelData, const OfxRectI& /*bounds*/,
OFX::PixelComponentEnum /*pixelComponents*/, int pixelComponentCount, const std::string& rawComponents, int /*rowBytes*/)
{
if (pixelComponentCount != 4) {
setPersistentMessage(OFX::Message::eMessageError, "", "Wrong pixel components");
OFX::throwSuiteStatusException(kOfxStatErrFormat);
}
if (filename.empty()) {
setPersistentMessage(OFX::Message::eMessageError, "", "No filename");
OFX::throwSuiteStatusException(kOfxStatErrFormat);
}
std::string layerID;
if (gHostIsNatron) {
std::string layerName;
std::vector<std::string> layerChannels = OFX::mapPixelComponentCustomToLayerChannels(rawComponents);
int numChannels = layerChannels.size();
if (numChannels==5) // layer+R+G+B+A
layerName=layerChannels[0];
if (!layerName.empty()) {
layerID = layerName;
}
}
GError *error = NULL;
RsvgHandle *handle;
RsvgDimensionData dimension;
cairo_surface_t *surface;
cairo_t *cr;
cairo_status_t status;
double imageWidth, imageHeight, scaleWidth, scaleHeight;
int dpi, width, height, renderWidth, renderHeight;
_dpi->getValueAtTime(time, dpi);
rsvg_set_default_dpi_x_y(dpi, dpi);
handle=rsvg_handle_new_from_file(filename.c_str(), &error);
if (error != NULL) {
setPersistentMessage(OFX::Message::eMessageError, "", "Failed to read SVG");
OFX::throwSuiteStatusException(kOfxStatErrFormat);
}
rsvg_handle_get_dimensions(handle, &dimension);
imageWidth = dimension.width;
imageHeight = dimension.height;
renderWidth= renderWindow.x2 - renderWindow.x1;
renderHeight= renderWindow.y2 - renderWindow.y1;
if (dpi != kParamDpiDefault) {
width = imageWidth * dpi / kParamDpiDefault;
height = imageHeight * dpi / kParamDpiDefault;
}
else {
width = imageWidth;
height = imageHeight;
}
if (width != renderWidth || height != renderHeight) {
setPersistentMessage(OFX::Message::eMessageError, "", "Image don't match RenderWindow");
OFX::throwSuiteStatusException(kOfxStatErrFormat);
}
surface=cairo_image_surface_create(CAIRO_FORMAT_ARGB32, width, height);
cr=cairo_create(surface);
scaleWidth = width / imageWidth;
scaleHeight = height / imageHeight;
cairo_scale(cr, scaleWidth, scaleHeight);
if (layerID.empty()) {
rsvg_handle_render_cairo(handle, cr);
}
else {
std::ostringstream layerSub;
layerSub << "#" << layerID;
rsvg_handle_render_cairo_sub(handle, cr, layerSub.str().c_str());
}
status = cairo_status(cr);
if (status) {
setPersistentMessage(OFX::Message::eMessageError, "", "Cairo Render failed");
OFX::throwSuiteStatusException(kOfxStatErrFormat);
}
cairo_surface_flush(surface);
unsigned char* cdata = cairo_image_surface_get_data(surface);
unsigned char* pixels = new unsigned char[width * height * pixelComponentCount];
for (int i = 0; i < width; ++i) {
for (int j = 0; j < height; ++j) {
for (int k = 0; k < pixelComponentCount; ++k)
pixels[(i + j * width) * pixelComponentCount + k] = cdata[(i + (height - 1 - j) * width) * pixelComponentCount + k];
}
}
int offset = 0;
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
pixelData[offset] = (float)pixels[offset + 2] / 255.f;
pixelData[offset + 1] = (float)pixels[offset + 1] / 255.f;
pixelData[offset + 2] = (float)pixels[offset] / 255.f;
pixelData[offset + 3] = (float)pixels[offset + 3] / 255.f;
offset += pixelComponentCount;
}
}
g_object_unref(handle);
cairo_destroy(cr);
cairo_surface_destroy(surface);
cdata = NULL;
error = NULL;
delete[] pixels;
}
bool ReadSVGPlugin::getFrameBounds(const std::string& filename,
OfxTime time,
OfxRectI *bounds,
double *par,
std::string* /*error*/,int *tile_width, int *tile_height)
{
if (filename.empty()) {
setPersistentMessage(OFX::Message::eMessageError, "", "No filename");
OFX::throwSuiteStatusException(kOfxStatErrFormat);
}
int dpi;
_dpi->getValueAtTime(time, dpi);
GError *error = NULL;
RsvgHandle *handle;
RsvgDimensionData dimension;
double imageWidth, imageHeight;
int width, height;
rsvg_set_default_dpi_x_y(dpi, dpi);
handle=rsvg_handle_new_from_file(filename.c_str(), &error);
if (error != NULL) {
setPersistentMessage(OFX::Message::eMessageError, "", "Failed to read SVG");
OFX::throwSuiteStatusException(kOfxStatErrFormat);
}
rsvg_handle_get_dimensions(handle, &dimension);
imageWidth = dimension.width;
imageHeight = dimension.height;
if (dpi != kParamDpiDefault) {
width = imageWidth * dpi / kParamDpiDefault;
height = imageHeight * dpi / kParamDpiDefault;
}
else {
width = imageWidth;
height = imageHeight;
}
g_object_unref(handle);
error = NULL;
if (width > 0 && height > 0) {
bounds->x1 = 0;
bounds->x2 = width;
bounds->y1 = 0;
bounds->y2 = height;
*par = 1.0;
}
*tile_width = *tile_height = 0;
return true;
}
void
ReadSVGPlugin::restoreState(const std::string& filename)
{
if (!filename.empty()) {
imageLayers.clear();
xmlDocPtr doc;
doc = xmlParseFile(filename.c_str());
xmlNode *root_element = NULL;
root_element = xmlDocGetRootElement(doc);
getLayers(root_element,&imageLayers);
xmlFreeDoc(doc);
GError *error = NULL;
RsvgHandle *handle;
handle=rsvg_handle_new_from_file(filename.c_str(), &error);
if (error != NULL) {
setPersistentMessage(OFX::Message::eMessageError, "", "Failed to read SVG");
}
g_object_unref(handle);
error = NULL;
}
else {
setPersistentMessage(OFX::Message::eMessageError, "", "Empty and/or corrupt image");
}
}
void ReadSVGPlugin::onInputFileChanged(const std::string& newFile,
bool setColorSpace,
OFX::PreMultiplicationEnum *premult,
OFX::PixelComponentEnum *components,int */*componentCount*/)
{
assert(premult && components);
restoreState(newFile);
if (setColorSpace) {
# ifdef OFX_IO_USING_OCIO
_ocio->setInputColorspace("sRGB");
# endif
}
*components = OFX::ePixelComponentRGBA;
*premult = OFX::eImageUnPreMultiplied;
}
using namespace OFX;
mDeclareReaderPluginFactory(ReadSVGPluginFactory, {}, false);
void
ReadSVGPluginFactory::load()
{
_extensions.clear();
_extensions.push_back("svg");
_extensions.push_back("svgz");
}
/** @brief The basic describe function, passed a plugin descriptor */
void ReadSVGPluginFactory::describe(OFX::ImageEffectDescriptor &desc)
{
GenericReaderDescribe(desc, _extensions, kPluginEvaluation, kSupportsTiles, kIsMultiPlanar);
desc.setLabel(kPluginName);
desc.setPluginDescription("Fast SVG (Scalable Vector Graphics) reader using librsvg and Cairo.");
}
/** @brief The describe in context function, passed a plugin descriptor and a context */
void ReadSVGPluginFactory::describeInContext(OFX::ImageEffectDescriptor &desc, ContextEnum context)
{
gHostIsNatron = (OFX::getImageEffectHostDescription()->isNatron);
PageParamDescriptor *page = GenericReaderDescribeInContextBegin(desc, context, isVideoStreamPlugin(), kSupportsRGBA, kSupportsRGB, kSupportsAlpha, kSupportsTiles, false);
{
IntParamDescriptor* param = desc.defineIntParam(kParamDpi);
param->setLabel(kParamDpiLabel);
param->setHint(kParamDpiHint);
param->setRange(1, 10000);
param->setDisplayRange(1, 500);
param->setDefault(kParamDpiDefault);
param->setAnimates(false);
param->setLayoutHint(OFX::eLayoutHintDivider);
page->addChild(*param);
}
GenericReaderDescribeInContextEnd(desc, context, page, "reference", "reference");
}
/** @brief The create instance function, the plugin must return an object derived from the \ref OFX::ImageEffect class */
ImageEffect* ReadSVGPluginFactory::createInstance(OfxImageEffectHandle handle,
ContextEnum /*context*/)
{
ReadSVGPlugin* ret = new ReadSVGPlugin(handle, _extensions);
ret->restoreStateFromParameters();
return ret;
}
static ReadSVGPluginFactory p(kPluginIdentifier, kPluginVersionMajor, kPluginVersionMinor);
mRegisterPluginFactoryInstance(p)
<|endoftext|> |
<commit_before>// Copyright 2019 DeepMind Technologies Limited.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "reverb/cc/client.h"
#include <memory>
#include <string>
#include <vector>
#include <cstdint>
#include "absl/strings/str_cat.h"
#include "tensorflow/core/framework/op.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/resource_op_kernel.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/tensor_shape.h"
#include "tensorflow/core/lib/core/status.h"
namespace deepmind {
namespace reverb {
namespace {
using ::tensorflow::tstring;
using ::tensorflow::errors::InvalidArgument;
REGISTER_OP("ReverbClient")
.Output("handle: resource")
.Attr("server_address: string")
.Attr("container: string = ''")
.Attr("shared_name: string = ''")
.SetIsStateful()
.SetShapeFn(tensorflow::shape_inference::ScalarShape)
.Doc(R"doc(
Constructs a `ClientResource` that constructs a `Client` connected to
`server_address`. The resource allows ops to share the stub across calls.
)doc");
REGISTER_OP("ReverbClientSample")
.Attr("Toutput_list: list(type) >= 0")
.Input("handle: resource")
.Input("table: string")
.Output("key: uint64")
.Output("probability: double")
.Output("table_size: int64")
.Output("priority: double")
.Output("outputs: Toutput_list")
.Doc(R"doc(
Blocking call to sample a single item from table `table` using shared resource.
A `SampleStream`-stream is opened between the client and the server and when
the one sample has been received, the stream is closed.
Prefer to use `ReverbDataset` when requesting more than one sample to avoid
opening and closing the stream with each call.
)doc");
REGISTER_OP("ReverbClientUpdatePriorities")
.Input("handle: resource")
.Input("table: string")
.Input("keys: uint64")
.Input("priorities: double")
.Doc(R"doc(
Blocking call to update the priorities of a collection of items. Keys that could
not be found in table `table` on server are ignored and does not impact the rest
of the request.
)doc");
REGISTER_OP("ReverbClientInsert")
.Attr("T: list(type) >= 0")
.Input("handle: resource")
.Input("data: T")
.Input("tables: string")
.Input("priorities: double")
.Doc(R"doc(
Blocking call to insert a single trajectory into one or more tables. The data
is treated as an episode constituting of a single timestep. Note that this mean
that when the item is sampled, it will be returned as a sequence of length 1,
containing `data`.
)doc");
class ClientResource : public tensorflow::ResourceBase {
public:
explicit ClientResource(const std::string& server_address)
: tensorflow::ResourceBase(),
client_(server_address),
server_address_(server_address) {}
std::string DebugString() const override {
return tensorflow::strings::StrCat("Client with server address: ",
server_address_);
}
Client* client() { return &client_; }
private:
Client client_;
std::string server_address_;
TF_DISALLOW_COPY_AND_ASSIGN(ClientResource);
};
class ClientHandleOp : public tensorflow::ResourceOpKernel<ClientResource> {
public:
explicit ClientHandleOp(tensorflow::OpKernelConstruction* context)
: tensorflow::ResourceOpKernel<ClientResource>(context) {
OP_REQUIRES_OK(context,
context->GetAttr("server_address", &server_address_));
}
private:
tensorflow::Status CreateResource(ClientResource** ret) override {
*ret = new ClientResource(server_address_);
return tensorflow::Status::OK();
}
std::string server_address_;
TF_DISALLOW_COPY_AND_ASSIGN(ClientHandleOp);
};
class SampleOp : public tensorflow::OpKernel {
public:
explicit SampleOp(tensorflow::OpKernelConstruction* context)
: OpKernel(context) {}
void Compute(tensorflow::OpKernelContext* context) override {
ClientResource* resource;
OP_REQUIRES_OK(context, LookupResource(context, HandleFromInput(context, 0),
&resource));
const tensorflow::Tensor* table_tensor;
OP_REQUIRES_OK(context, context->input("table", &table_tensor));
std::string table = table_tensor->scalar<tstring>()();
std::vector<tensorflow::Tensor> sample;
std::unique_ptr<Sampler> sampler;
Sampler::Options options;
options.max_samples = 1;
options.max_in_flight_samples_per_worker = 1;
constexpr auto kValidationTimeout = absl::Seconds(30);
OP_REQUIRES_OK(
context, resource->client()->NewSampler(
table, options, /*validation_timeout=*/kValidationTimeout,
&sampler));
OP_REQUIRES_OK(context, sampler->GetNextTimestep(&sample, nullptr));
OP_REQUIRES(context, sample.size() == context->num_outputs(),
InvalidArgument(
"Number of tensors in the replay sample did not match the "
"expected count."));
for (int i = 0; i < sample.size(); i++) {
tensorflow::Tensor* tensor;
OP_REQUIRES_OK(context,
context->allocate_output(i, sample[i].shape(), &tensor));
*tensor = std::move(sample[i]);
}
}
TF_DISALLOW_COPY_AND_ASSIGN(SampleOp);
};
class UpdatePrioritiesOp : public tensorflow::OpKernel {
public:
explicit UpdatePrioritiesOp(tensorflow::OpKernelConstruction* context)
: OpKernel(context) {}
void Compute(tensorflow::OpKernelContext* context) override {
ClientResource* resource;
OP_REQUIRES_OK(context, LookupResource(context, HandleFromInput(context, 0),
&resource));
const tensorflow::Tensor* table;
OP_REQUIRES_OK(context, context->input("table", &table));
const tensorflow::Tensor* keys;
OP_REQUIRES_OK(context, context->input("keys", &keys));
const tensorflow::Tensor* priorities;
OP_REQUIRES_OK(context, context->input("priorities", &priorities));
OP_REQUIRES(
context, keys->dims() == 1,
InvalidArgument("Tensors `keys` and `priorities` must be of rank 1."));
OP_REQUIRES(context, keys->shape() == priorities->shape(),
InvalidArgument(
"Tensors `keys` and `priorities` do not match in shape."));
std::string table_str = table->scalar<tstring>()();
std::vector<KeyWithPriority> updates;
for (int i = 0; i < keys->dim_size(0); i++) {
KeyWithPriority update;
update.set_key(keys->flat<tensorflow::uint64>()(i));
update.set_priority(priorities->flat<double>()(i));
updates.push_back(std::move(update));
}
// The call will only fail if the Reverb-server is brought down during an
// active call (e.g preempted). When this happens the request is retried and
// since MutatePriorities sets `wait_for_ready` the request will no be sent
// before the server is brought up again. It is therefore no problem to have
// this retry in this tight loop.
tensorflow::Status status;
do {
status = resource->client()->MutatePriorities(table_str, updates, {});
} while (tensorflow::errors::IsUnavailable(status) ||
tensorflow::errors::IsDeadlineExceeded(status));
OP_REQUIRES_OK(context, status);
}
TF_DISALLOW_COPY_AND_ASSIGN(UpdatePrioritiesOp);
};
class InsertOp : public tensorflow::OpKernel {
public:
explicit InsertOp(tensorflow::OpKernelConstruction* context)
: OpKernel(context) {}
void Compute(tensorflow::OpKernelContext* context) override {
ClientResource* resource;
OP_REQUIRES_OK(context, LookupResource(context, HandleFromInput(context, 0),
&resource));
const tensorflow::Tensor* tables;
OP_REQUIRES_OK(context, context->input("tables", &tables));
const tensorflow::Tensor* priorities;
OP_REQUIRES_OK(context, context->input("priorities", &priorities));
OP_REQUIRES(context, tables->dims() == 1 && priorities->dims() == 1,
InvalidArgument(
"Tensors `tables` and `priorities` must be of rank 1."));
OP_REQUIRES(
context, tables->shape() == priorities->shape(),
InvalidArgument(
"Tensors `tables` and `priorities` do not match in shape."));
tensorflow::OpInputList data;
OP_REQUIRES_OK(context, context->input_list("data", &data));
std::vector<tensorflow::Tensor> tensors;
for (const auto& i : data) {
tensors.push_back(i);
}
std::unique_ptr<Writer> writer;
OP_REQUIRES_OK(context,
resource->client()->NewWriter(1, 1, false, &writer));
OP_REQUIRES_OK(context, writer->Append(std::move(tensors)));
auto tables_t = tables->flat<tstring>();
auto priorities_t = priorities->flat<double>();
for (int i = 0; i < tables->dim_size(0); i++) {
OP_REQUIRES_OK(context,
writer->CreateItem(tables_t(i), 1, priorities_t(i)));
}
OP_REQUIRES_OK(context, writer->Close());
}
TF_DISALLOW_COPY_AND_ASSIGN(InsertOp);
};
REGISTER_KERNEL_BUILDER(Name("ReverbClient").Device(tensorflow::DEVICE_CPU),
ClientHandleOp);
REGISTER_KERNEL_BUILDER(
Name("ReverbClientInsert").Device(tensorflow::DEVICE_CPU), InsertOp);
REGISTER_KERNEL_BUILDER(
Name("ReverbClientSample").Device(tensorflow::DEVICE_CPU), SampleOp);
REGISTER_KERNEL_BUILDER(
Name("ReverbClientUpdatePriorities").Device(tensorflow::DEVICE_CPU),
UpdatePrioritiesOp);
} // namespace
} // namespace reverb
} // namespace deepmind
<commit_msg>Add shape information to error message when keys and priorities tensors don't match.<commit_after>// Copyright 2019 DeepMind Technologies Limited.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "reverb/cc/client.h"
#include <memory>
#include <string>
#include <vector>
#include <cstdint>
#include "absl/strings/str_cat.h"
#include "tensorflow/core/framework/op.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/resource_op_kernel.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/tensor_shape.h"
#include "tensorflow/core/lib/core/status.h"
namespace deepmind {
namespace reverb {
namespace {
using ::tensorflow::tstring;
using ::tensorflow::errors::InvalidArgument;
REGISTER_OP("ReverbClient")
.Output("handle: resource")
.Attr("server_address: string")
.Attr("container: string = ''")
.Attr("shared_name: string = ''")
.SetIsStateful()
.SetShapeFn(tensorflow::shape_inference::ScalarShape)
.Doc(R"doc(
Constructs a `ClientResource` that constructs a `Client` connected to
`server_address`. The resource allows ops to share the stub across calls.
)doc");
REGISTER_OP("ReverbClientSample")
.Attr("Toutput_list: list(type) >= 0")
.Input("handle: resource")
.Input("table: string")
.Output("key: uint64")
.Output("probability: double")
.Output("table_size: int64")
.Output("priority: double")
.Output("outputs: Toutput_list")
.Doc(R"doc(
Blocking call to sample a single item from table `table` using shared resource.
A `SampleStream`-stream is opened between the client and the server and when
the one sample has been received, the stream is closed.
Prefer to use `ReverbDataset` when requesting more than one sample to avoid
opening and closing the stream with each call.
)doc");
REGISTER_OP("ReverbClientUpdatePriorities")
.Input("handle: resource")
.Input("table: string")
.Input("keys: uint64")
.Input("priorities: double")
.Doc(R"doc(
Blocking call to update the priorities of a collection of items. Keys that could
not be found in table `table` on server are ignored and does not impact the rest
of the request.
)doc");
REGISTER_OP("ReverbClientInsert")
.Attr("T: list(type) >= 0")
.Input("handle: resource")
.Input("data: T")
.Input("tables: string")
.Input("priorities: double")
.Doc(R"doc(
Blocking call to insert a single trajectory into one or more tables. The data
is treated as an episode constituting of a single timestep. Note that this mean
that when the item is sampled, it will be returned as a sequence of length 1,
containing `data`.
)doc");
class ClientResource : public tensorflow::ResourceBase {
public:
explicit ClientResource(const std::string& server_address)
: tensorflow::ResourceBase(),
client_(server_address),
server_address_(server_address) {}
std::string DebugString() const override {
return tensorflow::strings::StrCat("Client with server address: ",
server_address_);
}
Client* client() { return &client_; }
private:
Client client_;
std::string server_address_;
TF_DISALLOW_COPY_AND_ASSIGN(ClientResource);
};
class ClientHandleOp : public tensorflow::ResourceOpKernel<ClientResource> {
public:
explicit ClientHandleOp(tensorflow::OpKernelConstruction* context)
: tensorflow::ResourceOpKernel<ClientResource>(context) {
OP_REQUIRES_OK(context,
context->GetAttr("server_address", &server_address_));
}
private:
tensorflow::Status CreateResource(ClientResource** ret) override {
*ret = new ClientResource(server_address_);
return tensorflow::Status::OK();
}
std::string server_address_;
TF_DISALLOW_COPY_AND_ASSIGN(ClientHandleOp);
};
class SampleOp : public tensorflow::OpKernel {
public:
explicit SampleOp(tensorflow::OpKernelConstruction* context)
: OpKernel(context) {}
void Compute(tensorflow::OpKernelContext* context) override {
ClientResource* resource;
OP_REQUIRES_OK(context, LookupResource(context, HandleFromInput(context, 0),
&resource));
const tensorflow::Tensor* table_tensor;
OP_REQUIRES_OK(context, context->input("table", &table_tensor));
std::string table = table_tensor->scalar<tstring>()();
std::vector<tensorflow::Tensor> sample;
std::unique_ptr<Sampler> sampler;
Sampler::Options options;
options.max_samples = 1;
options.max_in_flight_samples_per_worker = 1;
constexpr auto kValidationTimeout = absl::Seconds(30);
OP_REQUIRES_OK(
context, resource->client()->NewSampler(
table, options, /*validation_timeout=*/kValidationTimeout,
&sampler));
OP_REQUIRES_OK(context, sampler->GetNextTimestep(&sample, nullptr));
OP_REQUIRES(context, sample.size() == context->num_outputs(),
InvalidArgument(
"Number of tensors in the replay sample did not match the "
"expected count."));
for (int i = 0; i < sample.size(); i++) {
tensorflow::Tensor* tensor;
OP_REQUIRES_OK(context,
context->allocate_output(i, sample[i].shape(), &tensor));
*tensor = std::move(sample[i]);
}
}
TF_DISALLOW_COPY_AND_ASSIGN(SampleOp);
};
class UpdatePrioritiesOp : public tensorflow::OpKernel {
public:
explicit UpdatePrioritiesOp(tensorflow::OpKernelConstruction* context)
: OpKernel(context) {}
void Compute(tensorflow::OpKernelContext* context) override {
ClientResource* resource;
OP_REQUIRES_OK(context, LookupResource(context, HandleFromInput(context, 0),
&resource));
const tensorflow::Tensor* table;
OP_REQUIRES_OK(context, context->input("table", &table));
const tensorflow::Tensor* keys;
OP_REQUIRES_OK(context, context->input("keys", &keys));
const tensorflow::Tensor* priorities;
OP_REQUIRES_OK(context, context->input("priorities", &priorities));
OP_REQUIRES(
context, keys->dims() == 1,
InvalidArgument("Tensors `keys` and `priorities` must be of rank 1."));
OP_REQUIRES(context, keys->shape() == priorities->shape(),
InvalidArgument(
"Tensors `keys` and `priorities` do not match in shape (",
keys->shape().DebugString(), " vs. ",
priorities->shape().DebugString(), ")"));
std::string table_str = table->scalar<tstring>()();
std::vector<KeyWithPriority> updates;
for (int i = 0; i < keys->dim_size(0); i++) {
KeyWithPriority update;
update.set_key(keys->flat<tensorflow::uint64>()(i));
update.set_priority(priorities->flat<double>()(i));
updates.push_back(std::move(update));
}
// The call will only fail if the Reverb-server is brought down during an
// active call (e.g preempted). When this happens the request is retried and
// since MutatePriorities sets `wait_for_ready` the request will no be sent
// before the server is brought up again. It is therefore no problem to have
// this retry in this tight loop.
tensorflow::Status status;
do {
status = resource->client()->MutatePriorities(table_str, updates, {});
} while (tensorflow::errors::IsUnavailable(status) ||
tensorflow::errors::IsDeadlineExceeded(status));
OP_REQUIRES_OK(context, status);
}
TF_DISALLOW_COPY_AND_ASSIGN(UpdatePrioritiesOp);
};
class InsertOp : public tensorflow::OpKernel {
public:
explicit InsertOp(tensorflow::OpKernelConstruction* context)
: OpKernel(context) {}
void Compute(tensorflow::OpKernelContext* context) override {
ClientResource* resource;
OP_REQUIRES_OK(context, LookupResource(context, HandleFromInput(context, 0),
&resource));
const tensorflow::Tensor* tables;
OP_REQUIRES_OK(context, context->input("tables", &tables));
const tensorflow::Tensor* priorities;
OP_REQUIRES_OK(context, context->input("priorities", &priorities));
OP_REQUIRES(context, tables->dims() == 1 && priorities->dims() == 1,
InvalidArgument(
"Tensors `tables` and `priorities` must be of rank 1."));
OP_REQUIRES(
context, tables->shape() == priorities->shape(),
InvalidArgument(
"Tensors `tables` and `priorities` do not match in shape."));
tensorflow::OpInputList data;
OP_REQUIRES_OK(context, context->input_list("data", &data));
std::vector<tensorflow::Tensor> tensors;
for (const auto& i : data) {
tensors.push_back(i);
}
std::unique_ptr<Writer> writer;
OP_REQUIRES_OK(context,
resource->client()->NewWriter(1, 1, false, &writer));
OP_REQUIRES_OK(context, writer->Append(std::move(tensors)));
auto tables_t = tables->flat<tstring>();
auto priorities_t = priorities->flat<double>();
for (int i = 0; i < tables->dim_size(0); i++) {
OP_REQUIRES_OK(context,
writer->CreateItem(tables_t(i), 1, priorities_t(i)));
}
OP_REQUIRES_OK(context, writer->Close());
}
TF_DISALLOW_COPY_AND_ASSIGN(InsertOp);
};
REGISTER_KERNEL_BUILDER(Name("ReverbClient").Device(tensorflow::DEVICE_CPU),
ClientHandleOp);
REGISTER_KERNEL_BUILDER(
Name("ReverbClientInsert").Device(tensorflow::DEVICE_CPU), InsertOp);
REGISTER_KERNEL_BUILDER(
Name("ReverbClientSample").Device(tensorflow::DEVICE_CPU), SampleOp);
REGISTER_KERNEL_BUILDER(
Name("ReverbClientUpdatePriorities").Device(tensorflow::DEVICE_CPU),
UpdatePrioritiesOp);
} // namespace
} // namespace reverb
} // namespace deepmind
<|endoftext|> |
<commit_before>/*=========================================================================
Library: CTK
Copyright (c) Kitware Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0.txt
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=========================================================================*/
// Qt includes
#include <QDebug>
#include <QAbstractItemModel>
#include <QStandardItemModel>
// CTK includes
#include "ctkErrorLogWidget.h"
#include "ui_ctkErrorLogWidget.h"
#include <ctkErrorLogModel.h>
class ctkErrorLogWidgetPrivate : public Ui_ctkErrorLogWidget
{
Q_DECLARE_PUBLIC(ctkErrorLogWidget);
protected:
ctkErrorLogWidget* const q_ptr;
public:
typedef ctkErrorLogWidgetPrivate Self;
ctkErrorLogWidgetPrivate(ctkErrorLogWidget& object);
ctkErrorLogLevel::LogLevels ErrorButtonFilter;
ctkErrorLogLevel::LogLevels WarningButtonFilter;
ctkErrorLogLevel::LogLevels InfoButtonFilter;
void init();
QSharedPointer<QItemSelectionModel> SelectionModel;
};
// --------------------------------------------------------------------------
// ctkErrorLogWidgetPrivate methods
// --------------------------------------------------------------------------
ctkErrorLogWidgetPrivate::ctkErrorLogWidgetPrivate(ctkErrorLogWidget& object)
: q_ptr(&object)
{
this->ErrorButtonFilter = ctkErrorLogLevel::Error | ctkErrorLogLevel::Critical | ctkErrorLogLevel::Fatal;
this->WarningButtonFilter = ctkErrorLogLevel::Warning;
this->InfoButtonFilter = ctkErrorLogLevel::Info | ctkErrorLogLevel::Debug | ctkErrorLogLevel::Trace | ctkErrorLogLevel::Status;
}
// --------------------------------------------------------------------------
void ctkErrorLogWidgetPrivate::init()
{
Q_Q(ctkErrorLogWidget);
// this->ShowAllEntryButton->setIcon();
this->ShowErrorEntryButton->setIcon(q->style()->standardIcon(QStyle::SP_MessageBoxCritical));
this->ShowWarningEntryButton->setIcon(q->style()->standardIcon(QStyle::SP_MessageBoxWarning));
this->ShowInfoEntryButton->setIcon(q->style()->standardIcon(QStyle::SP_MessageBoxInformation));
this->ClearButton->setIcon(q->style()->standardIcon(QStyle::SP_DialogDiscardButton));
QObject::connect(this->ShowAllEntryButton, SIGNAL(clicked()),
q, SLOT(setAllEntriesVisible()));
QObject::connect(this->ShowErrorEntryButton, SIGNAL(clicked(bool)),
q, SLOT(setErrorEntriesVisible(bool)));
QObject::connect(this->ShowWarningEntryButton, SIGNAL(clicked(bool)),
q, SLOT(setWarningEntriesVisible(bool)));
QObject::connect(this->ShowInfoEntryButton, SIGNAL(clicked(bool)),
q, SLOT(setInfoEntriesVisible(bool)));
QObject::connect(this->ClearButton, SIGNAL(clicked()),
q, SLOT(removeEntries()));
}
// --------------------------------------------------------------------------
// ctkErrorLogWidget methods
//------------------------------------------------------------------------------
ctkErrorLogWidget::ctkErrorLogWidget(QWidget * newParent)
: Superclass(newParent)
, d_ptr(new ctkErrorLogWidgetPrivate(*this))
{
Q_D(ctkErrorLogWidget);
d->setupUi(this);
d->init();
this->setErrorLogModel(new ctkErrorLogModel(d->ErrorLogTableView));
}
//------------------------------------------------------------------------------
ctkErrorLogWidget::~ctkErrorLogWidget()
{
}
//------------------------------------------------------------------------------
ctkErrorLogAbstractModel* ctkErrorLogWidget::errorLogModel()const
{
Q_D(const ctkErrorLogWidget);
QAbstractItemModel* model = d->ErrorLogTableView->model();
ctkErrorLogAbstractModel * errorLogModel = qobject_cast<ctkErrorLogAbstractModel*>(model);
Q_ASSERT(model ? errorLogModel != 0 : true);
return errorLogModel;
}
//------------------------------------------------------------------------------
void ctkErrorLogWidget::setErrorLogModel(ctkErrorLogAbstractModel * newErrorLogModel)
{
Q_D(ctkErrorLogWidget);
if (newErrorLogModel == this->errorLogModel())
{
return;
}
if (this->errorLogModel())
{
disconnect(this->errorLogModel(), SIGNAL(rowsInserted(QModelIndex,int,int)),
this, SLOT(onRowsInserted(QModelIndex,int,int)));
disconnect(this->errorLogModel(), SIGNAL(logLevelFilterChanged()),
this, SLOT(onLogLevelFilterChanged()));
disconnect(d->SelectionModel.data(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)),
this, SLOT(onSelectionChanged(QItemSelection,QItemSelection)));
d->SelectionModel.clear();
}
d->ErrorLogTableView->setModel(newErrorLogModel);
if (newErrorLogModel)
{
connect(this->errorLogModel(), SIGNAL(rowsInserted(QModelIndex,int,int)),
this, SLOT(onRowsInserted(QModelIndex,int,int)));
connect(this->errorLogModel(), SIGNAL(logLevelFilterChanged()),
this, SLOT(onLogLevelFilterChanged()));
ctkErrorLogLevel::LogLevels logLevelFilter = newErrorLogModel->logLevelFilter();
this->setErrorEntriesVisible(logLevelFilter & d->ErrorButtonFilter);
this->setWarningEntriesVisible(logLevelFilter & d->WarningButtonFilter);
this->setInfoEntriesVisible(logLevelFilter & d->InfoButtonFilter);
this->errorLogModel()->filterEntry(logLevelFilter & ctkErrorLogLevel::Unknown);
// Setup selection model
d->SelectionModel = QSharedPointer<QItemSelectionModel>(new QItemSelectionModel(this->errorLogModel()));
d->SelectionModel->reset();
connect(d->SelectionModel.data(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)),
this, SLOT(onSelectionChanged(QItemSelection,QItemSelection)));
d->ErrorLogTableView->setSelectionModel(d->SelectionModel.data());
// Resize time column only if there are rows
if (this->errorLogModel()->rowCount() > 0)
{
d->ErrorLogTableView->resizeColumnToContents(ctkErrorLogModel::TimeColumn);
}
}
else
{
this->setAllEntriesVisible(0);
}
d->ErrorLogTableView->setColumnHidden(ctkErrorLogModel::ThreadIdColumn, true);
}
// --------------------------------------------------------------------------
void ctkErrorLogWidget::setColumnHidden(int columnId, bool hidden) const
{
Q_D(const ctkErrorLogWidget);
d->ErrorLogTableView->setColumnHidden(columnId, hidden);
}
// --------------------------------------------------------------------------
void ctkErrorLogWidget::setAllEntriesVisible(bool visibility)
{
this->setErrorEntriesVisible(visibility);
this->setWarningEntriesVisible(visibility);
this->setInfoEntriesVisible(visibility);
this->setUnknownEntriesVisible(visibility);
}
// --------------------------------------------------------------------------
void ctkErrorLogWidget::setErrorEntriesVisible(bool visibility)
{
Q_D(ctkErrorLogWidget);
if (!this->errorLogModel())
{
return;
}
this->errorLogModel()->filterEntry(d->ErrorButtonFilter, /* disableFilter= */ !visibility);
}
// --------------------------------------------------------------------------
void ctkErrorLogWidget::setWarningEntriesVisible(bool visibility)
{
Q_D(ctkErrorLogWidget);
if (!this->errorLogModel())
{
return;
}
this->errorLogModel()->filterEntry(d->WarningButtonFilter, /* disableFilter= */ !visibility);
}
// --------------------------------------------------------------------------
void ctkErrorLogWidget::setInfoEntriesVisible(bool visibility)
{
Q_D(ctkErrorLogWidget);
if (!this->errorLogModel())
{
return;
}
this->errorLogModel()->filterEntry(d->InfoButtonFilter, /* disableFilter= */ !visibility);
}
// --------------------------------------------------------------------------
void ctkErrorLogWidget::setUnknownEntriesVisible(bool visibility)
{
if (!this->errorLogModel())
{
return;
}
this->errorLogModel()->filterEntry(ctkErrorLogLevel::Unknown,
/* disableFilter= */ !visibility);
}
// --------------------------------------------------------------------------
void ctkErrorLogWidget::onRowsInserted(const QModelIndex &/*parent*/, int /*first*/, int /*last*/)
{
Q_D(ctkErrorLogWidget);
if (d->ErrorLogTableView->model()->rowCount() == 1)
{
// For performance reason, resize first column only when first entry is added
d->ErrorLogTableView->resizeColumnToContents(ctkErrorLogModel::TimeColumn);
}
}
// --------------------------------------------------------------------------
void ctkErrorLogWidget::onLogLevelFilterChanged()
{
Q_D(ctkErrorLogWidget);
Q_ASSERT(this->errorLogModel());
ctkErrorLogLevel::LogLevels logLevelFilter = this->errorLogModel()->logLevelFilter();
d->ShowErrorEntryButton->setChecked(logLevelFilter & d->ErrorButtonFilter);
d->ShowWarningEntryButton->setChecked(logLevelFilter & d->WarningButtonFilter);
d->ShowInfoEntryButton->setChecked(logLevelFilter & d->InfoButtonFilter);
}
// --------------------------------------------------------------------------
void ctkErrorLogWidget::removeEntries()
{
Q_ASSERT(this->errorLogModel());
this->errorLogModel()->clear();
}
// --------------------------------------------------------------------------
void ctkErrorLogWidget::onSelectionChanged(const QItemSelection & selected,
const QItemSelection & deselected)
{
// QTime start = QTime::currentTime();
Q_D(ctkErrorLogWidget);
Q_UNUSED(selected);
Q_UNUSED(deselected);
QModelIndexList selectedRows =
d->SelectionModel->selectedRows(ctkErrorLogModel::DescriptionColumn);
qSort(selectedRows.begin(), selectedRows.end());
QStringList descriptions;
foreach(const QModelIndex& index, selectedRows)
{
descriptions << index.data(ctkErrorLogModel::DescriptionTextRole).toString();
}
d->ErrorLogDescription->setText(descriptions.join("\n"));
// fprintf(stdout, "onSelectionChanged: %d\n", start.msecsTo(QTime::currentTime()));
}
<commit_msg>COMP: Fix qSort deprecation warning<commit_after>/*=========================================================================
Library: CTK
Copyright (c) Kitware Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0.txt
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=========================================================================*/
// Qt includes
#include <QDebug>
#include <QAbstractItemModel>
#include <QStandardItemModel>
// CTK includes
#include "ctkErrorLogWidget.h"
#include "ui_ctkErrorLogWidget.h"
#include <ctkErrorLogModel.h>
class ctkErrorLogWidgetPrivate : public Ui_ctkErrorLogWidget
{
Q_DECLARE_PUBLIC(ctkErrorLogWidget);
protected:
ctkErrorLogWidget* const q_ptr;
public:
typedef ctkErrorLogWidgetPrivate Self;
ctkErrorLogWidgetPrivate(ctkErrorLogWidget& object);
ctkErrorLogLevel::LogLevels ErrorButtonFilter;
ctkErrorLogLevel::LogLevels WarningButtonFilter;
ctkErrorLogLevel::LogLevels InfoButtonFilter;
void init();
QSharedPointer<QItemSelectionModel> SelectionModel;
};
// --------------------------------------------------------------------------
// ctkErrorLogWidgetPrivate methods
// --------------------------------------------------------------------------
ctkErrorLogWidgetPrivate::ctkErrorLogWidgetPrivate(ctkErrorLogWidget& object)
: q_ptr(&object)
{
this->ErrorButtonFilter = ctkErrorLogLevel::Error | ctkErrorLogLevel::Critical | ctkErrorLogLevel::Fatal;
this->WarningButtonFilter = ctkErrorLogLevel::Warning;
this->InfoButtonFilter = ctkErrorLogLevel::Info | ctkErrorLogLevel::Debug | ctkErrorLogLevel::Trace | ctkErrorLogLevel::Status;
}
// --------------------------------------------------------------------------
void ctkErrorLogWidgetPrivate::init()
{
Q_Q(ctkErrorLogWidget);
// this->ShowAllEntryButton->setIcon();
this->ShowErrorEntryButton->setIcon(q->style()->standardIcon(QStyle::SP_MessageBoxCritical));
this->ShowWarningEntryButton->setIcon(q->style()->standardIcon(QStyle::SP_MessageBoxWarning));
this->ShowInfoEntryButton->setIcon(q->style()->standardIcon(QStyle::SP_MessageBoxInformation));
this->ClearButton->setIcon(q->style()->standardIcon(QStyle::SP_DialogDiscardButton));
QObject::connect(this->ShowAllEntryButton, SIGNAL(clicked()),
q, SLOT(setAllEntriesVisible()));
QObject::connect(this->ShowErrorEntryButton, SIGNAL(clicked(bool)),
q, SLOT(setErrorEntriesVisible(bool)));
QObject::connect(this->ShowWarningEntryButton, SIGNAL(clicked(bool)),
q, SLOT(setWarningEntriesVisible(bool)));
QObject::connect(this->ShowInfoEntryButton, SIGNAL(clicked(bool)),
q, SLOT(setInfoEntriesVisible(bool)));
QObject::connect(this->ClearButton, SIGNAL(clicked()),
q, SLOT(removeEntries()));
}
// --------------------------------------------------------------------------
// ctkErrorLogWidget methods
//------------------------------------------------------------------------------
ctkErrorLogWidget::ctkErrorLogWidget(QWidget * newParent)
: Superclass(newParent)
, d_ptr(new ctkErrorLogWidgetPrivate(*this))
{
Q_D(ctkErrorLogWidget);
d->setupUi(this);
d->init();
this->setErrorLogModel(new ctkErrorLogModel(d->ErrorLogTableView));
}
//------------------------------------------------------------------------------
ctkErrorLogWidget::~ctkErrorLogWidget()
{
}
//------------------------------------------------------------------------------
ctkErrorLogAbstractModel* ctkErrorLogWidget::errorLogModel()const
{
Q_D(const ctkErrorLogWidget);
QAbstractItemModel* model = d->ErrorLogTableView->model();
ctkErrorLogAbstractModel * errorLogModel = qobject_cast<ctkErrorLogAbstractModel*>(model);
Q_ASSERT(model ? errorLogModel != 0 : true);
return errorLogModel;
}
//------------------------------------------------------------------------------
void ctkErrorLogWidget::setErrorLogModel(ctkErrorLogAbstractModel * newErrorLogModel)
{
Q_D(ctkErrorLogWidget);
if (newErrorLogModel == this->errorLogModel())
{
return;
}
if (this->errorLogModel())
{
disconnect(this->errorLogModel(), SIGNAL(rowsInserted(QModelIndex,int,int)),
this, SLOT(onRowsInserted(QModelIndex,int,int)));
disconnect(this->errorLogModel(), SIGNAL(logLevelFilterChanged()),
this, SLOT(onLogLevelFilterChanged()));
disconnect(d->SelectionModel.data(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)),
this, SLOT(onSelectionChanged(QItemSelection,QItemSelection)));
d->SelectionModel.clear();
}
d->ErrorLogTableView->setModel(newErrorLogModel);
if (newErrorLogModel)
{
connect(this->errorLogModel(), SIGNAL(rowsInserted(QModelIndex,int,int)),
this, SLOT(onRowsInserted(QModelIndex,int,int)));
connect(this->errorLogModel(), SIGNAL(logLevelFilterChanged()),
this, SLOT(onLogLevelFilterChanged()));
ctkErrorLogLevel::LogLevels logLevelFilter = newErrorLogModel->logLevelFilter();
this->setErrorEntriesVisible(logLevelFilter & d->ErrorButtonFilter);
this->setWarningEntriesVisible(logLevelFilter & d->WarningButtonFilter);
this->setInfoEntriesVisible(logLevelFilter & d->InfoButtonFilter);
this->errorLogModel()->filterEntry(logLevelFilter & ctkErrorLogLevel::Unknown);
// Setup selection model
d->SelectionModel = QSharedPointer<QItemSelectionModel>(new QItemSelectionModel(this->errorLogModel()));
d->SelectionModel->reset();
connect(d->SelectionModel.data(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)),
this, SLOT(onSelectionChanged(QItemSelection,QItemSelection)));
d->ErrorLogTableView->setSelectionModel(d->SelectionModel.data());
// Resize time column only if there are rows
if (this->errorLogModel()->rowCount() > 0)
{
d->ErrorLogTableView->resizeColumnToContents(ctkErrorLogModel::TimeColumn);
}
}
else
{
this->setAllEntriesVisible(0);
}
d->ErrorLogTableView->setColumnHidden(ctkErrorLogModel::ThreadIdColumn, true);
}
// --------------------------------------------------------------------------
void ctkErrorLogWidget::setColumnHidden(int columnId, bool hidden) const
{
Q_D(const ctkErrorLogWidget);
d->ErrorLogTableView->setColumnHidden(columnId, hidden);
}
// --------------------------------------------------------------------------
void ctkErrorLogWidget::setAllEntriesVisible(bool visibility)
{
this->setErrorEntriesVisible(visibility);
this->setWarningEntriesVisible(visibility);
this->setInfoEntriesVisible(visibility);
this->setUnknownEntriesVisible(visibility);
}
// --------------------------------------------------------------------------
void ctkErrorLogWidget::setErrorEntriesVisible(bool visibility)
{
Q_D(ctkErrorLogWidget);
if (!this->errorLogModel())
{
return;
}
this->errorLogModel()->filterEntry(d->ErrorButtonFilter, /* disableFilter= */ !visibility);
}
// --------------------------------------------------------------------------
void ctkErrorLogWidget::setWarningEntriesVisible(bool visibility)
{
Q_D(ctkErrorLogWidget);
if (!this->errorLogModel())
{
return;
}
this->errorLogModel()->filterEntry(d->WarningButtonFilter, /* disableFilter= */ !visibility);
}
// --------------------------------------------------------------------------
void ctkErrorLogWidget::setInfoEntriesVisible(bool visibility)
{
Q_D(ctkErrorLogWidget);
if (!this->errorLogModel())
{
return;
}
this->errorLogModel()->filterEntry(d->InfoButtonFilter, /* disableFilter= */ !visibility);
}
// --------------------------------------------------------------------------
void ctkErrorLogWidget::setUnknownEntriesVisible(bool visibility)
{
if (!this->errorLogModel())
{
return;
}
this->errorLogModel()->filterEntry(ctkErrorLogLevel::Unknown,
/* disableFilter= */ !visibility);
}
// --------------------------------------------------------------------------
void ctkErrorLogWidget::onRowsInserted(const QModelIndex &/*parent*/, int /*first*/, int /*last*/)
{
Q_D(ctkErrorLogWidget);
if (d->ErrorLogTableView->model()->rowCount() == 1)
{
// For performance reason, resize first column only when first entry is added
d->ErrorLogTableView->resizeColumnToContents(ctkErrorLogModel::TimeColumn);
}
}
// --------------------------------------------------------------------------
void ctkErrorLogWidget::onLogLevelFilterChanged()
{
Q_D(ctkErrorLogWidget);
Q_ASSERT(this->errorLogModel());
ctkErrorLogLevel::LogLevels logLevelFilter = this->errorLogModel()->logLevelFilter();
d->ShowErrorEntryButton->setChecked(logLevelFilter & d->ErrorButtonFilter);
d->ShowWarningEntryButton->setChecked(logLevelFilter & d->WarningButtonFilter);
d->ShowInfoEntryButton->setChecked(logLevelFilter & d->InfoButtonFilter);
}
// --------------------------------------------------------------------------
void ctkErrorLogWidget::removeEntries()
{
Q_ASSERT(this->errorLogModel());
this->errorLogModel()->clear();
}
// --------------------------------------------------------------------------
void ctkErrorLogWidget::onSelectionChanged(const QItemSelection & selected,
const QItemSelection & deselected)
{
// QTime start = QTime::currentTime();
Q_D(ctkErrorLogWidget);
Q_UNUSED(selected);
Q_UNUSED(deselected);
QModelIndexList selectedRows =
d->SelectionModel->selectedRows(ctkErrorLogModel::DescriptionColumn);
std::sort(selectedRows.begin(), selectedRows.end());
QStringList descriptions;
foreach(const QModelIndex& index, selectedRows)
{
descriptions << index.data(ctkErrorLogModel::DescriptionTextRole).toString();
}
d->ErrorLogDescription->setText(descriptions.join("\n"));
// fprintf(stdout, "onSelectionChanged: %d\n", start.msecsTo(QTime::currentTime()));
}
<|endoftext|> |
<commit_before>/* Copyright 2017 The Apollo Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=========================================================================*/
#include "modules/map/hdmap/hdmap_util.h"
#include "modules/common/util/file.h"
#include "modules/common/util/string_tokenizer.h"
namespace apollo {
namespace hdmap {
namespace {
// Find the first existing file from a list of candidates: "file_a|file_b|...".
std::string FindFirstExist(const std::string& dir, const std::string& files) {
const auto candidates =
apollo::common::util::StringTokenizer::Split(files, "|");
for (const auto& filename : candidates) {
const std::string file_path =
apollo::common::util::StrCat(FLAGS_map_dir, "/", filename);
if (apollo::common::util::PathExists(file_path)) {
return file_path;
}
}
AERROR << "No existing file found in " << dir << "/" << files;
return "";
}
} // namespace
std::string BaseMapFile() {
return FindFirstExist(FLAGS_map_dir, FLAGS_base_map_filename);
}
std::string SimMapFile() {
return FindFirstExist(FLAGS_map_dir, FLAGS_sim_map_filename);
}
std::string RoutingMapFile() {
return FindFirstExist(FLAGS_map_dir, FLAGS_sim_map_filename);
}
std::unique_ptr<HDMap> CreateMap(const std::string& map_file_path) {
std::unique_ptr<HDMap> hdmap(new HDMap());
if (hdmap->load_map_from_file(map_file_path) != 0) {
AERROR << "Failed to load HDMap " << map_file_path;
hdmap.reset(nullptr);
} else {
AINFO << "Load HDMap succ.: " << map_file_path;
}
return hdmap;
}
HDMapUtil::HDMapUtil() {}
const HDMap* HDMapUtil::BaseMap() {
if (base_map_ == nullptr) {
std::lock_guard<std::mutex> lock(base_map_mutex_);
if (base_map_ == nullptr) { // Double check.
base_map_ = CreateMap(BaseMapFile());
}
}
return base_map_.get();
}
const HDMap& HDMapUtil::BaseMapRef() {
return *CHECK_NOTNULL(BaseMap());
}
bool HDMapUtil::ReloadBaseMap() {
std::lock_guard<std::mutex> lock(base_map_mutex_);
base_map_ = CreateMap(BaseMapFile());
return base_map_ != nullptr;
}
} // namespace hdmap
} // namespace apollo
<commit_msg>map: fix routing map file name.<commit_after>/* Copyright 2017 The Apollo Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=========================================================================*/
#include "modules/map/hdmap/hdmap_util.h"
#include "modules/common/util/file.h"
#include "modules/common/util/string_tokenizer.h"
namespace apollo {
namespace hdmap {
namespace {
// Find the first existing file from a list of candidates: "file_a|file_b|...".
std::string FindFirstExist(const std::string& dir, const std::string& files) {
const auto candidates =
apollo::common::util::StringTokenizer::Split(files, "|");
for (const auto& filename : candidates) {
const std::string file_path =
apollo::common::util::StrCat(FLAGS_map_dir, "/", filename);
if (apollo::common::util::PathExists(file_path)) {
return file_path;
}
}
AERROR << "No existing file found in " << dir << "/" << files;
return "";
}
} // namespace
std::string BaseMapFile() {
return FindFirstExist(FLAGS_map_dir, FLAGS_base_map_filename);
}
std::string SimMapFile() {
return FindFirstExist(FLAGS_map_dir, FLAGS_sim_map_filename);
}
std::string RoutingMapFile() {
return FindFirstExist(FLAGS_map_dir, FLAGS_routing_map_filename);
}
std::unique_ptr<HDMap> CreateMap(const std::string& map_file_path) {
std::unique_ptr<HDMap> hdmap(new HDMap());
if (hdmap->load_map_from_file(map_file_path) != 0) {
AERROR << "Failed to load HDMap " << map_file_path;
hdmap.reset(nullptr);
} else {
AINFO << "Load HDMap succ.: " << map_file_path;
}
return hdmap;
}
HDMapUtil::HDMapUtil() {}
const HDMap* HDMapUtil::BaseMap() {
if (base_map_ == nullptr) {
std::lock_guard<std::mutex> lock(base_map_mutex_);
if (base_map_ == nullptr) { // Double check.
base_map_ = CreateMap(BaseMapFile());
}
}
return base_map_.get();
}
const HDMap& HDMapUtil::BaseMapRef() {
return *CHECK_NOTNULL(BaseMap());
}
bool HDMapUtil::ReloadBaseMap() {
std::lock_guard<std::mutex> lock(base_map_mutex_);
base_map_ = CreateMap(BaseMapFile());
return base_map_ != nullptr;
}
} // namespace hdmap
} // namespace apollo
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: basicbox.cxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: rt $ $Date: 2005-09-07 19:54:48 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#include <ide_pch.hxx>
#pragma hdrstop
#include <basidesh.hrc>
#include <basidesh.hxx>
#include <basobj.hxx>
#include <basicbox.hxx>
#include <iderid.hxx>
#include <iderdll.hxx>
#include <bastypes.hxx>
#ifndef _BASTYPE2_HXX
#include "bastype2.hxx"
#endif
#ifndef _BASDOC_HXX
#include "basdoc.hxx"
#endif
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
SFX_IMPL_TOOLBOX_CONTROL( LibBoxControl, SfxStringItem );
LibBoxControl::LibBoxControl( USHORT nSlotId, USHORT nId, ToolBox& rTbx )
: SfxToolBoxControl( nSlotId, nId, rTbx )
{
}
LibBoxControl::~LibBoxControl()
{
}
void LibBoxControl::StateChanged( USHORT nSID, SfxItemState eState, const SfxPoolItem* pState )
{
BasicLibBox* pBox = (BasicLibBox*) GetToolBox().GetItemWindow( GetId() );
DBG_ASSERT( pBox, "Box not found" );
if ( !pBox )
return;
if ( eState != SFX_ITEM_AVAILABLE )
pBox->Disable();
else
{
pBox->Enable();
if ( pState->ISA(SfxStringItem) )
pBox->Update( (const SfxStringItem*)pState );
else
pBox->Update( NULL );
}
}
Window* LibBoxControl::CreateItemWindow( Window *pParent )
{
return new BasicLibBox( pParent, m_xFrame );
}
BasicLibBox::BasicLibBox( Window* pParent, const uno::Reference< frame::XFrame >& rFrame ) :
ListBox( pParent, WinBits( WB_BORDER | WB_DROPDOWN ) ),
m_xFrame( rFrame )
{
FillBox();
bIgnoreSelect = TRUE; // Select von 0 noch nicht weiterleiten
bFillBox = TRUE;
SelectEntryPos( 0 );
aCurText = GetEntry( 0 );
SetSizePixel( Size( 250, 200 ) );
bIgnoreSelect = FALSE;
StartListening( *SFX_APP(), TRUE /* Nur einmal anmelden */ );
}
__EXPORT BasicLibBox::~BasicLibBox()
{
}
void __EXPORT BasicLibBox::Update( const SfxStringItem* pItem )
{
// Immer auf dem laufenden sein...
// if ( !pItem || !pItem->GetValue().Len() )
FillBox();
if ( pItem )
{
aCurText = pItem->GetValue();
if ( aCurText.Len() == 0 )
aCurText = String( IDEResId( RID_STR_ALL ) );
}
if ( GetSelectEntry() != aCurText )
SelectEntry( aCurText );
}
void __EXPORT BasicLibBox::ReleaseFocus()
{
SfxViewShell* pCurSh = SfxViewShell::Current();
DBG_ASSERT( pCurSh, "Current ViewShell not found!" );
if ( pCurSh )
{
Window* pShellWin = pCurSh->GetWindow();
if ( !pShellWin ) // sonst werde ich ihn nicht los
pShellWin = Application::GetDefDialogParent();
pShellWin->GrabFocus();
}
}
void __EXPORT BasicLibBox::SFX_NOTIFY( SfxBroadcaster& rBC, const TypeId&,
const SfxHint& rHint, const TypeId& )
{
if ( rHint.IsA( TYPE( SfxEventHint ) ) )
{
switch ( ((SfxEventHint&)rHint).GetEventId() )
{
case SFX_EVENT_CREATEDOC:
case SFX_EVENT_OPENDOC:
{
FillBox(); // IDE reagiert selbst, wenn == aktuelle Lib
}
break;
case SFX_EVENT_SAVEASDOC:
{
FillBox( TRUE );
}
break;
case SFX_EVENT_CLOSEDOC:
{
if ( SFX_APP()->IsInBasicCall() ) // Nicht wenn Office beendet
FillBox();
}
break;
}
}
}
void BasicLibBox::FillBox( BOOL bSelect )
{
SetUpdateMode( FALSE );
bIgnoreSelect = TRUE;
aCurText = GetSelectEntry();
SelectEntryPos( 0 );
Clear();
// create list box entries
USHORT nPos = InsertEntry( String( IDEResId( RID_STR_ALL ) ), LISTBOX_APPEND );
SetEntryData( nPos, new BasicLibEntry( 0, LIBRARY_LOCATION_UNKNOWN, String() ) );
InsertEntries( 0, LIBRARY_LOCATION_USER );
InsertEntries( 0, LIBRARY_LOCATION_SHARE );
SfxObjectShell* pShell = SfxObjectShell::GetFirst();
while ( pShell )
{
// only if there's a corresponding window (not for remote documents)
if ( SfxViewFrame::GetFirst( pShell ) && !pShell->ISA( BasicDocShell ) )
InsertEntries( pShell, LIBRARY_LOCATION_DOCUMENT );
pShell = SfxObjectShell::GetNext( *pShell );
}
SetUpdateMode( TRUE );
if ( bSelect )
{
SelectEntry( aCurText );
if ( !GetSelectEntryCount() )
{
SelectEntryPos( GetEntryCount() ); // gibst es nicht => leer?
aCurText = GetSelectEntry();
}
}
bIgnoreSelect = FALSE;
}
void BasicLibBox::InsertEntries( SfxObjectShell* pShell, LibraryLocation eLocation )
{
// get a sorted list of library names
Sequence< ::rtl::OUString > aLibNames = BasicIDE::GetLibraryNames( pShell );
sal_Int32 nLibCount = aLibNames.getLength();
const ::rtl::OUString* pLibNames = aLibNames.getConstArray();
for ( sal_Int32 i = 0 ; i < nLibCount ; ++i )
{
String aLibName = pLibNames[ i ];
if ( eLocation == BasicIDE::GetLibraryLocation( pShell, aLibName ) )
{
String aName( BasicIDE::GetTitle( pShell, eLocation, SFX_TITLE_CAPTION ) );
String aEntryText( CreateMgrAndLibStr( aName, aLibName ) );
USHORT nPos = InsertEntry( aEntryText, LISTBOX_APPEND );
SetEntryData( nPos, new BasicLibEntry( pShell, eLocation, aLibName ) );
}
}
}
long BasicLibBox::PreNotify( NotifyEvent& rNEvt )
{
long nDone = 0;
if( rNEvt.GetType() == EVENT_KEYINPUT )
{
KeyEvent aKeyEvt = *rNEvt.GetKeyEvent();
USHORT nKeyCode = aKeyEvt.GetKeyCode().GetCode();
switch( nKeyCode )
{
case KEY_RETURN:
{
NotifyIDE();
nDone = 1;
}
break;
case KEY_ESCAPE:
{
SelectEntry( aCurText );
ReleaseFocus();
nDone = 1;
}
break;
}
}
else if( rNEvt.GetType() == EVENT_GETFOCUS )
{
if ( bFillBox )
{
FillBox();
bFillBox = FALSE;
}
}
else if( rNEvt.GetType() == EVENT_LOSEFOCUS )
{
if ( !HasChildPathFocus( TRUE ) )
{
bIgnoreSelect = TRUE;
bFillBox = TRUE;
}
}
return nDone ? nDone : ListBox::PreNotify( rNEvt );
}
void __EXPORT BasicLibBox::Select()
{
if ( !IsTravelSelect() )
{
if ( !bIgnoreSelect )
NotifyIDE();
else
SelectEntry( aCurText ); // Seit 306... (Select nach Escape)
}
}
void BasicLibBox::NotifyIDE()
{
USHORT nSelPos = GetSelectEntryPos();
BasicLibEntry* pEntry = (BasicLibEntry*)GetEntryData( nSelPos );
if ( pEntry )
{
SfxObjectShell* pShell = pEntry->GetShell();
SfxObjectShellItem aShellItem( SID_BASICIDE_ARG_SHELL, pShell );
String aLibName = pEntry->GetLibName();
SfxStringItem aLibNameItem( SID_BASICIDE_ARG_LIBNAME, aLibName );
BasicIDEShell* pIDEShell = IDE_DLL()->GetShell();
SfxViewFrame* pViewFrame = pIDEShell ? pIDEShell->GetViewFrame() : NULL;
SfxDispatcher* pDispatcher = pViewFrame ? pViewFrame->GetDispatcher() : NULL;
if ( pDispatcher )
{
pDispatcher->Execute( SID_BASICIDE_LIBSELECTED,
SFX_CALLMODE_SYNCHRON, &aShellItem, &aLibNameItem, 0L );
}
}
ReleaseFocus();
}
<commit_msg>INTEGRATION: CWS memory02 (1.8.8); FILE MERGED 2005/10/05 13:14:44 tbe 1.8.8.1: #i54860# MLK: memory leak in BasicLibbox::InsertEntries()<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: basicbox.cxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: rt $ $Date: 2006-01-10 14:02:07 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#include <ide_pch.hxx>
#pragma hdrstop
#include <basidesh.hrc>
#include <basidesh.hxx>
#include <basobj.hxx>
#include <basicbox.hxx>
#include <iderid.hxx>
#include <iderdll.hxx>
#include <bastypes.hxx>
#ifndef _BASTYPE2_HXX
#include "bastype2.hxx"
#endif
#ifndef _BASDOC_HXX
#include "basdoc.hxx"
#endif
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
SFX_IMPL_TOOLBOX_CONTROL( LibBoxControl, SfxStringItem );
LibBoxControl::LibBoxControl( USHORT nSlotId, USHORT nId, ToolBox& rTbx )
: SfxToolBoxControl( nSlotId, nId, rTbx )
{
}
LibBoxControl::~LibBoxControl()
{
}
void LibBoxControl::StateChanged( USHORT nSID, SfxItemState eState, const SfxPoolItem* pState )
{
BasicLibBox* pBox = (BasicLibBox*) GetToolBox().GetItemWindow( GetId() );
DBG_ASSERT( pBox, "Box not found" );
if ( !pBox )
return;
if ( eState != SFX_ITEM_AVAILABLE )
pBox->Disable();
else
{
pBox->Enable();
if ( pState->ISA(SfxStringItem) )
pBox->Update( (const SfxStringItem*)pState );
else
pBox->Update( NULL );
}
}
Window* LibBoxControl::CreateItemWindow( Window *pParent )
{
return new BasicLibBox( pParent, m_xFrame );
}
BasicLibBox::BasicLibBox( Window* pParent, const uno::Reference< frame::XFrame >& rFrame ) :
ListBox( pParent, WinBits( WB_BORDER | WB_DROPDOWN ) ),
m_xFrame( rFrame )
{
FillBox();
bIgnoreSelect = TRUE; // Select von 0 noch nicht weiterleiten
bFillBox = TRUE;
SelectEntryPos( 0 );
aCurText = GetEntry( 0 );
SetSizePixel( Size( 250, 200 ) );
bIgnoreSelect = FALSE;
StartListening( *SFX_APP(), TRUE /* Nur einmal anmelden */ );
}
__EXPORT BasicLibBox::~BasicLibBox()
{
DeleteEntryData();
}
void __EXPORT BasicLibBox::Update( const SfxStringItem* pItem )
{
// Immer auf dem laufenden sein...
// if ( !pItem || !pItem->GetValue().Len() )
FillBox();
if ( pItem )
{
aCurText = pItem->GetValue();
if ( aCurText.Len() == 0 )
aCurText = String( IDEResId( RID_STR_ALL ) );
}
if ( GetSelectEntry() != aCurText )
SelectEntry( aCurText );
}
void __EXPORT BasicLibBox::ReleaseFocus()
{
SfxViewShell* pCurSh = SfxViewShell::Current();
DBG_ASSERT( pCurSh, "Current ViewShell not found!" );
if ( pCurSh )
{
Window* pShellWin = pCurSh->GetWindow();
if ( !pShellWin ) // sonst werde ich ihn nicht los
pShellWin = Application::GetDefDialogParent();
pShellWin->GrabFocus();
}
}
void __EXPORT BasicLibBox::SFX_NOTIFY( SfxBroadcaster& rBC, const TypeId&,
const SfxHint& rHint, const TypeId& )
{
if ( rHint.IsA( TYPE( SfxEventHint ) ) )
{
switch ( ((SfxEventHint&)rHint).GetEventId() )
{
case SFX_EVENT_CREATEDOC:
case SFX_EVENT_OPENDOC:
{
FillBox(); // IDE reagiert selbst, wenn == aktuelle Lib
}
break;
case SFX_EVENT_SAVEASDOC:
{
FillBox( TRUE );
}
break;
case SFX_EVENT_CLOSEDOC:
{
if ( SFX_APP()->IsInBasicCall() ) // Nicht wenn Office beendet
FillBox();
}
break;
}
}
}
void BasicLibBox::FillBox( BOOL bSelect )
{
SetUpdateMode( FALSE );
bIgnoreSelect = TRUE;
aCurText = GetSelectEntry();
SelectEntryPos( 0 );
Clear();
// create list box entries
USHORT nPos = InsertEntry( String( IDEResId( RID_STR_ALL ) ), LISTBOX_APPEND );
SetEntryData( nPos, new BasicLibEntry( 0, LIBRARY_LOCATION_UNKNOWN, String() ) );
InsertEntries( 0, LIBRARY_LOCATION_USER );
InsertEntries( 0, LIBRARY_LOCATION_SHARE );
SfxObjectShell* pShell = SfxObjectShell::GetFirst();
while ( pShell )
{
// only if there's a corresponding window (not for remote documents)
if ( SfxViewFrame::GetFirst( pShell ) && !pShell->ISA( BasicDocShell ) )
InsertEntries( pShell, LIBRARY_LOCATION_DOCUMENT );
pShell = SfxObjectShell::GetNext( *pShell );
}
SetUpdateMode( TRUE );
if ( bSelect )
{
SelectEntry( aCurText );
if ( !GetSelectEntryCount() )
{
SelectEntryPos( GetEntryCount() ); // gibst es nicht => leer?
aCurText = GetSelectEntry();
}
}
bIgnoreSelect = FALSE;
}
void BasicLibBox::InsertEntries( SfxObjectShell* pShell, LibraryLocation eLocation )
{
// get a sorted list of library names
Sequence< ::rtl::OUString > aLibNames = BasicIDE::GetLibraryNames( pShell );
sal_Int32 nLibCount = aLibNames.getLength();
const ::rtl::OUString* pLibNames = aLibNames.getConstArray();
for ( sal_Int32 i = 0 ; i < nLibCount ; ++i )
{
String aLibName = pLibNames[ i ];
if ( eLocation == BasicIDE::GetLibraryLocation( pShell, aLibName ) )
{
String aName( BasicIDE::GetTitle( pShell, eLocation, SFX_TITLE_CAPTION ) );
String aEntryText( CreateMgrAndLibStr( aName, aLibName ) );
USHORT nPos = InsertEntry( aEntryText, LISTBOX_APPEND );
SetEntryData( nPos, new BasicLibEntry( pShell, eLocation, aLibName ) );
}
}
}
void BasicLibBox::DeleteEntryData()
{
USHORT nCount = GetEntryCount();
for ( USHORT i = 0; i < nCount; ++i )
{
BasicLibEntry* pEntry = (BasicLibEntry*)GetEntryData( i );
delete pEntry;
}
}
long BasicLibBox::PreNotify( NotifyEvent& rNEvt )
{
long nDone = 0;
if( rNEvt.GetType() == EVENT_KEYINPUT )
{
KeyEvent aKeyEvt = *rNEvt.GetKeyEvent();
USHORT nKeyCode = aKeyEvt.GetKeyCode().GetCode();
switch( nKeyCode )
{
case KEY_RETURN:
{
NotifyIDE();
nDone = 1;
}
break;
case KEY_ESCAPE:
{
SelectEntry( aCurText );
ReleaseFocus();
nDone = 1;
}
break;
}
}
else if( rNEvt.GetType() == EVENT_GETFOCUS )
{
if ( bFillBox )
{
FillBox();
bFillBox = FALSE;
}
}
else if( rNEvt.GetType() == EVENT_LOSEFOCUS )
{
if ( !HasChildPathFocus( TRUE ) )
{
bIgnoreSelect = TRUE;
bFillBox = TRUE;
}
}
return nDone ? nDone : ListBox::PreNotify( rNEvt );
}
void __EXPORT BasicLibBox::Select()
{
if ( !IsTravelSelect() )
{
if ( !bIgnoreSelect )
NotifyIDE();
else
SelectEntry( aCurText ); // Seit 306... (Select nach Escape)
}
}
void BasicLibBox::NotifyIDE()
{
USHORT nSelPos = GetSelectEntryPos();
BasicLibEntry* pEntry = (BasicLibEntry*)GetEntryData( nSelPos );
if ( pEntry )
{
SfxObjectShell* pShell = pEntry->GetShell();
SfxObjectShellItem aShellItem( SID_BASICIDE_ARG_SHELL, pShell );
String aLibName = pEntry->GetLibName();
SfxStringItem aLibNameItem( SID_BASICIDE_ARG_LIBNAME, aLibName );
BasicIDEShell* pIDEShell = IDE_DLL()->GetShell();
SfxViewFrame* pViewFrame = pIDEShell ? pIDEShell->GetViewFrame() : NULL;
SfxDispatcher* pDispatcher = pViewFrame ? pViewFrame->GetDispatcher() : NULL;
if ( pDispatcher )
{
pDispatcher->Execute( SID_BASICIDE_LIBSELECTED,
SFX_CALLMODE_SYNCHRON, &aShellItem, &aLibNameItem, 0L );
}
}
ReleaseFocus();
}
void BasicLibBox::Clear()
{
DeleteEntryData();
ListBox::Clear();
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: bastype2.hxx,v $
*
* $Revision: 1.11 $
*
* last change: $Author: vg $ $Date: 2007-01-16 16:30:57 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _BASTYPE2_HXX
#define _BASTYPE2_HXX
#include <memory>
#ifndef _SOLAR_H
#include "tools/solar.h"
#endif
#define _SVICNVW_HXX
#ifndef _SVTREEBOX_HXX //autogen
#include <svtools/svtreebx.hxx>
#endif
#ifndef _SFXLSTNER_HXX
#include <svtools/lstner.hxx>
#endif
#ifndef _SB_SBSTAR_HXX //autogen
#include <basic/sbstar.hxx>
#endif
#ifndef _SBXITEM_HXX
#include <sbxitem.hxx>
#endif
#ifndef _BASOBJ_HXX
#include "basobj.hxx"
#endif
enum BasicEntryType { OBJ_TYPE_UNKNOWN, OBJ_TYPE_SHELL, OBJ_TYPE_LIBRARY, OBJ_TYPE_MODULE, OBJ_TYPE_DIALOG, OBJ_TYPE_METHOD };
#define BROWSEMODE_MODULES 0x01
#define BROWSEMODE_SUBS 0x02
#define BROWSEMODE_DIALOGS 0x04
class SbMethod;
class SbxObject;
class SbModule;
class SvLBoxEntry;
class SbxVariable;
class String;
class BasicEntry
{
private:
BasicEntryType m_eType;
public:
BasicEntry( BasicEntryType eType ) { m_eType = eType; }
BasicEntry( const BasicEntry& r ) { m_eType = r.m_eType; }
virtual ~BasicEntry();
BasicEntryType GetType() const { return m_eType; }
};
class BasicShellEntry : public BasicEntry
{
private:
SfxObjectShell* m_pShell;
LibraryLocation m_eLocation;
public:
BasicShellEntry( SfxObjectShell* pShell, LibraryLocation eLocation, BasicEntryType eType = OBJ_TYPE_SHELL );
virtual ~BasicShellEntry();
SfxObjectShell* GetShell() const { return m_pShell; }
LibraryLocation GetLocation() const { return m_eLocation; }
};
class BasicLibEntry : public BasicShellEntry
{
private:
String m_aLibName;
public:
BasicLibEntry( SfxObjectShell* pShell, LibraryLocation eLocation, const String& rLibName, BasicEntryType eType = OBJ_TYPE_LIBRARY );
virtual ~BasicLibEntry();
const String& GetLibName() const { return m_aLibName; }
};
class BasicEntryDescriptor
{
SfxObjectShell* m_pShell;
LibraryLocation m_eLocation;
String m_aLibName;
String m_aName;
String m_aMethodName;
BasicEntryType m_eType;
public:
BasicEntryDescriptor();
BasicEntryDescriptor( SfxObjectShell* pShell, LibraryLocation eLocation, const String& rLibName, const String& rName, BasicEntryType eType );
BasicEntryDescriptor( SfxObjectShell* pShell, LibraryLocation eLocation, const String& rLibName, const String& rName, const String& rMethodName, BasicEntryType eType );
virtual ~BasicEntryDescriptor();
BasicEntryDescriptor( const BasicEntryDescriptor& rDesc );
BasicEntryDescriptor& operator=( const BasicEntryDescriptor& rDesc );
bool operator==( const BasicEntryDescriptor& rDesc ) const;
SfxObjectShell* GetShell() const { return m_pShell; }
void SetShell( SfxObjectShell* pShell ) { m_pShell = pShell; }
LibraryLocation GetLocation() const { return m_eLocation; }
void SetLocation( LibraryLocation eLocation ) { m_eLocation = eLocation; }
const String& GetLibName() const { return m_aLibName; }
void SetLibName( const String& aLibName ) { m_aLibName = aLibName; }
const String& GetName() const { return m_aName; }
void SetName( const String& aName ) { m_aName = aName; }
const String& GetMethodName() const { return m_aMethodName; }
void SetMethodName( const String& aMethodName ) { m_aMethodName = aMethodName; }
BasicEntryType GetType() const { return m_eType; }
void SetType( BasicEntryType eType ) { m_eType = eType; }
};
/****************************************
Zuordnung von Typen und Pointern in BasicEntrys:
OBJ_TYPE_SHELL BasicShellEntry
OBJ_TYPE_LIBRARY BasicEntry
OBJ_TYPE_MODULE BasicEntry
OBJ_TYPE_DIALOG BasicEntry
OBJ_TYPE_METHOD BasicEntry
******************************************/
class BasicTreeListBox : public SvTreeListBox, public SfxListener
{
private:
USHORT nMode;
void SetEntryBitmaps( SvLBoxEntry * pEntry, const Image& rImage, const Image& rImageHC );
protected:
void ExpandTree( SvLBoxEntry* pRootEntry );
virtual void RequestingChilds( SvLBoxEntry* pParent );
virtual void ExpandedHdl();
virtual SvLBoxEntry* CloneEntry( SvLBoxEntry* pSource );
virtual long ExpandingHdl();
void ImpCreateLibEntries( SvLBoxEntry* pShellRootEntry, SfxObjectShell* pShell, LibraryLocation eLocation );
void ImpCreateLibSubEntries( SvLBoxEntry* pLibRootEntry, SfxObjectShell* pShell, const String& rLibName );
using Control::Notify;
virtual void SFX_NOTIFY( SfxBroadcaster& rBC, const TypeId& rBCType, const SfxHint& rHint, const TypeId& rHintType );
public:
BasicTreeListBox( Window* pParent, const ResId& rRes );
~BasicTreeListBox();
void ScanEntry( SfxObjectShell* pShell, LibraryLocation eLocation );
void ScanAllEntries();
void UpdateEntries();
void ExpandAllTrees();
BOOL IsEntryProtected( SvLBoxEntry* pEntry );
void SetMode( USHORT nM ) { nMode = nM; }
USHORT GetMode() const { return nMode; }
SbModule* FindModule( SvLBoxEntry* pEntry );
SbxVariable* FindVariable( SvLBoxEntry* pEntry );
SvLBoxEntry* FindRootEntry( SfxObjectShell* pShell, LibraryLocation eLocation );
SvLBoxEntry* FindEntry( SvLBoxEntry* pParent, const String& rText, BasicEntryType eType );
BasicEntryDescriptor GetEntryDescriptor( SvLBoxEntry* pEntry );
USHORT ConvertType( BasicEntryType eType );
bool IsValidEntry( SvLBoxEntry* pEntry );
SvLBoxEntry* AddEntry( const String& rText, const Image& rImage, const Image& rImageHC,
SvLBoxEntry* pParent, bool bChildrenOnDemand,
std::auto_ptr< BasicEntry > aUserData );
String GetRootEntryName( SfxObjectShell* pShell, LibraryLocation eLocation );
void GetRootEntryBitmaps( SfxObjectShell* pShell, Image& rImage, Image& rImageHC );
void SetCurrentEntry( BasicEntryDescriptor& rDesc );
};
#endif // _BASTYPE2_HXX
<commit_msg>INTEGRATION: CWS basmgr02 (1.11.4); FILE MERGED 2007/02/21 09:37:42 fs 1.11.4.1: #i73331# encapsulate (nearly) all usages of SfxObjectShell in the ScriptDocument class<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: bastype2.hxx,v $
*
* $Revision: 1.12 $
*
* last change: $Author: obo $ $Date: 2007-03-15 15:55:20 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _BASTYPE2_HXX
#define _BASTYPE2_HXX
#include <memory>
#ifndef _SOLAR_H
#include "tools/solar.h"
#endif
#define _SVICNVW_HXX
#ifndef _SVTREEBOX_HXX //autogen
#include <svtools/svtreebx.hxx>
#endif
#ifndef _SFXLSTNER_HXX
#include <svtools/lstner.hxx>
#endif
#ifndef _SB_SBSTAR_HXX //autogen
#include <basic/sbstar.hxx>
#endif
#ifndef _SBXITEM_HXX
#include <sbxitem.hxx>
#endif
#ifndef _BASOBJ_HXX
#include "basobj.hxx"
#endif
enum BasicEntryType { OBJ_TYPE_UNKNOWN, OBJ_TYPE_DOCUMENT, OBJ_TYPE_LIBRARY, OBJ_TYPE_MODULE, OBJ_TYPE_DIALOG, OBJ_TYPE_METHOD };
#define BROWSEMODE_MODULES 0x01
#define BROWSEMODE_SUBS 0x02
#define BROWSEMODE_DIALOGS 0x04
class SbMethod;
class SbxObject;
class SbModule;
class SvLBoxEntry;
class SbxVariable;
class String;
class BasicEntry
{
private:
BasicEntryType m_eType;
public:
BasicEntry( BasicEntryType eType ) { m_eType = eType; }
BasicEntry( const BasicEntry& r ) { m_eType = r.m_eType; }
virtual ~BasicEntry();
BasicEntryType GetType() const { return m_eType; }
};
class BasicDocumentEntry : public BasicEntry
{
private:
ScriptDocument m_aDocument;
LibraryLocation m_eLocation;
public:
BasicDocumentEntry( const ScriptDocument& rDocument, LibraryLocation eLocation, BasicEntryType eType = OBJ_TYPE_DOCUMENT );
virtual ~BasicDocumentEntry();
const ScriptDocument&
GetDocument() const { return m_aDocument; }
LibraryLocation GetLocation() const { return m_eLocation; }
};
class BasicLibEntry : public BasicDocumentEntry
{
private:
String m_aLibName;
public:
BasicLibEntry( const ScriptDocument& rDocument, LibraryLocation eLocation, const String& rLibName, BasicEntryType eType = OBJ_TYPE_LIBRARY );
virtual ~BasicLibEntry();
const String& GetLibName() const { return m_aLibName; }
};
class BasicEntryDescriptor
{
ScriptDocument m_aDocument;
LibraryLocation m_eLocation;
String m_aLibName;
String m_aName;
String m_aMethodName;
BasicEntryType m_eType;
public:
BasicEntryDescriptor();
BasicEntryDescriptor( const ScriptDocument& rDocument, LibraryLocation eLocation, const String& rLibName, const String& rName, BasicEntryType eType );
BasicEntryDescriptor( const ScriptDocument& rDocument, LibraryLocation eLocation, const String& rLibName, const String& rName, const String& rMethodName, BasicEntryType eType );
virtual ~BasicEntryDescriptor();
BasicEntryDescriptor( const BasicEntryDescriptor& rDesc );
BasicEntryDescriptor& operator=( const BasicEntryDescriptor& rDesc );
bool operator==( const BasicEntryDescriptor& rDesc ) const;
const ScriptDocument&
GetDocument() const { return m_aDocument; }
void SetDocument( const ScriptDocument& rDocument ) { m_aDocument = rDocument; }
LibraryLocation GetLocation() const { return m_eLocation; }
void SetLocation( LibraryLocation eLocation ) { m_eLocation = eLocation; }
const String& GetLibName() const { return m_aLibName; }
void SetLibName( const String& aLibName ) { m_aLibName = aLibName; }
const String& GetName() const { return m_aName; }
void SetName( const String& aName ) { m_aName = aName; }
const String& GetMethodName() const { return m_aMethodName; }
void SetMethodName( const String& aMethodName ) { m_aMethodName = aMethodName; }
BasicEntryType GetType() const { return m_eType; }
void SetType( BasicEntryType eType ) { m_eType = eType; }
};
/****************************************
Zuordnung von Typen und Pointern in BasicEntrys:
OBJ_TYPE_DOCUMENT BasicDocumentEntry
OBJ_TYPE_LIBRARY BasicEntry
OBJ_TYPE_MODULE BasicEntry
OBJ_TYPE_DIALOG BasicEntry
OBJ_TYPE_METHOD BasicEntry
******************************************/
class BasicTreeListBox : public SvTreeListBox, public SfxListener
{
private:
USHORT nMode;
void SetEntryBitmaps( SvLBoxEntry * pEntry, const Image& rImage, const Image& rImageHC );
protected:
void ExpandTree( SvLBoxEntry* pRootEntry );
virtual void RequestingChilds( SvLBoxEntry* pParent );
virtual void ExpandedHdl();
virtual SvLBoxEntry* CloneEntry( SvLBoxEntry* pSource );
virtual long ExpandingHdl();
void ImpCreateLibEntries( SvLBoxEntry* pShellRootEntry, const ScriptDocument& rDocument, LibraryLocation eLocation );
void ImpCreateLibSubEntries( SvLBoxEntry* pLibRootEntry, const ScriptDocument& rDocument, const String& rLibName );
using Control::Notify;
virtual void SFX_NOTIFY( SfxBroadcaster& rBC, const TypeId& rBCType, const SfxHint& rHint, const TypeId& rHintType );
public:
BasicTreeListBox( Window* pParent, const ResId& rRes );
~BasicTreeListBox();
void ScanEntry( const ScriptDocument& rDocument, LibraryLocation eLocation );
void ScanAllEntries();
void UpdateEntries();
void ExpandAllTrees();
BOOL IsEntryProtected( SvLBoxEntry* pEntry );
void SetMode( USHORT nM ) { nMode = nM; }
USHORT GetMode() const { return nMode; }
SbModule* FindModule( SvLBoxEntry* pEntry );
SbxVariable* FindVariable( SvLBoxEntry* pEntry );
SvLBoxEntry* FindRootEntry( const ScriptDocument& rDocument, LibraryLocation eLocation );
SvLBoxEntry* FindEntry( SvLBoxEntry* pParent, const String& rText, BasicEntryType eType );
BasicEntryDescriptor GetEntryDescriptor( SvLBoxEntry* pEntry );
USHORT ConvertType( BasicEntryType eType );
bool IsValidEntry( SvLBoxEntry* pEntry );
SvLBoxEntry* AddEntry( const String& rText, const Image& rImage, const Image& rImageHC,
SvLBoxEntry* pParent, bool bChildrenOnDemand,
std::auto_ptr< BasicEntry > aUserData );
String GetRootEntryName( const ScriptDocument& rDocument, LibraryLocation eLocation );
void GetRootEntryBitmaps( const ScriptDocument& rDocument, Image& rImage, Image& rImageHC );
void SetCurrentEntry( BasicEntryDescriptor& rDesc );
};
#endif // _BASTYPE2_HXX
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: bastype4.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: hr $ $Date: 2000-12-07 16:15:25 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _BASTYPE4_HXX
#define _BASTYPE4_HXX
#ifndef _TABBAR_HXX //autogen
#include <svtools/tabbar.hxx>
#endif
class EditEngine;
class EditView;
class ExtendedTabBar : public TabBar
{
EditEngine* pEditEngine;
EditView* pEditView;
BOOL bIsInKeyInput;
#if _SOLAR__PRIVATE
void ImpCheckEditEngine( BOOL bKeepNewText );
#endif
protected:
virtual void MouseButtonDown( const MouseEvent& rMEvt );
virtual void MouseButtonUp( const MouseEvent& rMEvt );
virtual void MouseMove( const MouseEvent& rMEvt );
virtual void LoseFocus();
virtual void KeyInput( const KeyEvent& rKEvent );
virtual void Paint( const Rectangle& );
virtual BOOL StartRenamingTab( USHORT nCurId );
virtual BOOL AllowRenamingTab( USHORT nCurId, const String& rNewName );
virtual void TabRenamed( USHORT nCurId, const String& rNewName );
public:
ExtendedTabBar( Window* pParent, WinBits nStyle );
~ExtendedTabBar();
void RenameSelectedTab();
BOOL IsInEditMode() const { return pEditEngine ? TRUE : FALSE; }
void StopEditMode( BOOL bKeepCurText = FALSE );
};
#endif //_BASTYPE4_HXX
<commit_msg>INTEGRATION: CWS ooo19126 (1.2.412); FILE MERGED 2005/09/05 13:55:33 rt 1.2.412.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: bastype4.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2005-09-07 20:01:19 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _BASTYPE4_HXX
#define _BASTYPE4_HXX
#ifndef _TABBAR_HXX //autogen
#include <svtools/tabbar.hxx>
#endif
class EditEngine;
class EditView;
class ExtendedTabBar : public TabBar
{
EditEngine* pEditEngine;
EditView* pEditView;
BOOL bIsInKeyInput;
#if _SOLAR__PRIVATE
void ImpCheckEditEngine( BOOL bKeepNewText );
#endif
protected:
virtual void MouseButtonDown( const MouseEvent& rMEvt );
virtual void MouseButtonUp( const MouseEvent& rMEvt );
virtual void MouseMove( const MouseEvent& rMEvt );
virtual void LoseFocus();
virtual void KeyInput( const KeyEvent& rKEvent );
virtual void Paint( const Rectangle& );
virtual BOOL StartRenamingTab( USHORT nCurId );
virtual BOOL AllowRenamingTab( USHORT nCurId, const String& rNewName );
virtual void TabRenamed( USHORT nCurId, const String& rNewName );
public:
ExtendedTabBar( Window* pParent, WinBits nStyle );
~ExtendedTabBar();
void RenameSelectedTab();
BOOL IsInEditMode() const { return pEditEngine ? TRUE : FALSE; }
void StopEditMode( BOOL bKeepCurText = FALSE );
};
#endif //_BASTYPE4_HXX
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2014 Cloudius Systems, Ltd.
*/
#pragma once
#include <experimental/optional>
#include <boost/any.hpp>
#include <boost/functional/hash.hpp>
#include <iostream>
#include <sstream>
#include "core/sstring.hh"
#include "core/shared_ptr.hh"
#include "utils/UUID.hh"
#include "net/byteorder.hh"
#include "db_clock.hh"
#include "bytes.hh"
namespace cql3 {
class cql3_type;
}
using object_opt = std::experimental::optional<boost::any>;
class marshal_exception : public std::exception {
sstring _why;
public:
marshal_exception() : _why("marshalling error") {}
marshal_exception(sstring why) : _why(sstring("marshaling error: ") + why) {}
virtual const char* why() const { return _why.c_str(); }
};
struct runtime_exception : public std::exception {
sstring _why;
public:
runtime_exception(sstring why) : _why(sstring("runtime error: ") + why) {}
virtual const char* why() const { return _why.c_str(); }
};
inline int32_t compare_unsigned(bytes_view v1, bytes_view v2) {
auto n = memcmp(v1.begin(), v2.begin(), std::min(v1.size(), v2.size()));
if (n) {
return n;
}
return (int32_t) (v1.size() - v2.size());
}
class abstract_type {
sstring _name;
public:
abstract_type(sstring name) : _name(name) {}
virtual ~abstract_type() {}
virtual void serialize(const boost::any& value, std::ostream& out) = 0;
virtual bool less(bytes_view v1, bytes_view v2) = 0;
virtual size_t hash(bytes_view v) = 0;
virtual bool equal(bytes_view v1, bytes_view v2) {
if (is_byte_order_equal()) {
return compare_unsigned(v1, v2) == 0;
}
return compare(v1, v2) == 0;
}
virtual int32_t compare(bytes_view v1, bytes_view v2) {
if (less(v1, v2)) {
return -1;
} else if (less(v2, v1)) {
return 1;
} else {
return 0;
}
}
virtual object_opt deserialize(bytes_view v) = 0;
virtual void validate(const bytes& v) {
// FIXME
}
virtual void validate_collection_member(const bytes& v, const bytes& collection_name) {
validate(v);
}
virtual bool is_compatible_with(abstract_type& previous) {
// FIXME
abort();
return false;
}
/*
* Types which are wrappers over other types should override this.
* For example the reversed_type returns the type it is reversing.
*/
virtual abstract_type& underlying_type() {
return *this;
}
/**
* Returns true if values of the other AbstractType can be read and "reasonably" interpreted by the this
* AbstractType. Note that this is a weaker version of isCompatibleWith, as it does not require that both type
* compare values the same way.
*
* The restriction on the other type being "reasonably" interpreted is to prevent, for example, IntegerType from
* being compatible with all other types. Even though any byte string is a valid IntegerType value, it doesn't
* necessarily make sense to interpret a UUID or a UTF8 string as an integer.
*
* Note that a type should be compatible with at least itself.
*/
bool is_value_compatible_with(abstract_type& other) {
return is_value_compatible_with_internal(other.underlying_type());
}
protected:
/**
* Needed to handle ReversedType in value-compatibility checks. Subclasses should implement this instead of
* is_value_compatible_with().
*/
virtual bool is_value_compatible_with_internal(abstract_type& other) {
return is_compatible_with(other);
}
public:
virtual object_opt compose(const bytes& v) {
return deserialize(v);
}
bytes decompose(const boost::any& value) {
// FIXME: optimize
std::ostringstream oss;
serialize(value, oss);
auto s = oss.str();
return bytes(s.data(), s.size());
}
sstring name() const {
return _name;
}
virtual bool is_byte_order_comparable() const {
return false;
}
/**
* When returns true then equal values have the same byte representation and if byte
* representation is different, the values are not equal.
*
* When returns false, nothing can be inferred.
*/
virtual bool is_byte_order_equal() const {
// If we're byte order comparable, then we must also be byte order equal.
return is_byte_order_comparable();
}
virtual sstring get_string(const bytes& b) {
validate(b);
return to_string(b);
}
virtual sstring to_string(const bytes& b) = 0;
virtual bytes from_string(sstring_view text) = 0;
virtual bool is_counter() { return false; }
virtual bool is_collection() { return false; }
virtual bool is_multi_cell() { return false; }
virtual ::shared_ptr<cql3::cql3_type> as_cql3_type() = 0;
};
using data_type = shared_ptr<abstract_type>;
inline
size_t hash_value(const shared_ptr<abstract_type>& x) {
return std::hash<abstract_type*>()(x.get());
}
template <typename Type>
shared_ptr<abstract_type> data_type_for();
class serialized_compare {
data_type _type;
public:
serialized_compare(data_type type) : _type(type) {}
bool operator()(const bytes& v1, const bytes& v2) const {
return _type->less(v1, v2);
}
};
using key_compare = serialized_compare;
// FIXME: add missing types
extern thread_local shared_ptr<abstract_type> int32_type;
extern thread_local shared_ptr<abstract_type> long_type;
extern thread_local shared_ptr<abstract_type> ascii_type;
extern thread_local shared_ptr<abstract_type> bytes_type;
extern thread_local shared_ptr<abstract_type> utf8_type;
extern thread_local shared_ptr<abstract_type> boolean_type;
extern thread_local shared_ptr<abstract_type> date_type;
extern thread_local shared_ptr<abstract_type> timeuuid_type;
extern thread_local shared_ptr<abstract_type> timestamp_type;
extern thread_local shared_ptr<abstract_type> uuid_type;
extern thread_local shared_ptr<abstract_type> inet_addr_type;
extern thread_local shared_ptr<abstract_type> float_type;
extern thread_local shared_ptr<abstract_type> double_type;
template <>
inline
shared_ptr<abstract_type> data_type_for<int32_t>() {
return int32_type;
}
template <>
inline
shared_ptr<abstract_type> data_type_for<int64_t>() {
return long_type;
}
template <>
inline
shared_ptr<abstract_type> data_type_for<sstring>() {
return utf8_type;
}
namespace std {
template <>
struct hash<shared_ptr<abstract_type>> : boost::hash<shared_ptr<abstract_type>> {
};
}
inline
bytes
to_bytes(const char* x) {
return bytes(reinterpret_cast<const char*>(x), std::strlen(x));
}
inline
bytes
to_bytes(const std::string& x) {
return bytes(reinterpret_cast<const char*>(x.data()), x.size());
}
inline
bytes
to_bytes(sstring_view x) {
return bytes(x.begin(), x.size());
}
inline
bytes
to_bytes(const sstring& x) {
return bytes(reinterpret_cast<const char*>(x.c_str()), x.size());
}
inline
bytes
to_bytes(const utils::UUID& uuid) {
struct {
uint64_t msb;
uint64_t lsb;
} tmp = { net::hton(uint64_t(uuid.get_most_significant_bits())),
net::hton(uint64_t(uuid.get_least_significant_bits())) };
return bytes(reinterpret_cast<char*>(&tmp), 16);
}
// This follows java.util.Comparator
// FIXME: Choose a better place than database.hh
template <typename T>
struct comparator {
comparator() = default;
comparator(std::function<int32_t (T& v1, T& v2)> fn)
: _compare_fn(std::move(fn))
{ }
int32_t compare() { return _compare_fn(); }
private:
std::function<int32_t (T& v1, T& v2)> _compare_fn;
};
inline bool
less_unsigned(bytes_view v1, bytes_view v2) {
return compare_unsigned(v1, v2) < 0;
}
class serialized_hash {
private:
data_type _type;
public:
serialized_hash(data_type type) : _type(type) {}
size_t operator()(const bytes& v) const {
return _type->hash(v);
}
};
class serialized_equal {
private:
data_type _type;
public:
serialized_equal(data_type type) : _type(type) {}
bool operator()(const bytes& v1, const bytes& v2) const {
return _type->equal(v1, v2);
}
};
template<typename Type>
static inline
typename Type::value_type deserialize_value(Type& t, bytes_view v) {
return t.deserialize_value(v);
}
template<typename Type>
static inline
bytes serialize_value(Type& t, const typename Type::value_type& value) {
std::ostringstream oss;
t.serialize_value(value, oss);
auto s = oss.str();
return bytes(s.data(), s.size());
}
template<typename T>
T read_simple(bytes_view& v) {
if (v.size() < sizeof(T)) {
throw marshal_exception();
}
auto p = v.begin();
v.remove_prefix(sizeof(T));
return net::ntoh(*reinterpret_cast<const net::packed<T>*>(p));
}
template<typename T>
T read_simple_exactly(bytes_view& v) {
if (v.size() != sizeof(T)) {
throw marshal_exception();
}
auto p = v.begin();
v.remove_prefix(sizeof(T));
return net::ntoh(*reinterpret_cast<const net::packed<T>*>(p));
}
template<typename T>
object_opt read_simple_opt(bytes_view& v) {
if (v.empty()) {
return {};
}
if (v.size() != sizeof(T)) {
throw marshal_exception();
}
auto p = v.begin();
v.remove_prefix(sizeof(T));
return boost::any(net::ntoh(*reinterpret_cast<const net::packed<T>*>(p)));
}
<commit_msg>types: Add read_simple_short_string<commit_after>/*
* Copyright (C) 2014 Cloudius Systems, Ltd.
*/
#pragma once
#include <experimental/optional>
#include <boost/any.hpp>
#include <boost/functional/hash.hpp>
#include <iostream>
#include <sstream>
#include "core/sstring.hh"
#include "core/shared_ptr.hh"
#include "utils/UUID.hh"
#include "net/byteorder.hh"
#include "db_clock.hh"
#include "bytes.hh"
namespace cql3 {
class cql3_type;
}
using object_opt = std::experimental::optional<boost::any>;
class marshal_exception : public std::exception {
sstring _why;
public:
marshal_exception() : _why("marshalling error") {}
marshal_exception(sstring why) : _why(sstring("marshaling error: ") + why) {}
virtual const char* why() const { return _why.c_str(); }
};
struct runtime_exception : public std::exception {
sstring _why;
public:
runtime_exception(sstring why) : _why(sstring("runtime error: ") + why) {}
virtual const char* why() const { return _why.c_str(); }
};
inline int32_t compare_unsigned(bytes_view v1, bytes_view v2) {
auto n = memcmp(v1.begin(), v2.begin(), std::min(v1.size(), v2.size()));
if (n) {
return n;
}
return (int32_t) (v1.size() - v2.size());
}
class abstract_type {
sstring _name;
public:
abstract_type(sstring name) : _name(name) {}
virtual ~abstract_type() {}
virtual void serialize(const boost::any& value, std::ostream& out) = 0;
virtual bool less(bytes_view v1, bytes_view v2) = 0;
virtual size_t hash(bytes_view v) = 0;
virtual bool equal(bytes_view v1, bytes_view v2) {
if (is_byte_order_equal()) {
return compare_unsigned(v1, v2) == 0;
}
return compare(v1, v2) == 0;
}
virtual int32_t compare(bytes_view v1, bytes_view v2) {
if (less(v1, v2)) {
return -1;
} else if (less(v2, v1)) {
return 1;
} else {
return 0;
}
}
virtual object_opt deserialize(bytes_view v) = 0;
virtual void validate(const bytes& v) {
// FIXME
}
virtual void validate_collection_member(const bytes& v, const bytes& collection_name) {
validate(v);
}
virtual bool is_compatible_with(abstract_type& previous) {
// FIXME
abort();
return false;
}
/*
* Types which are wrappers over other types should override this.
* For example the reversed_type returns the type it is reversing.
*/
virtual abstract_type& underlying_type() {
return *this;
}
/**
* Returns true if values of the other AbstractType can be read and "reasonably" interpreted by the this
* AbstractType. Note that this is a weaker version of isCompatibleWith, as it does not require that both type
* compare values the same way.
*
* The restriction on the other type being "reasonably" interpreted is to prevent, for example, IntegerType from
* being compatible with all other types. Even though any byte string is a valid IntegerType value, it doesn't
* necessarily make sense to interpret a UUID or a UTF8 string as an integer.
*
* Note that a type should be compatible with at least itself.
*/
bool is_value_compatible_with(abstract_type& other) {
return is_value_compatible_with_internal(other.underlying_type());
}
protected:
/**
* Needed to handle ReversedType in value-compatibility checks. Subclasses should implement this instead of
* is_value_compatible_with().
*/
virtual bool is_value_compatible_with_internal(abstract_type& other) {
return is_compatible_with(other);
}
public:
virtual object_opt compose(const bytes& v) {
return deserialize(v);
}
bytes decompose(const boost::any& value) {
// FIXME: optimize
std::ostringstream oss;
serialize(value, oss);
auto s = oss.str();
return bytes(s.data(), s.size());
}
sstring name() const {
return _name;
}
virtual bool is_byte_order_comparable() const {
return false;
}
/**
* When returns true then equal values have the same byte representation and if byte
* representation is different, the values are not equal.
*
* When returns false, nothing can be inferred.
*/
virtual bool is_byte_order_equal() const {
// If we're byte order comparable, then we must also be byte order equal.
return is_byte_order_comparable();
}
virtual sstring get_string(const bytes& b) {
validate(b);
return to_string(b);
}
virtual sstring to_string(const bytes& b) = 0;
virtual bytes from_string(sstring_view text) = 0;
virtual bool is_counter() { return false; }
virtual bool is_collection() { return false; }
virtual bool is_multi_cell() { return false; }
virtual ::shared_ptr<cql3::cql3_type> as_cql3_type() = 0;
};
using data_type = shared_ptr<abstract_type>;
inline
size_t hash_value(const shared_ptr<abstract_type>& x) {
return std::hash<abstract_type*>()(x.get());
}
template <typename Type>
shared_ptr<abstract_type> data_type_for();
class serialized_compare {
data_type _type;
public:
serialized_compare(data_type type) : _type(type) {}
bool operator()(const bytes& v1, const bytes& v2) const {
return _type->less(v1, v2);
}
};
using key_compare = serialized_compare;
// FIXME: add missing types
extern thread_local shared_ptr<abstract_type> int32_type;
extern thread_local shared_ptr<abstract_type> long_type;
extern thread_local shared_ptr<abstract_type> ascii_type;
extern thread_local shared_ptr<abstract_type> bytes_type;
extern thread_local shared_ptr<abstract_type> utf8_type;
extern thread_local shared_ptr<abstract_type> boolean_type;
extern thread_local shared_ptr<abstract_type> date_type;
extern thread_local shared_ptr<abstract_type> timeuuid_type;
extern thread_local shared_ptr<abstract_type> timestamp_type;
extern thread_local shared_ptr<abstract_type> uuid_type;
extern thread_local shared_ptr<abstract_type> inet_addr_type;
extern thread_local shared_ptr<abstract_type> float_type;
extern thread_local shared_ptr<abstract_type> double_type;
template <>
inline
shared_ptr<abstract_type> data_type_for<int32_t>() {
return int32_type;
}
template <>
inline
shared_ptr<abstract_type> data_type_for<int64_t>() {
return long_type;
}
template <>
inline
shared_ptr<abstract_type> data_type_for<sstring>() {
return utf8_type;
}
namespace std {
template <>
struct hash<shared_ptr<abstract_type>> : boost::hash<shared_ptr<abstract_type>> {
};
}
inline
bytes
to_bytes(const char* x) {
return bytes(reinterpret_cast<const char*>(x), std::strlen(x));
}
inline
bytes
to_bytes(const std::string& x) {
return bytes(reinterpret_cast<const char*>(x.data()), x.size());
}
inline
bytes
to_bytes(sstring_view x) {
return bytes(x.begin(), x.size());
}
inline
bytes
to_bytes(const sstring& x) {
return bytes(reinterpret_cast<const char*>(x.c_str()), x.size());
}
inline
bytes
to_bytes(const utils::UUID& uuid) {
struct {
uint64_t msb;
uint64_t lsb;
} tmp = { net::hton(uint64_t(uuid.get_most_significant_bits())),
net::hton(uint64_t(uuid.get_least_significant_bits())) };
return bytes(reinterpret_cast<char*>(&tmp), 16);
}
// This follows java.util.Comparator
// FIXME: Choose a better place than database.hh
template <typename T>
struct comparator {
comparator() = default;
comparator(std::function<int32_t (T& v1, T& v2)> fn)
: _compare_fn(std::move(fn))
{ }
int32_t compare() { return _compare_fn(); }
private:
std::function<int32_t (T& v1, T& v2)> _compare_fn;
};
inline bool
less_unsigned(bytes_view v1, bytes_view v2) {
return compare_unsigned(v1, v2) < 0;
}
class serialized_hash {
private:
data_type _type;
public:
serialized_hash(data_type type) : _type(type) {}
size_t operator()(const bytes& v) const {
return _type->hash(v);
}
};
class serialized_equal {
private:
data_type _type;
public:
serialized_equal(data_type type) : _type(type) {}
bool operator()(const bytes& v1, const bytes& v2) const {
return _type->equal(v1, v2);
}
};
template<typename Type>
static inline
typename Type::value_type deserialize_value(Type& t, bytes_view v) {
return t.deserialize_value(v);
}
template<typename Type>
static inline
bytes serialize_value(Type& t, const typename Type::value_type& value) {
std::ostringstream oss;
t.serialize_value(value, oss);
auto s = oss.str();
return bytes(s.data(), s.size());
}
template<typename T>
T read_simple(bytes_view& v) {
if (v.size() < sizeof(T)) {
throw marshal_exception();
}
auto p = v.begin();
v.remove_prefix(sizeof(T));
return net::ntoh(*reinterpret_cast<const net::packed<T>*>(p));
}
template<typename T>
T read_simple_exactly(bytes_view& v) {
if (v.size() != sizeof(T)) {
throw marshal_exception();
}
auto p = v.begin();
v.remove_prefix(sizeof(T));
return net::ntoh(*reinterpret_cast<const net::packed<T>*>(p));
}
template<typename T>
object_opt read_simple_opt(bytes_view& v) {
if (v.empty()) {
return {};
}
if (v.size() != sizeof(T)) {
throw marshal_exception();
}
auto p = v.begin();
v.remove_prefix(sizeof(T));
return boost::any(net::ntoh(*reinterpret_cast<const net::packed<T>*>(p)));
}
inline sstring read_simple_short_string(bytes_view& v) {
uint16_t len = read_simple<uint16_t>(v);
if (v.size() < len) {
throw marshal_exception();
}
sstring ret(sstring::initialized_later(), len);
std::copy(v.begin(), v.begin() + len, ret.begin());
v.remove_prefix(len);
return ret;
}
<|endoftext|> |
<commit_before>#include <stan/io/random_var_context.hpp>
#include <stan/io/empty_var_context.hpp>
#include <gtest/gtest.h>
#include <boost/random/additive_combine.hpp> // L'Ecuyer RNG
#include <boost/random/uniform_real_distribution.hpp>
#include <test/test-models/good/services/test_lp.hpp>
class random_var_context : public testing::Test {
public:
random_var_context()
: empty_context(),
model(empty_context, static_cast<std::stringstream*>(0)),
rng(0) { }
stan::io::empty_var_context empty_context;
stan_model model;
boost::ecuyer1988 rng;
};
TEST_F(random_var_context, contains_r) {
stan::io::random_var_context context(model, rng, 2, false);
EXPECT_FALSE(context.contains_r(""));
EXPECT_TRUE(context.contains_r("y"));
}
TEST_F(random_var_context, vals_r) {
stan::io::random_var_context context(model, rng, 2, false);
std::vector<double> vals_r;
EXPECT_NO_THROW(vals_r = context.vals_r(""));
EXPECT_EQ(0, vals_r.size());
EXPECT_NO_THROW(vals_r = context.vals_r("y"));
ASSERT_EQ(2, vals_r.size());
EXPECT_GT(vals_r[0], -10);
EXPECT_LT(vals_r[0], 10);
EXPECT_GT(vals_r[1], -100);
EXPECT_LT(vals_r[1], 10);
}
TEST_F(random_var_context, dims_r) {
stan::io::random_var_context context(model, rng, 2, false);
std::vector<size_t> dims_r;
EXPECT_NO_THROW(dims_r = context.dims_r(""));
EXPECT_EQ(0, dims_r.size());
EXPECT_NO_THROW(dims_r = context.dims_r("y"));
ASSERT_EQ(1, dims_r.size());
EXPECT_EQ(2, dims_r[0]);
}
TEST_F(random_var_context, contains_i) {
stan::io::random_var_context context(model, rng, 2, false);
EXPECT_FALSE(context.contains_i(""));
}
TEST_F(random_var_context, vals_i) {
stan::io::random_var_context context(model, rng, 2, false);
std::vector<int> vals_i;
EXPECT_NO_THROW(vals_i = context.vals_i(""));
EXPECT_EQ(0, vals_i.size());
}
TEST_F(random_var_context, dims_i) {
stan::io::random_var_context context(model, rng, 2, false);
std::vector<size_t> dims_i;
EXPECT_NO_THROW(dims_i = context.dims_i(""));
EXPECT_EQ(0, dims_i.size());
}
TEST_F(random_var_context, names_r) {
stan::io::random_var_context context(model, rng, 2, false);
std::vector<std::string> names_r;
EXPECT_NO_THROW(context.names_r(names_r));
EXPECT_EQ(1, names_r.size());
}
TEST_F(random_var_context, names_i) {
stan::io::random_var_context context(model, rng, 2, false);
std::vector<std::string> names_i;
EXPECT_NO_THROW(context.names_i(names_i));
EXPECT_EQ(0, names_i.size());
}
<commit_msg>Adding additional test for random_var_context that shows the current behavior<commit_after>#include <stan/io/random_var_context.hpp>
#include <stan/io/empty_var_context.hpp>
#include <gtest/gtest.h>
#include <boost/random/additive_combine.hpp> // L'Ecuyer RNG
#include <boost/random/uniform_real_distribution.hpp>
#include <test/test-models/good/services/test_lp.hpp>
#include <test/unit/util.hpp>
namespace test {
// mock_throwing_model_in_write_array throws exception in the write_array()
// method
class mock_throwing_model_in_write_array: public stan::model::prob_grad {
public:
mock_throwing_model_in_write_array():
stan::model::prob_grad(1),
templated_log_prob_calls(0),
transform_inits_calls(0),
write_array_calls(0),
log_prob_return_value(0.0) { }
void reset() {
templated_log_prob_calls = 0;
transform_inits_calls = 0;
write_array_calls = 0;
log_prob_return_value = 0.0;
}
template <bool propto__, bool jacobian__, typename T__>
T__ log_prob(std::vector<T__>& params_r__,
std::vector<int>& params_i__,
std::ostream* pstream__ = 0) const {
++templated_log_prob_calls;
return log_prob_return_value;
}
void transform_inits(const stan::io::var_context& context__,
std::vector<int>& params_i__,
std::vector<double>& params_r__,
std::ostream* pstream__) const {
++transform_inits_calls;
for (size_t n = 0; n < params_r__.size(); ++n) {
params_r__[n] = n;
}
}
void get_dims(std::vector<std::vector<size_t> >& dimss__) const {
dimss__.resize(0);
std::vector<size_t> scalar_dim;
dimss__.push_back(scalar_dim);
}
void constrained_param_names(std::vector<std::string>& param_names__,
bool include_tparams__ = true,
bool include_gqs__ = true) const {
param_names__.push_back("theta");
}
void get_param_names(std::vector<std::string>& names) const {
constrained_param_names(names);
}
void unconstrained_param_names(std::vector<std::string>& param_names__,
bool include_tparams__ = true,
bool include_gqs__ = true) const {
param_names__.clear();
for (size_t n = 0; n < num_params_r__; ++n) {
std::stringstream param_name;
param_name << "param_" << n;
param_names__.push_back(param_name.str());
}
}
template <typename RNG>
void write_array(RNG& base_rng__,
std::vector<double>& params_r__,
std::vector<int>& params_i__,
std::vector<double>& vars__,
bool include_tparams__ = true,
bool include_gqs__ = true,
std::ostream* pstream__ = 0) const {
++write_array_calls;
throw std::domain_error("throwing within write_array");
vars__.resize(0);
for (size_t i = 0; i < params_r__.size(); ++i)
vars__.push_back(params_r__[i]);
}
mutable int templated_log_prob_calls;
mutable int transform_inits_calls;
mutable int write_array_calls;
double log_prob_return_value;
};
}
class random_var_context : public testing::Test {
public:
random_var_context()
: empty_context(),
model(empty_context, static_cast<std::stringstream*>(0)),
rng(0),
throwing_model() { }
stan::io::empty_var_context empty_context;
stan_model model;
boost::ecuyer1988 rng;
test::mock_throwing_model_in_write_array throwing_model;
};
TEST_F(random_var_context, contains_r) {
stan::io::random_var_context context(model, rng, 2, false);
EXPECT_FALSE(context.contains_r(""));
EXPECT_TRUE(context.contains_r("y"));
}
TEST_F(random_var_context, vals_r) {
stan::io::random_var_context context(model, rng, 2, false);
std::vector<double> vals_r;
EXPECT_NO_THROW(vals_r = context.vals_r(""));
EXPECT_EQ(0, vals_r.size());
EXPECT_NO_THROW(vals_r = context.vals_r("y"));
ASSERT_EQ(2, vals_r.size());
EXPECT_GT(vals_r[0], -10);
EXPECT_LT(vals_r[0], 10);
EXPECT_GT(vals_r[1], -100);
EXPECT_LT(vals_r[1], 10);
}
TEST_F(random_var_context, dims_r) {
stan::io::random_var_context context(model, rng, 2, false);
std::vector<size_t> dims_r;
EXPECT_NO_THROW(dims_r = context.dims_r(""));
EXPECT_EQ(0, dims_r.size());
EXPECT_NO_THROW(dims_r = context.dims_r("y"));
ASSERT_EQ(1, dims_r.size());
EXPECT_EQ(2, dims_r[0]);
}
TEST_F(random_var_context, contains_i) {
stan::io::random_var_context context(model, rng, 2, false);
EXPECT_FALSE(context.contains_i(""));
}
TEST_F(random_var_context, vals_i) {
stan::io::random_var_context context(model, rng, 2, false);
std::vector<int> vals_i;
EXPECT_NO_THROW(vals_i = context.vals_i(""));
EXPECT_EQ(0, vals_i.size());
}
TEST_F(random_var_context, dims_i) {
stan::io::random_var_context context(model, rng, 2, false);
std::vector<size_t> dims_i;
EXPECT_NO_THROW(dims_i = context.dims_i(""));
EXPECT_EQ(0, dims_i.size());
}
TEST_F(random_var_context, names_r) {
stan::io::random_var_context context(model, rng, 2, false);
std::vector<std::string> names_r;
EXPECT_NO_THROW(context.names_r(names_r));
EXPECT_EQ(1, names_r.size());
}
TEST_F(random_var_context, names_i) {
stan::io::random_var_context context(model, rng, 2, false);
std::vector<std::string> names_i;
EXPECT_NO_THROW(context.names_i(names_i));
EXPECT_EQ(0, names_i.size());
}
TEST_F(random_var_context, construct) {
EXPECT_THROW_MSG(stan::io::random_var_context(throwing_model, rng, 2, false),
std::domain_error,
"throwing within write_array");
}
<|endoftext|> |
<commit_before>/* -*- mode:linux -*- */
/**
* \file grid_world.cc
*
*
*
* \author Ethan Burns
* \date 2008-10-08
*/
#include <iostream>
#include <fstream>
#include <map>
#include <string>
#include <vector>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "../util/eps.h"
#include "grid_state.h"
#include "grid_world.h"
using namespace std;
/**
* Create a new GridWorld.
* \param s The istream to read the world file from.
*/
GridWorld::GridWorld(istream &s)
{
char line[100];
char c;
s >> height;
s >> width;
s >> line;
if(strcmp(line, "Board:") != 0) {
cerr << "Parse error: expected \"Board:\"" << endl;
exit(EXIT_FAILURE);
}
c = s.get(); // new-line
if (c != '\n') {
cerr << endl << "Parse error: [" << c << "]" << endl;
exit(EXIT_FAILURE);
}
for (int h = 0; h < height; h += 1) {
for (int w = 0; w < width; w += 1) {
c = s.get();
if (c == '#')
obstacles[width * h + w] = true;
}
c = s.get(); // new-line
if (c != '\n') {
cerr << endl << "Parse error: [" << c << "]" << endl;
exit(EXIT_FAILURE);
}
}
// Cost (Unit/Life)
s >> line;
// Movement (Four-way/Eight-way)
s >> line;
s >> start_x;
s >> start_y;
s >> goal_x;
s >> goal_y;
states.resize(width * height, 0UL);
expanded = 0;
}
/**
* Get the initial state.
* \return A new state (that must be deleted by the caller) that
* represents the initial state.
*/
State *GridWorld::initial_state(void)
{
return new GridState(this, NULL, 0, start_x, start_y);
}
/**
* Expand a gridstate.
* \param state The state to expand.
* \return A newly allocated vector of newly allocated children
* states. All of this must be deleted by the caller.
*/
vector<const State*> *GridWorld::expand(const State *state)
{
const int cost = 1;
const GridState *s;
vector<const State*> *children;
s = dynamic_cast<const GridState*>(state);
children = new vector<const State*>();
#if defined(ENABLE_IMAGES)
expanded += 1;
expanded_state(s);
#endif // ENABLE_IMAGSE
if (s->get_x() > 0 && !is_obstacle(s->get_x() - 1, s->get_y())) {
children->push_back(new GridState(this, state, s->get_g() + cost,
s->get_x() - 1, s->get_y()));
}
if (s->get_x() < width - 1 && !is_obstacle(s->get_x() + 1, s->get_y())) {
children->push_back(new GridState(this, state, s->get_g() + cost,
s->get_x() + 1, s->get_y()));
}
if (s->get_y() > 0 && !is_obstacle(s->get_x(), s->get_y() - 1)) {
children->push_back(new GridState(this, state, s->get_g() + cost,
s->get_x(), s->get_y() - 1));
}
if (s->get_y() < height - 1 && !is_obstacle(s->get_x(), s->get_y() + 1)) {
children->push_back(new GridState(this, state, s->get_g() + cost,
s->get_x(), s->get_y() + 1));
}
return children;
}
/**
* Get the x-coordinate of the goal.
* \return the x-coordinate of the goal.
*/
int GridWorld::get_goal_x(void) const
{
return goal_x;
}
/**
* Get the y-coordinate of the goal.
* \return the y-coordinate of the goal.
*/
int GridWorld::get_goal_y(void) const
{
return goal_y;
}
/**
* Get the world width.
* \return The world width.
*/
int GridWorld::get_width(void) const
{
return width;
}
/**
* Get the world height.
* \return The world height.
*/
int GridWorld::get_height(void) const
{
return height;
}
/**
* Test if there is an obstacle at the given location.
*/
bool GridWorld::is_obstacle(int x, int y) const
{
map<int, bool>::const_iterator iter;
iter = obstacles.find(width * y + x);
return iter != obstacles.end();
}
/**
* Prints the grid world to the given stream.
* \param o The output stream to print to.
* \param path An optional parameter that is a vector of states that
* form a path in the world. If given, this path will be displayed.
*/
void GridWorld::print(ostream &o, const vector<const State *> *path = NULL) const
{
o << height << " " << width << endl;
o << "Board:" << endl;
for (int h = 0; h < height; h += 1) {
for (int w = 0; w < width; w += 1) {
if (is_obstacle(w, h))
o << "#";
else if (path && on_path(path, w, h))
o << "o";
else
o << " ";
}
o << endl;;
}
o << "Unit" << endl;
o << "Four-way" << endl;
o << start_x << " " << start_y << "\t" << goal_x << " " << goal_y << endl;
}
/**
* Test whether or not a location is on the given path.
* \param path The path.
* \param x The x-coordinate to test.
* \param y The y-coordinate to test.
*/
bool GridWorld::on_path(const vector<const State *> *path, int x, int y) const
{
if (!path)
return false;
for (unsigned int i = 0; i < path->size(); i += 1) {
const GridState *s = dynamic_cast<const GridState *>(path->at(i));
if (s->get_x() == x && s->get_y() == y)
return true;
}
return false;
}
#if defined(ENABLE_IMAGES)
/**
* Mark a state as expanded, if this was the first time that the state
* was expanded, it is marked in the states field so that we can make
* a display of when each state was expanded.
* \param s The state that was expanded.
*/
void GridWorld::expanded_state(const GridState *s)
{
int index = s->get_y() * width + s->get_x();
// this should be made atomic
if (states[index] == 0)
states[index] = expanded;
}
/**
* Export an image of the order of state expansions to an encapsulated
* post script file.
* \param file The name of the file to export to.
*/
void GridWorld::export_eps(string file) const
{
const int min_size = 500;
string data;
EPS image(width, height);
if (width < min_size && height < min_size) {
float min_side = width < height ? width : height;
image.set_scale(min_size / min_side);
}
// Image red data
for (int y = height - 1; y >= 0; y -= 1) {
for (int x = 0; x < width; x += 1) {
int i = y * width + x;
char red, green, blue;
if (is_obstacle(x, y)) {
// black
red = green = blue = 0x00;
} else if (states[i] == 0) {
// white
red = green = blue = 0xFF;
} else {
// A certain shade of red
double total = expanded * 1.2;
double time = states[i];
red = (1.0 - (time / total)) * 0xFF;
green = blue = 0x00;
}
data += red;
data += green;
data += blue;
}
}
image.set_data(data);
image.output(file);
}
#endif // ENABLE_IMAGES
<commit_msg>Stealing Jordan's colorizing.<commit_after>/* -*- mode:linux -*- */
/**
* \file grid_world.cc
*
*
*
* \author Ethan Burns
* \date 2008-10-08
*/
#include <iostream>
#include <fstream>
#include <map>
#include <string>
#include <vector>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "../util/eps.h"
#include "grid_state.h"
#include "grid_world.h"
using namespace std;
/**
* Create a new GridWorld.
* \param s The istream to read the world file from.
*/
GridWorld::GridWorld(istream &s)
{
char line[100];
char c;
s >> height;
s >> width;
s >> line;
if(strcmp(line, "Board:") != 0) {
cerr << "Parse error: expected \"Board:\"" << endl;
exit(EXIT_FAILURE);
}
c = s.get(); // new-line
if (c != '\n') {
cerr << endl << "Parse error: [" << c << "]" << endl;
exit(EXIT_FAILURE);
}
for (int h = 0; h < height; h += 1) {
for (int w = 0; w < width; w += 1) {
c = s.get();
if (c == '#')
obstacles[width * h + w] = true;
}
c = s.get(); // new-line
if (c != '\n') {
cerr << endl << "Parse error: [" << c << "]" << endl;
exit(EXIT_FAILURE);
}
}
// Cost (Unit/Life)
s >> line;
// Movement (Four-way/Eight-way)
s >> line;
s >> start_x;
s >> start_y;
s >> goal_x;
s >> goal_y;
states.resize(width * height, 0UL);
expanded = 0;
}
/**
* Get the initial state.
* \return A new state (that must be deleted by the caller) that
* represents the initial state.
*/
State *GridWorld::initial_state(void)
{
return new GridState(this, NULL, 0, start_x, start_y);
}
/**
* Expand a gridstate.
* \param state The state to expand.
* \return A newly allocated vector of newly allocated children
* states. All of this must be deleted by the caller.
*/
vector<const State*> *GridWorld::expand(const State *state)
{
const int cost = 1;
const GridState *s;
vector<const State*> *children;
s = dynamic_cast<const GridState*>(state);
children = new vector<const State*>();
#if defined(ENABLE_IMAGES)
expanded += 1;
expanded_state(s);
#endif // ENABLE_IMAGSE
if (s->get_x() > 0 && !is_obstacle(s->get_x() - 1, s->get_y())) {
children->push_back(new GridState(this, state, s->get_g() + cost,
s->get_x() - 1, s->get_y()));
}
if (s->get_x() < width - 1 && !is_obstacle(s->get_x() + 1, s->get_y())) {
children->push_back(new GridState(this, state, s->get_g() + cost,
s->get_x() + 1, s->get_y()));
}
if (s->get_y() > 0 && !is_obstacle(s->get_x(), s->get_y() - 1)) {
children->push_back(new GridState(this, state, s->get_g() + cost,
s->get_x(), s->get_y() - 1));
}
if (s->get_y() < height - 1 && !is_obstacle(s->get_x(), s->get_y() + 1)) {
children->push_back(new GridState(this, state, s->get_g() + cost,
s->get_x(), s->get_y() + 1));
}
return children;
}
/**
* Get the x-coordinate of the goal.
* \return the x-coordinate of the goal.
*/
int GridWorld::get_goal_x(void) const
{
return goal_x;
}
/**
* Get the y-coordinate of the goal.
* \return the y-coordinate of the goal.
*/
int GridWorld::get_goal_y(void) const
{
return goal_y;
}
/**
* Get the world width.
* \return The world width.
*/
int GridWorld::get_width(void) const
{
return width;
}
/**
* Get the world height.
* \return The world height.
*/
int GridWorld::get_height(void) const
{
return height;
}
/**
* Test if there is an obstacle at the given location.
*/
bool GridWorld::is_obstacle(int x, int y) const
{
map<int, bool>::const_iterator iter;
iter = obstacles.find(width * y + x);
return iter != obstacles.end();
}
/**
* Prints the grid world to the given stream.
* \param o The output stream to print to.
* \param path An optional parameter that is a vector of states that
* form a path in the world. If given, this path will be displayed.
*/
void GridWorld::print(ostream &o, const vector<const State *> *path = NULL) const
{
o << height << " " << width << endl;
o << "Board:" << endl;
for (int h = 0; h < height; h += 1) {
for (int w = 0; w < width; w += 1) {
if (is_obstacle(w, h))
o << "#";
else if (path && on_path(path, w, h))
o << "o";
else
o << " ";
}
o << endl;;
}
o << "Unit" << endl;
o << "Four-way" << endl;
o << start_x << " " << start_y << "\t" << goal_x << " " << goal_y << endl;
}
/**
* Test whether or not a location is on the given path.
* \param path The path.
* \param x The x-coordinate to test.
* \param y The y-coordinate to test.
*/
bool GridWorld::on_path(const vector<const State *> *path, int x, int y) const
{
if (!path)
return false;
for (unsigned int i = 0; i < path->size(); i += 1) {
const GridState *s = dynamic_cast<const GridState *>(path->at(i));
if (s->get_x() == x && s->get_y() == y)
return true;
}
return false;
}
#if defined(ENABLE_IMAGES)
/**
* Mark a state as expanded, if this was the first time that the state
* was expanded, it is marked in the states field so that we can make
* a display of when each state was expanded.
* \param s The state that was expanded.
*/
void GridWorld::expanded_state(const GridState *s)
{
int index = s->get_y() * width + s->get_x();
// this should be made atomic
if (states[index] == 0)
states[index] = expanded;
}
/**
* Export an image of the order of state expansions to an encapsulated
* post script file.
* \param file The name of the file to export to.
*/
void GridWorld::export_eps(string file) const
{
const int min_size = 500;
int granularity = expanded < 500 ? 500 / expanded : expanded / 500;
string data;
EPS image(width, height);
if (width < min_size && height < min_size) {
float min_side = width < height ? width : height;
image.set_scale(min_size / min_side);
}
// Image red data
for (int y = height - 1; y >= 0; y -= 1) {
for (int x = 0; x < width; x += 1) {
int i = y * width + x;
char red, green, blue;
if (is_obstacle(x, y)) {
// black
red = green = blue = 0x00;
} else if (states[i] == 0) {
// white
red = green = blue = 0xFF;
} else {
// A certain shade of orange
int number = states[i];
int x = expanded < 500 ? number * granularity
: number / granularity;
if (x < 125) {
red = 255;
green = 255;
blue = 125 - x;
} else if (x < 380) {
red = 255;
green = 255 - (x - 125);
blue = 0;
} else {
red = 255 - (x - 380);
green = blue = 0;
}
}
data += red;
data += green;
data += blue;
}
}
image.set_data(data);
image.output(file);
}
#endif // ENABLE_IMAGES
<|endoftext|> |
<commit_before>#include <QTimer>
#include "server-status-service.h"
#include "seafile-applet.h"
#include "account-mgr.h"
#include "api/api-error.h"
#include "api/requests.h"
namespace {
const int kRefreshInterval = 3 * 60 * 1000; // 3 min
const int kRefreshIntervalForUnconnected = 30 * 1000; // 30 sec
}
SINGLETON_IMPL(ServerStatusService)
ServerStatusService::ServerStatusService(QObject *parent)
: QObject(parent)
{
refresh_timer_ = new QTimer(this);
refresh_unconnected_timer_ = new QTimer(this);
connect(refresh_timer_, SIGNAL(timeout()),
this, SLOT(refresh()));
connect(refresh_unconnected_timer_, SIGNAL(timeout()),
this, SLOT(refreshUnconnected()));
refresh();
}
void ServerStatusService::start()
{
refresh_timer_->start(kRefreshInterval);
refresh_unconnected_timer_->start(kRefreshIntervalForUnconnected);
}
void ServerStatusService::stop()
{
refresh_timer_->stop();
refresh_unconnected_timer_->stop();
}
void ServerStatusService::refresh(bool only_refresh_unconnected)
{
const std::vector<Account>& accounts = seafApplet->accountManager()->accounts();
for (int i = 0; i < accounts.size(); i++) {
const QUrl& url = accounts[i].serverUrl;
if (requests_.contains(url.host())) {
return;
}
if (!statuses_.contains(url.host())) {
statuses_[url.host()] = ServerStatus(url, false);
}
if (only_refresh_unconnected && isServerConnected(url)) {
return;
}
pingServer(url);
}
}
void ServerStatusService::pingServer(const QUrl& url)
{
PingServerRequest *req = new PingServerRequest(url);
connect(req, SIGNAL(success()),
this, SLOT(onPingServerSuccess()));
connect(req, SIGNAL(failed(const ApiError&)),
this, SLOT(onPingServerFailed()));
req->setIgnoreSslErrors(true);
req->send();
requests_[url.host()] = req;
}
void ServerStatusService::onPingServerSuccess()
{
PingServerRequest *req = (PingServerRequest *)sender();
statuses_[req->url().host()] = ServerStatus(req->url(), true);
emit serverStatusChanged();
requests_.remove(req->url().host());
}
void ServerStatusService::onPingServerFailed()
{
PingServerRequest *req = (PingServerRequest *)sender();
statuses_[req->url().host()] = ServerStatus(req->url(), false);
emit serverStatusChanged();
requests_.remove(req->url().host());
}
bool ServerStatusService::allServersConnected() const
{
foreach (const ServerStatus& status, statuses()) {
if (!status.connected) {
return false;
}
}
return true;
}
bool ServerStatusService::allServersDisconnected() const
{
foreach (const ServerStatus& status, statuses()) {
if (status.connected) {
return false;
}
}
return true;
}
bool ServerStatusService::isServerConnected(const QUrl& url) const
{
return statuses_.value(url.host()).connected;
}
<commit_msg>fix memory leaks when the client pings<commit_after>#include <QTimer>
#include "server-status-service.h"
#include "seafile-applet.h"
#include "account-mgr.h"
#include "api/api-error.h"
#include "api/requests.h"
namespace {
const int kRefreshInterval = 3 * 60 * 1000; // 3 min
const int kRefreshIntervalForUnconnected = 30 * 1000; // 30 sec
}
SINGLETON_IMPL(ServerStatusService)
ServerStatusService::ServerStatusService(QObject *parent)
: QObject(parent)
{
refresh_timer_ = new QTimer(this);
refresh_unconnected_timer_ = new QTimer(this);
connect(refresh_timer_, SIGNAL(timeout()),
this, SLOT(refresh()));
connect(refresh_unconnected_timer_, SIGNAL(timeout()),
this, SLOT(refreshUnconnected()));
refresh();
}
void ServerStatusService::start()
{
refresh_timer_->start(kRefreshInterval);
refresh_unconnected_timer_->start(kRefreshIntervalForUnconnected);
}
void ServerStatusService::stop()
{
refresh_timer_->stop();
refresh_unconnected_timer_->stop();
}
void ServerStatusService::refresh(bool only_refresh_unconnected)
{
const std::vector<Account>& accounts = seafApplet->accountManager()->accounts();
for (size_t i = 0; i < accounts.size(); i++) {
const QUrl& url = accounts[i].serverUrl;
if (requests_.contains(url.host())) {
return;
}
if (!statuses_.contains(url.host())) {
statuses_[url.host()] = ServerStatus(url, false);
}
if (only_refresh_unconnected && isServerConnected(url)) {
return;
}
pingServer(url);
}
}
void ServerStatusService::pingServer(const QUrl& url)
{
PingServerRequest *req = new PingServerRequest(url);
connect(req, SIGNAL(success()),
this, SLOT(onPingServerSuccess()));
connect(req, SIGNAL(failed(const ApiError&)),
this, SLOT(onPingServerFailed()));
req->setIgnoreSslErrors(true);
req->send();
requests_[url.host()] = req;
}
void ServerStatusService::onPingServerSuccess()
{
PingServerRequest *req = (PingServerRequest *)sender();
statuses_[req->url().host()] = ServerStatus(req->url(), true);
emit serverStatusChanged();
requests_.take(req->url().host())->deleteLater();
}
void ServerStatusService::onPingServerFailed()
{
PingServerRequest *req = (PingServerRequest *)sender();
statuses_[req->url().host()] = ServerStatus(req->url(), false);
emit serverStatusChanged();
requests_.take(req->url().host())->deleteLater();
}
bool ServerStatusService::allServersConnected() const
{
foreach (const ServerStatus& status, statuses()) {
if (!status.connected) {
return false;
}
}
return true;
}
bool ServerStatusService::allServersDisconnected() const
{
foreach (const ServerStatus& status, statuses()) {
if (status.connected) {
return false;
}
}
return true;
}
bool ServerStatusService::isServerConnected(const QUrl& url) const
{
return statuses_.value(url.host()).connected;
}
<|endoftext|> |
<commit_before>// (C) 2014 Arek Olek
#include <functional>
#include <unordered_map>
#include <boost/functional/hash.hpp>
#include <boost/graph/adjacency_matrix.hpp>
#include "debug.hpp"
#include "range.hpp"
namespace detail {
boost::adjacency_matrix<boost::undirectedS> typedef graph;
}
namespace std {
template<typename S, typename T>
struct hash<pair<S, T>> {
inline size_t operator()(const pair<S, T> & v) const {
size_t seed = 0;
boost::hash_combine(seed, v.first);
boost::hash_combine(seed, v.second);
return seed;
}
};
}
template <class Graph>
class leaf_info {
public:
leaf_info(Graph const & T_) : T(T_) {
update();
}
bool is_path() const {
return L.size() == 2;
}
std::vector<unsigned> const & leaves() const {
return L;
}
unsigned branching(unsigned l) const {
// b(l)
return B.at(l);
}
unsigned parent(unsigned x, unsigned l) const {
// x->l
return P.at(uintpair(l, x));
}
unsigned branching_neighbor(unsigned l) const {
// b(l)->l
return parent(branching(l), l);
}
unsigned branching_neighbor(unsigned l, unsigned x) const {
// b(l)->x
return BN.at(uintpair(l, x));
}
bool on_branch(unsigned l, unsigned x) const {
return l == x || branching(l) == x || BN.count(uintpair(l, x)) == 0;
}
bool is_short(unsigned l) {
return parent(branching(l), l) == l;
}
void update() {
L.clear();
B.clear();
P.clear();
BN.clear();
for(auto v : range(vertices(T)))
if(degree(v, T) == 1) {
L.push_back(v);
traverse(v, T);
}
}
void traverse(unsigned l, Graph const & T) {
traverse(l, l, l, T);
}
void traverse(unsigned l, unsigned a, unsigned b, Graph const & T) {
do {
std::tie(a, b) = next(a, b, T);
P[uintpair(l, b)] = a;
} while(degree(b, T) == 2);
if(degree(b, T) > 2) {
B[l] = b;
for(auto v : range(adjacent_vertices(b, T)))
if(v != a)
traverse(l, v, b, v, T);
}
}
void traverse(unsigned l, unsigned blx, unsigned a, unsigned b, Graph const & T) {
P[uintpair(l, b)] = a;
BN[uintpair(l, b)] = blx;
while(degree(b, T) == 2) {
std::tie(a, b) = next(a, b, T);
P[uintpair(l, b)] = a;
BN[uintpair(l, b)] = blx;
}
if(degree(b, T) > 2) {
for(auto v : range(adjacent_vertices(b, T)))
if(v != a)
traverse(l, blx, b, v, T);
}
}
std::pair<unsigned, unsigned> next(unsigned a, unsigned b, Graph const & T) {
auto it = adjacent_vertices(b, T).first;
return std::make_pair(b, a == *it ? *(++it) : *it);
}
private:
Graph const& T;
std::vector<unsigned> L;
std::pair<unsigned, unsigned> typedef uintpair;
std::unordered_map<unsigned, unsigned> B;
std::unordered_map<uintpair, unsigned> P, BN;
};
class prieto {
public:
template<class Graph, class Tree>
int operator()(Graph& G, Tree& T) {
//detail::graph M(num_vertices(G));
//detail::copy_edges(G, M);
leaf_info<Tree> info(T);
int i = -1;
do {
++i;
//show("tree" + std::to_string(i++) + ".dot", M, T);
} while(!info.is_path() && rule2(G, T, info));
return i;
}
};
template <class Graph, class Tree, class LeafInfo>
bool rule1(Graph& G, Tree& T, LeafInfo& info) {
for(auto l1 : info.leaves())
for(auto l2 : info.leaves())
if(edge(l1, l2, G).second) {
auto x = l1;
auto y = *adjacent_vertices(l1, T).first;
while(y != l2) {
x = y;
y = info.parent(y, l2);
if(degree(x, T) > 2 && degree(y, T) > 2) {
add_edge(l1, l2, T);
remove_edge(x, y, T);
info.update();
return true;
}
}
}
return false;
}
template <class Graph, class Tree, class LeafInfo>
bool rule2(Graph& G, Tree& T, LeafInfo& info) {
for(auto l1 : info.leaves())
for(auto l2 : info.leaves())
if(edge(l1, l2, G).second) {
add_edge(l1, l2, T);
auto b = info.branching(l1);
remove_edge(b, info.parent(b, l1), T);
info.update();
return true;
}
return false;
}
template <class Graph, class Tree, class LeafInfo>
bool rule3(Graph& G, Tree& T, LeafInfo& info) {
for(auto l : info.leaves())
for(auto x : range(adjacent_vertices(l, G)))
if(!info.on_branch(l, x)) {
auto xl = info.parent(x, l);
if(degree(xl, T) > 2) {
add_edge(l, x, T);
remove_edge(x, xl, T);
info.update();
return true;
}
}
return false;
}
template <class Graph, class Tree, class LeafInfo>
bool rule4(Graph& G, Tree& T, LeafInfo& info) {
int n = num_vertices(G);
std::vector<std::vector<std::pair<int,int>>> extra(n);
for(auto l : info.leaves())
for(auto x : range(adjacent_vertices(l, G)))
if(!info.on_branch(l, x)) {
auto xl = info.parent(x, l);
if(degree(xl, T) == 2)
extra[xl].emplace_back(l, x);
}
for(int l2 : info.leaves())
for(int xl = 0; xl < n; ++xl)
if(!extra[xl].empty() && edge(l2, xl, G).second) {
int l, x;
if(extra[xl].size() == 1 && extra[xl].begin()->first == l2) continue;
std::tie(l, x) = extra[xl].begin()->first == l2 ? *(extra[xl].begin()+1) : *extra[xl].begin();
add_edge(l, x, T);
remove_edge(x, xl, T);
info.update();
add_edge(l2, xl, T);
auto b = info.branching(l2);
remove_edge(b, info.parent(b, l2), T);
info.update();
return true;
}
return false;
}
template <class Graph, class Tree, class LeafInfo>
bool rule5(Graph& G, Tree& T, LeafInfo& info) {
for(auto l : info.leaves())
for(auto x : range(adjacent_vertices(l, G)))
if(!info.on_branch(l, x)) {
auto bl = info.branching(l);
auto blx = info.branching_neighbor(l, x);
if(degree(blx, T) > 2) {
add_edge(l, x, T);
remove_edge(bl, blx, T);
info.update();
return true;
}
}
return false;
}
template <class Graph, class Tree, class LeafInfo>
bool rule6(Graph& G, Tree& T, LeafInfo& info) {
int n = num_vertices(G);
std::vector<std::vector<std::pair<int,int>>> extra(n);
for(auto l : info.leaves())
for(auto x : range(adjacent_vertices(l, G)))
if(!info.on_branch(l, x)) {
auto blx = info.branching_neighbor(l, x);
if(degree(blx, T) == 2) {
extra[blx].emplace_back(l, x);
}
}
for(int l2 : info.leaves())
for(int blx = 0; blx < n; ++blx)
if(!extra[blx].empty() && edge(l2, blx, G).second) {
int l, x;
if(extra[blx].size() == 1 && extra[blx].begin()->first == l2) continue;
std::tie(l, x) = extra[blx].begin()->first == l2 ? *(extra[blx].begin()+1) : *extra[blx].begin();
add_edge(l, x, T);
remove_edge(info.branching(l), blx, T);
info.update();
add_edge(l2, blx, T);
auto b = info.branching(l2);
remove_edge(b, info.parent(b, l2), T);
info.update();
return true;
}
return false;
}
template <class Graph, class Tree, class LeafInfo>
bool rule7(Graph& G, Tree& T, LeafInfo& info) {
for(auto e : range(edges(T))) {
auto x = source(e, T);
auto y = target(e, T);
for(auto l : info.leaves()) {
if(info.is_short(l)
&& !edge(l, x, T).second && !edge(l, y, T).second
&& edge(l, x, G).second && edge(l, y, G).second) {
add_edge(l, x, T);
add_edge(l, y, T);
remove_edge(x, y, T);
remove_edge(l, info.branching(l), T);
info.update();
return true;
}
}
}
return false;
}
template <class Graph, class Tree, class LeafInfo>
bool rule8(Graph& G, Tree& T, LeafInfo& info) {
for(auto l1 : info.leaves()) if(!info.is_short(l1)) {
for(auto l2 : info.leaves()) if(/*!info.is_short(l2) && */l1 != l2) {
auto bl = info.branching(l1);
auto blp = info.parent(bl, l1);
if(edge(blp, l2, G).second) {
add_edge(blp, l2, T);
remove_edge(blp, bl, T);
info.update();
return true;
}
}
}
return false;
}
class lost_light {
public:
template <class Graph, class Tree>
int operator() (Graph& G, Tree& T) {
leaf_info<Tree> info(T);
std::function<bool(Graph&,Tree&,leaf_info<Tree>&)> typedef rule;
std::vector<rule> rules {
rule2<Graph,Tree,leaf_info<Tree>>,
rule3<Graph,Tree,leaf_info<Tree>>,
rule4<Graph,Tree,leaf_info<Tree>>,
rule5<Graph,Tree,leaf_info<Tree>>,
rule6<Graph,Tree,leaf_info<Tree>>,
};
int i = 0;
bool applied = true;
while(applied && !info.is_path()) {
applied = false;
for(auto rule : rules) {
if(rule(G, T, info)) {
++i;
applied = true;
break;
}
}
}
return i;
}
};
class lost {
public:
template <class Graph, class Tree>
int operator() (Graph& G, Tree& T) {
leaf_info<Tree> info(T);
std::function<bool(Graph&,Tree&,leaf_info<Tree>&)> typedef rule;
std::vector<rule> rules {
rule1<Graph,Tree,leaf_info<Tree>>,
rule2<Graph,Tree,leaf_info<Tree>>,
rule3<Graph,Tree,leaf_info<Tree>>,
rule4<Graph,Tree,leaf_info<Tree>>,
rule5<Graph,Tree,leaf_info<Tree>>,
rule6<Graph,Tree,leaf_info<Tree>>,
rule7<Graph,Tree,leaf_info<Tree>>,
rule8<Graph,Tree,leaf_info<Tree>>,
};
int i = 0;
bool applied = true;
while(applied && !info.is_path()) {
applied = false;
for(auto rule : rules) {
if(rule(G, T, info)) {
++i;
applied = true;
break;
}
}
}
return i;
}
};
<commit_msg>rule 9<commit_after>// (C) 2014 Arek Olek
#include <functional>
#include <unordered_map>
#include <boost/functional/hash.hpp>
#include <boost/graph/adjacency_matrix.hpp>
#include "debug.hpp"
#include "range.hpp"
namespace detail {
boost::adjacency_matrix<boost::undirectedS> typedef graph;
}
namespace std {
template<typename S, typename T>
struct hash<pair<S, T>> {
inline size_t operator()(const pair<S, T> & v) const {
size_t seed = 0;
boost::hash_combine(seed, v.first);
boost::hash_combine(seed, v.second);
return seed;
}
};
}
template <class Graph>
class leaf_info {
public:
leaf_info(Graph const & T_) : T(T_) {
update();
}
bool is_path() const {
return L.size() == 2;
}
std::vector<unsigned> const & leaves() const {
return L;
}
unsigned branching(unsigned l) const {
// b(l)
return B.at(l);
}
unsigned parent(unsigned x, unsigned l) const {
// x->l
return P.at(uintpair(l, x));
}
unsigned branching_neighbor(unsigned l) const {
// b(l)->l
return parent(branching(l), l);
}
unsigned branching_neighbor(unsigned l, unsigned x) const {
// b(l)->x
return BN.at(uintpair(l, x));
}
unsigned branch(unsigned x) const {
// l: x ∈ br(l)
return BR.find(x)->second;
}
bool on_branch(unsigned l, unsigned x) const {
return l == x || branching(l) == x || (on_trunk(x) ? false : branch(x) == l);
}
bool on_trunk(unsigned x) const {
return BR.count(x) == 0;
}
bool is_short(unsigned l) const {
return parent(branching(l), l) == l;
}
void update() {
L.clear();
B.clear();
P.clear();
BN.clear();
BR.clear();
for(auto v : range(vertices(T)))
if(degree(v, T) == 1) {
L.push_back(v);
traverse(v, T);
}
}
void traverse(unsigned l, Graph const & T) {
traverse(l, l, l, T);
}
void traverse(unsigned l, unsigned a, unsigned b, Graph const & T) {
do {
std::tie(a, b) = next(a, b, T);
P[uintpair(l, b)] = a;
BR.emplace(a, l);
} while(degree(b, T) == 2);
BR.emplace(b, l);
if(degree(b, T) > 2) {
B[l] = b;
for(auto v : range(adjacent_vertices(b, T)))
if(v != a)
traverse(l, v, b, v, T);
}
}
void traverse(unsigned l, unsigned blx, unsigned a, unsigned b, Graph const & T) {
P[uintpair(l, b)] = a;
BN[uintpair(l, b)] = blx;
while(degree(b, T) == 2) {
std::tie(a, b) = next(a, b, T);
P[uintpair(l, b)] = a;
BN[uintpair(l, b)] = blx;
}
if(degree(b, T) > 2) {
for(auto v : range(adjacent_vertices(b, T)))
if(v != a)
traverse(l, blx, b, v, T);
}
}
std::pair<unsigned, unsigned> next(unsigned a, unsigned b, Graph const & T) {
auto it = adjacent_vertices(b, T).first;
return std::make_pair(b, a == *it ? *(++it) : *it);
}
private:
Graph const& T;
std::vector<unsigned> L;
std::pair<unsigned, unsigned> typedef uintpair;
std::unordered_multimap<unsigned, unsigned> BR;
std::unordered_map<unsigned, unsigned> B;
std::unordered_map<uintpair, unsigned> P, BN;
};
class prieto {
public:
template<class Graph, class Tree>
int operator()(Graph& G, Tree& T) {
//detail::graph M(num_vertices(G));
//detail::copy_edges(G, M);
leaf_info<Tree> info(T);
int i = -1;
do {
++i;
//show("tree" + std::to_string(i++) + ".dot", M, T);
} while(!info.is_path() && rule2(G, T, info));
return i;
}
};
template <class Graph, class Tree, class LeafInfo>
bool rule1(Graph& G, Tree& T, LeafInfo& info) {
for(auto l1 : info.leaves())
for(auto l2 : info.leaves())
if(edge(l1, l2, G).second) {
auto x = l1;
auto y = *adjacent_vertices(l1, T).first;
while(y != l2) {
x = y;
y = info.parent(y, l2);
if(degree(x, T) > 2 && degree(y, T) > 2) {
add_edge(l1, l2, T);
remove_edge(x, y, T);
info.update();
return true;
}
}
}
return false;
}
template <class Graph, class Tree, class LeafInfo>
bool rule2(Graph& G, Tree& T, LeafInfo& info) {
for(auto l1 : info.leaves())
for(auto l2 : info.leaves())
if(edge(l1, l2, G).second) {
add_edge(l1, l2, T);
auto b = info.branching(l1);
remove_edge(b, info.parent(b, l1), T);
info.update();
return true;
}
return false;
}
template <class Graph, class Tree, class LeafInfo>
bool rule3(Graph& G, Tree& T, LeafInfo& info) {
for(auto l : info.leaves())
for(auto x : range(adjacent_vertices(l, G)))
if(!info.on_branch(l, x)) {
auto xl = info.parent(x, l);
if(degree(xl, T) > 2) {
add_edge(l, x, T);
remove_edge(x, xl, T);
info.update();
return true;
}
}
return false;
}
template <class Graph, class Tree, class LeafInfo>
bool rule4(Graph& G, Tree& T, LeafInfo& info) {
int n = num_vertices(G);
std::vector<std::vector<std::pair<int,int>>> extra(n);
for(auto l : info.leaves())
for(auto x : range(adjacent_vertices(l, G)))
if(!info.on_branch(l, x)) {
auto xl = info.parent(x, l);
if(degree(xl, T) == 2)
extra[xl].emplace_back(l, x);
}
for(int l2 : info.leaves())
for(int xl = 0; xl < n; ++xl)
if(!extra[xl].empty() && edge(l2, xl, G).second) {
int l, x;
if(extra[xl].size() == 1 && extra[xl].begin()->first == l2) continue;
std::tie(l, x) = extra[xl].begin()->first == l2 ? *(extra[xl].begin()+1) : *extra[xl].begin();
add_edge(l, x, T);
remove_edge(x, xl, T);
info.update();
add_edge(l2, xl, T);
auto b = info.branching(l2);
remove_edge(b, info.parent(b, l2), T);
info.update();
return true;
}
return false;
}
template <class Graph, class Tree, class LeafInfo>
bool rule5(Graph& G, Tree& T, LeafInfo& info) {
for(auto l : info.leaves())
for(auto x : range(adjacent_vertices(l, G)))
if(!info.on_branch(l, x)) {
auto bl = info.branching(l);
auto blx = info.branching_neighbor(l, x);
if(degree(blx, T) > 2) {
add_edge(l, x, T);
remove_edge(bl, blx, T);
info.update();
return true;
}
}
return false;
}
template <class Graph, class Tree, class LeafInfo>
bool rule6(Graph& G, Tree& T, LeafInfo& info) {
int n = num_vertices(G);
std::vector<std::vector<std::pair<int,int>>> extra(n);
for(auto l : info.leaves())
for(auto x : range(adjacent_vertices(l, G)))
if(!info.on_branch(l, x)) {
auto blx = info.branching_neighbor(l, x);
if(degree(blx, T) == 2) {
extra[blx].emplace_back(l, x);
}
}
for(int l2 : info.leaves())
for(int blx = 0; blx < n; ++blx)
if(!extra[blx].empty() && edge(l2, blx, G).second) {
int l, x;
if(extra[blx].size() == 1 && extra[blx].begin()->first == l2) continue;
std::tie(l, x) = extra[blx].begin()->first == l2 ? *(extra[blx].begin()+1) : *extra[blx].begin();
add_edge(l, x, T);
remove_edge(info.branching(l), blx, T);
info.update();
add_edge(l2, blx, T);
auto b = info.branching(l2);
remove_edge(b, info.parent(b, l2), T);
info.update();
return true;
}
return false;
}
template <class Graph, class Tree, class LeafInfo>
bool rule7(Graph& G, Tree& T, LeafInfo& info) {
for(auto e : range(edges(T))) {
auto x = source(e, T);
auto y = target(e, T);
for(auto l : info.leaves()) {
if(info.is_short(l)
&& !edge(l, x, T).second && !edge(l, y, T).second
&& edge(l, x, G).second && edge(l, y, G).second) {
add_edge(l, x, T);
add_edge(l, y, T);
remove_edge(x, y, T);
remove_edge(l, info.branching(l), T);
info.update();
return true;
}
}
}
return false;
}
template <class Graph, class Tree, class LeafInfo>
bool rule8(Graph& G, Tree& T, LeafInfo& info) {
for(auto l1 : info.leaves()) if(!info.is_short(l1)) {
for(auto l2 : info.leaves()) if(/*!info.is_short(l2) && */l1 != l2) {
auto bl = info.branching(l1);
auto blp = info.parent(bl, l1);
if(edge(blp, l2, G).second) {
add_edge(blp, l2, T);
remove_edge(blp, bl, T);
info.update();
return true;
}
}
}
return false;
}
template <class Graph, class Tree, class LeafInfo>
bool rule9(Graph& G, Tree& T, LeafInfo& info) {
std::vector<unsigned> lg;
for(auto l : info.leaves())
if(!info.is_short(l))
lg.push_back(l);
unsigned n = lg.size();
std::vector<bool> m(n * n);
enumerate(lg, [&](unsigned i, unsigned l1) {
enumerate(lg, [&](unsigned j, unsigned l2) {
m[i*n + j] =
info.branching(l1) != info.branching(l2) &&
edge(
info.branching_neighbor(l1),
info.branching_neighbor(l2),
G).second;
});
});
enumerate(lg, [&](unsigned i, unsigned l1) {
unsigned count = 0, l2 = 0;
bool ok = false;
for(auto x : range(adjacent_vertices(l1, G)))
if(!info.on_branch(l1, x)) {
++count;
if(info.on_trunk(x) || degree(x, T) > 2)
ok = true;
else if(count == 1)
l2 = info.branch(x);
else if(l2 != info.branch(x))
ok = true;
if(ok) break;
}
if(count == 0)
for(unsigned j = 0; j < lg.size(); ++j)
m[i*n + j] = false;
else if(!ok)
for(unsigned j = 0; j < lg.size(); ++j)
if(lg[j] == l2)
m[i*n + j] = false;
});
for(unsigned i = 0; i < lg.size(); ++i) {
unsigned l1 = lg[i];
for(unsigned j = 0; j < lg.size(); ++j) {
unsigned l2 = lg[j];
if(m[i*n + j]) {
for(auto x : range(adjacent_vertices(l1, G)))
if(!info.on_branch(l1, x) && (!info.on_branch(l2, x) || degree(x, T) > 2)) {
show("nine1.dot", G, T);
unsigned bn1 = info.branching_neighbor(l1);
unsigned bn2 = info.branching_neighbor(l2);
add_edge(l1, x, T);
add_edge(bn1, bn2, T);
remove_edge(info.branching(l1), bn1, T);
remove_edge(info.branching(l2), bn2, T);
info.update();
show("nine2.dot", G, T);
return true;
}
assert(false);
}
}
}
return false;
}
class lost_light {
public:
template <class Graph, class Tree>
int operator() (Graph& G, Tree& T) {
leaf_info<Tree> info(T);
std::function<bool(Graph&,Tree&,leaf_info<Tree>&)> typedef rule;
std::vector<rule> rules {
rule2<Graph,Tree,leaf_info<Tree>>,
rule3<Graph,Tree,leaf_info<Tree>>,
rule4<Graph,Tree,leaf_info<Tree>>,
rule5<Graph,Tree,leaf_info<Tree>>,
rule6<Graph,Tree,leaf_info<Tree>>,
};
int i = 0;
bool applied = true;
while(applied && !info.is_path()) {
applied = false;
for(auto rule : rules) {
if(rule(G, T, info)) {
++i;
applied = true;
break;
}
}
}
return i;
}
};
class lost {
public:
template <class Graph, class Tree>
int operator() (Graph& G, Tree& T) {
leaf_info<Tree> info(T);
std::function<bool(Graph&,Tree&,leaf_info<Tree>&)> typedef rule;
std::vector<rule> rules {
rule1<Graph,Tree,leaf_info<Tree>>,
rule2<Graph,Tree,leaf_info<Tree>>,
rule3<Graph,Tree,leaf_info<Tree>>,
rule4<Graph,Tree,leaf_info<Tree>>,
rule5<Graph,Tree,leaf_info<Tree>>,
rule6<Graph,Tree,leaf_info<Tree>>,
rule7<Graph,Tree,leaf_info<Tree>>,
rule8<Graph,Tree,leaf_info<Tree>>,
rule9<Graph,Tree,leaf_info<Tree>>,
};
int i = 0;
bool applied = true;
while(applied && !info.is_path()) {
applied = false;
for(auto rule : rules) {
if(rule(G, T, info)) {
++i;
applied = true;
break;
}
}
}
return i;
}
};
<|endoftext|> |
<commit_before>#include <iostream>
#include <queue>
#include <stdio.h>
using namespace std;
#include "Binary-tree.hpp"
#include "pretty-print.hpp"
// Функция создает сбалансированное дерево и возращает корневой узел дерева
Node* createBalancedTree(Node** node, int *&val, int cnt, int depth)
{
if (cnt <= 0)
return NULL;
if ((*node) == NULL) {
(*node) = new Node(*val);
++val;
--cnt;
}
int cntl = cnt / 2;
int cntr = cnt - cntl;
if (cntl > 0) {
createBalancedTree(&(*node)->left, val, cntl);
}
if (cntr > 0) {
createBalancedTree(&(*node)->right, val, cntr);
}
return (*node);
}
int main()
{
#define ARRSIZE 11
int data[ARRSIZE] = {25, 50, 10, 5, 30, 55, 0, 40, 35, 15, 45};
for (int i = 0; i < ARRSIZE; i++)
cout << data[i] << " ";
cout << endl << endl;
// Создаем переменную узла и сохраняем в неё корневой узел хаотично заполненного дерева
//printPretty(createSampleTree());
// Exer.1 - Balanced B-Tree
Node* node = NULL;
int *it = (int *)&data;
printf("before it: %p\n", it);
printPretty(createBalancedTree(&node, it, ARRSIZE, 0));
printf("after it: %p\n", it);
return 0;
}
<commit_msg>#fix build<commit_after>#include <iostream>
#include <queue>
#include <stdio.h>
using namespace std;
#include "Binary-tree.hpp"
#include "pretty-print.hpp"
// Функция создает сбалансированное дерево и возращает корневой узел дерева
Node* createBalancedTree(Node** node, int *&val, int cnt)
{
if (cnt <= 0)
return NULL;
if ((*node) == NULL) {
(*node) = new Node(*val);
++val;
--cnt;
}
int cntl = cnt / 2;
int cntr = cnt - cntl;
if (cntl > 0) {
createBalancedTree(&(*node)->left, val, cntl);
}
if (cntr > 0) {
createBalancedTree(&(*node)->right, val, cntr);
}
return (*node);
}
int main()
{
#define ARRSIZE 11
int data[ARRSIZE] = {25, 50, 10, 5, 30, 55, 0, 40, 35, 15, 45};
for (int i = 0; i < ARRSIZE; i++)
cout << data[i] << " ";
cout << endl << endl;
// Exer.1 - Balanced B-Tree
Node* node = NULL;
int *it = (int *)&data;
printPretty(createBalancedTree(&node, it, ARRSIZE));
return 0;
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <queue>
#include <stdio.h>
using namespace std;
#include "Binary-tree.hpp"
#include "pretty-print.hpp"
// Функция создает сбалансированное дерево и возращает корневой узел дерева
Node* createBalancedBTree(Node** node, int *&value, int cnt)
{
if (cnt <= 0)
return NULL;
if (node == NULL) {
Node* tmp = NULL;
node = &tmp;
}
if ((*node) == NULL) {
(*node) = new Node(*value);
++value;
--cnt;
}
int cntr = cnt / 2;
int cntl = cnt - cntr;
if (cntl > 0)
createBalancedBTree(&(*node)->left, value, cntl);
if (cntr > 0)
createBalancedBTree(&(*node)->right, value, cntr);
return (*node);
}
// Функция создает бинарное дерево поиска и возращает корневой узел дерева
Node* insertSearchBTree(Node** node, int value)
{
if ((*node) == NULL) {
(*node) = new Node(value);
return *node;
}
if ((*node)->data > value) {
return insertSearchBTree(&(*node)->left, value);
} else if ((*node)->data < value) {
return insertSearchBTree(&(*node)->right, value);
} else {
std::cout << "something going wrong! " << value << endl;
}
}
// Функция создает бинарное дерево поиска и возращает корневой узел дерева
Node* createSearchBTree(int *array, int size)
{
Node* node = NULL;
for (int i = 0; i < size; ++i)
insertSearchBTree(&node, array[i]);
return node;
}
void findRowsSumm(Node *node, int *rows, int currentDepth)
{
if (node == NULL)
return;
rows[currentDepth] += node->data;
findRowsSumm(node->left, rows, currentDepth+1);
findRowsSumm(node->right, rows, currentDepth+1);
}
int findRowWithMaxSumm(Node *node, int rowsCount)
{
if (node == NULL)
return -1;
int *rowsSumm = new int[rowsCount];
for (int i = 0; i < rowsCount; ++i)
rowsSumm[i] = 0;
findRowsSumm(node, rowsSumm, 0);
int maxRow = -1;
int maxValue = 0;
for (int i = 0; i < rowsCount; i++)
{
if ((rowsSumm[i] >= 0) && (rowsSumm[i] > maxValue)) {
maxRow = i;
maxValue = rowsSumm[i];
}
}
return maxRow;
}
int main()
{
int data[] = {35, 55, 15, 50, 40, 0, 10, 45, 5, 30, 25};
int size = sizeof(data) / (sizeof(data[0]));
cout << "Exer.1 - Balanced B-Tree" << endl;
int *it = (int *)&data;
Node* balancedBTreeRoot = createBalancedBTree(NULL, it, size);
printPretty(balancedBTreeRoot);
cout << endl;
cout << "Exer.2 - Search B-Tree" << endl;
Node* searchBTreeRoot = createSearchBTree(data, size);
printPretty(searchBTreeRoot);
cout << endl;
cout << "Exer.6 - Find row with max summ of values from search B-Tree" << endl;
printPretty(searchBTreeRoot);
cout << "Count starts from 0, -1 = no values found" << endl;
cout << "Answer is " << findRowWithMaxSumm(searchBTreeRoot, size) << endl;
cout << endl;
return 0;
}
<commit_msg>lab5 free nodes memory<commit_after>#include <iostream>
#include <queue>
#include <stdio.h>
using namespace std;
#include "Binary-tree.hpp"
#include "pretty-print.hpp"
// Функция создает сбалансированное дерево и возращает корневой узел дерева
Node* createBalancedBTree(Node** node, int *&value, int cnt)
{
if (cnt <= 0)
return NULL;
if (node == NULL) {
Node* tmp = NULL;
node = &tmp;
}
if ((*node) == NULL) {
(*node) = new Node(*value);
++value;
--cnt;
}
int cntr = cnt / 2;
int cntl = cnt - cntr;
if (cntl > 0)
createBalancedBTree(&(*node)->left, value, cntl);
if (cntr > 0)
createBalancedBTree(&(*node)->right, value, cntr);
return (*node);
}
// Функция создает бинарное дерево поиска и возращает корневой узел дерева
Node* insertSearchBTree(Node** node, int value)
{
if ((*node) == NULL) {
(*node) = new Node(value);
return *node;
}
if ((*node)->data > value) {
return insertSearchBTree(&(*node)->left, value);
} else if ((*node)->data < value) {
return insertSearchBTree(&(*node)->right, value);
} else {
std::cout << "something going wrong! " << value << endl;
}
}
// Функция создает бинарное дерево поиска и возращает корневой узел дерева
Node* createSearchBTree(int *array, int size)
{
Node* node = NULL;
for (int i = 0; i < size; ++i)
insertSearchBTree(&node, array[i]);
return node;
}
void findRowsSumm(Node *node, int *rows, int currentDepth)
{
if (node == NULL)
return;
rows[currentDepth] += node->data;
findRowsSumm(node->left, rows, currentDepth+1);
findRowsSumm(node->right, rows, currentDepth+1);
}
int findRowWithMaxSumm(Node *node, int rowsCount)
{
if (node == NULL)
return -1;
int *rowsSumm = new int[rowsCount];
for (int i = 0; i < rowsCount; ++i)
rowsSumm[i] = 0;
findRowsSumm(node, rowsSumm, 0);
int maxRow = -1;
int maxValue = 0;
for (int i = 0; i < rowsCount; i++)
{
if ((rowsSumm[i] >= 0) && (rowsSumm[i] > maxValue)) {
maxRow = i;
maxValue = rowsSumm[i];
}
}
delete [] rowsSumm;
return maxRow;
}
void destroyTree(Node *node) {
if (node != NULL) {
destroyTree(node->left);
destroyTree(node->right);
}
delete node;
}
int main()
{
int data[] = {35, 55, 15, 50, 40, 0, 10, 45, 5, 30, 25};
int size = sizeof(data) / (sizeof(data[0]));
cout << "Exer.1 - Balanced B-Tree" << endl;
int *it = (int *)&data;
Node* balancedBTreeRoot = createBalancedBTree(NULL, it, size);
printPretty(balancedBTreeRoot);
destroyTree(balancedBTreeRoot);
cout << endl;
cout << "Exer.2 - Search B-Tree" << endl;
Node* searchBTreeRoot = createSearchBTree(data, size);
printPretty(searchBTreeRoot);
// destroyTree(searchBTreeRoot);
cout << endl;
cout << "Exer.6 - Find row with max summ of values from search B-Tree" << endl;
printPretty(searchBTreeRoot);
int row = findRowWithMaxSumm(searchBTreeRoot, size);
destroyTree(searchBTreeRoot);
cout << "Count starts from 0, -1 = no values found" << endl;
cout << "Answer is " << row << endl;
cout << endl;
return 0;
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2015 Juniper Networks, Inc. All rights reserved.
*/
#include <sys/socket.h>
#if defined(__linux__)
#include <linux/netlink.h>
#elif defined(__FreeBSD__)
#include "vr_os.h"
#endif
#include <fcntl.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <asm/types.h>
#include <boost/asio.hpp>
#include <base/timer.h>
#include <base/task_trigger.h>
#include <net/address_util.h>
#include <cmn/agent_cmn.h>
#include <services/services_init.h>
#include <uve/stats_collector.h>
#include <services/icmp_error_proto.h>
#include <pkt/flow_proto.h>
#include <ksync/ksync_index.h>
#include <ksync/ksync_entry.h>
#include <ksync/ksync_object.h>
#include <ksync/ksync_netlink.h>
#include <ksync/ksync_sock.h>
#include <ksync/ksync_sock_user.h>
#include <vr_types.h>
#include <nl_util.h>
#include <vr_flow.h>
#include <vr_genetlink.h>
#include "ksync_init.h"
#include "ksync_flow_memory.h"
#include "sandesh_ksync.h"
#ifdef _WIN32
#include <windows_shmem_ioctl.h>
#endif
using namespace boost::asio::ip;
static const int kTestFlowTableSize = 131072 * sizeof(vr_flow_entry);
KSyncMemory::KSyncMemory(KSync *ksync, uint32_t minor_id) :
ksync_(ksync),
table_path_(),
major_devid_(0),
minor_devid_(minor_id),
table_size_(0),
table_entries_count_(0),
audit_timer_(TimerManager::CreateTimer
(*(ksync->agent()->event_manager())->io_service(),
" Audit Timer",
ksync->agent()->task_scheduler()->GetTaskId(kTaskFlowAudit),
0)),
audit_timeout_(0),
audit_yield_(0),
audit_interval_(0),
audit_idx_(0),
audit_list_() {
}
KSyncMemory::~KSyncMemory() {
TimerManager::DeleteTimer(audit_timer_);
}
void KSyncMemory::Init() {
audit_interval_ = kAuditYieldTimer;
audit_timeout_ = kAuditTimeout;
uint32_t table_count = table_entries_count_;
// Compute number of entries to visit per timer interval so that complete
// table can be visited in kAuditSweepTime
uint32_t timer_per_sec = 1000 / kAuditYieldTimer;
uint32_t timer_per_sweep = kAuditSweepTime * timer_per_sec;
audit_yield_ = table_count / timer_per_sweep;
if (audit_yield_ > kAuditYieldMax)
audit_yield_ = kAuditYieldMax;
if (audit_yield_ < kAuditYieldMin)
audit_yield_ = kAuditYieldMin;
audit_timer_->Start(audit_interval_,
boost::bind(&KSyncMemory::AuditProcess, this));
}
void KSyncMemory::Mmap(bool unlink_node) {
// Remove the existing /dev/ file first. We will add it again in vr_table_map
if (unlink_node) {
const char *error_msg = vr_table_unlink(table_path_.c_str());
if (error_msg) {
LOG(DEBUG, "Error unmapping KSync memory: " << error_msg);
assert(0);
}
}
const char *mmap_error_msg = vr_table_map(major_devid_, minor_devid_, table_path_.c_str(),
table_size_, &table_);
if (mmap_error_msg) {
LOG(DEBUG, "Error mapping KSync memory. Device: " << table_path_ << "; " << mmap_error_msg);
assert(0);
}
table_entries_count_ = table_size_ / get_entry_size();
SetTableSize();
}
// Steps to map table entry
// - Query the table parameters from kernel
// - Create device /dev/ with major-num and minor-num
// - Map device memory
void KSyncMemory::InitMem() {
struct nl_client *cl;
int attr_len;
int encode_len, ret;
assert((cl = nl_register_client()) != NULL);
#ifdef _WIN32
cl->cl_win_pipe = CreateFile(KSYNC_PATH, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
assert(cl->cl_win_pipe != INVALID_HANDLE_VALUE);
cl->cl_recvmsg = win_nl_client_recvmsg;
#else
assert(nl_socket(cl, AF_NETLINK, SOCK_DGRAM, NETLINK_GENERIC) > 0);
assert(nl_connect(cl, 0, 0) == 0);
#endif
assert(vrouter_obtain_family_id(cl) > 0);
assert(nl_build_nlh(cl, cl->cl_genl_family_id, NLM_F_REQUEST) == 0);
assert(nl_build_genlh(cl, SANDESH_REQUEST, 0) == 0);
attr_len = nl_get_attr_hdr_size();
encode_len = EncodeReq(cl, attr_len);
nl_build_attr(cl, encode_len, NL_ATTR_VR_MESSAGE_PROTOCOL);
nl_update_nlh(cl);
if ((ret = nl_sendmsg(cl)) < 0) {
LOG(DEBUG, "Error requesting Table message. Error : " << ret);
assert(0);
}
while ((ret = nl_recvmsg(cl)) > 0) {
KSyncSockNetlink::NetlinkDecoder(cl->cl_buf,
KSyncSock::GetAgentSandeshContext(0));
}
nl_free_client(cl);
Mmap(true);
return;
}
void KSyncMemory::InitTest() {
assert(0);
}
void KSyncMemory::Shutdown() {
assert(0);
}
bool KSyncMemory::AuditProcess() {
// Get current time
uint64_t t = UTCTimestampUsec();
while (!audit_list_.empty()) {
AuditEntry list_entry = audit_list_.front();
// audit_list_ is sorted on last time of insertion in the list
// So, break on finding first entry that cannot be aged
if ((t - list_entry.timeout) < audit_timeout_) {
/* Wait for audit_timeout_ to create short for the entry */
break;
}
uint32_t idx = list_entry.audit_idx;
uint32_t gen_id = list_entry.audit_gen_id;
audit_list_.pop_front();
DecrementHoldFlowCounter();
CreateProtoAuditEntry(idx, gen_id);
}
uint32_t count = 0;
uint8_t gen_id;
assert(audit_yield_);
while (count < audit_yield_) {
if (IsInactiveEntry(audit_idx_, gen_id)) {
IncrementHoldFlowCounter();
audit_list_.push_back(AuditEntry(audit_idx_, gen_id, t));
}
count++;
audit_idx_++;
if (audit_idx_ == table_entries_count_) {
UpdateAgentHoldFlowCounter();
audit_idx_ = 0;
}
}
return true;
}
#ifndef _WIN32
void KSyncMemory::GetTableSize() {
struct nl_client *cl;
int attr_len;
int encode_len;
assert((cl = nl_register_client()) != NULL);
cl->cl_genl_family_id = KSyncSock::GetNetlinkFamilyId();
assert(nl_build_nlh(cl, cl->cl_genl_family_id, NLM_F_REQUEST) == 0);
assert(nl_build_genlh(cl, SANDESH_REQUEST, 0) == 0);
attr_len = nl_get_attr_hdr_size();
encode_len = EncodeReq(cl, attr_len);
nl_build_attr(cl, encode_len, NL_ATTR_VR_MESSAGE_PROTOCOL);
nl_update_nlh(cl);
#ifdef AGENT_VROUTER_TCP
tcp::socket socket(*(ksync_->agent()->event_manager()->io_service()));
tcp::endpoint endpoint(ksync_->agent()->vrouter_server_ip(),
ksync_->agent()->vrouter_server_port());
#else
boost::asio::local::stream_protocol::socket
socket(*(ksync_->agent()->event_manager()->io_service()));
boost::asio::local::stream_protocol::endpoint
endpoint(KSYNC_AGENT_VROUTER_SOCK_PATH);
#endif
boost::system::error_code ec;
socket.connect(endpoint, ec);
if (ec) {
assert(0);
}
socket.send(boost::asio::buffer(cl->cl_buf, cl->cl_buf_offset), 0, ec);
if (ec) {
assert(0);
}
uint32_t len_read = 0;
uint32_t data_len = sizeof(struct nlmsghdr);
while (len_read < data_len) {
len_read = socket.read_some(boost::asio::buffer(cl->cl_buf + len_read,
cl->cl_buf_len), ec);
if (ec) {
assert(0);
}
if (len_read > sizeof(struct nlmsghdr)) {
const struct nlmsghdr *nlh =
(const struct nlmsghdr *)((cl->cl_buf));
data_len = nlh->nlmsg_len;
}
}
KSyncSockNetlink::NetlinkDecoder(cl->cl_buf,
KSyncSock::GetAgentSandeshContext(0));
nl_free_client(cl);
}
void KSyncMemory::MapSharedMemory() {
GetTableSize();
Mmap(false);
}
#endif
<commit_msg>Committing on behalf of Naveen<commit_after>/*
* Copyright (c) 2015 Juniper Networks, Inc. All rights reserved.
*/
#include <sys/socket.h>
#if defined(__linux__)
#include <linux/netlink.h>
#elif defined(__FreeBSD__)
#include "vr_os.h"
#endif
#include <fcntl.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <asm/types.h>
#include <boost/asio.hpp>
#include <base/timer.h>
#include <base/task_trigger.h>
#include <net/address_util.h>
#include <cmn/agent_cmn.h>
#include <services/services_init.h>
#include <uve/stats_collector.h>
#include <services/icmp_error_proto.h>
#include <pkt/flow_proto.h>
#include <ksync/ksync_index.h>
#include <ksync/ksync_entry.h>
#include <ksync/ksync_object.h>
#include <ksync/ksync_netlink.h>
#include <ksync/ksync_sock.h>
#include <ksync/ksync_sock_user.h>
#include <vr_types.h>
#include <nl_util.h>
#include <vr_flow.h>
#include <ini_parser.h>
#include <vr_genetlink.h>
#include "ksync_init.h"
#include "ksync_flow_memory.h"
#include "sandesh_ksync.h"
#ifdef _WIN32
#include <windows_shmem_ioctl.h>
#endif
using namespace boost::asio::ip;
static const int kTestFlowTableSize = 131072 * sizeof(vr_flow_entry);
KSyncMemory::KSyncMemory(KSync *ksync, uint32_t minor_id) :
ksync_(ksync),
table_path_(),
major_devid_(0),
minor_devid_(minor_id),
table_size_(0),
table_entries_count_(0),
audit_timer_(TimerManager::CreateTimer
(*(ksync->agent()->event_manager())->io_service(),
" Audit Timer",
ksync->agent()->task_scheduler()->GetTaskId(kTaskFlowAudit),
0)),
audit_timeout_(0),
audit_yield_(0),
audit_interval_(0),
audit_idx_(0),
audit_list_() {
}
KSyncMemory::~KSyncMemory() {
TimerManager::DeleteTimer(audit_timer_);
}
void KSyncMemory::Init() {
audit_interval_ = kAuditYieldTimer;
audit_timeout_ = kAuditTimeout;
uint32_t table_count = table_entries_count_;
// Compute number of entries to visit per timer interval so that complete
// table can be visited in kAuditSweepTime
uint32_t timer_per_sec = 1000 / kAuditYieldTimer;
uint32_t timer_per_sweep = kAuditSweepTime * timer_per_sec;
audit_yield_ = table_count / timer_per_sweep;
if (audit_yield_ > kAuditYieldMax)
audit_yield_ = kAuditYieldMax;
if (audit_yield_ < kAuditYieldMin)
audit_yield_ = kAuditYieldMin;
audit_timer_->Start(audit_interval_,
boost::bind(&KSyncMemory::AuditProcess, this));
}
void KSyncMemory::Mmap(bool unlink_node) {
// Remove the existing /dev/ file first. We will add it again in vr_table_map
if (unlink_node) {
const char *error_msg = vr_table_unlink(table_path_.c_str());
if (error_msg) {
LOG(DEBUG, "Error unmapping KSync memory: " << error_msg);
assert(0);
}
}
parse_ini_file();
const char *mmap_error_msg = vr_table_map(major_devid_, minor_devid_, table_path_.c_str(),
table_size_, &table_);
if (mmap_error_msg) {
LOG(DEBUG, "Error mapping KSync memory. Device: " << table_path_ << "; " << mmap_error_msg);
assert(0);
}
table_entries_count_ = table_size_ / get_entry_size();
SetTableSize();
}
// Steps to map table entry
// - Query the table parameters from kernel
// - Create device /dev/ with major-num and minor-num
// - Map device memory
void KSyncMemory::InitMem() {
struct nl_client *cl;
int attr_len;
int encode_len, ret;
assert((cl = nl_register_client()) != NULL);
#ifdef _WIN32
cl->cl_win_pipe = CreateFile(KSYNC_PATH, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
assert(cl->cl_win_pipe != INVALID_HANDLE_VALUE);
cl->cl_recvmsg = win_nl_client_recvmsg;
#else
assert(nl_socket(cl, AF_NETLINK, SOCK_DGRAM, NETLINK_GENERIC) > 0);
assert(nl_connect(cl, 0, 0) == 0);
#endif
assert(vrouter_obtain_family_id(cl) > 0);
assert(nl_build_nlh(cl, cl->cl_genl_family_id, NLM_F_REQUEST) == 0);
assert(nl_build_genlh(cl, SANDESH_REQUEST, 0) == 0);
attr_len = nl_get_attr_hdr_size();
encode_len = EncodeReq(cl, attr_len);
nl_build_attr(cl, encode_len, NL_ATTR_VR_MESSAGE_PROTOCOL);
nl_update_nlh(cl);
if ((ret = nl_sendmsg(cl)) < 0) {
LOG(DEBUG, "Error requesting Table message. Error : " << ret);
assert(0);
}
while ((ret = nl_recvmsg(cl)) > 0) {
KSyncSockNetlink::NetlinkDecoder(cl->cl_buf,
KSyncSock::GetAgentSandeshContext(0));
}
nl_free_client(cl);
Mmap(true);
return;
}
void KSyncMemory::InitTest() {
assert(0);
}
void KSyncMemory::Shutdown() {
assert(0);
}
bool KSyncMemory::AuditProcess() {
// Get current time
uint64_t t = UTCTimestampUsec();
while (!audit_list_.empty()) {
AuditEntry list_entry = audit_list_.front();
// audit_list_ is sorted on last time of insertion in the list
// So, break on finding first entry that cannot be aged
if ((t - list_entry.timeout) < audit_timeout_) {
/* Wait for audit_timeout_ to create short for the entry */
break;
}
uint32_t idx = list_entry.audit_idx;
uint32_t gen_id = list_entry.audit_gen_id;
audit_list_.pop_front();
DecrementHoldFlowCounter();
CreateProtoAuditEntry(idx, gen_id);
}
uint32_t count = 0;
uint8_t gen_id;
assert(audit_yield_);
while (count < audit_yield_) {
if (IsInactiveEntry(audit_idx_, gen_id)) {
IncrementHoldFlowCounter();
audit_list_.push_back(AuditEntry(audit_idx_, gen_id, t));
}
count++;
audit_idx_++;
if (audit_idx_ == table_entries_count_) {
UpdateAgentHoldFlowCounter();
audit_idx_ = 0;
}
}
return true;
}
#ifndef _WIN32
void KSyncMemory::GetTableSize() {
struct nl_client *cl;
int attr_len;
int encode_len;
assert((cl = nl_register_client()) != NULL);
cl->cl_genl_family_id = KSyncSock::GetNetlinkFamilyId();
assert(nl_build_nlh(cl, cl->cl_genl_family_id, NLM_F_REQUEST) == 0);
assert(nl_build_genlh(cl, SANDESH_REQUEST, 0) == 0);
attr_len = nl_get_attr_hdr_size();
encode_len = EncodeReq(cl, attr_len);
nl_build_attr(cl, encode_len, NL_ATTR_VR_MESSAGE_PROTOCOL);
nl_update_nlh(cl);
#ifdef AGENT_VROUTER_TCP
tcp::socket socket(*(ksync_->agent()->event_manager()->io_service()));
tcp::endpoint endpoint(ksync_->agent()->vrouter_server_ip(),
ksync_->agent()->vrouter_server_port());
#else
boost::asio::local::stream_protocol::socket
socket(*(ksync_->agent()->event_manager()->io_service()));
boost::asio::local::stream_protocol::endpoint
endpoint(KSYNC_AGENT_VROUTER_SOCK_PATH);
#endif
boost::system::error_code ec;
socket.connect(endpoint, ec);
if (ec) {
assert(0);
}
socket.send(boost::asio::buffer(cl->cl_buf, cl->cl_buf_offset), 0, ec);
if (ec) {
assert(0);
}
uint32_t len_read = 0;
uint32_t data_len = sizeof(struct nlmsghdr);
while (len_read < data_len) {
len_read = socket.read_some(boost::asio::buffer(cl->cl_buf + len_read,
cl->cl_buf_len), ec);
if (ec) {
assert(0);
}
if (len_read > sizeof(struct nlmsghdr)) {
const struct nlmsghdr *nlh =
(const struct nlmsghdr *)((cl->cl_buf));
data_len = nlh->nlmsg_len;
}
}
KSyncSockNetlink::NetlinkDecoder(cl->cl_buf,
KSyncSock::GetAgentSandeshContext(0));
nl_free_client(cl);
}
void KSyncMemory::MapSharedMemory() {
GetTableSize();
Mmap(false);
}
#endif
<|endoftext|> |
<commit_before><commit_msg>bnc#887225: OOXML import: Correctly apply table style for lastRow.<commit_after><|endoftext|> |
<commit_before>#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QMessageBox>
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow)
{}
void MainWindow::setIP(QHostAddress myIP, QHostAddress partnerIP)
{
ui->setupUi(this);
ui->ErrorLabel->setText("No error :)");
//Camera and image processer settings
CaptureCamera.open(0);
if(CaptureCamera.isOpened() == false)
{
ui->ErrorLabel->setText("Camera Error");
std::cerr<< "Camera open error" <<std::endl;
}
CamSize = OriginalImageMat.size();
Processer = new ImageProcesser(CamSize);
ProcessTimer = new QTimer(this);
connect(ProcessTimer, SIGNAL(timeout()), this, SLOT(processVideoAndUpdateQUI()));
ProcessTimer->start(100); //tested with QElapsedTimer, 50 was too low... it generated runtime between 60-90 msec
//with this we have ~12 msec :)
//Add the graphics to graphicsview
scene = new QGraphicsScene(0,0,Settings::SCREEN_WIDTH,Settings::SCREEN_HEIGHT,ui->graphicsView);
ui->graphicsView->setScene(scene);
//Other initializations
myRoad = new Road();
lives = Settings::STARTLIFE;
ui->MyLifeLCD->display(lives);
distance = 0;
QObject::connect(myRoad, SIGNAL(sendLifeNumber(int)), this, SLOT(receiveLifeNumber(int)));
QObject::connect(myRoad, SIGNAL(sendDistanceNumber(int)), this, SLOT(receiveDistanceNumber(int)));
QObject::connect(myRoad, SIGNAL(stopGame()), this, SLOT(lose()));
scene->addItem(myRoad);
//Start the game
QObject::connect(&timer, SIGNAL(timeout()), scene, SLOT(advance()));
MyIpAddr=myIP;
ui->MyIP->setText("My IP: " + MyIpAddr.toString());
PartnerIpAddr=partnerIP;
ui->PartnerIP->setText("Partner IP: " + PartnerIpAddr.toString());
n = new Network();
n->setIp(MyIpAddr,PartnerIpAddr);
n->startBinding();
QObject::connect(n, SIGNAL(receivedImage(QImage)), this, SLOT(receiveNetworkImage(QImage)));
gameStarted = false;
this->show();
}
void MainWindow::receiveLifeNumber(int i)
{
lives = i;
if(lives>=0) ui->MyLifeLCD->display(lives);
}
void MainWindow::receiveDistanceNumber(int i)
{
distance = i;
ui->MyDistLCD->display(distance);
}
void MainWindow::lose(){
timer.stop();
QMessageBox::StandardButton reply;
reply = QMessageBox::question(this, "Rematch", "Would you like to restart the game?",
QMessageBox::Yes|QMessageBox::No);
if (reply == QMessageBox::Yes) {
restart();
} else {
closeVideoStream();
close();
exit(0);
}
}
void MainWindow::processVideoAndUpdateQUI()
{
ProcUpdateElapsedTime.start();
CaptureCamera.read(OriginalImageMat);
if (OriginalImageMat.empty()) return;
cv::resize(OriginalImageMat, ResizedImageMat, cv::Size(352,220), 0, 0, cv::INTER_CUBIC); //resizing the image to fit in the UI
cv::flip(ResizedImageMat, ResizedImageMat, 1); //eliminating the mirror effect
//Add the picture to the processer
int move = Processer->getMove(ResizedImageMat);
//std::cout << "move: " << move <<std::endl;
//Move the car
if(prevmove == 0)
{
myRoad->moveCar(move);
}
prevmove = move;
cv::cvtColor(ResizedImageMat, ResizedImageMat, CV_BGR2RGB); //converting the image to RGB
cv::rectangle(ResizedImageMat,cv::Rect(0, 0, 100, 130),cv::Scalar(200));
cv::rectangle(ResizedImageMat,cv::Rect(250,0,102,130),cv::Scalar(200));
QImage OriginalImage((uchar*)ResizedImageMat.data,
ResizedImageMat.cols,
ResizedImageMat.rows,
ResizedImageMat.step,
QImage::Format_RGB888); //Creating the QImage for the label
NetworkSendImage = OriginalImage;
NetworkSendImage = NetworkSendImage.scaledToHeight(165);
ui->MyVideoLabel->setPixmap(QPixmap::fromImage(OriginalImage));
//Sending number of lives and distance embedded in the image
NetworkSendImage.setText("lives", QString::number(lives));
NetworkSendImage.setText("distance", QString::number(distance));
n->sendData(NetworkSendImage); //sending the image over the network
if(lives < 0)
{
lose();
}
// std::cerr << "processVideoAndUpdateQUI() elapsed time: " << ProcUpdateElapsedTime.elapsed() << " msec" << std::endl << std::endl;
}
//Public slot that receives the image from the networking thread
void MainWindow::receiveNetworkImage(QImage q)
{
if (!gameStarted)
{
//Start the game
timer.start(Settings::FREQUENCY);
gameStarted = true;
}
ui->NetworkCamVideo->setPixmap(QPixmap::fromImage(q)); //putting the received image to the gui
std::cout << "network lives: " << q.text("lives").toInt() << std::endl;
if(q.text("lives").toInt()>=0) ui->NetworkLifeLCD->display(q.text("lives"));
else{
lose();
}
//else timer.stop();
ui->NetworkDistLCD->display(q.text("distance"));
}
MainWindow::~MainWindow()
{
delete ui;
delete ProcessTimer;
delete Processer;
delete n;
delete scene;
delete myCar;
delete myRoad;
}
void MainWindow::closeVideoStream()
{
ProcessTimer->stop();
//std::cout << "Video process timer stopped" <<std::endl;
CaptureCamera.release();
//std::cout << "Camera released" <<std::endl;
}
void MainWindow::restart()
{
delete myRoad;
myRoad = new Road();
lives = Settings::STARTLIFE;
ui->MyLifeLCD->display(lives);
distance = 0;
ui->MyDistLCD->display(distance);
scene->addItem(myRoad);
timer.start(Settings::FREQUENCY);
}
// Kezeli a billentyűlenyomást
void MainWindow::keyPressEvent(QKeyEvent *event){
switch (event->key())
{
case Qt::Key_Right:
myRoad->moveCar(1); //turn right;
break;
case Qt::Key_Left:
myRoad->moveCar(-1); //turn left;
break;
case Qt::Key_Escape:
closeVideoStream();
close();
exit(0);
break;
default:
break;
}
}
<commit_msg>done for today hopefully :)<commit_after>#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QMessageBox>
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow)
{}
void MainWindow::setIP(QHostAddress myIP, QHostAddress partnerIP)
{
ui->setupUi(this);
ui->ErrorLabel->setText("No error :)");
//Camera and image processer settings
CaptureCamera.open(0);
if(CaptureCamera.isOpened() == false)
{
ui->ErrorLabel->setText("Camera Error");
std::cerr<< "Camera open error" <<std::endl;
}
CamSize = OriginalImageMat.size();
Processer = new ImageProcesser(CamSize);
ProcessTimer = new QTimer(this);
connect(ProcessTimer, SIGNAL(timeout()), this, SLOT(processVideoAndUpdateQUI()));
ProcessTimer->start(100); //tested with QElapsedTimer, 50 was too low... it generated runtime between 60-90 msec
//with this we have ~12 msec :)
//Add the graphics to graphicsview
scene = new QGraphicsScene(0,0,Settings::SCREEN_WIDTH,Settings::SCREEN_HEIGHT,ui->graphicsView);
ui->graphicsView->setScene(scene);
//Other initializations
myRoad = new Road();
lives = Settings::STARTLIFE;
ui->MyLifeLCD->display(lives);
distance = 0;
QObject::connect(myRoad, SIGNAL(sendLifeNumber(int)), this, SLOT(receiveLifeNumber(int)));
QObject::connect(myRoad, SIGNAL(sendDistanceNumber(int)), this, SLOT(receiveDistanceNumber(int)));
scene->addItem(myRoad);
//Start the game
QObject::connect(&timer, SIGNAL(timeout()), scene, SLOT(advance()));
MyIpAddr=myIP;
ui->MyIP->setText("My IP: " + MyIpAddr.toString());
PartnerIpAddr=partnerIP;
ui->PartnerIP->setText("Partner IP: " + PartnerIpAddr.toString());
n = new Network();
n->setIp(MyIpAddr,PartnerIpAddr);
n->startBinding();
QObject::connect(n, SIGNAL(receivedImage(QImage)), this, SLOT(receiveNetworkImage(QImage)));
gameStarted = false;
this->show();
}
void MainWindow::receiveLifeNumber(int i)
{
lives = i;
if(lives>=0) ui->MyLifeLCD->display(lives);
}
void MainWindow::receiveDistanceNumber(int i)
{
distance = i;
ui->MyDistLCD->display(distance);
}
void MainWindow::lose(){
timer.stop();
QString msg;
if (lives <0)
msg = "You lost, I'm sorry...\n\nWould you like to restart the game?";
else
msg = "YOU WON, congratulations!\n\nWould you like to restart the game?";
QMessageBox::StandardButton reply;
reply = QMessageBox::question(this, "Rematch", msg,
QMessageBox::Yes|QMessageBox::No);
if (reply == QMessageBox::Yes) {
restart();
} else {
closeVideoStream();
close();
exit(0);
}
}
void MainWindow::processVideoAndUpdateQUI()
{
ProcUpdateElapsedTime.start();
CaptureCamera.read(OriginalImageMat);
if (OriginalImageMat.empty()) return;
cv::resize(OriginalImageMat, ResizedImageMat, cv::Size(352,220), 0, 0, cv::INTER_CUBIC); //resizing the image to fit in the UI
cv::flip(ResizedImageMat, ResizedImageMat, 1); //eliminating the mirror effect
//Add the picture to the processer
int move = Processer->getMove(ResizedImageMat);
//std::cout << "move: " << move <<std::endl;
//Move the car
if(prevmove == 0)
{
myRoad->moveCar(move);
}
prevmove = move;
cv::cvtColor(ResizedImageMat, ResizedImageMat, CV_BGR2RGB); //converting the image to RGB
cv::rectangle(ResizedImageMat,cv::Rect(0, 0, 100, 130),cv::Scalar(200));
cv::rectangle(ResizedImageMat,cv::Rect(250,0,102,130),cv::Scalar(200));
QImage OriginalImage((uchar*)ResizedImageMat.data,
ResizedImageMat.cols,
ResizedImageMat.rows,
ResizedImageMat.step,
QImage::Format_RGB888); //Creating the QImage for the label
NetworkSendImage = OriginalImage;
NetworkSendImage = NetworkSendImage.scaledToHeight(165);
ui->MyVideoLabel->setPixmap(QPixmap::fromImage(OriginalImage));
//Sending number of lives and distance embedded in the image
NetworkSendImage.setText("lives", QString::number(lives));
NetworkSendImage.setText("distance", QString::number(distance));
n->sendData(NetworkSendImage); //sending the image over the network
if(lives < 0)
{
lose();
}
// std::cerr << "processVideoAndUpdateQUI() elapsed time: " << ProcUpdateElapsedTime.elapsed() << " msec" << std::endl << std::endl;
}
//Public slot that receives the image from the networking thread
void MainWindow::receiveNetworkImage(QImage q)
{
if (!gameStarted)
{
//Start the game
timer.start(Settings::FREQUENCY);
gameStarted = true;
}
ui->NetworkCamVideo->setPixmap(QPixmap::fromImage(q)); //putting the received image to the gui
//std::cout << "network lives: " << q.text("lives").toInt() << std::endl;
if(q.text("lives").toInt()>=0) ui->NetworkLifeLCD->display(q.text("lives"));
else{
lose();
}
//else timer.stop();
ui->NetworkDistLCD->display(q.text("distance"));
}
MainWindow::~MainWindow()
{
delete ui;
delete ProcessTimer;
delete Processer;
delete n;
delete scene;
delete myCar;
delete myRoad;
}
void MainWindow::closeVideoStream()
{
ProcessTimer->stop();
//std::cout << "Video process timer stopped" <<std::endl;
CaptureCamera.release();
//std::cout << "Camera released" <<std::endl;
}
void MainWindow::restart()
{
delete myRoad;
myRoad = new Road();
lives = Settings::STARTLIFE;
ui->MyLifeLCD->display(lives);
distance = 0;
ui->MyDistLCD->display(distance);
scene->addItem(myRoad);
timer.start(Settings::FREQUENCY);
}
// Kezeli a billentyűlenyomást
void MainWindow::keyPressEvent(QKeyEvent *event){
switch (event->key())
{
case Qt::Key_Right:
myRoad->moveCar(1); //turn right;
break;
case Qt::Key_Left:
myRoad->moveCar(-1); //turn left;
break;
case Qt::Key_Escape:
closeVideoStream();
close();
exit(0);
break;
default:
break;
}
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2016 Barrett Adair
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
HEADER GUARDS INTENTIONALLY OMITTED
DO NOT INCLUDE THIS HEADER DIRECTLY
*/
#define BOOST_CLBL_TRTS_NOEXCEPT_SPEC
#define BOOST_CLBL_TRTS_IS_NOEXCEPT std::false_type
#include <boost/callable_traits/detail/unguarded/pmf_4.hpp>
#undef BOOST_CLBL_TRTS_NOEXCEPT_SPEC
#undef BOOST_CLBL_TRTS_IS_NOEXCEPT
#ifdef BOOST_CLBL_TRTS_ENABLE_NOEXCEPT_TYPES
#define BOOST_CLBL_TRTS_NOEXCEPT_SPEC noexcept
#define BOOST_CLBL_TRTS_IS_NOEXCEPT std::true_type
#include <boost/callable_traits/detail/unguarded/pmf_4.hpp>
#undef BOOST_CLBL_TRTS_NOEXCEPT_SPEC
#undef BOOST_CLBL_TRTS_IS_NOEXCEPT
#endif // #ifdef BOOST_CLBL_TRTS_ENABLE_NOEXCEPT_TYPES<commit_msg>Delete pmf_3.hpp<commit_after><|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: StaticSet.hxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: rt $ $Date: 2005-09-08 10:04:12 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef DBACCESS_CORE_API_STATICSET_HXX
#define DBACCESS_CORE_API_STATICSET_HXX
#ifndef DBACCESS_CORE_API_CACHESET_HXX
#include "CacheSet.hxx"
#endif
namespace dbaccess
{
// is used when nothing is supported by the driver
// we use a snapshot
class OStaticSet : public OCacheSet
{
ORowSetMatrix m_aSet;
ORowSetMatrix::iterator m_aSetIter;
sal_Bool m_bEnd;
sal_Bool fetchRow();
void fillAllRows();
public:
OStaticSet()
: m_aSetIter(m_aSet.end())
, m_bEnd(sal_False)
{
m_aSet.push_back(NULL); // this is the beforefirst record
}
virtual void fillValueRow(ORowSetRow& _rRow,sal_Int32 _nPosition);
// ::com::sun::star::sdbcx::XRowLocate
virtual ::com::sun::star::uno::Any SAL_CALL getBookmark( const ORowSetRow& _rRow ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL moveToBookmark( const ::com::sun::star::uno::Any& bookmark ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL moveRelativeToBookmark( const ::com::sun::star::uno::Any& bookmark, sal_Int32 rows ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Int32 SAL_CALL compareBookmarks( const ::com::sun::star::uno::Any& first, const ::com::sun::star::uno::Any& second ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL hasOrderedBookmarks( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Int32 SAL_CALL hashBookmark( const ::com::sun::star::uno::Any& bookmark ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
// ::com::sun::star::sdbc::XResultSet
virtual sal_Bool SAL_CALL next( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL isBeforeFirst( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL isAfterLast( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL isFirst( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL isLast( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL beforeFirst( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL afterLast( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL first( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL last( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Int32 SAL_CALL getRow( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL absolute( sal_Int32 row ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL relative( sal_Int32 rows ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL previous( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL refreshRow( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL rowUpdated( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL rowInserted( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL rowDeleted( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
// ::com::sun::star::sdbcx::XDeleteRows
virtual ::com::sun::star::uno::Sequence< sal_Int32 > SAL_CALL deleteRows( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& rows,const connectivity::OSQLTable& _xTable ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
// ::com::sun::star::sdbc::XResultSetUpdate
virtual void SAL_CALL insertRow( const ORowSetRow& _rInsertRow,const connectivity::OSQLTable& _xTable ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL updateRow(const ORowSetRow& _rInsertRow,const ORowSetRow& _rOrginalRow,const connectivity::OSQLTable& _xTable ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL deleteRow(const ORowSetRow& _rInsertRow,const connectivity::OSQLTable& _xTable ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL cancelRowUpdates( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL moveToInsertRow( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL moveToCurrentRow( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
};
}
#endif //DBACCESS_CORE_API_STATICSET_HXX
<commit_msg>INTEGRATION: CWS warnings01 (1.8.50); FILE MERGED 2006/03/24 15:35:47 fs 1.8.50.1: #i57457# warning-free code (unxlngi6/.pro + unxsoli4.pro)<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: StaticSet.hxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: hr $ $Date: 2006-06-20 02:38:06 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef DBACCESS_CORE_API_STATICSET_HXX
#define DBACCESS_CORE_API_STATICSET_HXX
#ifndef DBACCESS_CORE_API_CACHESET_HXX
#include "CacheSet.hxx"
#endif
namespace dbaccess
{
// is used when nothing is supported by the driver
// we use a snapshot
class OStaticSet : public OCacheSet
{
ORowSetMatrix m_aSet;
ORowSetMatrix::iterator m_aSetIter;
sal_Bool m_bEnd;
sal_Bool fetchRow();
void fillAllRows();
public:
OStaticSet()
: m_aSetIter(m_aSet.end())
, m_bEnd(sal_False)
{
m_aSet.push_back(NULL); // this is the beforefirst record
}
virtual void fillValueRow(ORowSetRow& _rRow,sal_Int32 _nPosition);
// ::com::sun::star::sdbcx::XRowLocate
virtual ::com::sun::star::uno::Any SAL_CALL getBookmark() throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL moveToBookmark( const ::com::sun::star::uno::Any& bookmark ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL moveRelativeToBookmark( const ::com::sun::star::uno::Any& bookmark, sal_Int32 rows ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Int32 SAL_CALL compareBookmarks( const ::com::sun::star::uno::Any& first, const ::com::sun::star::uno::Any& second ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL hasOrderedBookmarks( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Int32 SAL_CALL hashBookmark( const ::com::sun::star::uno::Any& bookmark ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
// ::com::sun::star::sdbc::XResultSet
virtual sal_Bool SAL_CALL next( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL isBeforeFirst( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL isAfterLast( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL isFirst( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL isLast( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL beforeFirst( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL afterLast( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL first( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL last( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Int32 SAL_CALL getRow( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL absolute( sal_Int32 row ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL relative( sal_Int32 rows ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL previous( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL refreshRow( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL rowUpdated( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL rowInserted( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL rowDeleted( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
// ::com::sun::star::sdbcx::XDeleteRows
virtual ::com::sun::star::uno::Sequence< sal_Int32 > SAL_CALL deleteRows( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& rows,const connectivity::OSQLTable& _xTable ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
// ::com::sun::star::sdbc::XResultSetUpdate
virtual void SAL_CALL insertRow( const ORowSetRow& _rInsertRow,const connectivity::OSQLTable& _xTable ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL updateRow(const ORowSetRow& _rInsertRow,const ORowSetRow& _rOrginalRow,const connectivity::OSQLTable& _xTable ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL deleteRow(const ORowSetRow& _rInsertRow,const connectivity::OSQLTable& _xTable ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL cancelRowUpdates( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL moveToInsertRow( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL moveToCurrentRow( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
};
}
#endif //DBACCESS_CORE_API_STATICSET_HXX
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: RelationDlg.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: oj $ $Date: 2001-10-08 07:26:30 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the License); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an AS IS basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef DBAUI_RELATIONDIALOG_HXX
#define DBAUI_RELATIONDIALOG_HXX
#ifndef _DIALOG_HXX //autogen
#include <vcl/dialog.hxx>
#endif
#ifndef _BUTTON_HXX //autogen
#include <vcl/button.hxx>
#endif
#ifndef _FIXED_HXX //autogen
#include <vcl/fixed.hxx>
#endif
#ifndef _EDIT_HXX //autogen
#include <vcl/edit.hxx>
#endif
#ifndef _SV_LSTBOX_HXX //autogen
#include <vcl/lstbox.hxx>
#endif
#ifndef _SVTOOLS_EDITBROWSEBOX_HXX_
#include <svtools/editbrowsebox.hxx>
#endif
#ifndef _SV_MSGBOX_HXX
#include <vcl/msgbox.hxx>
#endif
#ifndef DBAUI_RTABLECONNECTIONDATA_HXX
#include "RTableConnectionData.hxx"
#endif
#ifndef _COM_SUN_STAR_SDBC_XCONNECTION_HPP_
#include <com/sun/star/sdbc/XConnection.hpp>
#endif
namespace dbaui
{
//========================================================================
class ORelationDialog;
typedef ::svt::EditBrowseBox ORelationControl_Base;
class ORelationControl : public ORelationControl_Base
{
friend class ORelationDialog;
ULONG m_nDeActivateEvent;
::svt::ListBoxControl* m_pListCell;
ORelationTableConnectionData* m_pConnData;
long m_nDataPos;
::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet> m_xSourceDef;
::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet> m_xDestDef;
void SetDef(const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& xDest,sal_Int32 _nPos);
void fillListBox(const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& _xDest);
public:
ORelationControl( ORelationDialog* pParent );
virtual ~ORelationControl();
void SetSourceDef(const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& _xNewSource);
void SetDestDef(const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& _xNewDest);
protected:
virtual void Resize();
virtual long PreNotify(NotifyEvent& rNEvt );
virtual BOOL IsTabAllowed(BOOL bForward) const;
virtual void Init(ORelationTableConnectionData* _pConnData);
virtual void Init() { ORelationControl_Base::Init(); }
virtual void InitController( ::svt::CellControllerRef& rController, long nRow, USHORT nCol );
virtual ::svt::CellController* GetController( long nRow, USHORT nCol );
virtual void PaintCell( OutputDevice& rDev, const Rectangle& rRect, USHORT nColId ) const;
virtual BOOL SeekRow( long nRow );
virtual BOOL SaveModified();
virtual String GetCellText( long nRow, USHORT nColId );
virtual void CellModified();
private:
DECL_LINK( AsynchActivate, void* );
DECL_LINK( AsynchDeactivate, void* );
};
class OJoinTableView;
//========================================================================
class ORelationDialog : public ModalDialog
{
FixedLine aFL_InvolvedTables;
ListBox m_lmbLeftTable,
m_lmbRightTable;
FixedLine aFL_InvolvedFields;
FixedLine aFL_CascUpd;
RadioButton aRB_NoCascUpd,
aRB_CascUpd,
aRB_CascUpdNull,
aRB_CascUpdDefault;
FixedLine aFL_CascDel;
RadioButton aRB_NoCascDel,
aRB_CascDel,
aRB_CascDelNull,
aRB_CascDelDefault;
OKButton aPB_OK;
CancelButton aPB_CANCEL;
HelpButton aPB_HELP;
ORelationControl* m_pRC_Tables;
ORelationTableConnectionData* m_pConnData;
ORelationTableConnectionData* m_pOrigConnData;
::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection > m_xConnection;
String m_strCurrentLeft;
String m_strCurrentRight;
BOOL m_bTriedOneUpdate;
public:
ORelationDialog(OJoinTableView* pParent,
ORelationTableConnectionData* pConnectionData,
BOOL bAllowTableSelect = FALSE );
virtual ~ORelationDialog();
::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection > getConnection(){ return m_xConnection; }
void NotifyCellChange();
virtual short Execute();
protected:
void Init(ORelationTableConnectionData* _pConnData);
private:
DECL_LINK( OKClickHdl, Button* );
DECL_LINK( OnTableChanged, ListBox* );
};
}
#endif // DBAUI_RELATIONDIALOG_HXX
<commit_msg>#86640# fillListBox signature changed<commit_after>/*************************************************************************
*
* $RCSfile: RelationDlg.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: fs $ $Date: 2001-10-16 15:12:29 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the License); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an AS IS basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef DBAUI_RELATIONDIALOG_HXX
#define DBAUI_RELATIONDIALOG_HXX
#ifndef _DIALOG_HXX //autogen
#include <vcl/dialog.hxx>
#endif
#ifndef _BUTTON_HXX //autogen
#include <vcl/button.hxx>
#endif
#ifndef _FIXED_HXX //autogen
#include <vcl/fixed.hxx>
#endif
#ifndef _EDIT_HXX //autogen
#include <vcl/edit.hxx>
#endif
#ifndef _SV_LSTBOX_HXX //autogen
#include <vcl/lstbox.hxx>
#endif
#ifndef _SVTOOLS_EDITBROWSEBOX_HXX_
#include <svtools/editbrowsebox.hxx>
#endif
#ifndef _SV_MSGBOX_HXX
#include <vcl/msgbox.hxx>
#endif
#ifndef DBAUI_RTABLECONNECTIONDATA_HXX
#include "RTableConnectionData.hxx"
#endif
#ifndef _COM_SUN_STAR_SDBC_XCONNECTION_HPP_
#include <com/sun/star/sdbc/XConnection.hpp>
#endif
namespace dbaui
{
//========================================================================
class ORelationDialog;
typedef ::svt::EditBrowseBox ORelationControl_Base;
class ORelationControl : public ORelationControl_Base
{
friend class ORelationDialog;
ULONG m_nDeActivateEvent;
::svt::ListBoxControl* m_pListCell;
ORelationTableConnectionData* m_pConnData;
long m_nDataPos;
::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet> m_xSourceDef;
::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet> m_xDestDef;
void SetDef(const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& xDest,sal_Int32 _nPos);
void fillListBox(const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& _xDest,long nRow,USHORT nColumnId);
public:
ORelationControl( ORelationDialog* pParent );
virtual ~ORelationControl();
void SetSourceDef(const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& _xNewSource);
void SetDestDef(const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& _xNewDest);
protected:
virtual void Resize();
virtual long PreNotify(NotifyEvent& rNEvt );
virtual BOOL IsTabAllowed(BOOL bForward) const;
virtual void Init(ORelationTableConnectionData* _pConnData);
virtual void Init() { ORelationControl_Base::Init(); }
virtual void InitController( ::svt::CellControllerRef& rController, long nRow, USHORT nCol );
virtual ::svt::CellController* GetController( long nRow, USHORT nCol );
virtual void PaintCell( OutputDevice& rDev, const Rectangle& rRect, USHORT nColId ) const;
virtual BOOL SeekRow( long nRow );
virtual BOOL SaveModified();
virtual String GetCellText( long nRow, USHORT nColId );
virtual void CellModified();
private:
DECL_LINK( AsynchActivate, void* );
DECL_LINK( AsynchDeactivate, void* );
};
class OJoinTableView;
//========================================================================
class ORelationDialog : public ModalDialog
{
FixedLine aFL_InvolvedTables;
ListBox m_lmbLeftTable,
m_lmbRightTable;
FixedLine aFL_InvolvedFields;
FixedLine aFL_CascUpd;
RadioButton aRB_NoCascUpd,
aRB_CascUpd,
aRB_CascUpdNull,
aRB_CascUpdDefault;
FixedLine aFL_CascDel;
RadioButton aRB_NoCascDel,
aRB_CascDel,
aRB_CascDelNull,
aRB_CascDelDefault;
OKButton aPB_OK;
CancelButton aPB_CANCEL;
HelpButton aPB_HELP;
ORelationControl* m_pRC_Tables;
ORelationTableConnectionData* m_pConnData;
ORelationTableConnectionData* m_pOrigConnData;
::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection > m_xConnection;
String m_strCurrentLeft;
String m_strCurrentRight;
BOOL m_bTriedOneUpdate;
public:
ORelationDialog(OJoinTableView* pParent,
ORelationTableConnectionData* pConnectionData,
BOOL bAllowTableSelect = FALSE );
virtual ~ORelationDialog();
::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection > getConnection(){ return m_xConnection; }
void NotifyCellChange();
virtual short Execute();
protected:
void Init(ORelationTableConnectionData* _pConnData);
private:
DECL_LINK( OKClickHdl, Button* );
DECL_LINK( OnTableChanged, ListBox* );
};
}
#endif // DBAUI_RELATIONDIALOG_HXX
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: undosqledit.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: oj $ $Date: 2002-08-19 07:28:27 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the License); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an AS IS basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef DBAUI_UNDOSQLEDIT_HXX
#define DBAUI_UNDOSQLEDIT_HXX
#ifndef DBAUI_GENERALUNDO_HXX
#include "GeneralUndo.hxx"
#endif
#ifndef _DBU_CONTROL_HRC_
#include "dbu_control.hrc"
#endif
namespace dbaui
{
class OSqlEdit;
// ================================================================================================
// OSqlEditUndoAct - Undo-class for changing sql text
//------------------------------------------------------------------------
class OSqlEditUndoAct : public OCommentUndoAction
{
protected:
OSqlEdit* m_pOwner;
String m_strNextText;
virtual void Undo() { ToggleText(); }
virtual void Redo() { ToggleText(); }
void ToggleText();
public:
OSqlEditUndoAct(OSqlEdit* pEdit) : OCommentUndoAction(STR_QUERY_UNDO_MODIFYSQLEDIT), m_pOwner(pEdit) { }
void SetOriginalText(const String& strText) { m_strNextText = strText; }
};
}
#endif // DBAUI_UNDOSQLEDIT_HXX
<commit_msg>INTEGRATION: CWS insight01 (1.4.108); FILE MERGED 2004/07/09 13:44:05 oj 1.4.108.1: resource changes<commit_after>/*************************************************************************
*
* $RCSfile: undosqledit.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: hr $ $Date: 2004-08-02 16:03:20 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the License); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an AS IS basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef DBAUI_UNDOSQLEDIT_HXX
#define DBAUI_UNDOSQLEDIT_HXX
#ifndef DBAUI_GENERALUNDO_HXX
#include "GeneralUndo.hxx"
#endif
#ifndef _DBU_CONTROL_HRC_
#include "dbu_control.hrc"
#endif
namespace dbaui
{
class OSqlEdit;
// ================================================================================================
// OSqlEditUndoAct - Undo-class for changing sql text
//------------------------------------------------------------------------
class OSqlEditUndoAct : public OCommentUndoAction
{
protected:
OSqlEdit* m_pOwner;
String m_strNextText;
virtual void Undo() { ToggleText(); }
virtual void Redo() { ToggleText(); }
void ToggleText();
public:
OSqlEditUndoAct(OSqlEdit* pEdit) : OCommentUndoAction(STR_QUERY_UNDO_MODIFYSQLEDIT), m_pOwner(pEdit) { }
void SetOriginalText(const String& strText) { m_strNextText =strText; }
};
}
#endif // DBAUI_UNDOSQLEDIT_HXX
<|endoftext|> |
<commit_before><commit_msg>unused parameter<commit_after><|endoftext|> |
<commit_before>#include "doorman.h"
#include <wiringPi.h>
#include <string>
#include <cstdio>
#include <cmath>
#include <fstream>
#include <iostream>
#include <cstdlib>
using namespace std;
string command_read("read");
string command_readHuman("read-human");
string command_write("write");
#define COUNT 500000
int content[COUNT];
char newline = '\n';
int do_read(char *file, bool human) {
cerr << "Listening... ";
for (int i = 0; i < COUNT; i++) {
content[i] = doorman::read();
doorman::sleep();
}
cerr << "Done" << newline;
ostream *output;
if (file != 0) {
output = new ofstream(file);
} else {
output = &cout;
}
cerr << "Writing... ";
if (human) {
int count = 0;
int current, previous = -1;
for (int i = 0; i < COUNT; i++) {
current = content[i];
if (current == previous) {
count++;
} else {
if (previous != -1) {
count = (int) round(count / 20.f);
if (count > 20) {
*output << newline;
} else {
for (int j = 0; j < count; j++) {
*output << previous;
}
}
}
previous = current;
count = 1;
}
}
} else {
for (int i = 0; i < COUNT; i++) {
*output << content[i];
}
}
cerr << "Done" << newline;
return 0;
}
int do_write(char *channel_str, char *sound_str) {
static int delay = 200;
int channel = atoi(channel_str);
int sound = atoi(sound_str);
static int channel_map[] = {0b1111,0b0011,0b1011,0b0000,0b1000,0b0100,0b1100,0b0101,0b1101,0b0001,0b1001,0b0010,0b1010,0b0110,0b1110,0b0111};
if(channel > channel_map.size() && channel > 0){
cerr << "Channel not existing" << newline
return 1
}
int channel_bit = channel_map[channel - 1];
static int sound_map[] = {0b11110111,0b11111011,0b11111101};
if(sound > sound_map.size() && sound > 0){
cerr << "Channel not existing" << newline
return 1
}
int sound_bit = sound_map[sound - 1];
for(int i = 0; i < 10; i++){
for(int j = 3; j >= 0; j--){
doorman::write(1);
delayMicroseconds(delay);
doorman::write(0);
delayMicroseconds(delay);
doorman::write(channel_bit & (1 << j));
delayMicroseconds(delay);
}
for(int j=7; j >= 0; j--){
doorman::write(1);
delayMicroseconds(delay);
doorman::write(0);
delayMicroseconds(delay);
doorman::write(sound_bit & (1 << j));
delayMicroseconds(delay);
}
doorman::write(1);
delayMicroseconds(delay);
doorman::write(0);
delayMicroseconds(delay*30);
}
return 0;
}
int main(int argc, char ** argv) {
if (argc < 2) {
fprintf(stderr, "Invalid number of arguments: %d, at least 2 \nUsage: %s <mode>\n", argc - 1, argv[0]);
return 1;
}
char *command = argv[2];
char *file = (argc == 3) ? argv[3] : 0;
doorman::setup();
if (command_read == argv[1]) {
return do_read(file, false);
} else if (command_readHuman == argv[1]) {
return do_read(file, true);
} else if (command_write == argv[1] && argc == 4) {
return do_write(argv[2], argv[3]);
} else {
fprintf(stderr, "Invalid mode \"%s\", valid modes are \"read\", \"read-human\" and \"write <channel> <sound>\"\n", argv[1]);
}
}
<commit_msg>Fix for if statement<commit_after>#include "doorman.h"
#include <wiringPi.h>
#include <string>
#include <cstdio>
#include <cmath>
#include <fstream>
#include <iostream>
#include <cstdlib>
using namespace std;
string command_read("read");
string command_readHuman("read-human");
string command_write("write");
#define COUNT 500000
int content[COUNT];
char newline = '\n';
int do_read(char *file, bool human) {
cerr << "Listening... ";
for (int i = 0; i < COUNT; i++) {
content[i] = doorman::read();
doorman::sleep();
}
cerr << "Done" << newline;
ostream *output;
if (file != 0) {
output = new ofstream(file);
} else {
output = &cout;
}
cerr << "Writing... ";
if (human) {
int count = 0;
int current, previous = -1;
for (int i = 0; i < COUNT; i++) {
current = content[i];
if (current == previous) {
count++;
} else {
if (previous != -1) {
count = (int) round(count / 20.f);
if (count > 20) {
*output << newline;
} else {
for (int j = 0; j < count; j++) {
*output << previous;
}
}
}
previous = current;
count = 1;
}
}
} else {
for (int i = 0; i < COUNT; i++) {
*output << content[i];
}
}
cerr << "Done" << newline;
return 0;
}
int do_write(char *channel_str, char *sound_str) {
static int delay = 200;
int channel = atoi(channel_str);
int sound = atoi(sound_str);
static int channel_map[] = {0b1111,0b0011,0b1011,0b0000,0b1000,0b0100,0b1100,0b0101,0b1101,0b0001,0b1001,0b0010,0b1010,0b0110,0b1110,0b0111};
if(channel > channel_map.size() || channel < 1){
cerr << "Channel not existing" << newline
return 1
}
int channel_bit = channel_map[channel - 1];
static int sound_map[] = {0b11110111,0b11111011,0b11111101};
if(sound > sound_map.size() || channel < 1){
cerr << "Channel not existing" << newline
return 1
}
int sound_bit = sound_map[sound - 1];
for(int i = 0; i < 10; i++){
for(int j = 3; j >= 0; j--){
doorman::write(1);
delayMicroseconds(delay);
doorman::write(0);
delayMicroseconds(delay);
doorman::write(channel_bit & (1 << j));
delayMicroseconds(delay);
}
for(int j=7; j >= 0; j--){
doorman::write(1);
delayMicroseconds(delay);
doorman::write(0);
delayMicroseconds(delay);
doorman::write(sound_bit & (1 << j));
delayMicroseconds(delay);
}
doorman::write(1);
delayMicroseconds(delay);
doorman::write(0);
delayMicroseconds(delay*30);
}
return 0;
}
int main(int argc, char ** argv) {
if (argc < 2) {
fprintf(stderr, "Invalid number of arguments: %d, at least 2 \nUsage: %s <mode>\n", argc - 1, argv[0]);
return 1;
}
char *command = argv[2];
char *file = (argc == 3) ? argv[3] : 0;
doorman::setup();
if (command_read == argv[1]) {
return do_read(file, false);
} else if (command_readHuman == argv[1]) {
return do_read(file, true);
} else if (command_write == argv[1] && argc == 4) {
return do_write(argv[2], argv[3]);
} else {
fprintf(stderr, "Invalid mode \"%s\", valid modes are \"read\", \"read-human\" and \"write <channel> <sound>\"\n", argv[1]);
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/translate/translate_infobar_delegate2.h"
#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/translate/translate_infobar_view.h"
#include "chrome/browser/translate/translate_manager2.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
// static
TranslateInfoBarDelegate2* TranslateInfoBarDelegate2::CreateInstance(
Type type,
TranslateErrors::Type error,
TabContents* tab_contents,
const std::string& original_language,
const std::string& target_language) {
if (!TranslateManager2::IsSupportedLanguage(original_language) ||
!TranslateManager2::IsSupportedLanguage(target_language)) {
return NULL;
}
return new TranslateInfoBarDelegate2(type, error, tab_contents,
original_language, target_language);
}
TranslateInfoBarDelegate2::TranslateInfoBarDelegate2(
Type type,
TranslateErrors::Type error,
TabContents* tab_contents,
const std::string& original_language,
const std::string& target_language)
: InfoBarDelegate(tab_contents),
type_(type),
background_animation_(NONE),
tab_contents_(tab_contents),
original_language_index_(-1),
target_language_index_(-1),
error_(error),
infobar_view_(NULL),
prefs_(tab_contents_->profile()->GetPrefs()) {
DCHECK((type_ != TRANSLATION_ERROR && error == TranslateErrors::NONE) ||
(type_ == TRANSLATION_ERROR && error != TranslateErrors::NONE));
std::vector<std::string> language_codes;
TranslateManager2::GetSupportedLanguages(&language_codes);
languages_.reserve(language_codes.size());
for (std::vector<std::string>::const_iterator iter = language_codes.begin();
iter != language_codes.end(); ++iter) {
std::string language_code = *iter;
if (language_code == original_language)
original_language_index_ = iter - language_codes.begin();
else if (language_code == target_language)
target_language_index_ = iter - language_codes.begin();
string16 language_name = GetLanguageDisplayableName(language_code);
// Insert the language in languages_ in alphabetical order.
std::vector<LanguageNamePair>::iterator iter2;
for (iter2 = languages_.begin(); iter2 != languages_.end(); ++iter2) {
if (language_name.compare(iter2->second) < 0)
break;
}
languages_.insert(iter2, LanguageNamePair(language_code, language_name));
}
DCHECK(original_language_index_ != -1);
DCHECK(target_language_index_ != -1);
}
int TranslateInfoBarDelegate2::GetLanguageCount() const {
return static_cast<int>(languages_.size());
}
const std::string& TranslateInfoBarDelegate2::GetLanguageCodeAt(
int index) const {
DCHECK(index >=0 && index < GetLanguageCount());
return languages_[index].first;
}
const string16& TranslateInfoBarDelegate2::GetLanguageDisplayableNameAt(
int index) const {
DCHECK(index >=0 && index < GetLanguageCount());
return languages_[index].second;
}
const std::string& TranslateInfoBarDelegate2::GetOriginalLanguageCode() const {
return GetLanguageCodeAt(original_language_index());
}
const std::string& TranslateInfoBarDelegate2::GetTargetLanguageCode() const {
return GetLanguageCodeAt(target_language_index());
}
void TranslateInfoBarDelegate2::SetOriginalLanguage(int language_index) {
DCHECK(language_index < static_cast<int>(languages_.size()));
original_language_index_ = language_index;
if (infobar_view_)
infobar_view_->OriginalLanguageChanged();
if (type_ == AFTER_TRANSLATE)
Translate();
}
void TranslateInfoBarDelegate2::SetTargetLanguage(int language_index) {
DCHECK(language_index < static_cast<int>(languages_.size()));
target_language_index_ = language_index;
if (infobar_view_)
infobar_view_->TargetLanguageChanged();
if (type_ == AFTER_TRANSLATE)
Translate();
}
bool TranslateInfoBarDelegate2::IsError() {
return type_ == TRANSLATION_ERROR;
}
void TranslateInfoBarDelegate2::Translate() {
Singleton<TranslateManager2>::get()->TranslatePage(
tab_contents_,
GetLanguageCodeAt(original_language_index()),
GetLanguageCodeAt(target_language_index()));
}
void TranslateInfoBarDelegate2::RevertTranslation() {
Singleton<TranslateManager2>::get()->RevertTranslation(tab_contents_);
tab_contents_->RemoveInfoBar(this);
}
void TranslateInfoBarDelegate2::TranslationDeclined() {
// Remember that the user declined the translation so as to prevent showing a
// translate infobar for that page again. (TranslateManager initiates
// translations when getting a LANGUAGE_DETERMINED from the page, which
// happens when a load stops. That could happen multiple times, including
// after the user already declined the translation.)
tab_contents_->language_state().set_translation_declined(true);
}
void TranslateInfoBarDelegate2::InfoBarDismissed() {
if (type_ != BEFORE_TRANSLATE)
return;
// The user closed the infobar without clicking the translate button.
TranslationDeclined();
UMA_HISTOGRAM_COUNTS("Translate.DeclineTranslateCloseInfobar", 1);
}
SkBitmap* TranslateInfoBarDelegate2::GetIcon() const {
return ResourceBundle::GetSharedInstance().GetBitmapNamed(
IDR_INFOBAR_TRANSLATE);
}
InfoBarDelegate::Type TranslateInfoBarDelegate2::GetInfoBarType() {
return InfoBarDelegate::PAGE_ACTION_TYPE;
}
bool TranslateInfoBarDelegate2::IsLanguageBlacklisted() {
const std::string& original_lang =
GetLanguageCodeAt(original_language_index());
return prefs_.IsLanguageBlacklisted(original_lang);
}
void TranslateInfoBarDelegate2::ToggleLanguageBlacklist() {
const std::string& original_lang =
GetLanguageCodeAt(original_language_index());
if (prefs_.IsLanguageBlacklisted(original_lang)) {
prefs_.RemoveLanguageFromBlacklist(original_lang);
} else {
prefs_.BlacklistLanguage(original_lang);
tab_contents_->RemoveInfoBar(this);
}
}
bool TranslateInfoBarDelegate2::IsSiteBlacklisted() {
std::string host = GetPageHost();
return !host.empty() && prefs_.IsSiteBlacklisted(host);
}
void TranslateInfoBarDelegate2::ToggleSiteBlacklist() {
std::string host = GetPageHost();
if (host.empty())
return;
if (prefs_.IsSiteBlacklisted(host)) {
prefs_.RemoveSiteFromBlacklist(host);
} else {
prefs_.BlacklistSite(host);
tab_contents_->RemoveInfoBar(this);
}
}
bool TranslateInfoBarDelegate2::ShouldAlwaysTranslate() {
return prefs_.IsLanguagePairWhitelisted(GetOriginalLanguageCode(),
GetTargetLanguageCode());
}
void TranslateInfoBarDelegate2::ToggleAlwaysTranslate() {
std::string original_lang = GetOriginalLanguageCode();
std::string target_lang = GetTargetLanguageCode();
if (prefs_.IsLanguagePairWhitelisted(original_lang, target_lang))
prefs_.RemoveLanguagePairFromWhitelist(original_lang, target_lang);
else
prefs_.WhitelistLanguagePair(original_lang, target_lang);
}
string16 TranslateInfoBarDelegate2::GetMessageInfoBarText() {
switch (type_) {
case TRANSLATING:
return l10n_util::GetStringFUTF16(
IDS_TRANSLATE_INFOBAR_TRANSLATING_TO,
GetLanguageDisplayableNameAt(target_language_index_));
case TRANSLATION_ERROR:
switch (error_) {
case TranslateErrors::NETWORK:
return l10n_util::GetStringUTF16(
IDS_TRANSLATE_INFOBAR_ERROR_CANT_CONNECT);
case TranslateErrors::INITIALIZATION_ERROR:
case TranslateErrors::TRANSLATION_ERROR:
return l10n_util::GetStringUTF16(
IDS_TRANSLATE_INFOBAR_ERROR_CANT_TRANSLATE);
default:
NOTREACHED();
return string16();
}
default:
NOTREACHED();
return string16();
}
}
string16 TranslateInfoBarDelegate2::GetMessageInfoBarButtonText() {
switch (type_) {
case TRANSLATING:
return string16();
case TRANSLATION_ERROR:
return l10n_util::GetStringUTF16(IDS_TRANSLATE_INFOBAR_RETRY);
default:
NOTREACHED();
return string16();
}
}
void TranslateInfoBarDelegate2::MessageInfoBarButtonPressed() {
DCHECK(type_ == TRANSLATION_ERROR);
Singleton<TranslateManager2>::get()->TranslatePage(
tab_contents_,
GetLanguageCodeAt(original_language_index()),
GetLanguageCodeAt(target_language_index()));
}
void TranslateInfoBarDelegate2::UpdateBackgroundAnimation(
TranslateInfoBarDelegate2* previous_infobar) {
if (!previous_infobar || previous_infobar->IsError() == IsError()) {
background_animation_ = NONE;
return;
}
background_animation_ = IsError() ? NORMAL_TO_ERROR : ERROR_TO_NORMAL;
}
std::string TranslateInfoBarDelegate2::GetPageHost() {
NavigationEntry* entry = tab_contents_->controller().GetActiveEntry();
return entry ? entry->url().HostNoBrackets() : std::string();
}
// static
string16 TranslateInfoBarDelegate2::GetLanguageDisplayableName(
const std::string& language_code) {
return l10n_util::GetDisplayNameForLocale(
language_code, g_browser_process->GetApplicationLocale(), true);
}
// static
void TranslateInfoBarDelegate2::GetAfterTranslateStrings(
std::vector<string16>* strings, bool* swap_languages) {
DCHECK(strings);
DCHECK(swap_languages);
std::vector<size_t> offsets;
string16 text =
l10n_util::GetStringFUTF16(IDS_TRANSLATE_INFOBAR_AFTER_MESSAGE,
string16(), string16(), &offsets);
DCHECK(offsets.size() == 2U);
if (offsets[0] > offsets[1]) {
// Target language comes before source.
int tmp = offsets[0];
offsets[0] = offsets[0];
offsets[1] = tmp;
*swap_languages = true;
} else {
*swap_languages = false;
}
strings->push_back(text.substr(0, offsets[0]));
strings->push_back(text.substr(offsets[0], offsets[1]));
strings->push_back(text.substr(offsets[1]));
}
#if !defined(OS_WIN) && !defined(OS_CHROMEOS)
// Necessary so we link OK on Mac and Linux while the new translate infobars
// are being ported to these platforms.
InfoBar* TranslateInfoBarDelegate2::CreateInfoBar() {
return NULL;
}
#endif
<commit_msg>Coverity: fix wrong assignment in swap in TranslateInfoBarDelegate2::GetAfterTranslateStrings.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <algorithm>
#include "chrome/browser/translate/translate_infobar_delegate2.h"
#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/translate/translate_infobar_view.h"
#include "chrome/browser/translate/translate_manager2.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
// static
TranslateInfoBarDelegate2* TranslateInfoBarDelegate2::CreateInstance(
Type type,
TranslateErrors::Type error,
TabContents* tab_contents,
const std::string& original_language,
const std::string& target_language) {
if (!TranslateManager2::IsSupportedLanguage(original_language) ||
!TranslateManager2::IsSupportedLanguage(target_language)) {
return NULL;
}
return new TranslateInfoBarDelegate2(type, error, tab_contents,
original_language, target_language);
}
TranslateInfoBarDelegate2::TranslateInfoBarDelegate2(
Type type,
TranslateErrors::Type error,
TabContents* tab_contents,
const std::string& original_language,
const std::string& target_language)
: InfoBarDelegate(tab_contents),
type_(type),
background_animation_(NONE),
tab_contents_(tab_contents),
original_language_index_(-1),
target_language_index_(-1),
error_(error),
infobar_view_(NULL),
prefs_(tab_contents_->profile()->GetPrefs()) {
DCHECK((type_ != TRANSLATION_ERROR && error == TranslateErrors::NONE) ||
(type_ == TRANSLATION_ERROR && error != TranslateErrors::NONE));
std::vector<std::string> language_codes;
TranslateManager2::GetSupportedLanguages(&language_codes);
languages_.reserve(language_codes.size());
for (std::vector<std::string>::const_iterator iter = language_codes.begin();
iter != language_codes.end(); ++iter) {
std::string language_code = *iter;
if (language_code == original_language)
original_language_index_ = iter - language_codes.begin();
else if (language_code == target_language)
target_language_index_ = iter - language_codes.begin();
string16 language_name = GetLanguageDisplayableName(language_code);
// Insert the language in languages_ in alphabetical order.
std::vector<LanguageNamePair>::iterator iter2;
for (iter2 = languages_.begin(); iter2 != languages_.end(); ++iter2) {
if (language_name.compare(iter2->second) < 0)
break;
}
languages_.insert(iter2, LanguageNamePair(language_code, language_name));
}
DCHECK(original_language_index_ != -1);
DCHECK(target_language_index_ != -1);
}
int TranslateInfoBarDelegate2::GetLanguageCount() const {
return static_cast<int>(languages_.size());
}
const std::string& TranslateInfoBarDelegate2::GetLanguageCodeAt(
int index) const {
DCHECK(index >=0 && index < GetLanguageCount());
return languages_[index].first;
}
const string16& TranslateInfoBarDelegate2::GetLanguageDisplayableNameAt(
int index) const {
DCHECK(index >=0 && index < GetLanguageCount());
return languages_[index].second;
}
const std::string& TranslateInfoBarDelegate2::GetOriginalLanguageCode() const {
return GetLanguageCodeAt(original_language_index());
}
const std::string& TranslateInfoBarDelegate2::GetTargetLanguageCode() const {
return GetLanguageCodeAt(target_language_index());
}
void TranslateInfoBarDelegate2::SetOriginalLanguage(int language_index) {
DCHECK(language_index < static_cast<int>(languages_.size()));
original_language_index_ = language_index;
if (infobar_view_)
infobar_view_->OriginalLanguageChanged();
if (type_ == AFTER_TRANSLATE)
Translate();
}
void TranslateInfoBarDelegate2::SetTargetLanguage(int language_index) {
DCHECK(language_index < static_cast<int>(languages_.size()));
target_language_index_ = language_index;
if (infobar_view_)
infobar_view_->TargetLanguageChanged();
if (type_ == AFTER_TRANSLATE)
Translate();
}
bool TranslateInfoBarDelegate2::IsError() {
return type_ == TRANSLATION_ERROR;
}
void TranslateInfoBarDelegate2::Translate() {
Singleton<TranslateManager2>::get()->TranslatePage(
tab_contents_,
GetLanguageCodeAt(original_language_index()),
GetLanguageCodeAt(target_language_index()));
}
void TranslateInfoBarDelegate2::RevertTranslation() {
Singleton<TranslateManager2>::get()->RevertTranslation(tab_contents_);
tab_contents_->RemoveInfoBar(this);
}
void TranslateInfoBarDelegate2::TranslationDeclined() {
// Remember that the user declined the translation so as to prevent showing a
// translate infobar for that page again. (TranslateManager initiates
// translations when getting a LANGUAGE_DETERMINED from the page, which
// happens when a load stops. That could happen multiple times, including
// after the user already declined the translation.)
tab_contents_->language_state().set_translation_declined(true);
}
void TranslateInfoBarDelegate2::InfoBarDismissed() {
if (type_ != BEFORE_TRANSLATE)
return;
// The user closed the infobar without clicking the translate button.
TranslationDeclined();
UMA_HISTOGRAM_COUNTS("Translate.DeclineTranslateCloseInfobar", 1);
}
SkBitmap* TranslateInfoBarDelegate2::GetIcon() const {
return ResourceBundle::GetSharedInstance().GetBitmapNamed(
IDR_INFOBAR_TRANSLATE);
}
InfoBarDelegate::Type TranslateInfoBarDelegate2::GetInfoBarType() {
return InfoBarDelegate::PAGE_ACTION_TYPE;
}
bool TranslateInfoBarDelegate2::IsLanguageBlacklisted() {
const std::string& original_lang =
GetLanguageCodeAt(original_language_index());
return prefs_.IsLanguageBlacklisted(original_lang);
}
void TranslateInfoBarDelegate2::ToggleLanguageBlacklist() {
const std::string& original_lang =
GetLanguageCodeAt(original_language_index());
if (prefs_.IsLanguageBlacklisted(original_lang)) {
prefs_.RemoveLanguageFromBlacklist(original_lang);
} else {
prefs_.BlacklistLanguage(original_lang);
tab_contents_->RemoveInfoBar(this);
}
}
bool TranslateInfoBarDelegate2::IsSiteBlacklisted() {
std::string host = GetPageHost();
return !host.empty() && prefs_.IsSiteBlacklisted(host);
}
void TranslateInfoBarDelegate2::ToggleSiteBlacklist() {
std::string host = GetPageHost();
if (host.empty())
return;
if (prefs_.IsSiteBlacklisted(host)) {
prefs_.RemoveSiteFromBlacklist(host);
} else {
prefs_.BlacklistSite(host);
tab_contents_->RemoveInfoBar(this);
}
}
bool TranslateInfoBarDelegate2::ShouldAlwaysTranslate() {
return prefs_.IsLanguagePairWhitelisted(GetOriginalLanguageCode(),
GetTargetLanguageCode());
}
void TranslateInfoBarDelegate2::ToggleAlwaysTranslate() {
std::string original_lang = GetOriginalLanguageCode();
std::string target_lang = GetTargetLanguageCode();
if (prefs_.IsLanguagePairWhitelisted(original_lang, target_lang))
prefs_.RemoveLanguagePairFromWhitelist(original_lang, target_lang);
else
prefs_.WhitelistLanguagePair(original_lang, target_lang);
}
string16 TranslateInfoBarDelegate2::GetMessageInfoBarText() {
switch (type_) {
case TRANSLATING:
return l10n_util::GetStringFUTF16(
IDS_TRANSLATE_INFOBAR_TRANSLATING_TO,
GetLanguageDisplayableNameAt(target_language_index_));
case TRANSLATION_ERROR:
switch (error_) {
case TranslateErrors::NETWORK:
return l10n_util::GetStringUTF16(
IDS_TRANSLATE_INFOBAR_ERROR_CANT_CONNECT);
case TranslateErrors::INITIALIZATION_ERROR:
case TranslateErrors::TRANSLATION_ERROR:
return l10n_util::GetStringUTF16(
IDS_TRANSLATE_INFOBAR_ERROR_CANT_TRANSLATE);
default:
NOTREACHED();
return string16();
}
default:
NOTREACHED();
return string16();
}
}
string16 TranslateInfoBarDelegate2::GetMessageInfoBarButtonText() {
switch (type_) {
case TRANSLATING:
return string16();
case TRANSLATION_ERROR:
return l10n_util::GetStringUTF16(IDS_TRANSLATE_INFOBAR_RETRY);
default:
NOTREACHED();
return string16();
}
}
void TranslateInfoBarDelegate2::MessageInfoBarButtonPressed() {
DCHECK(type_ == TRANSLATION_ERROR);
Singleton<TranslateManager2>::get()->TranslatePage(
tab_contents_,
GetLanguageCodeAt(original_language_index()),
GetLanguageCodeAt(target_language_index()));
}
void TranslateInfoBarDelegate2::UpdateBackgroundAnimation(
TranslateInfoBarDelegate2* previous_infobar) {
if (!previous_infobar || previous_infobar->IsError() == IsError()) {
background_animation_ = NONE;
return;
}
background_animation_ = IsError() ? NORMAL_TO_ERROR : ERROR_TO_NORMAL;
}
std::string TranslateInfoBarDelegate2::GetPageHost() {
NavigationEntry* entry = tab_contents_->controller().GetActiveEntry();
return entry ? entry->url().HostNoBrackets() : std::string();
}
// static
string16 TranslateInfoBarDelegate2::GetLanguageDisplayableName(
const std::string& language_code) {
return l10n_util::GetDisplayNameForLocale(
language_code, g_browser_process->GetApplicationLocale(), true);
}
// static
void TranslateInfoBarDelegate2::GetAfterTranslateStrings(
std::vector<string16>* strings, bool* swap_languages) {
DCHECK(strings);
DCHECK(swap_languages);
std::vector<size_t> offsets;
string16 text =
l10n_util::GetStringFUTF16(IDS_TRANSLATE_INFOBAR_AFTER_MESSAGE,
string16(), string16(), &offsets);
DCHECK(offsets.size() == 2U);
if (offsets[0] > offsets[1]) {
// Target language comes before source.
std::swap(offsets[0], offsets[1]);
*swap_languages = true;
} else {
*swap_languages = false;
}
strings->push_back(text.substr(0, offsets[0]));
strings->push_back(text.substr(offsets[0], offsets[1]));
strings->push_back(text.substr(offsets[1]));
}
#if !defined(OS_WIN) && !defined(OS_CHROMEOS)
// Necessary so we link OK on Mac and Linux while the new translate infobars
// are being ported to these platforms.
InfoBar* TranslateInfoBarDelegate2::CreateInfoBar() {
return NULL;
}
#endif
<|endoftext|> |
<commit_before>// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <mesos/quota/quota.hpp>
#include <process/metrics/metrics.hpp>
#include <stout/strings.hpp>
#include "master/allocator/mesos/hierarchical.hpp"
#include "master/allocator/mesos/metrics.hpp"
using std::string;
using std::vector;
using process::metrics::Gauge;
namespace mesos {
namespace internal {
namespace master {
namespace allocator {
namespace internal {
Metrics::Metrics(const HierarchicalAllocatorProcess& _allocator)
: allocator(_allocator.self()),
event_queue_dispatches(
"allocator/mesos/event_queue_dispatches",
process::defer(
allocator, &HierarchicalAllocatorProcess::_event_queue_dispatches)),
event_queue_dispatches_(
"allocator/event_queue_dispatches",
process::defer(
allocator, &HierarchicalAllocatorProcess::_event_queue_dispatches)),
allocation_runs("allocator/mesos/allocation_runs"),
allocation_run("allocator/mesos/allocation_run", Hours(1))
{
process::metrics::add(event_queue_dispatches);
process::metrics::add(event_queue_dispatches_);
process::metrics::add(allocation_runs);
process::metrics::add(allocation_run);
// Create and install gauges for the total and allocated
// amount of standard scalar resources.
//
// TODO(bbannier) Add support for more than just scalar resources.
// TODO(bbannier) Simplify this once MESOS-3214 is fixed.
// TODO(dhamon): Set these up dynamically when adding a slave based on the
// resources the slave exposes.
string resources[] = {"cpus", "mem", "disk"};
foreach (const string& resource, resources) {
Gauge total(
"allocator/mesos/resources/" + resource + "/total",
defer(allocator,
&HierarchicalAllocatorProcess::_resources_total,
resource));
Gauge offered_or_allocated(
"allocator/mesos/resources/" + resource + "/offered_or_allocated",
defer(allocator,
&HierarchicalAllocatorProcess::_resources_offered_or_allocated,
resource));
resources_total.push_back(total);
resources_offered_or_allocated.push_back(offered_or_allocated);
process::metrics::add(total);
process::metrics::add(offered_or_allocated);
}
}
Metrics::~Metrics()
{
process::metrics::remove(event_queue_dispatches);
process::metrics::remove(event_queue_dispatches_);
process::metrics::remove(allocation_runs);
process::metrics::remove(allocation_run);
foreach (const Gauge& gauge, resources_total) {
process::metrics::remove(gauge);
}
foreach (const Gauge& gauge, resources_offered_or_allocated) {
process::metrics::remove(gauge);
}
foreachkey(const string& role, quota_allocated) {
foreachvalue(const Gauge& gauge, quota_allocated[role]) {
process::metrics::remove(gauge);
}
}
foreachkey(const string& role, quota_guarantee) {
foreachvalue(const Gauge& gauge, quota_guarantee[role]) {
process::metrics::remove(gauge);
}
}
}
void Metrics::setQuota(const string& role, const Quota& quota)
{
CHECK(!quota_allocated.contains(role));
hashmap<string, Gauge> allocated;
hashmap<string, Gauge> guarantees;
foreach (const Resource& resource, quota.info.guarantee()) {
CHECK_EQ(Value::SCALAR, resource.type());
double value = resource.scalar().value();
Gauge guarantee = Gauge(
"allocator/mesos/quota"
"/roles/" + role +
"/resources/" + resource.name() +
"/guarantee",
process::defer([value]() { return value; }));
Gauge offered_or_allocated(
"allocator/mesos/quota"
"/roles/" + role +
"/resources/" + resource.name() +
"/offered_or_allocated",
defer(allocator,
&HierarchicalAllocatorProcess::_quota_allocated,
role,
resource.name()));
guarantees.put(resource.name(), guarantee);
allocated.put(resource.name(), offered_or_allocated);
process::metrics::add(guarantee);
process::metrics::add(offered_or_allocated);
}
quota_allocated[role] = allocated;
quota_guarantee[role] = guarantees;
}
void Metrics::removeQuota(const string& role)
{
CHECK(quota_allocated.contains(role));
foreachvalue (const Gauge& gauge, quota_allocated[role]) {
process::metrics::remove(gauge);
}
quota_allocated.erase(role);
}
} // namespace internal {
} // namespace allocator {
} // namespace master {
} // namespace internal {
} // namespace mesos {
<commit_msg>Style fix in allocator metrics.<commit_after>// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <mesos/quota/quota.hpp>
#include <process/metrics/metrics.hpp>
#include <stout/strings.hpp>
#include "master/allocator/mesos/hierarchical.hpp"
#include "master/allocator/mesos/metrics.hpp"
using std::string;
using std::vector;
using process::metrics::Gauge;
namespace mesos {
namespace internal {
namespace master {
namespace allocator {
namespace internal {
Metrics::Metrics(const HierarchicalAllocatorProcess& _allocator)
: allocator(_allocator.self()),
event_queue_dispatches(
"allocator/mesos/event_queue_dispatches",
process::defer(
allocator, &HierarchicalAllocatorProcess::_event_queue_dispatches)),
event_queue_dispatches_(
"allocator/event_queue_dispatches",
process::defer(
allocator, &HierarchicalAllocatorProcess::_event_queue_dispatches)),
allocation_runs("allocator/mesos/allocation_runs"),
allocation_run("allocator/mesos/allocation_run", Hours(1))
{
process::metrics::add(event_queue_dispatches);
process::metrics::add(event_queue_dispatches_);
process::metrics::add(allocation_runs);
process::metrics::add(allocation_run);
// Create and install gauges for the total and allocated
// amount of standard scalar resources.
//
// TODO(bbannier) Add support for more than just scalar resources.
// TODO(bbannier) Simplify this once MESOS-3214 is fixed.
// TODO(dhamon): Set these up dynamically when adding a slave based on the
// resources the slave exposes.
string resources[] = {"cpus", "mem", "disk"};
foreach (const string& resource, resources) {
Gauge total(
"allocator/mesos/resources/" + resource + "/total",
defer(allocator,
&HierarchicalAllocatorProcess::_resources_total,
resource));
Gauge offered_or_allocated(
"allocator/mesos/resources/" + resource + "/offered_or_allocated",
defer(allocator,
&HierarchicalAllocatorProcess::_resources_offered_or_allocated,
resource));
resources_total.push_back(total);
resources_offered_or_allocated.push_back(offered_or_allocated);
process::metrics::add(total);
process::metrics::add(offered_or_allocated);
}
}
Metrics::~Metrics()
{
process::metrics::remove(event_queue_dispatches);
process::metrics::remove(event_queue_dispatches_);
process::metrics::remove(allocation_runs);
process::metrics::remove(allocation_run);
foreach (const Gauge& gauge, resources_total) {
process::metrics::remove(gauge);
}
foreach (const Gauge& gauge, resources_offered_or_allocated) {
process::metrics::remove(gauge);
}
foreachkey (const string& role, quota_allocated) {
foreachvalue (const Gauge& gauge, quota_allocated[role]) {
process::metrics::remove(gauge);
}
}
foreachkey (const string& role, quota_guarantee) {
foreachvalue (const Gauge& gauge, quota_guarantee[role]) {
process::metrics::remove(gauge);
}
}
}
void Metrics::setQuota(const string& role, const Quota& quota)
{
CHECK(!quota_allocated.contains(role));
hashmap<string, Gauge> allocated;
hashmap<string, Gauge> guarantees;
foreach (const Resource& resource, quota.info.guarantee()) {
CHECK_EQ(Value::SCALAR, resource.type());
double value = resource.scalar().value();
Gauge guarantee = Gauge(
"allocator/mesos/quota"
"/roles/" + role +
"/resources/" + resource.name() +
"/guarantee",
process::defer([value]() { return value; }));
Gauge offered_or_allocated(
"allocator/mesos/quota"
"/roles/" + role +
"/resources/" + resource.name() +
"/offered_or_allocated",
defer(allocator,
&HierarchicalAllocatorProcess::_quota_allocated,
role,
resource.name()));
guarantees.put(resource.name(), guarantee);
allocated.put(resource.name(), offered_or_allocated);
process::metrics::add(guarantee);
process::metrics::add(offered_or_allocated);
}
quota_allocated[role] = allocated;
quota_guarantee[role] = guarantees;
}
void Metrics::removeQuota(const string& role)
{
CHECK(quota_allocated.contains(role));
foreachvalue (const Gauge& gauge, quota_allocated[role]) {
process::metrics::remove(gauge);
}
quota_allocated.erase(role);
}
} // namespace internal {
} // namespace allocator {
} // namespace master {
} // namespace internal {
} // namespace mesos {
<|endoftext|> |
<commit_before>/*++
Copyright (c) 2006 Microsoft Corporation
Module Name:
smtlib_frontend.cpp
Abstract:
Frontend for reading Smtlib input files
Author:
Nikolaj Bjorner (nbjorner) 2006-11-3.
Revision History:
Leonardo de Moura: new SMT 2.0 front-end, removed support for .smtc files and smtcmd_solver object.
--*/
#include<iostream>
#include<time.h>
#include<signal.h>
#include"smtlib_solver.h"
#include"timeout.h"
#include"smt2parser.h"
#include"dl_cmds.h"
#include"dbg_cmds.h"
#include"polynomial_cmds.h"
#include"subpaving_cmds.h"
#include"smt_strategic_solver.h"
#include"smt_solver.h"
extern bool g_display_statistics;
extern void display_config();
static clock_t g_start_time;
static smtlib::solver* g_solver = 0;
static cmd_context * g_cmd_context = 0;
static void display_statistics() {
clock_t end_time = clock();
if ((g_solver || g_cmd_context) && g_display_statistics) {
std::cout.flush();
std::cerr.flush();
if (g_solver) {
g_solver->display_statistics();
memory::display_max_usage(std::cout);
std::cout << "time: " << ((static_cast<double>(end_time) - static_cast<double>(g_start_time)) / CLOCKS_PER_SEC) << " secs\n";
}
else if (g_cmd_context) {
g_cmd_context->set_regular_stream("stdout");
g_cmd_context->display_statistics(true, ((static_cast<double>(end_time) - static_cast<double>(g_start_time)) / CLOCKS_PER_SEC));
}
}
}
static void on_timeout() {
#pragma omp critical (g_display_stats)
{
display_statistics();
exit(0);
}
}
static void on_ctrl_c(int) {
signal (SIGINT, SIG_DFL);
#pragma omp critical (g_display_stats)
{
display_statistics();
}
raise(SIGINT);
}
unsigned read_smtlib_file(char const * benchmark_file) {
g_start_time = clock();
register_on_timeout_proc(on_timeout);
signal(SIGINT, on_ctrl_c);
smtlib::solver solver;
g_solver = &solver;
bool ok = true;
ok = solver.solve_smt(benchmark_file);
if (!ok) {
if (benchmark_file) {
std::cerr << "ERROR: solving '" << benchmark_file << "'.\n";
}
else {
std::cerr << "ERROR: solving input stream.\n";
}
}
#pragma omp critical (g_display_stats)
{
display_statistics();
register_on_timeout_proc(0);
g_solver = 0;
}
return solver.get_error_code();
}
unsigned read_smtlib2_commands(char const * file_name) {
g_start_time = clock();
register_on_timeout_proc(on_timeout);
signal(SIGINT, on_ctrl_c);
cmd_context ctx;
ctx.set_solver_factory(mk_smt_strategic_solver_factory());
ctx.set_interpolating_solver_factory(mk_smt_solver_factory());
install_dl_cmds(ctx);
install_dbg_cmds(ctx);
install_polynomial_cmds(ctx);
install_subpaving_cmds(ctx);
g_cmd_context = &ctx;
signal(SIGINT, on_ctrl_c);
bool result = true;
if (file_name) {
std::ifstream in(file_name);
if (in.bad() || in.fail()) {
std::cerr << "(error \"failed to open file '" << file_name << "'\")" << std::endl;
exit(ERR_OPEN_FILE);
}
result = parse_smt2_commands(ctx, in);
in.close();
}
else {
result = parse_smt2_commands(ctx, std::cin, true);
}
#pragma omp critical (g_display_stats)
{
display_statistics();
g_cmd_context = 0;
}
return result ? 0 : 1;
}
<commit_msg>undid previous fix<commit_after>/*++
Copyright (c) 2006 Microsoft Corporation
Module Name:
smtlib_frontend.cpp
Abstract:
Frontend for reading Smtlib input files
Author:
Nikolaj Bjorner (nbjorner) 2006-11-3.
Revision History:
Leonardo de Moura: new SMT 2.0 front-end, removed support for .smtc files and smtcmd_solver object.
--*/
#include<iostream>
#include<time.h>
#include<signal.h>
#include"smtlib_solver.h"
#include"timeout.h"
#include"smt2parser.h"
#include"dl_cmds.h"
#include"dbg_cmds.h"
#include"polynomial_cmds.h"
#include"subpaving_cmds.h"
#include"smt_strategic_solver.h"
#include"smt_solver.h"
extern bool g_display_statistics;
extern void display_config();
static clock_t g_start_time;
static smtlib::solver* g_solver = 0;
static cmd_context * g_cmd_context = 0;
static void display_statistics() {
clock_t end_time = clock();
if ((g_solver || g_cmd_context) && g_display_statistics) {
std::cout.flush();
std::cerr.flush();
if (g_solver) {
g_solver->display_statistics();
memory::display_max_usage(std::cout);
std::cout << "time: " << ((static_cast<double>(end_time) - static_cast<double>(g_start_time)) / CLOCKS_PER_SEC) << " secs\n";
}
else if (g_cmd_context) {
g_cmd_context->set_regular_stream("stdout");
g_cmd_context->display_statistics(true, ((static_cast<double>(end_time) - static_cast<double>(g_start_time)) / CLOCKS_PER_SEC));
}
}
}
static void on_timeout() {
#pragma omp critical (g_display_stats)
{
display_statistics();
exit(0);
}
}
static void on_ctrl_c(int) {
signal (SIGINT, SIG_DFL);
#pragma omp critical (g_display_stats)
{
display_statistics();
}
raise(SIGINT);
}
unsigned read_smtlib_file(char const * benchmark_file) {
g_start_time = clock();
register_on_timeout_proc(on_timeout);
signal(SIGINT, on_ctrl_c);
smtlib::solver solver;
g_solver = &solver;
bool ok = true;
ok = solver.solve_smt(benchmark_file);
if (!ok) {
if (benchmark_file) {
std::cerr << "ERROR: solving '" << benchmark_file << "'.\n";
}
else {
std::cerr << "ERROR: solving input stream.\n";
}
}
#pragma omp critical (g_display_stats)
{
display_statistics();
register_on_timeout_proc(0);
g_solver = 0;
}
return solver.get_error_code();
}
unsigned read_smtlib2_commands(char const * file_name) {
g_start_time = clock();
register_on_timeout_proc(on_timeout);
signal(SIGINT, on_ctrl_c);
cmd_context ctx;
ctx.set_solver_factory(mk_smt_strategic_solver_factory());
ctx.set_interpolating_solver_factory(mk_smt_solver_factory());
install_dl_cmds(ctx);
install_dbg_cmds(ctx);
install_polynomial_cmds(ctx);
install_subpaving_cmds(ctx);
g_cmd_context = &ctx;
signal(SIGINT, on_ctrl_c);
bool result = true;
if (file_name) {
std::ifstream in(file_name);
if (in.bad() || in.fail()) {
std::cerr << "(error \"failed to open file '" << file_name << "'\")" << std::endl;
exit(ERR_OPEN_FILE);
}
result = parse_smt2_commands(ctx, in);
}
else {
result = parse_smt2_commands(ctx, std::cin, true);
}
#pragma omp critical (g_display_stats)
{
display_statistics();
g_cmd_context = 0;
}
return result ? 0 : 1;
}
<|endoftext|> |
<commit_before>/*
The MIT License(MIT)
Copyright(c) 2015 Armen Amirkhanian
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files(the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions :
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
// FuBeam (*Fu*damental Beam)
// Author: Armen Amirkhanian
// Calculates the deflection of a beam on an elastic foundation with possible separation.
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
#include <exception>
#include <cmath>
int main(){
std::string temp_diff, beam_thick, beam_leng, Em, rho, cote, kvalue;
std::string num_points, file_name;
double dT, h, L, E, UW, alpha, k;
std::cout << "Enter temperature differential (deg F): ";
std::cin >> temp_diff;
std::cout << temp_diff << " deg F\n";
std::cout << "Enter beam thickness (in): ";
std::cin >> beam_thick;
std::cout << beam_thick << " in\n";
std::cout << "Enter beam length (in): ";
std::cin >> beam_leng;
std::cout << beam_leng << " in\n";
std::cout << "Enter beam modulus of elasticity (psi): ";
std::cin >> Em;
std::cout << Em << " psi\n";
std::cout << "Enter beam unit weight (lbs/ft3): ";
std::cin >> rho;
std::cout << rho << " lbs/ft3\n";
std::cout << "Enter the beam coeff. of thermal expansion (1/F x10-5): ";
std::cin >> cote;
std::cout << cote << "E-05 /F\n";
std::cout << "Enter subgrad k-value (pci): ";
std::cin >> kvalue;
std::cout << kvalue << " pci\n";
std::cout << "How many points to generate for plot? ";
std::cin >> num_points;
std::cout << num_points << " points will be generated.\n";
std::cout << "Enter file name for output of points: ";
std::cin >> file_name;
std::cout << "Data points will be outputted to " << file_name;
try{
dT = stod(temp_diff);
h = stod(beam_thick);
L = stod(beam_leng);
E = stod(Em);
UW = stod(rho);
alpha = stod(cote);
k = stod(kvalue);
}
catch (const std::invalid_argument ia){
std::cout << "\nOne of the values entered is incorrect.\nGeneral Error: INVALID ARGUMENT\nSpecific Error: " << ia.what() << "\nTHIS ERROR IS IRRECOVERABLE. PROGRAM TERMINATING...\n";
exit(EXIT_FAILURE);
}
catch (...){
std::cout << "\nGENERAL EXCEPTION THROWN. UNRECOVERABLE. PROGRAM TERMINATING...\n";
exit(EXIT_FAILURE);
}
std::ofstream output_file;
// The underscore for the hardfail option is a bit puzzling. There is no data from MSDN about it.
output_file.exceptions(std::ofstream::failbit | std::ofstream::badbit | std::ofstream::_Hardfail);
try{
output_file.open(file_name);
}
catch (std::ofstream::failure e){
std::cout << "Failure reading creating file. Please make sure the file name does not conflict with an existing name. Also make sure you have write access to the location you are outputting data to.";
exit(EXIT_FAILURE);
}
}<commit_msg>First MWE. F4 calculation factor needs to be looked up and coded in.<commit_after>/*
The MIT License(MIT)
Copyright(c) 2015 Armen Amirkhanian
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files(the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions :
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
// FuBeam (*Fu*damental Beam)
// Author: Armen Amirkhanian
// Calculates the deflection of a beam on an elastic foundation with possible separation.
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
#include <exception>
#include <cmath>
// Deflection due to uniform load and Winkler foundation
double uni_defl(double beta, double UW, double L, double C2, double C3, double C4, double C11, double E, double I, double x){
// Ra, Ma, and thetaA boundary conditions go to zero for loading conditions
// The entire equation for uniform load deflection is included in case
// there is a desire to model different conditions in the future
double Ra, Ma, thetaA, F1, F2, F3, F4, F5, wAp;
Ra = 0;
Ma = 0;
thetaA = 0;
F1 = cosh(beta*x)*cos(beta*x);
F2 = cosh(beta*x)*sin(beta*x) + sinh(beta*x)*cos(beta*x);
F3 = sinh(beta*x)*sin(beta*x);
F5 = 1 - cosh(beta*x)*cos(beta*x);
wAp = (UW*(C4*C2 - 2 * pow(C3, 2))) / (4 * E*I*pow(beta, 4)*C11);
double wp;
wp = wAp*F1 + (thetaA*F2) / (2 * beta) + (Ma*F3) / (2 * E*I*pow(beta, 2)) + (Ra*F4) / (4 * E*I*pow(beta, 3)) - (UW*F5) / (4 * E*I*pow(beta, 4));
return wp;
}
// Deflection due to temperature differential
double temp_defl(double dT, double beta, double t, double gamma, double E, double I, double C1, double C2, double C3, double C4, double C11){
// Ra and Ma boundary conditions go to zero for the loading conditions
// The entire equation of temperature deflection is included in case
// there is a desire to model different conditions in the future
double Ra, Ma, F1, F2, F3, F4, thetaA, wAT, x;
Ra = 0;
Ma = 0;
thetaA = (-(dT)*gamma*(C1*C2 + C3*C4 - C2)) / (beta*t*C11);
wAT = (-(dT)*gamma*(pow(C4, 2) + 2 * C1*C3 - 2 * C3)) / (2 * pow(beta, 2)*t*C11);
F1 = cosh(beta*x)*cos(beta*x);
F2 = cosh(beta*x)*sin(beta*x) + sinh(beta*x)*cos(beta*x);
F3 = sinh(beta*x)*sin(beta*x);
double wt;
wt = wAT*F1 + (thetaA*F2) / (2 * beta) + (Ma*F3) / (2 * E*I*pow(beta, 2)) + (Ra*F4) / (4 * E*I*pow(beta, 3)) - ((dT)*gamma*F3) / (2 * t*pow(beta, 2));
return wt;
}
int main(){
std::string temp_diff, beam_thick, beam_leng, beam_width, Em, rho, cote, kvalue;
std::string num_points, file_name;
double dT, h, L, bo, E, UW, gamma, k, x;
int N;
std::cout << "Enter temperature differential (deg F): ";
std::cin >> temp_diff;
std::cout << temp_diff << " deg F\n";
std::cout << "Enter beam thickness (in): ";
std::cin >> beam_thick;
std::cout << beam_thick << " in\n";
std::cout << "Enter beam length (in): ";
std::cin >> beam_leng;
std::cout << beam_leng << " in\n";
std::cout << "Enter beam width (in): ";
std::cin >> beam_width;
std::cout << beam_width << " in\n";
std::cout << "Enter beam modulus of elasticity (psi): ";
std::cin >> Em;
std::cout << Em << " psi\n";
std::cout << "Enter beam unit weight (lbs/ft3): ";
std::cin >> rho;
std::cout << rho << " lbs/ft3\n";
std::cout << "Enter the beam coeff. of thermal expansion (1/F x10-5): ";
std::cin >> cote;
std::cout << cote << "E-05 /F\n";
std::cout << "Enter subgrad k-value (pci): ";
std::cin >> kvalue;
std::cout << kvalue << " pci\n";
std::cout << "How many points to generate for plot? ";
std::cin >> num_points;
std::cout << num_points << " points will be generated.\n";
std::cout << "Enter file name for output of points: ";
std::cin >> file_name;
std::cout << "Data points will be outputted to " << file_name;
try{
dT = stod(temp_diff);
h = stod(beam_thick);
L = stod(beam_leng);
bo = stod(beam_width);
E = stod(Em);
UW = stod(rho);
gamma = stod(cote);
k = stod(kvalue);
N = stod(num_points);
}
catch (const std::invalid_argument ia){
std::cout << "\nOne of the values entered is incorrect.\nGeneral Error: INVALID ARGUMENT\nSpecific Error: " << ia.what() << "\nTHIS ERROR IS IRRECOVERABLE. PROGRAM TERMINATING...\n";
exit(EXIT_FAILURE);
}
catch (...){
std::cout << "\nGENERAL EXCEPTION THROWN. UNRECOVERABLE. PROGRAM TERMINATING...\n";
exit(EXIT_FAILURE);
}
std::ofstream output_file;
// The underscore for the hardfail option is a bit puzzling. There is no data from MSDN about it.
output_file.exceptions(std::ofstream::failbit | std::ofstream::badbit | std::ofstream::_Hardfail);
try{
output_file.open(file_name);
}
catch (std::ofstream::failure e){
std::cout << "Failure reading creating file. Please make sure the file name does not conflict with an existing name. Also make sure you have write access to the location you are outputting data to.";
exit(EXIT_FAILURE);
}
// Calculate moment of inertia
double I;
I = (bo*pow(h,3)) / 12.0;
// Calculate beta factor, constant for any location
double beta;
beta = pow((bo*k)/(4*E*I), 1.0 / 4.0);
// Calculate boundary condition factors
double C1, C2, C3, C4, C11;
C1 = cosh(beta*L)*cos(beta*L);
C2 = cosh(beta*L)*sin(beta*L) + sinh(beta*L)*cos(beta*L);
C3 = sinh(beta*L)*sin(beta*L);
C4 = cosh(beta*L)*sin(beta*L) - sinh(beta*L)*cos(beta*L);
C11 = pow(sinh(beta*L), 2) - pow(sin(beta*L), 2);
// Write header for output file
output_file << "Output file from FuBeam\n";
output_file << "Temperature differential: " << temp_diff << " deg F\n";
output_file << "Beam thickness: " << beam_thick << " in\n";
output_file << "Beam length: " << beam_leng << " in\n";
output_file << "Beam width: " << beam_width << " in\n";
output_file << "Elastic Modulus: " << Em << " psi\n";
output_file << "Unit weight: " << rho << " lbs/ft3\n";
output_file << "Coeff. of thermal expansion: " << cote << "E-05 /F\n";
output_file << "Subgrade modulus: " << kvalue << " pci\n";
output_file << num_points << " points will be generated.\n";
output_file << "Dist. From End [in]\t" << "Deflection [in]\n";
for (int i = 0; i < N; i++){
x = (i / N)*L;
output_file << x << "\t";
output_file << temp_defl(dT, beta, h, gamma, E, I, C1, C2, C3, C4, C11) + uni_defl(beta, UW, L, C2, C3, C4, C11, E, I, x) << "\n";
}
}<|endoftext|> |
<commit_before>/* Copyright 2007-2015 QReal Research Group
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License. */
#include "metaEditorSupportPlugin.h"
#include <QtCore/QProcess>
#include <QtWidgets/QApplication>
#include <QtWidgets/QFileDialog>
#include <QtWidgets/QMessageBox>
#include <QtWidgets/QProgressBar>
#include <QtWidgets/QDesktopWidget>
#include <qrkernel/settingsManager.h>
#include <qrmc/metaCompiler.h>
#include "editorGenerator.h"
#include "xmlParser.h"
using namespace qReal;
using namespace metaEditor;
MetaEditorSupportPlugin::MetaEditorSupportPlugin()
: mGenerateEditorForQrxcAction(NULL)
, mGenerateEditorWithQrmcAction(NULL)
, mParseEditorXmlAction(NULL)
, mRepoControlApi(NULL)
, mCompilerSettingsPage(new PreferencesCompilerPage())
{
}
MetaEditorSupportPlugin::~MetaEditorSupportPlugin()
{
}
void MetaEditorSupportPlugin::init(PluginConfigurator const &configurator)
{
mMainWindowInterface = &configurator.mainWindowInterpretersInterface();
mLogicalRepoApi = &configurator.logicalModelApi().mutableLogicalRepoApi();
mRepoControlApi = &configurator.repoControlInterface();
}
QList<ActionInfo> MetaEditorSupportPlugin::actions()
{
mGenerateEditorForQrxcAction.setText(tr("Generate editor"));
ActionInfo generateEditorForQrxcActionInfo(&mGenerateEditorForQrxcAction, "generators", "tools");
connect(&mGenerateEditorForQrxcAction, SIGNAL(triggered()), this, SLOT(generateEditorForQrxc()));
mGenerateEditorWithQrmcAction.setText(tr("Generate editor (qrmc)"));
ActionInfo generateEditorWithQrmcActionInfo(&mGenerateEditorWithQrmcAction, "generators", "tools");
connect(&mGenerateEditorWithQrmcAction, SIGNAL(triggered()), this, SLOT(generateEditorWithQrmc()));
/*
mParseEditorXmlAction.setText(tr("Parse editor xml")); // button for parsing xml, doesn't work
ActionInfo parseEditorXmlActionInfo(&mParseEditorXmlAction, "generators", "tools");
connect(&mParseEditorXmlAction, SIGNAL(triggered()), this, SLOT(parseEditorXml()));
*/
return QList<ActionInfo>() << generateEditorForQrxcActionInfo
<< generateEditorWithQrmcActionInfo;
//<< parseEditorXmlActionInfo;
}
QPair<QString, gui::PreferencesPage *> MetaEditorSupportPlugin::preferencesPage()
{
return qMakePair(QObject::tr("Compiler"), static_cast<gui::PreferencesPage *>(mCompilerSettingsPage));
}
void MetaEditorSupportPlugin::generateEditorForQrxc()
{
EditorGenerator editorGenerator(*mLogicalRepoApi, *mMainWindowInterface->errorReporter());
QDir dir(".");
QHash<Id, QPair<QString, QString> > metamodelList = editorGenerator.getMetamodelList();
foreach (Id const &key, metamodelList.keys()) {
QString const nameOfTheDirectory = metamodelList[key].first;
QString const pathToQRealRoot = metamodelList[key].second;
dir.mkpath(nameOfTheDirectory);
QPair<QString, QString> const metamodelNames = editorGenerator.generateEditor(key, nameOfTheDirectory, pathToQRealRoot);
if (!mMainWindowInterface->errorReporter()->wereErrors()) {
if (QMessageBox::question(mMainWindowInterface->windowWidget()
, tr("loading.."), QString(tr("Do you want to load generated editor %1?")).arg(metamodelNames.first),
QMessageBox::Yes, QMessageBox::No) == QMessageBox::No)
{
return;
}
loadNewEditor(nameOfTheDirectory, metamodelNames
, SettingsManager::value("pathToQmake").toString()
, SettingsManager::value("pathToMake").toString()
, SettingsManager::value("pluginExtension").toString()
, SettingsManager::value("prefix").toString()
, mLogicalRepoApi->stringProperty(key, "buildConfiguration"));
}
}
if (metamodelList.isEmpty()) {
mMainWindowInterface->errorReporter()->addError(tr("There is nothing to generate"));
}
}
void MetaEditorSupportPlugin::generateEditorWithQrmc()
{
qrmc::MetaCompiler metaCompiler(qApp->applicationDirPath() + "/../../qrmc", mLogicalRepoApi);
IdList const metamodels = mLogicalRepoApi->children(Id::rootId());
QProgressBar *progress = new QProgressBar(mMainWindowInterface->windowWidget());
progress->show();
int const progressBarWidth = 240;
int const progressBarHeight = 20;
QApplication::processEvents();
QRect const screenRect = qApp->desktop()->availableGeometry();
progress->move(screenRect.width() / 2 - progressBarWidth / 2, screenRect.height() / 2 - progressBarHeight / 2);
progress->setFixedWidth(progressBarWidth);
progress->setFixedHeight(progressBarHeight);
progress->setRange(0, 100);
int forEditor = 60 / metamodels.size();
foreach (Id const &key, metamodels) {
QString const objectType = key.element();
if (objectType == "MetamodelDiagram" && mLogicalRepoApi->isLogicalElement(key)) {
QString nameOfTheDirectory = mLogicalRepoApi->stringProperty(key, "name of the directory");
QString nameOfMetamodel = mLogicalRepoApi->stringProperty(key, "name");
QString nameOfPlugin = nameOfTheDirectory.split("/").last();
if (QMessageBox::question(mMainWindowInterface->windowWidget()
, tr("loading..")
, QString(tr("Do you want to compile and load editor %1?")).arg(nameOfPlugin)
, QMessageBox::Yes, QMessageBox::No)
== QMessageBox::No)
{
continue;
}
progress->setValue(5);
if (!metaCompiler.compile(nameOfMetamodel)) { // generating source code for all metamodels
QMessageBox::warning(mMainWindowInterface->windowWidget()
, tr("error")
, tr("Cannot generate source code for editor ") + nameOfPlugin);
continue;
}
progress->setValue(20);
QStringList qmakeArgs;
qmakeArgs.append("CONFIG+=" + mLogicalRepoApi->stringProperty(key, "buildConfiguration"));
qmakeArgs.append(nameOfMetamodel + ".pro");
QProcess builder;
builder.setWorkingDirectory(nameOfTheDirectory);
const QStringList environment = QProcess::systemEnvironment();
builder.setEnvironment(environment);
builder.start(SettingsManager::value("pathToQmake").toString(), qmakeArgs);
qDebug() << "qmake";
if ((builder.waitForFinished()) && (builder.exitCode() == 0)) {
progress->setValue(40);
builder.start(SettingsManager::value("pathToMake").toString());
bool finished = builder.waitForFinished(100000);
qDebug() << "make";
if (finished && (builder.exitCode() == 0)) {
qDebug() << "make ok";
progress->setValue(progress->value() + forEditor / 2);
QString normalizedName = nameOfPlugin.at(0).toUpper() + nameOfPlugin.mid(1);
if (!nameOfPlugin.isEmpty()) {
if (!mMainWindowInterface->unloadPlugin(normalizedName)) {
QMessageBox::warning(mMainWindowInterface->windowWidget()
, tr("error")
, tr("cannot unload plugin ") + normalizedName);
progress->close();
delete progress;
continue;
}
}
QString suffix = "";
if (mLogicalRepoApi->stringProperty(key, "buildConfiguration") == "debug") {
suffix = "-d";
}
QString const generatedPluginFileName = SettingsManager::value("prefix").toString()
//+ nameOfPlugin
+ nameOfMetamodel
+ suffix
+ "."
+ SettingsManager::value("pluginExtension").toString()
;
if (mMainWindowInterface->loadPlugin(generatedPluginFileName, normalizedName)) {
progress->setValue(progress->value() + forEditor / 2);
}
}
progress->setValue(100);
}
}
}
if (progress->value() != 100) {
QMessageBox::warning(mMainWindowInterface->windowWidget(), tr("error"), tr("cannot load new editor"));
}
progress->setValue(100);
progress->close();
delete progress;
}
void MetaEditorSupportPlugin::parseEditorXml()
{
if (!mMainWindowInterface->pluginLoaded("MetaEditor")) {
QMessageBox::warning(mMainWindowInterface->windowWidget(), tr("error"), tr("required plugin (MetaEditor) is not loaded"));
return;
}
QDir dir(".");
QString directoryName = ".";
while (dir.cdUp()) {
QFileInfoList const infoList = dir.entryInfoList(QDir::Dirs);
foreach (QFileInfo const &directory, infoList){
if (directory.baseName() == "qrxml") {
directoryName = directory.absolutePath() + "/qrxml";
}
}
}
QString const fileName = QFileDialog::getOpenFileName(mMainWindowInterface->windowWidget()
, tr("Select xml file to parse")
, directoryName
, "XML files (*.xml)");
if (fileName.isEmpty())
return;
XmlParser parser(*mLogicalRepoApi);
parser.parseFile(fileName);
parser.loadIncludeList(fileName);
mMainWindowInterface->reinitModels();
}
void MetaEditorSupportPlugin::loadNewEditor(QString const &directoryName
, QPair<QString, QString> const &metamodelNames
, QString const &commandFirst
, QString const &commandSecond
, QString const &extension
, QString const &prefix
, QString const &buildConfiguration
)
{
int const progressBarWidth = 240;
int const progressBarHeight = 20;
QString const metamodelName = metamodelNames.first;
QString const normalizerMetamodelName = metamodelNames.second;
if ((commandFirst == "") || (commandSecond == "") || (extension == "")) {
QMessageBox::warning(mMainWindowInterface->windowWidget(), tr("error"), tr("please, fill compiler settings"));
return;
}
QString const normalizeDirName = metamodelName.at(0).toUpper() + metamodelName.mid(1);
QProgressBar * const progress = new QProgressBar(mMainWindowInterface->windowWidget());
progress->show();
QApplication::processEvents();
QRect const screenRect = qApp->desktop()->availableGeometry();
progress->move(screenRect.width() / 2 - progressBarWidth / 2, screenRect.height() / 2 - progressBarHeight / 2);
progress->setFixedWidth(progressBarWidth);
progress->setFixedHeight(progressBarHeight);
progress->setRange(0, 100);
progress->setValue(5);
const bool stateOfLoad = mMainWindowInterface->pluginLoaded(normalizeDirName);
if (!mMainWindowInterface->unloadPlugin(normalizeDirName)) {
progress->close();
delete progress;
return;
}
progress->setValue(20);
QStringList qmakeArgs;
qmakeArgs.append("CONFIG+=" + buildConfiguration);
qmakeArgs.append(metamodelName + ".pro");
QProcess builder;
builder.setWorkingDirectory(directoryName);
const QStringList environment = QProcess::systemEnvironment();
builder.setEnvironment(environment);
builder.start(commandFirst, qmakeArgs);
if ((builder.waitForFinished()) && (builder.exitCode() == 0)) {
progress->setValue(60);
builder.start(commandSecond);
if (builder.waitForFinished(60000) && (builder.exitCode() == 0)) {
progress->setValue(80);
if (stateOfLoad) {
QMessageBox::warning(mMainWindowInterface->windowWidget(), tr("Attention!"), tr("Please close QReal."));
progress->close();
delete progress;
return;
} else if (buildConfiguration == "debug") {
if (mMainWindowInterface->loadPlugin(prefix + metamodelName + "-d"+ "." + extension, normalizeDirName)) {
progress->setValue(100);
}
} else {
if (mMainWindowInterface->loadPlugin(prefix + metamodelName + "." + extension, normalizeDirName)) {
progress->setValue(100);
}
}
}
}
if (progress->value() == 20) {
QMessageBox::warning(mMainWindowInterface->windowWidget(), tr("error"), tr("cannot qmake new editor"));
} else if (progress->value() == 60) {
QMessageBox::warning(mMainWindowInterface->windowWidget(), tr("error"), tr("cannot make new editor"));
}
progress->setValue(100);
progress->close();
delete progress;
}
<commit_msg>- loading in palette is correct<commit_after>/* Copyright 2007-2015 QReal Research Group
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License. */
#include "metaEditorSupportPlugin.h"
#include <QtCore/QProcess>
#include <QtWidgets/QApplication>
#include <QtWidgets/QFileDialog>
#include <QtWidgets/QMessageBox>
#include <QtWidgets/QProgressBar>
#include <QtWidgets/QDesktopWidget>
#include <qrkernel/settingsManager.h>
#include <qrmc/metaCompiler.h>
#include "editorGenerator.h"
#include "xmlParser.h"
using namespace qReal;
using namespace metaEditor;
MetaEditorSupportPlugin::MetaEditorSupportPlugin()
: mGenerateEditorForQrxcAction(NULL)
, mGenerateEditorWithQrmcAction(NULL)
, mParseEditorXmlAction(NULL)
, mRepoControlApi(NULL)
, mCompilerSettingsPage(new PreferencesCompilerPage())
{
}
MetaEditorSupportPlugin::~MetaEditorSupportPlugin()
{
}
void MetaEditorSupportPlugin::init(PluginConfigurator const &configurator)
{
mMainWindowInterface = &configurator.mainWindowInterpretersInterface();
mLogicalRepoApi = &configurator.logicalModelApi().mutableLogicalRepoApi();
mRepoControlApi = &configurator.repoControlInterface();
}
QList<ActionInfo> MetaEditorSupportPlugin::actions()
{
mGenerateEditorForQrxcAction.setText(tr("Generate editor"));
ActionInfo generateEditorForQrxcActionInfo(&mGenerateEditorForQrxcAction, "generators", "tools");
connect(&mGenerateEditorForQrxcAction, SIGNAL(triggered()), this, SLOT(generateEditorForQrxc()));
mGenerateEditorWithQrmcAction.setText(tr("Generate editor (qrmc)"));
ActionInfo generateEditorWithQrmcActionInfo(&mGenerateEditorWithQrmcAction, "generators", "tools");
connect(&mGenerateEditorWithQrmcAction, SIGNAL(triggered()), this, SLOT(generateEditorWithQrmc()));
/*
mParseEditorXmlAction.setText(tr("Parse editor xml")); // button for parsing xml, doesn't work
ActionInfo parseEditorXmlActionInfo(&mParseEditorXmlAction, "generators", "tools");
connect(&mParseEditorXmlAction, SIGNAL(triggered()), this, SLOT(parseEditorXml()));
*/
return QList<ActionInfo>() << generateEditorForQrxcActionInfo
<< generateEditorWithQrmcActionInfo;
//<< parseEditorXmlActionInfo;
}
QPair<QString, gui::PreferencesPage *> MetaEditorSupportPlugin::preferencesPage()
{
return qMakePair(QObject::tr("Compiler"), static_cast<gui::PreferencesPage *>(mCompilerSettingsPage));
}
void MetaEditorSupportPlugin::generateEditorForQrxc()
{
EditorGenerator editorGenerator(*mLogicalRepoApi, *mMainWindowInterface->errorReporter());
QDir dir(".");
QHash<Id, QPair<QString, QString> > metamodelList = editorGenerator.getMetamodelList();
foreach (Id const &key, metamodelList.keys()) {
QString const nameOfTheDirectory = metamodelList[key].first;
QString const pathToQRealRoot = metamodelList[key].second;
dir.mkpath(nameOfTheDirectory);
QPair<QString, QString> const metamodelNames = editorGenerator.generateEditor(key, nameOfTheDirectory, pathToQRealRoot);
if (!mMainWindowInterface->errorReporter()->wereErrors()) {
if (QMessageBox::question(mMainWindowInterface->windowWidget()
, tr("loading.."), QString(tr("Do you want to load generated editor %1?")).arg(metamodelNames.first),
QMessageBox::Yes, QMessageBox::No) == QMessageBox::No)
{
return;
}
loadNewEditor(nameOfTheDirectory, metamodelNames
, SettingsManager::value("pathToQmake").toString()
, SettingsManager::value("pathToMake").toString()
, SettingsManager::value("pluginExtension").toString()
, SettingsManager::value("prefix").toString()
, mLogicalRepoApi->stringProperty(key, "buildConfiguration"));
}
}
if (metamodelList.isEmpty()) {
mMainWindowInterface->errorReporter()->addError(tr("There is nothing to generate"));
}
}
void MetaEditorSupportPlugin::generateEditorWithQrmc()
{
qrmc::MetaCompiler metaCompiler(qApp->applicationDirPath() + "/../../qrmc", mLogicalRepoApi);
IdList const metamodels = mLogicalRepoApi->children(Id::rootId());
QProgressBar *progress = new QProgressBar(mMainWindowInterface->windowWidget());
progress->show();
int const progressBarWidth = 240;
int const progressBarHeight = 20;
QApplication::processEvents();
QRect const screenRect = qApp->desktop()->availableGeometry();
progress->move(screenRect.width() / 2 - progressBarWidth / 2, screenRect.height() / 2 - progressBarHeight / 2);
progress->setFixedWidth(progressBarWidth);
progress->setFixedHeight(progressBarHeight);
progress->setRange(0, 100);
int forEditor = 60 / metamodels.size();
foreach (Id const &key, metamodels) {
QString const objectType = key.element();
if (objectType == "MetamodelDiagram" && mLogicalRepoApi->isLogicalElement(key)) {
QString nameOfTheDirectory = mLogicalRepoApi->stringProperty(key, "name of the directory");
QString nameOfMetamodel = mLogicalRepoApi->stringProperty(key, "name");
QString nameOfPlugin = nameOfTheDirectory.split("/").last();
if (QMessageBox::question(mMainWindowInterface->windowWidget()
, tr("loading..")
, QString(tr("Do you want to compile and load editor %1?")).arg(nameOfPlugin)
, QMessageBox::Yes, QMessageBox::No)
== QMessageBox::No)
{
continue;
}
progress->setValue(5);
if (!metaCompiler.compile(nameOfMetamodel)) { // generating source code for all metamodels
QMessageBox::warning(mMainWindowInterface->windowWidget()
, tr("error")
, tr("Cannot generate source code for editor ") + nameOfPlugin);
continue;
}
progress->setValue(20);
QStringList qmakeArgs;
qmakeArgs.append("CONFIG+=" + mLogicalRepoApi->stringProperty(key, "buildConfiguration"));
qmakeArgs.append(nameOfMetamodel + ".pro");
QProcess builder;
builder.setWorkingDirectory(nameOfTheDirectory);
const QStringList environment = QProcess::systemEnvironment();
builder.setEnvironment(environment);
builder.start(SettingsManager::value("pathToQmake").toString(), qmakeArgs);
qDebug() << "qmake";
if ((builder.waitForFinished()) && (builder.exitCode() == 0)) {
progress->setValue(40);
builder.start(SettingsManager::value("pathToMake").toString());
bool finished = builder.waitForFinished(100000);
qDebug() << "make";
if (finished && (builder.exitCode() == 0)) {
qDebug() << "make ok";
progress->setValue(progress->value() + forEditor / 2);
QString normalizedName = nameOfMetamodel.at(0).toUpper() + nameOfMetamodel.mid(1);
if (!nameOfMetamodel.isEmpty()) {
if (!mMainWindowInterface->unloadPlugin(normalizedName)) {
QMessageBox::warning(mMainWindowInterface->windowWidget()
, tr("error")
, tr("cannot unload plugin ") + normalizedName);
progress->close();
delete progress;
continue;
}
}
QString suffix = "";
if (mLogicalRepoApi->stringProperty(key, "buildConfiguration") == "debug") {
suffix = "-d";
}
QString const generatedPluginFileName = SettingsManager::value("prefix").toString()
+ nameOfMetamodel
+ suffix
+ "."
+ SettingsManager::value("pluginExtension").toString()
;
if (mMainWindowInterface->loadPlugin(generatedPluginFileName, normalizedName)) {
progress->setValue(progress->value() + forEditor / 2);
}
}
progress->setValue(100);
}
}
}
if (progress->value() != 100) {
QMessageBox::warning(mMainWindowInterface->windowWidget(), tr("error"), tr("cannot load new editor"));
}
progress->setValue(100);
progress->close();
delete progress;
}
void MetaEditorSupportPlugin::parseEditorXml()
{
if (!mMainWindowInterface->pluginLoaded("MetaEditor")) {
QMessageBox::warning(mMainWindowInterface->windowWidget(), tr("error"), tr("required plugin (MetaEditor) is not loaded"));
return;
}
QDir dir(".");
QString directoryName = ".";
while (dir.cdUp()) {
QFileInfoList const infoList = dir.entryInfoList(QDir::Dirs);
foreach (QFileInfo const &directory, infoList){
if (directory.baseName() == "qrxml") {
directoryName = directory.absolutePath() + "/qrxml";
}
}
}
QString const fileName = QFileDialog::getOpenFileName(mMainWindowInterface->windowWidget()
, tr("Select xml file to parse")
, directoryName
, "XML files (*.xml)");
if (fileName.isEmpty())
return;
XmlParser parser(*mLogicalRepoApi);
parser.parseFile(fileName);
parser.loadIncludeList(fileName);
mMainWindowInterface->reinitModels();
}
void MetaEditorSupportPlugin::loadNewEditor(QString const &directoryName
, QPair<QString, QString> const &metamodelNames
, QString const &commandFirst
, QString const &commandSecond
, QString const &extension
, QString const &prefix
, QString const &buildConfiguration
)
{
int const progressBarWidth = 240;
int const progressBarHeight = 20;
QString const metamodelName = metamodelNames.first;
QString const normalizerMetamodelName = metamodelNames.second;
if ((commandFirst == "") || (commandSecond == "") || (extension == "")) {
QMessageBox::warning(mMainWindowInterface->windowWidget(), tr("error"), tr("please, fill compiler settings"));
return;
}
QString const normalizeDirName = metamodelName.at(0).toUpper() + metamodelName.mid(1);
QProgressBar * const progress = new QProgressBar(mMainWindowInterface->windowWidget());
progress->show();
QApplication::processEvents();
QRect const screenRect = qApp->desktop()->availableGeometry();
progress->move(screenRect.width() / 2 - progressBarWidth / 2, screenRect.height() / 2 - progressBarHeight / 2);
progress->setFixedWidth(progressBarWidth);
progress->setFixedHeight(progressBarHeight);
progress->setRange(0, 100);
progress->setValue(5);
const bool stateOfLoad = mMainWindowInterface->pluginLoaded(normalizeDirName);
if (!mMainWindowInterface->unloadPlugin(normalizeDirName)) {
progress->close();
delete progress;
return;
}
progress->setValue(20);
QStringList qmakeArgs;
qmakeArgs.append("CONFIG+=" + buildConfiguration);
qmakeArgs.append(metamodelName + ".pro");
QProcess builder;
builder.setWorkingDirectory(directoryName);
const QStringList environment = QProcess::systemEnvironment();
builder.setEnvironment(environment);
builder.start(commandFirst, qmakeArgs);
if ((builder.waitForFinished()) && (builder.exitCode() == 0)) {
progress->setValue(60);
builder.start(commandSecond);
if (builder.waitForFinished(60000) && (builder.exitCode() == 0)) {
progress->setValue(80);
if (stateOfLoad) {
QMessageBox::warning(mMainWindowInterface->windowWidget(), tr("Attention!"), tr("Please close QReal."));
progress->close();
delete progress;
return;
} else if (buildConfiguration == "debug") {
if (mMainWindowInterface->loadPlugin(prefix + metamodelName + "-d"+ "." + extension, normalizeDirName)) {
progress->setValue(100);
}
} else {
if (mMainWindowInterface->loadPlugin(prefix + metamodelName + "." + extension, normalizeDirName)) {
progress->setValue(100);
}
}
}
}
if (progress->value() == 20) {
QMessageBox::warning(mMainWindowInterface->windowWidget(), tr("error"), tr("cannot qmake new editor"));
} else if (progress->value() == 60) {
QMessageBox::warning(mMainWindowInterface->windowWidget(), tr("error"), tr("cannot make new editor"));
}
progress->setValue(100);
progress->close();
delete progress;
}
<|endoftext|> |
<commit_before>#include "EnvMapMath.h"
#include "TextureUtils.h"
#include "CoordinateTransform.h"
#include "Actions/Actions.h"
#include "GaussianWeights.h"
#include <stdio.h>
void FastBlurCubemap::DoTask(const Texture& inputTex, Texture& outputTex)
{
if (!inputTex.m_cubemap)
{
printf("Error: For this task required cubmap.\n");
return;
}
int radius = m_blurRadius;
int kernelSize = 2 * radius + 1;
std::vector<double> kernel = GenerateKernel(1.0 / 3.0 * radius, kernelSize, 1000.0);
Texture tmpTex = outputTex;
Texture tmpTex2 = outputTex;
Texture resTex = outputTex;
for(int k = 0; k <6; ++k)
{
tmpTex = outputTex;
tmpTex2 = outputTex;
for(int ki = 0; ki <6; ++ki)
{
for (int i = 0;i<outputTex.m_height;i++)
{
for (int j = 0;j<outputTex.m_width;j++)
{
fpixel s(0.0, 0.0, 0.0);
for(int n = -radius; n < radius+1; ++n)
{
int j_ = j + n;
int k_ = ki;
if (ki != 2 && ki != 3)
{
if (j_ < 0)
{
j_ += outputTex.m_width;
switch(ki)
{
case 4:k_ = 0; break;
case 5:k_ = 1; break;
case 0:k_ = 5; break;
case 1:k_ = 4; break;
}
}
if (j_ >= outputTex.m_width)
{
j_ -= outputTex.m_width;
switch(ki)
{
case 0:k_ = 4; break;
case 1:k_ = 5; break;
case 5:k_ = 0; break;
case 4:k_ = 1; break;
}
}
s += outputTex.m_faces[k_].m_buff[j_ + i*outputTex.m_width] * kernel[n + radius];
}
else
{
if(k!= 0 && k!= 1)
{
if (ki==2)
{
if (j_ < 0)
{
j_ += outputTex.m_width;
k_ = 0;
s += outputTex.m_faces[k_].m_buff[(outputTex.m_width - i - 1) + j_*outputTex.m_width] * kernel[n + radius];
}
else if (j_ >= outputTex.m_width)
{
j_ -= outputTex.m_width;
j_ = outputTex.m_height - j_ - 1;
k_ = 1;
s += outputTex.m_faces[k_].m_buff[i + j_*outputTex.m_width] * kernel[n + radius];
}
else
{
s += outputTex.m_faces[k_].m_buff[j_ + i*outputTex.m_width] * kernel[n + radius];
}
}
else//ki = 3
{
if (j_ < 0)
{
j_ += outputTex.m_width;
k_ = 0;
s += outputTex.m_faces[k_].m_buff[i + (outputTex.m_height - j_ - 1)*outputTex.m_width] * kernel[n + radius];
}
else if (j_ >= outputTex.m_width)
{
j_ -= outputTex.m_width;
j_ = outputTex.m_height - j_ - 1;
k_ = 1;
s += outputTex.m_faces[k_].m_buff[(outputTex.m_width - i - 1) + (outputTex.m_height - j_ - 1)*outputTex.m_width] * kernel[n + radius];
}
else
{
s += outputTex.m_faces[k_].m_buff[j_ + i*outputTex.m_width] * kernel[n + radius];
}
}
}
else
{
int i_ = i + n;
int k_ = ki;
if (ki == 2)
{
if (i_ < 0)
{
i_ += outputTex.m_height;
k_ = 4;
s += outputTex.m_faces[k_].m_buff[j + i_*outputTex.m_width] * kernel[n + radius];
}
else if (i_ >= outputTex.m_width)
{
i_ -= outputTex.m_width;
i_ = outputTex.m_height - i_ - 1;
k_ = 5;
s += outputTex.m_faces[k_].m_buff[(outputTex.m_width - j - 1) + i_*outputTex.m_width] * kernel[n + radius];
}
else
{
s += outputTex.m_faces[k_].m_buff[j + i_*outputTex.m_width] * kernel[n + radius];
}
}
if (ki == 3)
{
if (i_ < 0)
{
i_ += outputTex.m_height;
i_ = outputTex.m_height - i_ - 1;
k_ = 5;
s += outputTex.m_faces[k_].m_buff[(outputTex.m_width - j - 1) + i_*outputTex.m_width] * kernel[n + radius];
}
else if (i_ >= outputTex.m_width)
{
i_ -= outputTex.m_width;
k_ = 4;
s += outputTex.m_faces[k_].m_buff[j + i_*outputTex.m_width] * kernel[n + radius];
}
else
{
s += outputTex.m_faces[k_].m_buff[j + i_*outputTex.m_width] * kernel[n + radius];
}
}
}
}
}
tmpTex.m_faces[ki].m_buff[j + i*outputTex.m_width] = s;
}
}
}
for (int j = 0 ;j<outputTex.m_width;j++)
{
for (int i = 0;i<outputTex.m_height;i++)
{
fpixel s(0.0, 0.0, 0.0);
for(int n = -radius; n < radius+1; ++n)
{
int i_ = i + n;
int k_ = k;
if (k == 2)
{
if (i_ < 0)
{
i_ += outputTex.m_height;
k_ = 4;
s += tmpTex.m_faces[k_].m_buff[j + i_*outputTex.m_width] * kernel[n + radius];
}
else if (i_ >= outputTex.m_width)
{
i_ -= outputTex.m_width;
i_ = outputTex.m_height - i_ - 1;
k_ = 5;
s += tmpTex.m_faces[k_].m_buff[(outputTex.m_width - j - 1) + i_*outputTex.m_width] * kernel[n + radius];
}
else
{
s += tmpTex.m_faces[k_].m_buff[j + i_*outputTex.m_width] * kernel[n + radius];
}
}
if (k == 3)
{
if (i_ < 0)
{
i_ += outputTex.m_height;
i_ = outputTex.m_height - i_ - 1;
k_ = 5;
s += tmpTex.m_faces[k_].m_buff[(outputTex.m_width - j - 1) + i_*outputTex.m_width] * kernel[n + radius];
}
else if (i_ >= outputTex.m_width)
{
i_ -= outputTex.m_width;
k_ = 4;
s += tmpTex.m_faces[k_].m_buff[j + i_*outputTex.m_width] * kernel[n + radius];
}
else
{
s += tmpTex.m_faces[k_].m_buff[j + i_*outputTex.m_width] * kernel[n + radius];
}
}
else if(k == 5)
{
if (i_ < 0)
{
i_ += outputTex.m_height;
i_ = outputTex.m_height - i_ - 1;
k_ = 3;
s += tmpTex.m_faces[k_].m_buff[(outputTex.m_width - j - 1) + i_*outputTex.m_width] * kernel[n + radius];
}
else if (i_ >= outputTex.m_width)
{
i_ -= outputTex.m_width;
i_ = outputTex.m_height - i_ - 1;
k_ = 2;
s += tmpTex.m_faces[k_].m_buff[(outputTex.m_width - j - 1) + i_*outputTex.m_width] * kernel[n + radius];
}
else
{
s += tmpTex.m_faces[k_].m_buff[j + i_*outputTex.m_width] * kernel[n + radius];
}
}
else if(k == 4)
{
if (i_ < 0)
{
i_ += outputTex.m_height;
k_ = 3;
s += tmpTex.m_faces[k_].m_buff[j + i_*outputTex.m_width] * kernel[n + radius];
}
else if (i_ >= outputTex.m_width)
{
i_ -= outputTex.m_width;
k_ = 2;
s += tmpTex.m_faces[k_].m_buff[j + i_*outputTex.m_width] * kernel[n + radius];
}
else
{
s += tmpTex.m_faces[k_].m_buff[j + i_*outputTex.m_width] * kernel[n + radius];
}
}
else if(k == 0)
{
if (i_ < 0)
{
i_ += outputTex.m_height;
i_ = outputTex.m_width - 1 - i_;
k_ = 3;
s += tmpTex.m_faces[k_].m_buff[i_ + j * outputTex.m_width] * kernel[n + radius];
}
else if (i_ >= outputTex.m_width)
{
i_ -= outputTex.m_width;
k_ = 2;
s += tmpTex.m_faces[k_].m_buff[i_ + (outputTex.m_height - j - 1)*outputTex.m_width] * kernel[n + radius];
}
else
{
s += tmpTex.m_faces[k_].m_buff[j + i_*outputTex.m_width] * kernel[n + radius];
}
}
else if(k == 1)
{
if (i_ < 0)
{
i_ += outputTex.m_height;
k_ = 3;
s += tmpTex.m_faces[k_].m_buff[i_ + (outputTex.m_height - j - 1) * outputTex.m_width] * kernel[n + radius];
}
else if (i_ >= outputTex.m_width)
{
i_ -= outputTex.m_width;
i_ = outputTex.m_width - 1 - i_;
k_ = 2;
s += tmpTex.m_faces[k_].m_buff[i_ + j * outputTex.m_width] * kernel[n + radius];
}
else
{
s += tmpTex.m_faces[k_].m_buff[j + i_*outputTex.m_width] * kernel[n + radius];
}
}
}
tmpTex2.m_faces[k].m_buff[j + i*outputTex.m_width] = s;
}
}
resTex.m_faces[k] = tmpTex2.m_faces[k];
}
outputTex = resTex;
outputTex.m_cubemap = true;
}
<commit_msg>Fixed crash<commit_after>#include "EnvMapMath.h"
#include "TextureUtils.h"
#include "CoordinateTransform.h"
#include "Actions/Actions.h"
#include "GaussianWeights.h"
#include <stdio.h>
void FastBlurCubemap::DoTask(const Texture& inputTex, Texture& outputTex)
{
if (!inputTex.m_cubemap)
{
printf("Error: For this task required cubmap.\n");
return;
}
outputTex = inputTex;
int radius = m_blurRadius;
int kernelSize = 2 * radius + 1;
std::vector<double> kernel = GenerateKernel(1.0 / 3.0 * radius, kernelSize, 1000.0);
Texture tmpTex = outputTex;
Texture tmpTex2 = outputTex;
Texture resTex = outputTex;
for(int k = 0; k <6; ++k)
{
tmpTex = outputTex;
tmpTex2 = outputTex;
for(int ki = 0; ki <6; ++ki)
{
for (int i = 0;i<outputTex.m_height;i++)
{
for (int j = 0;j<outputTex.m_width;j++)
{
fpixel s(0.0, 0.0, 0.0);
for(int n = -radius; n < radius+1; ++n)
{
int j_ = j + n;
int k_ = ki;
if (ki != 2 && ki != 3)
{
if (j_ < 0)
{
j_ += outputTex.m_width;
switch(ki)
{
case 4:k_ = 0; break;
case 5:k_ = 1; break;
case 0:k_ = 5; break;
case 1:k_ = 4; break;
}
}
if (j_ >= outputTex.m_width)
{
j_ -= outputTex.m_width;
switch(ki)
{
case 0:k_ = 4; break;
case 1:k_ = 5; break;
case 5:k_ = 0; break;
case 4:k_ = 1; break;
}
}
s += outputTex.m_faces[k_].m_buff[j_ + i*outputTex.m_width] * kernel[n + radius];
}
else
{
if(k!= 0 && k!= 1)
{
if (ki==2)
{
if (j_ < 0)
{
j_ += outputTex.m_width;
k_ = 0;
s += outputTex.m_faces[k_].m_buff[(outputTex.m_width - i - 1) + j_*outputTex.m_width] * kernel[n + radius];
}
else if (j_ >= outputTex.m_width)
{
j_ -= outputTex.m_width;
j_ = outputTex.m_height - j_ - 1;
k_ = 1;
s += outputTex.m_faces[k_].m_buff[i + j_*outputTex.m_width] * kernel[n + radius];
}
else
{
s += outputTex.m_faces[k_].m_buff[j_ + i*outputTex.m_width] * kernel[n + radius];
}
}
else//ki = 3
{
if (j_ < 0)
{
j_ += outputTex.m_width;
k_ = 0;
s += outputTex.m_faces[k_].m_buff[i + (outputTex.m_height - j_ - 1)*outputTex.m_width] * kernel[n + radius];
}
else if (j_ >= outputTex.m_width)
{
j_ -= outputTex.m_width;
j_ = outputTex.m_height - j_ - 1;
k_ = 1;
s += outputTex.m_faces[k_].m_buff[(outputTex.m_width - i - 1) + (outputTex.m_height - j_ - 1)*outputTex.m_width] * kernel[n + radius];
}
else
{
s += outputTex.m_faces[k_].m_buff[j_ + i*outputTex.m_width] * kernel[n + radius];
}
}
}
else
{
int i_ = i + n;
int k_ = ki;
if (ki == 2)
{
if (i_ < 0)
{
i_ += outputTex.m_height;
k_ = 4;
s += outputTex.m_faces[k_].m_buff[j + i_*outputTex.m_width] * kernel[n + radius];
}
else if (i_ >= outputTex.m_width)
{
i_ -= outputTex.m_width;
i_ = outputTex.m_height - i_ - 1;
k_ = 5;
s += outputTex.m_faces[k_].m_buff[(outputTex.m_width - j - 1) + i_*outputTex.m_width] * kernel[n + radius];
}
else
{
s += outputTex.m_faces[k_].m_buff[j + i_*outputTex.m_width] * kernel[n + radius];
}
}
if (ki == 3)
{
if (i_ < 0)
{
i_ += outputTex.m_height;
i_ = outputTex.m_height - i_ - 1;
k_ = 5;
s += outputTex.m_faces[k_].m_buff[(outputTex.m_width - j - 1) + i_*outputTex.m_width] * kernel[n + radius];
}
else if (i_ >= outputTex.m_width)
{
i_ -= outputTex.m_width;
k_ = 4;
s += outputTex.m_faces[k_].m_buff[j + i_*outputTex.m_width] * kernel[n + radius];
}
else
{
s += outputTex.m_faces[k_].m_buff[j + i_*outputTex.m_width] * kernel[n + radius];
}
}
}
}
}
tmpTex.m_faces[ki].m_buff[j + i*outputTex.m_width] = s;
}
}
}
for (int j = 0 ;j<outputTex.m_width;j++)
{
for (int i = 0;i<outputTex.m_height;i++)
{
fpixel s(0.0, 0.0, 0.0);
for(int n = -radius; n < radius+1; ++n)
{
int i_ = i + n;
int k_ = k;
if (k == 2)
{
if (i_ < 0)
{
i_ += outputTex.m_height;
k_ = 4;
s += tmpTex.m_faces[k_].m_buff[j + i_*outputTex.m_width] * kernel[n + radius];
}
else if (i_ >= outputTex.m_width)
{
i_ -= outputTex.m_width;
i_ = outputTex.m_height - i_ - 1;
k_ = 5;
s += tmpTex.m_faces[k_].m_buff[(outputTex.m_width - j - 1) + i_*outputTex.m_width] * kernel[n + radius];
}
else
{
s += tmpTex.m_faces[k_].m_buff[j + i_*outputTex.m_width] * kernel[n + radius];
}
}
if (k == 3)
{
if (i_ < 0)
{
i_ += outputTex.m_height;
i_ = outputTex.m_height - i_ - 1;
k_ = 5;
s += tmpTex.m_faces[k_].m_buff[(outputTex.m_width - j - 1) + i_*outputTex.m_width] * kernel[n + radius];
}
else if (i_ >= outputTex.m_width)
{
i_ -= outputTex.m_width;
k_ = 4;
s += tmpTex.m_faces[k_].m_buff[j + i_*outputTex.m_width] * kernel[n + radius];
}
else
{
s += tmpTex.m_faces[k_].m_buff[j + i_*outputTex.m_width] * kernel[n + radius];
}
}
else if(k == 5)
{
if (i_ < 0)
{
i_ += outputTex.m_height;
i_ = outputTex.m_height - i_ - 1;
k_ = 3;
s += tmpTex.m_faces[k_].m_buff[(outputTex.m_width - j - 1) + i_*outputTex.m_width] * kernel[n + radius];
}
else if (i_ >= outputTex.m_width)
{
i_ -= outputTex.m_width;
i_ = outputTex.m_height - i_ - 1;
k_ = 2;
s += tmpTex.m_faces[k_].m_buff[(outputTex.m_width - j - 1) + i_*outputTex.m_width] * kernel[n + radius];
}
else
{
s += tmpTex.m_faces[k_].m_buff[j + i_*outputTex.m_width] * kernel[n + radius];
}
}
else if(k == 4)
{
if (i_ < 0)
{
i_ += outputTex.m_height;
k_ = 3;
s += tmpTex.m_faces[k_].m_buff[j + i_*outputTex.m_width] * kernel[n + radius];
}
else if (i_ >= outputTex.m_width)
{
i_ -= outputTex.m_width;
k_ = 2;
s += tmpTex.m_faces[k_].m_buff[j + i_*outputTex.m_width] * kernel[n + radius];
}
else
{
s += tmpTex.m_faces[k_].m_buff[j + i_*outputTex.m_width] * kernel[n + radius];
}
}
else if(k == 0)
{
if (i_ < 0)
{
i_ += outputTex.m_height;
i_ = outputTex.m_width - 1 - i_;
k_ = 3;
s += tmpTex.m_faces[k_].m_buff[i_ + j * outputTex.m_width] * kernel[n + radius];
}
else if (i_ >= outputTex.m_width)
{
i_ -= outputTex.m_width;
k_ = 2;
s += tmpTex.m_faces[k_].m_buff[i_ + (outputTex.m_height - j - 1)*outputTex.m_width] * kernel[n + radius];
}
else
{
s += tmpTex.m_faces[k_].m_buff[j + i_*outputTex.m_width] * kernel[n + radius];
}
}
else if(k == 1)
{
if (i_ < 0)
{
i_ += outputTex.m_height;
k_ = 3;
s += tmpTex.m_faces[k_].m_buff[i_ + (outputTex.m_height - j - 1) * outputTex.m_width] * kernel[n + radius];
}
else if (i_ >= outputTex.m_width)
{
i_ -= outputTex.m_width;
i_ = outputTex.m_width - 1 - i_;
k_ = 2;
s += tmpTex.m_faces[k_].m_buff[i_ + j * outputTex.m_width] * kernel[n + radius];
}
else
{
s += tmpTex.m_faces[k_].m_buff[j + i_*outputTex.m_width] * kernel[n + radius];
}
}
}
tmpTex2.m_faces[k].m_buff[j + i*outputTex.m_width] = s;
}
}
resTex.m_faces[k] = tmpTex2.m_faces[k];
}
outputTex = resTex;
outputTex.m_cubemap = true;
}
<|endoftext|> |
<commit_before>/*****************************************************************************
shuffleBed.cpp
(c) 2009 - Aaron Quinlan
Hall Laboratory
Department of Biochemistry and Molecular Genetics
University of Virginia
aaronquinlan@gmail.com
Licenced under the GNU General Public License 2.0 license.
******************************************************************************/
#include "lineFileUtilities.h"
#include "shuffleBed.h"
BedShuffle::BedShuffle(string &bedFile, string &genomeFile,
string &excludeFile, string &includeFile,
bool haveSeed, bool haveExclude,
bool haveInclude, bool sameChrom,
float overlapFraction, int seed,
bool chooseChrom, bool isBedpe) {
_bedFile = bedFile;
_genomeFile = genomeFile;
_excludeFile = excludeFile;
_includeFile = includeFile;
_sameChrom = sameChrom;
_haveExclude = haveExclude;
_haveInclude = haveInclude;
_overlapFraction = overlapFraction;
_haveSeed = haveSeed;
_chooseChrom = chooseChrom;
_isBedpe = isBedpe;
// use the supplied seed for the random
// number generation if given. else,
// roll our own.
if (_haveSeed) {
_seed = seed;
srand(seed);
}
else {
// thanks to Rob Long for the tip.
_seed = (unsigned)time(0)+(unsigned)getpid();
srand(_seed);
}
if (_isBedpe == false)
_bed = new BedFile(bedFile);
else
_bedpe = new BedFilePE(bedFile);
_genome = new GenomeFile(genomeFile);
_chroms = _genome->getChromList();
_numChroms = _genome->getNumberOfChroms();
_genomeSize = _genome->getGenomeSize();
if (_haveExclude) {
_exclude = new BedFile(excludeFile);
_exclude->loadBedFileIntoMap();
}
if (_haveInclude) {
_include = new BedFile(includeFile);
_include->loadBedFileIntoMapNoBin();
_numIncludeChroms = 0;
masterBedMapNoBin::const_iterator it = _include->bedMapNoBin.begin();
masterBedMapNoBin::const_iterator itEnd = _include->bedMapNoBin.end();
for(; it != itEnd; ++it) {
_includeChroms.push_back(it->first);
_numIncludeChroms++;
}
}
if (_haveExclude == true && _haveInclude == false)
ShuffleWithExclusions();
else if (_haveExclude == false && _haveInclude == true)
ShuffleWithInclusions();
else
Shuffle();
}
BedShuffle::~BedShuffle(void) {
}
void BedShuffle::Shuffle() {
if (_isBedpe == false) {
BED bedEntry;
_bed->Open();
while (_bed->GetNextBed(bedEntry)) {
if (_bed->_status == BED_VALID) {
ChooseLocus(bedEntry);
_bed->reportBedNewLine(bedEntry);
}
}
_bed->Close();
}
// BEDPE input
else {
int lineNum = 0; // current input line number
BedLineStatus status;
BEDPE bedEntry;
_bedpe->Open();
while ((status = _bedpe->GetNextBedPE(bedEntry, lineNum)) != BED_INVALID)
{
if (status == BED_VALID) {
ChoosePairedLocus(bedEntry);
_bedpe->reportBedPENewLine(bedEntry);
}
}
_bedpe->Close();
}
}
void BedShuffle::ShuffleWithExclusions() {
if (_isBedpe == false) {
BED bedEntry;
_bed->Open();
while (_bed->GetNextBed(bedEntry)) {
if (_bed->_status == BED_VALID) {
// keep looking as long as the chosen
// locus happens to overlap with regions
// that the user wishes to exclude.
int tries = 0;
bool haveOverlap = false;
do
{
// choose a new locus
ChooseLocus(bedEntry);
haveOverlap = _exclude->anyHits(bedEntry.chrom,
bedEntry.start,
bedEntry.end,
bedEntry.strand,
false, false,
_overlapFraction, false);
tries++;
} while ((haveOverlap == true) && (tries <= MAX_TRIES));
if (tries > MAX_TRIES) {
cerr << "Error, line " << _bed->_lineNum
<< ": tried " << MAX_TRIES
<< " potential loci for entry, but could not avoid "
<< "excluded regions. Ignoring entry and moving on."
<< endl; }
else {
_bed->reportBedNewLine(bedEntry);
}
}
}
_bed->Close();
}
// BEDPE input
else {
int lineNum = 0; // current input line number
BedLineStatus status;
BEDPE bedEntry;
_bedpe->Open();
while ((status = _bedpe->GetNextBedPE(bedEntry, lineNum)) != BED_INVALID)
{
if (status == BED_VALID) {
// keep looking as long as the chosen
// locus happens to overlap with regions
// that the user wishes to exclude.
int tries = 0;
bool haveOverlap1 = false;
bool haveOverlap2 = false;
do
{
// choose a new locus
ChoosePairedLocus(bedEntry);
haveOverlap1 = _exclude->anyHits(bedEntry.chrom1,
bedEntry.start1,
bedEntry.end1,
bedEntry.strand1,
false, false,
_overlapFraction, false);
haveOverlap2 = _exclude->anyHits(bedEntry.chrom2,
bedEntry.start2,
bedEntry.end2,
bedEntry.strand2,
false, false,
_overlapFraction, false);
tries++;
} while (((haveOverlap1 == true) || (haveOverlap2 == true))
&& (tries <= MAX_TRIES));
if (tries > MAX_TRIES) {
cerr << "Error, line " << _bed->_lineNum
<< ": tried " << MAX_TRIES
<< " potential loci for entry, but could not avoid "
<< "excluded regions. Ignoring entry and moving on."
<< endl;
}
else {
_bedpe->reportBedPENewLine(bedEntry);
}
}
}
_bedpe->Close();
}
}
void BedShuffle::ShuffleWithInclusions() {
BED bedEntry; // used to store the current BED line from the BED file.
_bed->Open();
while (_bed->GetNextBed(bedEntry)) {
if (_bed->_status == BED_VALID) {
// choose a new locus
ChooseLocusFromInclusionFile(bedEntry);
_bed->reportBedNewLine(bedEntry);
}
}
_bed->Close();
}
void BedShuffle::ChooseLocus(BED &bedEntry) {
string randomChrom;
CHRPOS randomStart;
CHRPOS chromSize;
string chrom = bedEntry.chrom;
CHRPOS start = bedEntry.start;
CHRPOS end = bedEntry.end;
CHRPOS length = end - start;
// choose a position randomly among the _entire_ genome.
if (_chooseChrom == false)
{
do
{
// we need to combine two consective calls to rand()
// because RAND_MAX is 2^31 (2147483648), whereas
// mammalian genomes are obviously much larger.
uint32_t randStart = ((rand() << 31) | rand()) % _genomeSize;
// use the above randomStart (e.g., for human 0..3.1billion)
// to identify the chrom and start on that chrom.
pair<string, int> location = _genome->projectOnGenome(randStart);
bedEntry.chrom = location.first;
bedEntry.start = location.second;
bedEntry.end = bedEntry.start + length;
chromSize = _genome->getChromSize(location.first);
} while (bedEntry.end > chromSize);
// keep looking if we have exceeded the end of the chrom.
}
// OLD, quite arguably flawed, method.
// 1. Choose a chrom randomly (i.e., not weighted by size)
// 2. Choose a position on that chrom randomly
else
{
do
{
if (_sameChrom == false) {
randomChrom = _chroms[rand() % _numChroms];
chromSize = _genome->getChromSize(randomChrom);
randomStart = rand() % chromSize;
bedEntry.chrom = randomChrom;
bedEntry.start = randomStart;
bedEntry.end = randomStart + length;
}
else {
chromSize = _genome->getChromSize(chrom);
randomStart = rand() % chromSize;
bedEntry.start = randomStart;
bedEntry.end = randomStart + length;
}
} while (bedEntry.end > chromSize);
}
}
void BedShuffle::ChoosePairedLocus(BEDPE &b) {
CHRPOS foot1_len = b.end1 - b.start1;
CHRPOS foot2_len = b.end2 - b.start2;
CHRPOS length = b.end2 - b.start1;
if (b.chrom1 == b.chrom2)
{
CHRPOS chromSize;
do
{
uint32_t randStart = ((rand() << 31) | rand()) % _genomeSize;
pair<string, int> location = _genome->projectOnGenome(randStart);
b.chrom1 = location.first;
b.chrom2 = location.first;
b.start1 = location.second;
b.end1 = b.start1 + foot1_len;
b.end2 = b.start1 + length;
b.start2 = b.end2 - foot2_len;
chromSize = _genome->getChromSize(location.first);
} while ((b.end1 > chromSize) ||
(b.start2 > chromSize) ||
(b.end2 > chromSize));
// keep looking if we have exceeded the end of the chrom.
}
else
{
CHRPOS chromSize1, chromSize2;
do
{
uint32_t rand1Start = ((rand() << 31) | rand()) % _genomeSize;
uint32_t rand2Start = ((rand() << 31) | rand()) % _genomeSize;
pair<string, int> location1 = _genome->projectOnGenome(rand1Start);
pair<string, int> location2 = _genome->projectOnGenome(rand2Start);
b.chrom1 = location1.first;
b.chrom2 = location2.first;
b.start1 = location1.second;
b.start2 = location2.second;
b.end1 = b.start1 + foot1_len;
b.end2 = b.start2 + foot2_len;
chromSize1 = _genome->getChromSize(location1.first);
chromSize2 = _genome->getChromSize(location2.first);
} while ((b.end1 > chromSize1) ||
(b.end2 > chromSize2));
// keep looking if we have exceeded the end of the chrom.
}
}
void BedShuffle::ChooseLocusFromInclusionFile(BED &bedEntry) {
string chrom = bedEntry.chrom;
CHRPOS length = bedEntry.end - bedEntry.start;
string randomChrom;
CHRPOS randomStart;
BED includeInterval;
if (_sameChrom == false) {
// grab a random chromosome from the inclusion file.
randomChrom = _includeChroms[rand() % _numIncludeChroms];
// get the number of inclusion intervals for that chrom
size_t size = _include->bedMapNoBin[randomChrom].size();
// grab a random interval on the chosen chromosome.
size_t interval = rand() % size;
// retreive a ranom -incl interval on the selected chrom
includeInterval = _include->bedMapNoBin[randomChrom][interval];
bedEntry.chrom = randomChrom;
}
else {
// get the number of inclusion intervals for the original chrom
size_t size = _include->bedMapNoBin[chrom].size();
// grab a random interval on the chosen chromosome.
includeInterval = _include->bedMapNoBin[chrom][rand() % size];
}
randomStart = includeInterval.start + rand() % (includeInterval.size());
bedEntry.start = randomStart;
bedEntry.end = randomStart + length;
// use recursion to ensure that the chosen location
// doesn't go past the end of the chrom
if (bedEntry.end > ((size_t) _genome->getChromSize(chrom))) {
//bedEntry.end = _genome->getChromSize(chrom);
ChooseLocusFromInclusionFile(bedEntry);
}
}
<commit_msg>reset each bedpe<commit_after>/*****************************************************************************
shuffleBed.cpp
(c) 2009 - Aaron Quinlan
Hall Laboratory
Department of Biochemistry and Molecular Genetics
University of Virginia
aaronquinlan@gmail.com
Licenced under the GNU General Public License 2.0 license.
******************************************************************************/
#include "lineFileUtilities.h"
#include "shuffleBed.h"
BedShuffle::BedShuffle(string &bedFile, string &genomeFile,
string &excludeFile, string &includeFile,
bool haveSeed, bool haveExclude,
bool haveInclude, bool sameChrom,
float overlapFraction, int seed,
bool chooseChrom, bool isBedpe) {
_bedFile = bedFile;
_genomeFile = genomeFile;
_excludeFile = excludeFile;
_includeFile = includeFile;
_sameChrom = sameChrom;
_haveExclude = haveExclude;
_haveInclude = haveInclude;
_overlapFraction = overlapFraction;
_haveSeed = haveSeed;
_chooseChrom = chooseChrom;
_isBedpe = isBedpe;
// use the supplied seed for the random
// number generation if given. else,
// roll our own.
if (_haveSeed) {
_seed = seed;
srand(seed);
}
else {
// thanks to Rob Long for the tip.
_seed = (unsigned)time(0)+(unsigned)getpid();
srand(_seed);
}
if (_isBedpe == false)
_bed = new BedFile(bedFile);
else
_bedpe = new BedFilePE(bedFile);
_genome = new GenomeFile(genomeFile);
_chroms = _genome->getChromList();
_numChroms = _genome->getNumberOfChroms();
_genomeSize = _genome->getGenomeSize();
if (_haveExclude) {
_exclude = new BedFile(excludeFile);
_exclude->loadBedFileIntoMap();
}
if (_haveInclude) {
_include = new BedFile(includeFile);
_include->loadBedFileIntoMapNoBin();
_numIncludeChroms = 0;
masterBedMapNoBin::const_iterator it = _include->bedMapNoBin.begin();
masterBedMapNoBin::const_iterator itEnd = _include->bedMapNoBin.end();
for(; it != itEnd; ++it) {
_includeChroms.push_back(it->first);
_numIncludeChroms++;
}
}
if (_haveExclude == true && _haveInclude == false)
ShuffleWithExclusions();
else if (_haveExclude == false && _haveInclude == true)
ShuffleWithInclusions();
else
Shuffle();
}
BedShuffle::~BedShuffle(void) {
}
void BedShuffle::Shuffle() {
if (_isBedpe == false) {
BED bedEntry;
_bed->Open();
while (_bed->GetNextBed(bedEntry)) {
if (_bed->_status == BED_VALID) {
ChooseLocus(bedEntry);
_bed->reportBedNewLine(bedEntry);
}
}
_bed->Close();
}
// BEDPE input
else {
int lineNum = 0; // current input line number
BedLineStatus status;
BEDPE bedEntry, nullBedPE;
_bedpe->Open();
while ((status = _bedpe->GetNextBedPE(bedEntry, lineNum)) != BED_INVALID)
{
if (status == BED_VALID) {
ChoosePairedLocus(bedEntry);
_bedpe->reportBedPENewLine(bedEntry);
}
bedEntry = nullBedPE;
}
_bedpe->Close();
}
}
void BedShuffle::ShuffleWithExclusions() {
if (_isBedpe == false) {
BED bedEntry;
_bed->Open();
while (_bed->GetNextBed(bedEntry)) {
if (_bed->_status == BED_VALID) {
// keep looking as long as the chosen
// locus happens to overlap with regions
// that the user wishes to exclude.
int tries = 0;
bool haveOverlap = false;
do
{
// choose a new locus
ChooseLocus(bedEntry);
haveOverlap = _exclude->anyHits(bedEntry.chrom,
bedEntry.start,
bedEntry.end,
bedEntry.strand,
false, false,
_overlapFraction, false);
tries++;
} while ((haveOverlap == true) && (tries <= MAX_TRIES));
if (tries > MAX_TRIES) {
cerr << "Error, line " << _bed->_lineNum
<< ": tried " << MAX_TRIES
<< " potential loci for entry, but could not avoid "
<< "excluded regions. Ignoring entry and moving on."
<< endl; }
else {
_bed->reportBedNewLine(bedEntry);
}
}
}
_bed->Close();
}
// BEDPE input
else {
int lineNum = 0; // current input line number
BedLineStatus status;
BEDPE bedEntry;
_bedpe->Open();
while ((status = _bedpe->GetNextBedPE(bedEntry, lineNum)) != BED_INVALID)
{
if (status == BED_VALID) {
// keep looking as long as the chosen
// locus happens to overlap with regions
// that the user wishes to exclude.
int tries = 0;
bool haveOverlap1 = false;
bool haveOverlap2 = false;
do
{
// choose a new locus
ChoosePairedLocus(bedEntry);
haveOverlap1 = _exclude->anyHits(bedEntry.chrom1,
bedEntry.start1,
bedEntry.end1,
bedEntry.strand1,
false, false,
_overlapFraction, false);
haveOverlap2 = _exclude->anyHits(bedEntry.chrom2,
bedEntry.start2,
bedEntry.end2,
bedEntry.strand2,
false, false,
_overlapFraction, false);
tries++;
} while (((haveOverlap1 == true) || (haveOverlap2 == true))
&& (tries <= MAX_TRIES));
if (tries > MAX_TRIES) {
cerr << "Error, line " << _bed->_lineNum
<< ": tried " << MAX_TRIES
<< " potential loci for entry, but could not avoid "
<< "excluded regions. Ignoring entry and moving on."
<< endl;
}
else {
_bedpe->reportBedPENewLine(bedEntry);
}
}
}
_bedpe->Close();
}
}
void BedShuffle::ShuffleWithInclusions() {
BED bedEntry; // used to store the current BED line from the BED file.
_bed->Open();
while (_bed->GetNextBed(bedEntry)) {
if (_bed->_status == BED_VALID) {
// choose a new locus
ChooseLocusFromInclusionFile(bedEntry);
_bed->reportBedNewLine(bedEntry);
}
}
_bed->Close();
}
void BedShuffle::ChooseLocus(BED &bedEntry) {
string randomChrom;
CHRPOS randomStart;
CHRPOS chromSize;
string chrom = bedEntry.chrom;
CHRPOS start = bedEntry.start;
CHRPOS end = bedEntry.end;
CHRPOS length = end - start;
// choose a position randomly among the _entire_ genome.
if (_chooseChrom == false)
{
do
{
// we need to combine two consective calls to rand()
// because RAND_MAX is 2^31 (2147483648), whereas
// mammalian genomes are obviously much larger.
uint32_t randStart = ((rand() << 31) | rand()) % _genomeSize;
// use the above randomStart (e.g., for human 0..3.1billion)
// to identify the chrom and start on that chrom.
pair<string, int> location = _genome->projectOnGenome(randStart);
bedEntry.chrom = location.first;
bedEntry.start = location.second;
bedEntry.end = bedEntry.start + length;
chromSize = _genome->getChromSize(location.first);
} while (bedEntry.end > chromSize);
// keep looking if we have exceeded the end of the chrom.
}
// OLD, quite arguably flawed, method.
// 1. Choose a chrom randomly (i.e., not weighted by size)
// 2. Choose a position on that chrom randomly
else
{
do
{
if (_sameChrom == false) {
randomChrom = _chroms[rand() % _numChroms];
chromSize = _genome->getChromSize(randomChrom);
randomStart = rand() % chromSize;
bedEntry.chrom = randomChrom;
bedEntry.start = randomStart;
bedEntry.end = randomStart + length;
}
else {
chromSize = _genome->getChromSize(chrom);
randomStart = rand() % chromSize;
bedEntry.start = randomStart;
bedEntry.end = randomStart + length;
}
} while (bedEntry.end > chromSize);
}
}
void BedShuffle::ChoosePairedLocus(BEDPE &b) {
CHRPOS foot1_len = b.end1 - b.start1;
CHRPOS foot2_len = b.end2 - b.start2;
CHRPOS length = b.end2 - b.start1;
if (b.chrom1 == b.chrom2)
{
CHRPOS chromSize;
do
{
uint32_t randStart = ((rand() << 31) | rand()) % _genomeSize;
pair<string, int> location = _genome->projectOnGenome(randStart);
b.chrom1 = location.first;
b.chrom2 = location.first;
b.start1 = location.second;
b.end1 = b.start1 + foot1_len;
b.end2 = b.start1 + length;
b.start2 = b.end2 - foot2_len;
chromSize = _genome->getChromSize(location.first);
} while ((b.end1 > chromSize) ||
(b.start2 > chromSize) ||
(b.end2 > chromSize));
// keep looking if we have exceeded the end of the chrom.
}
else
{
CHRPOS chromSize1, chromSize2;
do
{
uint32_t rand1Start = ((rand() << 31) | rand()) % _genomeSize;
uint32_t rand2Start = ((rand() << 31) | rand()) % _genomeSize;
pair<string, int> location1 = _genome->projectOnGenome(rand1Start);
pair<string, int> location2 = _genome->projectOnGenome(rand2Start);
b.chrom1 = location1.first;
b.chrom2 = location2.first;
b.start1 = location1.second;
b.start2 = location2.second;
b.end1 = b.start1 + foot1_len;
b.end2 = b.start2 + foot2_len;
chromSize1 = _genome->getChromSize(location1.first);
chromSize2 = _genome->getChromSize(location2.first);
} while ((b.end1 > chromSize1) ||
(b.end2 > chromSize2));
// keep looking if we have exceeded the end of the chrom.
}
}
void BedShuffle::ChooseLocusFromInclusionFile(BED &bedEntry) {
string chrom = bedEntry.chrom;
CHRPOS length = bedEntry.end - bedEntry.start;
string randomChrom;
CHRPOS randomStart;
BED includeInterval;
if (_sameChrom == false) {
// grab a random chromosome from the inclusion file.
randomChrom = _includeChroms[rand() % _numIncludeChroms];
// get the number of inclusion intervals for that chrom
size_t size = _include->bedMapNoBin[randomChrom].size();
// grab a random interval on the chosen chromosome.
size_t interval = rand() % size;
// retreive a ranom -incl interval on the selected chrom
includeInterval = _include->bedMapNoBin[randomChrom][interval];
bedEntry.chrom = randomChrom;
}
else {
// get the number of inclusion intervals for the original chrom
size_t size = _include->bedMapNoBin[chrom].size();
// grab a random interval on the chosen chromosome.
includeInterval = _include->bedMapNoBin[chrom][rand() % size];
}
randomStart = includeInterval.start + rand() % (includeInterval.size());
bedEntry.start = randomStart;
bedEntry.end = randomStart + length;
// use recursion to ensure that the chosen location
// doesn't go past the end of the chrom
if (bedEntry.end > ((size_t) _genome->getChromSize(chrom))) {
//bedEntry.end = _genome->getChromSize(chrom);
ChooseLocusFromInclusionFile(bedEntry);
}
}
<|endoftext|> |
<commit_before>/*
* This file is a part of Xpiks - cross platform application for
* keywording and uploading images for microstocks
* Copyright (C) 2014-2016 Taras Kushnir <kushnirTV@gmail.com>
*
* Xpiks is distributed under the GNU General Public License, version 3.0
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "telemetryworker.h"
#include <QString>
#include <QUrl>
#include <QUrlQuery>
#include <QSysInfo>
#include <QByteArray>
#include <QTime>
#include <QRegExp>
#include <curl/curl.h>
#include <string>
#include "../Common/version.h"
void buildQuery(std::shared_ptr<Conectivity::AnalyticsUserEvent> &userEvent, const QString &userAgent, QUrlQuery &query) {
query.addQueryItem(QLatin1String("idsite"), QLatin1String("1"));
query.addQueryItem(QLatin1String("rec"), QLatin1String("1"));
query.addQueryItem(QLatin1String("url"), QString("/client/%1").arg(userEvent->getActionString()));
query.addQueryItem(QLatin1String("action_name"), userEvent->getActionString());
query.addQueryItem(QLatin1String("_id"), userAgent);
query.addQueryItem(QLatin1String("rand"), QString::number(qrand()));
query.addQueryItem(QLatin1String("apiv"), QLatin1String("1"));
query.addQueryItem(QLatin1String("h"), QString::number(userEvent->getHour()));
query.addQueryItem(QLatin1String("m"), QString::number(userEvent->getMinute()));
query.addQueryItem(QLatin1String("s"), QString::number(userEvent->getSecond()));
query.addQueryItem(QLatin1String("send_image"), QLatin1String("0"));
}
namespace Conectivity {
TelemetryWorker::TelemetryWorker(const QString &userAgent, const QString &reportingEndpoint, const QString &interfaceLanguage):
m_UserAgentId(userAgent),
m_ReportingEndpoint(reportingEndpoint),
m_InterfaceLanguage(interfaceLanguage)
{
}
bool TelemetryWorker::initWorker() {
return true;
}
void TelemetryWorker::processOneItem(std::shared_ptr<AnalyticsUserEvent> &item) {
LOG_INFO << "Reporting action:" << item->getActionString();
QUrlQuery query;
buildQuery(item, m_UserAgentId, query);
QString customVarsStr = QString::fromLatin1("{\"1\":[\"OS_type\",\"%1\"],\"2\":[\"OS_version\",\"%2\"],\"3\":[\"Xpiks_version\",\"%3\"],\"4\":[\"UI_language\",\"%4\"]}");
#if (QT_VERSION >= QT_VERSION_CHECK(5, 4, 0))
query.addQueryItem(QLatin1String("_cvar"),
customVarsStr
.arg(QSysInfo::productType())
.arg(QSysInfo::productVersion())
.arg(XPIKS_VERSION_STRING)
.arg(m_InterfaceLanguage));
#else
query.addQueryItem(QLatin1String("_cvar"),
customVarsStr
#ifdef Q_OS_WIN
.arg(QString("windows"))
#elsif Q_OS_DARWIN
.arg(QString("osx"))
#else
.arg(QString("Linux QT<5.4"))
#endif
.arg(QString("-"))
.arg(XPIKS_VERSION_STRING)
.arg(m_InterfaceLanguage));
#endif
#ifdef QT_DEBUG
LOG_DEBUG << "Telemetry request:" << m_ReportingEndpoint << query.toString();
#endif
sendOneReport(m_ReportingEndpoint, query.toString());
}
bool TelemetryWorker::sendOneReport(const QString &resource, const QString &payload) {
CURL *curl_handle;
CURLcode res;
/* init the curl session */
curl_handle = curl_easy_init();
std::string resourceString = resource.toStdString();
const char *url = resourceString.data();
/* specify URL to get */
curl_easy_setopt(curl_handle, CURLOPT_URL, url);
/* some servers don't like requests that are made without a user-agent
field, so we provide one */
QString userAgent;
#if defined(Q_OS_DARWIN)
userAgent = QString("Mozilla/5.0 (Macintosh; Mac OS X %2; rv:1.1) Qt Xpiks/1.1")
.arg(QSysInfo::productVersion());
#elif defined(Q_OS_WIN)
userAgent = QString("Mozilla/5.0 (Windows %2; rv:1.1) Qt Xpiks/1.1")
.arg(QSysInfo::productVersion());
#elif defined(Q_OS_LINUX)
userAgent = QString("Mozilla/5.0 (Linux %2; rv:1.1) Qt Xpiks/1.1")
#if (QT_VERSION >= QT_VERSION_CHECK(5, 4, 0))
.arg(QSysInfo::productVersion());
#else
.arg("?");
#endif
#endif
std::string userAgentString = userAgent.toStdString();
const char *userAgentData = userAgentString.data();
curl_easy_setopt(curl_handle, CURLOPT_USERAGENT, userAgentData);
std::string postString = payload.toStdString();
const char *postData = postString.data();
/* Now specify the POST data */
curl_easy_setopt(curl_handle, CURLOPT_POSTFIELDS, postData);
/* get it! */
res = curl_easy_perform(curl_handle);
const bool success = (CURLE_OK == res);
/* check for errors */
if(!success) {
LOG_WARNING << "curl_easy_perform() failed" << curl_easy_strerror(res);
}
/* cleanup curl stuff */
curl_easy_cleanup(curl_handle);
return success;
}
}
<commit_msg>POST request size for telemetry worker<commit_after>/*
* This file is a part of Xpiks - cross platform application for
* keywording and uploading images for microstocks
* Copyright (C) 2014-2016 Taras Kushnir <kushnirTV@gmail.com>
*
* Xpiks is distributed under the GNU General Public License, version 3.0
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "telemetryworker.h"
#include <QString>
#include <QUrl>
#include <QUrlQuery>
#include <QSysInfo>
#include <QByteArray>
#include <QTime>
#include <QRegExp>
#include <curl/curl.h>
#include <string>
#include "../Common/version.h"
void buildQuery(std::shared_ptr<Conectivity::AnalyticsUserEvent> &userEvent, const QString &userAgent, QUrlQuery &query) {
query.addQueryItem(QLatin1String("idsite"), QLatin1String("1"));
query.addQueryItem(QLatin1String("rec"), QLatin1String("1"));
query.addQueryItem(QLatin1String("url"), QString("/client/%1").arg(userEvent->getActionString()));
query.addQueryItem(QLatin1String("action_name"), userEvent->getActionString());
query.addQueryItem(QLatin1String("_id"), userAgent);
query.addQueryItem(QLatin1String("rand"), QString::number(qrand()));
query.addQueryItem(QLatin1String("apiv"), QLatin1String("1"));
query.addQueryItem(QLatin1String("h"), QString::number(userEvent->getHour()));
query.addQueryItem(QLatin1String("m"), QString::number(userEvent->getMinute()));
query.addQueryItem(QLatin1String("s"), QString::number(userEvent->getSecond()));
query.addQueryItem(QLatin1String("send_image"), QLatin1String("0"));
}
namespace Conectivity {
TelemetryWorker::TelemetryWorker(const QString &userAgent, const QString &reportingEndpoint, const QString &interfaceLanguage):
m_UserAgentId(userAgent),
m_ReportingEndpoint(reportingEndpoint),
m_InterfaceLanguage(interfaceLanguage)
{
}
bool TelemetryWorker::initWorker() {
return true;
}
void TelemetryWorker::processOneItem(std::shared_ptr<AnalyticsUserEvent> &item) {
LOG_INFO << "Reporting action:" << item->getActionString();
QUrlQuery query;
buildQuery(item, m_UserAgentId, query);
QString customVarsStr = QString::fromLatin1("{\"1\":[\"OS_type\",\"%1\"],\"2\":[\"OS_version\",\"%2\"],\"3\":[\"Xpiks_version\",\"%3\"],\"4\":[\"UI_language\",\"%4\"]}");
#if (QT_VERSION >= QT_VERSION_CHECK(5, 4, 0))
query.addQueryItem(QLatin1String("_cvar"),
customVarsStr
.arg(QSysInfo::productType())
.arg(QSysInfo::productVersion())
.arg(XPIKS_VERSION_STRING)
.arg(m_InterfaceLanguage));
#else
query.addQueryItem(QLatin1String("_cvar"),
customVarsStr
#ifdef Q_OS_WIN
.arg(QString("windows"))
#elsif Q_OS_DARWIN
.arg(QString("osx"))
#else
.arg(QString("Linux QT<5.4"))
#endif
.arg(QString("-"))
.arg(XPIKS_VERSION_STRING)
.arg(m_InterfaceLanguage));
#endif
#ifdef QT_DEBUG
LOG_DEBUG << "Telemetry request:" << m_ReportingEndpoint << query.toString();
#endif
sendOneReport(m_ReportingEndpoint, query.toString());
}
bool TelemetryWorker::sendOneReport(const QString &resource, const QString &payload) {
CURL *curl_handle;
CURLcode res;
/* init the curl session */
curl_handle = curl_easy_init();
std::string resourceString = resource.toStdString();
const char *url = resourceString.data();
/* specify URL to get */
curl_easy_setopt(curl_handle, CURLOPT_URL, url);
/* some servers don't like requests that are made without a user-agent
field, so we provide one */
QString userAgent;
#if defined(Q_OS_DARWIN)
userAgent = QString("Mozilla/5.0 (Macintosh; Mac OS X %2; rv:1.1) Qt Xpiks/1.1")
.arg(QSysInfo::productVersion());
#elif defined(Q_OS_WIN)
userAgent = QString("Mozilla/5.0 (Windows %2; rv:1.1) Qt Xpiks/1.1")
.arg(QSysInfo::productVersion());
#elif defined(Q_OS_LINUX)
userAgent = QString("Mozilla/5.0 (Linux %2; rv:1.1) Qt Xpiks/1.1")
#if (QT_VERSION >= QT_VERSION_CHECK(5, 4, 0))
.arg(QSysInfo::productVersion());
#else
.arg("?");
#endif
#endif
std::string userAgentString = userAgent.toStdString();
const char *userAgentData = userAgentString.data();
curl_easy_setopt(curl_handle, CURLOPT_USERAGENT, userAgentData);
std::string postString = payload.toStdString();
const char *postData = postString.data();
/* Now specify the POST data */
curl_easy_setopt(curl_handle, CURLOPT_POSTFIELDS, postData);
curl_easy_setopt(curl_handle, CURLOPT_POSTFIELDSIZE, (long)postString.size());
/* get it! */
res = curl_easy_perform(curl_handle);
const bool success = (CURLE_OK == res);
/* check for errors */
if(!success) {
LOG_WARNING << "curl_easy_perform() failed" << curl_easy_strerror(res);
}
/* cleanup curl stuff */
curl_easy_cleanup(curl_handle);
return success;
}
}
<|endoftext|> |
<commit_before>//
// Copyright (c) 2015, Microsoft Corporation
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
// IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
//
#include "pch.h"
#include <sstream>
#include "Bridge.h"
#include "BridgeDevice.h"
#include "DeviceProperty.h"
#include "PropertyInterface.h"
#include "DeviceInterface.h"
#include "AllJoynProperty.h"
#include "AllJoynHelper.h"
using namespace Platform;
using namespace Platform::Collections;
using namespace Windows::Foundation::Collections;
using namespace Windows::Foundation;
using namespace BridgeRT;
using namespace std;
using namespace Windows::Foundation;
DeviceProperty::DeviceProperty()
: m_deviceProperty(nullptr),
m_parent(nullptr),
m_AJBusObject(NULL),
m_registeredOnAllJoyn(false),
m_propertyInterface(nullptr)
{
}
DeviceProperty::~DeviceProperty()
{
}
QStatus DeviceProperty::Initialize(IAdapterProperty ^deviceProperty, PropertyInterface *propertyInterface, BridgeDevice ^parent, alljoyn_busobject busObject)
{
QStatus status = ER_OK;
string tempString;
// sanity check
if (nullptr == deviceProperty)
{
status = ER_BAD_ARG_1;
goto leave;
}
if (nullptr == propertyInterface)
{
status = ER_BAD_ARG_2;
goto leave;
}
if (nullptr == parent)
{
status = ER_BAD_ARG_3;
goto leave;
}
m_deviceProperty = deviceProperty;
m_propertyInterface = propertyInterface;
m_parent = parent;
m_AJBusObject = busObject;
status = PairAjProperties();
if (ER_OK != status)
{
goto leave;
}
m_registeredOnAllJoyn = true;
leave:
return status;
}
void DeviceProperty::Shutdown()
{
if (NULL != m_AJBusObject)
{
if (m_registeredOnAllJoyn)
{
// unregister bus object
alljoyn_busattachment_unregisterbusobject(m_parent->GetBusAttachment(), m_AJBusObject);
m_registeredOnAllJoyn = false;
}
alljoyn_busobject_destroy(m_AJBusObject);
m_AJBusObject = NULL;
}
m_propertyInterface = nullptr;
m_parent = nullptr;
m_AJBusObjectPath.clear();
m_AJpropertyAdapterValuePairs.clear();
}
QStatus BridgeRT::DeviceProperty::PairAjProperties()
{
QStatus status = ER_OK;
vector <IAdapterAttribute ^> tempList;
// create temporary list of IAdapterValue that have to match with one of the
// AllJoyn properties
for (auto adapterAttr : m_deviceProperty->Attributes)
{
tempList.push_back(adapterAttr);
}
// go through AllJoyn properties and find matching IAdapterValue
for (auto ajProperty : m_propertyInterface->GetAJProperties())
{
bool paired = false;
auto adapterAttr = tempList.end();
for (adapterAttr = tempList.begin(); adapterAttr != tempList.end(); adapterAttr++)
{
if (ajProperty->IsSameType(*adapterAttr))
{
AJpropertyAdapterValuePair tempPair = { ajProperty, *adapterAttr };
m_AJpropertyAdapterValuePairs.insert(std::make_pair(*ajProperty->GetName(), tempPair));
paired = true;
break;
}
}
if (!paired)
{
// a matching IAdapterValue must exist for each AllJoyn property
status = ER_INVALID_DATA;
goto leave;
}
// remove adapterValue from temp list
tempList.erase(adapterAttr);
}
leave:
return status;
}
QStatus AJ_CALL DeviceProperty::GetProperty(_In_ const void* context, _In_z_ const char* ifcName, _In_z_ const char* propName, _Out_ alljoyn_msgarg val)
{
QStatus status = ER_OK;
uint32 adapterStatus = ERROR_SUCCESS;
DeviceProperty *deviceProperty = nullptr;
IAdapterAttribute ^adapterAttr = nullptr;
IAdapterValue ^adapterValue = nullptr;
AllJoynProperty *ajProperty = nullptr;
IAdapterIoRequest^ request;
UNREFERENCED_PARAMETER(ifcName);
deviceProperty = (DeviceProperty *)context;
if (nullptr == deviceProperty) // sanity test
{
return ER_BAD_ARG_1;
}
// identify alljoyn property and its corresponding adapter value
auto index = deviceProperty->m_AJpropertyAdapterValuePairs.find(propName);
if (deviceProperty->m_AJpropertyAdapterValuePairs.end() == index)
{
status = ER_BUS_NO_SUCH_PROPERTY;
goto leave;
}
ajProperty = index->second.ajProperty;
adapterAttr = index->second.adapterAttr;
adapterValue = adapterAttr->Value;
// get value of adapter value
adapterStatus = DsbBridge::SingleInstance()->GetAdapter()->GetPropertyValue(deviceProperty->m_deviceProperty, adapterValue->Name, &adapterValue, &request);
if (ERROR_IO_PENDING == adapterStatus &&
nullptr != request)
{
// wait for completion
adapterStatus = request->Wait(WAIT_TIMEOUT_FOR_ADAPTER_OPERATION);
}
if (ERROR_SUCCESS != adapterStatus)
{
status = ER_OS_ERROR;
goto leave;
}
// build alljoyn response to get
status = AllJoynHelper::SetMsgArg(adapterValue, val);
leave:
return status;
}
QStatus AJ_CALL DeviceProperty::SetProperty(_In_ const void* context, _In_z_ const char* ifcName, _In_z_ const char* propName, _In_ alljoyn_msgarg val)
{
QStatus status = ER_OK;
uint32 adapterStatus = ERROR_SUCCESS;
DeviceProperty *deviceProperty = nullptr;
IAdapterAttribute^ adapterAttr = nullptr;
IAdapterValue ^adapterValue = nullptr;
AllJoynProperty *ajProperty = nullptr;
IAdapterIoRequest^ request;
UNREFERENCED_PARAMETER(ifcName);
deviceProperty = (DeviceProperty *)context;
if (nullptr == deviceProperty) // sanity test
{
return ER_BAD_ARG_1;
}
// identify alljoyn property and its corresponding adapter value
auto index = deviceProperty->m_AJpropertyAdapterValuePairs.find(propName);
if (deviceProperty->m_AJpropertyAdapterValuePairs.end() == index)
{
status = ER_BUS_NO_SUCH_PROPERTY;
goto leave;
}
ajProperty = index->second.ajProperty;
adapterAttr = index->second.adapterAttr;
adapterValue = adapterAttr->Value;
// update IAdapterValue from AllJoyn message
status = AllJoynHelper::GetAdapterValue(adapterValue, val);
if (ER_OK != status)
{
goto leave;
}
// set value in adapter
adapterStatus = DsbBridge::SingleInstance()->GetAdapter()->SetPropertyValue(deviceProperty->m_deviceProperty, adapterValue, &request);
if (ERROR_IO_PENDING == adapterStatus &&
nullptr != request)
{
// wait for completion
adapterStatus = request->Wait(WAIT_TIMEOUT_FOR_ADAPTER_OPERATION);
}
if (ERROR_ACCESS_DENIED == adapterStatus)
{
status = ER_BUS_PROPERTY_ACCESS_DENIED;
goto leave;
}
if (ERROR_SUCCESS != adapterStatus)
{
status = ER_BUS_PROPERTY_VALUE_NOT_SET;
goto leave;
}
leave:
return status;
}
void DeviceProperty::EmitSignalCOV(IAdapterValue ^newValue, const std::vector<alljoyn_sessionid>& sessionIds)
{
QStatus status = ER_OK;
alljoyn_msgarg msgArg = NULL;
auto valuePair = m_AJpropertyAdapterValuePairs.end();
// sanity check
if (nullptr == newValue)
{
goto leave;
}
// get AllJoyn property that match with IAdapterValue that has changed
for (valuePair = m_AJpropertyAdapterValuePairs.begin(); valuePair != m_AJpropertyAdapterValuePairs.end(); valuePair++)
{
if (valuePair->second.adapterAttr->Value->Name == newValue->Name)
{
break;
}
}
if (valuePair == m_AJpropertyAdapterValuePairs.end())
{
// can't find any Alljoyn property that correspond to IAdapterValue
goto leave;
}
// prepare signal arguments
msgArg = alljoyn_msgarg_create();
if (NULL == msgArg)
{
goto leave;
}
// build alljoyn message from IAdapterValue
status = AllJoynHelper::SetMsgArg(newValue, msgArg);
if (status != ER_OK)
{
goto leave;
}
for (auto sessionId : sessionIds)
{
// emit property change
alljoyn_busobject_emitpropertychanged(m_AJBusObject,
m_propertyInterface->GetInterface()->GetInterfaceName()->c_str(),
valuePair->second.ajProperty->GetName()->c_str(),
msgArg, sessionId);
}
leave:
if (NULL != msgArg)
{
alljoyn_msgarg_destroy(msgArg);
}
return;
}<commit_msg>Fixed crash on dispose of busobject<commit_after>//
// Copyright (c) 2015, Microsoft Corporation
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
// IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
//
#include "pch.h"
#include <sstream>
#include "Bridge.h"
#include "BridgeDevice.h"
#include "DeviceProperty.h"
#include "PropertyInterface.h"
#include "DeviceInterface.h"
#include "AllJoynProperty.h"
#include "AllJoynHelper.h"
using namespace Platform;
using namespace Platform::Collections;
using namespace Windows::Foundation::Collections;
using namespace Windows::Foundation;
using namespace BridgeRT;
using namespace std;
using namespace Windows::Foundation;
DeviceProperty::DeviceProperty()
: m_deviceProperty(nullptr),
m_parent(nullptr),
m_AJBusObject(NULL),
m_registeredOnAllJoyn(false),
m_propertyInterface(nullptr)
{
}
DeviceProperty::~DeviceProperty()
{
}
QStatus DeviceProperty::Initialize(IAdapterProperty ^deviceProperty, PropertyInterface *propertyInterface, BridgeDevice ^parent, alljoyn_busobject busObject)
{
QStatus status = ER_OK;
string tempString;
// sanity check
if (nullptr == deviceProperty)
{
status = ER_BAD_ARG_1;
goto leave;
}
if (nullptr == propertyInterface)
{
status = ER_BAD_ARG_2;
goto leave;
}
if (nullptr == parent)
{
status = ER_BAD_ARG_3;
goto leave;
}
m_deviceProperty = deviceProperty;
m_propertyInterface = propertyInterface;
m_parent = parent;
m_AJBusObject = busObject;
status = PairAjProperties();
if (ER_OK != status)
{
goto leave;
}
m_registeredOnAllJoyn = true;
leave:
return status;
}
void DeviceProperty::Shutdown()
{
m_propertyInterface = nullptr;
m_parent = nullptr;
m_AJBusObject = NULL;
m_AJBusObjectPath.clear();
m_AJpropertyAdapterValuePairs.clear();
}
QStatus BridgeRT::DeviceProperty::PairAjProperties()
{
QStatus status = ER_OK;
vector <IAdapterAttribute ^> tempList;
// create temporary list of IAdapterValue that have to match with one of the
// AllJoyn properties
for (auto adapterAttr : m_deviceProperty->Attributes)
{
tempList.push_back(adapterAttr);
}
// go through AllJoyn properties and find matching IAdapterValue
for (auto ajProperty : m_propertyInterface->GetAJProperties())
{
bool paired = false;
auto adapterAttr = tempList.end();
for (adapterAttr = tempList.begin(); adapterAttr != tempList.end(); adapterAttr++)
{
if (ajProperty->IsSameType(*adapterAttr))
{
AJpropertyAdapterValuePair tempPair = { ajProperty, *adapterAttr };
m_AJpropertyAdapterValuePairs.insert(std::make_pair(*ajProperty->GetName(), tempPair));
paired = true;
break;
}
}
if (!paired)
{
// a matching IAdapterValue must exist for each AllJoyn property
status = ER_INVALID_DATA;
goto leave;
}
// remove adapterValue from temp list
tempList.erase(adapterAttr);
}
leave:
return status;
}
QStatus AJ_CALL DeviceProperty::GetProperty(_In_ const void* context, _In_z_ const char* ifcName, _In_z_ const char* propName, _Out_ alljoyn_msgarg val)
{
QStatus status = ER_OK;
uint32 adapterStatus = ERROR_SUCCESS;
DeviceProperty *deviceProperty = nullptr;
IAdapterAttribute ^adapterAttr = nullptr;
IAdapterValue ^adapterValue = nullptr;
AllJoynProperty *ajProperty = nullptr;
IAdapterIoRequest^ request;
UNREFERENCED_PARAMETER(ifcName);
deviceProperty = (DeviceProperty *)context;
if (nullptr == deviceProperty) // sanity test
{
return ER_BAD_ARG_1;
}
// identify alljoyn property and its corresponding adapter value
auto index = deviceProperty->m_AJpropertyAdapterValuePairs.find(propName);
if (deviceProperty->m_AJpropertyAdapterValuePairs.end() == index)
{
status = ER_BUS_NO_SUCH_PROPERTY;
goto leave;
}
ajProperty = index->second.ajProperty;
adapterAttr = index->second.adapterAttr;
adapterValue = adapterAttr->Value;
// get value of adapter value
adapterStatus = DsbBridge::SingleInstance()->GetAdapter()->GetPropertyValue(deviceProperty->m_deviceProperty, adapterValue->Name, &adapterValue, &request);
if (ERROR_IO_PENDING == adapterStatus &&
nullptr != request)
{
// wait for completion
adapterStatus = request->Wait(WAIT_TIMEOUT_FOR_ADAPTER_OPERATION);
}
if (ERROR_SUCCESS != adapterStatus)
{
status = ER_OS_ERROR;
goto leave;
}
// build alljoyn response to get
status = AllJoynHelper::SetMsgArg(adapterValue, val);
leave:
return status;
}
QStatus AJ_CALL DeviceProperty::SetProperty(_In_ const void* context, _In_z_ const char* ifcName, _In_z_ const char* propName, _In_ alljoyn_msgarg val)
{
QStatus status = ER_OK;
uint32 adapterStatus = ERROR_SUCCESS;
DeviceProperty *deviceProperty = nullptr;
IAdapterAttribute^ adapterAttr = nullptr;
IAdapterValue ^adapterValue = nullptr;
AllJoynProperty *ajProperty = nullptr;
IAdapterIoRequest^ request;
UNREFERENCED_PARAMETER(ifcName);
deviceProperty = (DeviceProperty *)context;
if (nullptr == deviceProperty) // sanity test
{
return ER_BAD_ARG_1;
}
// identify alljoyn property and its corresponding adapter value
auto index = deviceProperty->m_AJpropertyAdapterValuePairs.find(propName);
if (deviceProperty->m_AJpropertyAdapterValuePairs.end() == index)
{
status = ER_BUS_NO_SUCH_PROPERTY;
goto leave;
}
ajProperty = index->second.ajProperty;
adapterAttr = index->second.adapterAttr;
adapterValue = adapterAttr->Value;
// update IAdapterValue from AllJoyn message
status = AllJoynHelper::GetAdapterValue(adapterValue, val);
if (ER_OK != status)
{
goto leave;
}
// set value in adapter
adapterStatus = DsbBridge::SingleInstance()->GetAdapter()->SetPropertyValue(deviceProperty->m_deviceProperty, adapterValue, &request);
if (ERROR_IO_PENDING == adapterStatus &&
nullptr != request)
{
// wait for completion
adapterStatus = request->Wait(WAIT_TIMEOUT_FOR_ADAPTER_OPERATION);
}
if (ERROR_ACCESS_DENIED == adapterStatus)
{
status = ER_BUS_PROPERTY_ACCESS_DENIED;
goto leave;
}
if (ERROR_SUCCESS != adapterStatus)
{
status = ER_BUS_PROPERTY_VALUE_NOT_SET;
goto leave;
}
leave:
return status;
}
void DeviceProperty::EmitSignalCOV(IAdapterValue ^newValue, const std::vector<alljoyn_sessionid>& sessionIds)
{
QStatus status = ER_OK;
alljoyn_msgarg msgArg = NULL;
auto valuePair = m_AJpropertyAdapterValuePairs.end();
// sanity check
if (nullptr == newValue)
{
goto leave;
}
// get AllJoyn property that match with IAdapterValue that has changed
for (valuePair = m_AJpropertyAdapterValuePairs.begin(); valuePair != m_AJpropertyAdapterValuePairs.end(); valuePair++)
{
if (valuePair->second.adapterAttr->Value->Name == newValue->Name)
{
break;
}
}
if (valuePair == m_AJpropertyAdapterValuePairs.end())
{
// can't find any Alljoyn property that correspond to IAdapterValue
goto leave;
}
// prepare signal arguments
msgArg = alljoyn_msgarg_create();
if (NULL == msgArg)
{
goto leave;
}
// build alljoyn message from IAdapterValue
status = AllJoynHelper::SetMsgArg(newValue, msgArg);
if (status != ER_OK)
{
goto leave;
}
for (auto sessionId : sessionIds)
{
// emit property change
alljoyn_busobject_emitpropertychanged(m_AJBusObject,
m_propertyInterface->GetInterface()->GetInterfaceName()->c_str(),
valuePair->second.ajProperty->GetName()->c_str(),
msgArg, sessionId);
}
leave:
if (NULL != msgArg)
{
alljoyn_msgarg_destroy(msgArg);
}
return;
}<|endoftext|> |
<commit_before>#include <Input/InputManager.hpp>
#include <Input/KeyList.hpp>
#include <Triggers/TriggerDatabase.hpp>
#include <Utils/VectorUtils.hpp>
namespace obe::Input
{
InputManager::InputManager()
: Registrable("InputManager"),
m_actionTriggers(
Triggers::TriggerDatabase::GetInstance()->createTriggerGroup(
"Global", "Actions"),
Triggers::TriggerGroupPtrRemover)
{
}
InputAction& InputManager::getAction(const std::string& actionId)
{
for (auto& action : m_allActions)
{
if (action->getId() == actionId)
{
return *action.get();
}
}
aube::ErrorHandler::Warn("ObEngine.Input.InputManager.UnknownAction",
{{"action", actionId}});
m_allActions.push_back(
std::make_unique<InputAction>(m_actionTriggers.get(), actionId));
return *m_allActions.back().get();
}
void InputManager::setEnabled(const bool state)
{
m_binderEnabled = state;
}
void InputManager::update()
{
if (m_binderEnabled)
{
const unsigned int actionsAmount = m_currentActions.size();
for (unsigned int i = 0; i < actionsAmount; i++)
{
if (i <
m_currentActions.size()) // Performance issue ? <REVISION>
m_currentActions[i]->update();
}
}
}
bool InputManager::actionExists(const std::string& actionId)
{
for (auto& action : m_allActions)
{
if (action->getId() == actionId)
{
return true;
}
}
return false;
}
void InputManager::clear()
{
m_currentActions.clear();
for (auto& action : m_allActions)
m_actionTriggers->removeTrigger(action->getId());
m_allActions.clear();
}
void InputManager::configure(vili::ComplexNode& config)
{
std::vector<std::string> alreadyInFile;
for (vili::ComplexNode* context : config.getAll<vili::ComplexNode>())
{
for (vili::Node* action : context->getAll())
{
if (!this->actionExists(action->getId()))
{
m_allActions.push_back(std::make_unique<InputAction>(
m_actionTriggers.get(), action->getId()));
}
else if (!Utils::Vector::contains(action->getId(),
alreadyInFile))
{
this->getAction(action->getId()).clearConditions();
}
auto inputCondition = [](InputManager* inputManager,
vili::Node* action,
vili::DataNode* condition) {
InputCondition actionCondition;
actionCondition.setCombinationCode(
condition->get<std::string>());
Debug::Log->debug(
"<InputManager> Associated Key '{0}' for Action '{1}'",
condition->get<std::string>(), action->getId());
inputManager->getAction(action->getId())
.addCondition(actionCondition);
};
if (action->getType() == vili::NodeType::DataNode)
{
inputCondition(this, action,
static_cast<vili::DataNode*>(action));
}
else if (action->getType() == vili::NodeType::ArrayNode)
{
for (vili::DataNode* condition :
*static_cast<vili::ArrayNode*>(action))
{
inputCondition(this, action, condition);
}
}
this->getAction(action->getId()).addContext(context->getId());
alreadyInFile.push_back(action->getId());
}
}
// Add Context keys in real time <REVISION>
}
void InputManager::clearContexts()
{
m_currentActions.clear();
}
InputManager& InputManager::addContext(const std::string& context)
{
Debug::Log->debug("<InputManager> Adding Context '{0}'", context);
for (auto& action : m_allActions)
{
if (Utils::Vector::contains(context, action->getContexts()) &&
!Utils::Vector::contains(action.get(), m_currentActions))
{
Debug::Log->debug(
"<InputManager> Add Action '{0}' in Context '{1}'",
action.get()->getId(), context);
m_currentActions.push_back(action.get());
}
}
return *this;
}
InputManager& InputManager::removeContext(const std::string& context)
{
//<REVISION> Multiple context, keep which one, remove keys of wrong
//context
m_currentActions.erase(
std::remove_if(
m_currentActions.begin(), m_currentActions.end(),
[&context](const InputAction* inputAction) -> bool {
auto& contexts = inputAction->getContexts();
return std::find(contexts.begin(),
contexts.end(),
context) != contexts.end();
}),
m_currentActions.end());
return *this;
}
void InputManager::setContext(const std::string& context)
{
this->clearContexts();
this->addContext(context);
}
std::vector<std::string> InputManager::getContexts()
{
std::vector<std::string> allContexts;
for (const InputAction* action : m_currentActions)
{
for (const std::string& context : action->getContexts())
{
if (!Utils::Vector::contains(context, allContexts))
{
allContexts.push_back(context);
}
}
}
return allContexts;
}
} // namespace obe::Input<commit_msg>Fix macOS build (I hope)<commit_after>#include <Input/InputManager.hpp>
#include <Input/KeyList.hpp>
#include <Triggers/TriggerDatabase.hpp>
#include <Utils/VectorUtils.hpp>
namespace obe::Input
{
InputManager::InputManager()
: Registrable("InputManager"),
m_actionTriggers(
Triggers::TriggerDatabase::GetInstance()->createTriggerGroup(
"Global", "Actions"),
Triggers::TriggerGroupPtrRemover)
{
}
InputAction& InputManager::getAction(const std::string& actionId)
{
for (auto& action : m_allActions)
{
if (action->getId() == actionId)
{
return *action.get();
}
}
aube::ErrorHandler::Warn("ObEngine.Input.InputManager.UnknownAction",
{{"action", actionId}});
m_allActions.push_back(
std::make_unique<InputAction>(m_actionTriggers.get(), actionId));
return *m_allActions.back().get();
}
void InputManager::setEnabled(const bool state)
{
m_binderEnabled = state;
}
void InputManager::update()
{
if (m_binderEnabled)
{
const unsigned int actionsAmount = m_currentActions.size();
for (unsigned int i = 0; i < actionsAmount; i++)
{
if (i <
m_currentActions.size()) // Performance issue ? <REVISION>
m_currentActions[i]->update();
}
}
}
bool InputManager::actionExists(const std::string& actionId)
{
for (auto& action : m_allActions)
{
if (action->getId() == actionId)
{
return true;
}
}
return false;
}
void InputManager::clear()
{
m_currentActions.clear();
for (auto& action : m_allActions)
m_actionTriggers->removeTrigger(action->getId());
m_allActions.clear();
}
void InputManager::configure(vili::ComplexNode& config)
{
std::vector<std::string> alreadyInFile;
for (vili::ComplexNode* context : config.getAll<vili::ComplexNode>())
{
for (vili::Node* action : context->getAll())
{
if (!this->actionExists(action->getId()))
{
m_allActions.push_back(std::make_unique<InputAction>(
m_actionTriggers.get(), action->getId()));
}
else if (!Utils::Vector::contains(action->getId(),
alreadyInFile))
{
this->getAction(action->getId()).clearConditions();
}
auto inputCondition = [](InputManager* inputManager,
vili::Node* action,
vili::DataNode* condition) {
InputCondition actionCondition;
actionCondition.setCombinationCode(
condition->get<std::string>());
Debug::Log->debug(
"<InputManager> Associated Key '{0}' for Action '{1}'",
condition->get<std::string>(), action->getId());
inputManager->getAction(action->getId())
.addCondition(actionCondition);
};
if (action->getType() == vili::NodeType::DataNode)
{
inputCondition(this, action,
static_cast<vili::DataNode*>(action));
}
else if (action->getType() == vili::NodeType::ArrayNode)
{
for (vili::DataNode* condition :
*static_cast<vili::ArrayNode*>(action))
{
inputCondition(this, action, condition);
}
}
this->getAction(action->getId()).addContext(context->getId());
alreadyInFile.push_back(action->getId());
}
}
// Add Context keys in real time <REVISION>
}
void InputManager::clearContexts()
{
m_currentActions.clear();
}
InputManager& InputManager::addContext(const std::string& context)
{
Debug::Log->debug("<InputManager> Adding Context '{0}'", context);
for (auto& action : m_allActions)
{
if (Utils::Vector::contains(context, action->getContexts()) &&
!Utils::Vector::contains(action.get(), m_currentActions))
{
Debug::Log->debug(
"<InputManager> Add Action '{0}' in Context '{1}'",
action.get()->getId(), context);
m_currentActions.push_back(action.get());
}
}
return *this;
}
InputManager& InputManager::removeContext(const std::string& context)
{
//<REVISION> Multiple context, keep which one, remove keys of wrong
//context
m_currentActions.erase(
std::remove_if(
m_currentActions.begin(), m_currentActions.end(),
[&context](const InputAction* inputAction) -> bool {
const auto& contexts = inputAction->getContexts();
return std::find(contexts.begin(),
contexts.end(),
context) != contexts.end();
}),
m_currentActions.end());
return *this;
}
void InputManager::setContext(const std::string& context)
{
this->clearContexts();
this->addContext(context);
}
std::vector<std::string> InputManager::getContexts()
{
std::vector<std::string> allContexts;
for (const InputAction* action : m_currentActions)
{
for (const std::string& context : action->getContexts())
{
if (!Utils::Vector::contains(context, allContexts))
{
allContexts.push_back(context);
}
}
}
return allContexts;
}
} // namespace obe::Input<|endoftext|> |
<commit_before>#include "TranslationOptionList.h"
#include "Util.h"
#include "TranslationOption.h"
#include <boost/foreach.hpp>
using namespace std;
namespace Moses
{
TranslationOptionList::
TranslationOptionList(const TranslationOptionList ©)
{
const_iterator iter;
for (iter = copy.begin(); iter != copy.end(); ++iter) {
const TranslationOption &origTransOpt = **iter;
TranslationOption *newTransOpt = new TranslationOption(origTransOpt);
Add(newTransOpt);
}
}
TranslationOptionList::
~TranslationOptionList()
{
RemoveAllInColl(m_coll);
}
TO_STRING_BODY(TranslationOptionList);
std::ostream& operator<<(std::ostream& out, const TranslationOptionList& coll)
{
TranslationOptionList::const_iterator iter;
for (iter = coll.begin(); iter != coll.end(); ++iter) {
const TranslationOption &transOpt = **iter;
out << transOpt << endl;
}
return out;
}
size_t
TranslationOptionList::
SelectNBest(size_t const N)
{
if (N == 0 || N <= m_coll.size()) return 0;
static TranslationOption::Better cmp;
NTH_ELEMENT4(m_coll.begin(), m_coll.begin() + N, m_coll.end(), cmp);
// delete the rest
for (size_t i = N ; i < m_coll.size() ; ++i) delete m_coll[i];
size_t ret = m_coll.size() - N;
m_coll.resize(N);
return ret;
}
size_t
TranslationOptionList::
PruneByThreshold(float const th)
{
if (m_coll.size() <= 1) return 0;
if (th == -std::numeric_limits<float>::infinity()) return 0;
// first, find the best score
float bestScore = -std::numeric_limits<float>::infinity();
BOOST_FOREACH(TranslationOption const* t, m_coll)
{
if (t->GetFutureScore() > bestScore)
bestScore = t->GetFutureScore();
}
size_t old_size = m_coll.size();
// then, remove items that are worse than best score + threshold
// why '+' th ??? Does this ever hold?
for (size_t i=0; i < m_coll.size() ; ++i)
{
if (m_coll[i]->GetFutureScore() < bestScore + th)
{
delete m_coll[i];
if(i + 1 < m_coll.size())
std::swap(m_coll[i],m_coll.back());
m_coll.pop_back();
}
}
m_coll.resize(m_coll.size());
return old_size - m_coll.size();
}
} // namespace
<commit_msg>Bug fix in TranslationOptionList::SelectNBest(N).<commit_after>#include "TranslationOptionList.h"
#include "Util.h"
#include "TranslationOption.h"
#include <boost/foreach.hpp>
using namespace std;
namespace Moses
{
TranslationOptionList::
TranslationOptionList(const TranslationOptionList ©)
{
const_iterator iter;
for (iter = copy.begin(); iter != copy.end(); ++iter) {
const TranslationOption &origTransOpt = **iter;
TranslationOption *newTransOpt = new TranslationOption(origTransOpt);
Add(newTransOpt);
}
}
TranslationOptionList::
~TranslationOptionList()
{
RemoveAllInColl(m_coll);
}
TO_STRING_BODY(TranslationOptionList);
std::ostream& operator<<(std::ostream& out, const TranslationOptionList& coll)
{
TranslationOptionList::const_iterator iter;
for (iter = coll.begin(); iter != coll.end(); ++iter) {
const TranslationOption &transOpt = **iter;
out << transOpt << endl;
}
return out;
}
size_t
TranslationOptionList::
SelectNBest(size_t const N)
{
if (N == 0 || N >= m_coll.size()) return 0;
static TranslationOption::Better cmp;
NTH_ELEMENT4(m_coll.begin(), m_coll.begin() + N, m_coll.end(), cmp);
// delete the rest
for (size_t i = N ; i < m_coll.size() ; ++i) delete m_coll[i];
size_t ret = m_coll.size() - N;
m_coll.resize(N);
return ret;
}
size_t
TranslationOptionList::
PruneByThreshold(float const th)
{
if (m_coll.size() <= 1) return 0;
if (th == -std::numeric_limits<float>::infinity()) return 0;
// first, find the best score
float bestScore = -std::numeric_limits<float>::infinity();
BOOST_FOREACH(TranslationOption const* t, m_coll)
{
if (t->GetFutureScore() > bestScore)
bestScore = t->GetFutureScore();
}
size_t old_size = m_coll.size();
// then, remove items that are worse than best score + threshold
// why '+' th ??? Does this ever hold?
for (size_t i=0; i < m_coll.size() ; ++i)
{
if (m_coll[i]->GetFutureScore() < bestScore + th)
{
delete m_coll[i];
if(i + 1 < m_coll.size())
std::swap(m_coll[i],m_coll.back());
m_coll.pop_back();
}
}
m_coll.resize(m_coll.size());
return old_size - m_coll.size();
}
} // namespace
<|endoftext|> |
<commit_before>#pragma once
#include "event.hpp"
#include "sdlwrap.hpp"
#include "spinner/abstbuff.hpp"
namespace rs {
template <class T>
using UPtr = std::unique_ptr<T>;
namespace msg {
struct DrawInit : MsgBase {};
struct MainInit : MsgBase {};
//! 描画リクエスト
struct DrawReq : MsgBase {};
//! スレッド終了リクエスト
struct QuitReq : MsgBase {};
//! スレッド状態値更新
struct State : MsgBase {
int state;
State(int st): state(st) {}
};
}
struct IDrawProc {
//! 描画コールバック
/*! 描画スレッドから呼ばれる */
/*! \param[in] accum 累積フレーム数
\return backbufferのswapをかける時はtrue */
virtual bool runU(uint64_t accum) = 0;
};
using UPDrawProc = UPtr<IDrawProc>;
struct IMainProc {
//! ゲームアップデートコールバック
/*! メインスレッドから呼ばれる */
/*! \return ゲーム終了時にfalseを返す */
virtual bool runU() = 0;
//! 描画コールバックインタフェースを作成
/*! 描画スレッドから呼ばれる */
virtual IDrawProc* initDraw() = 0;
};
using UPMainProc = UPtr<IMainProc>;
using MPCreate = std::function<IMainProc* ()>;
class DrawThread : public ThreadL<void (Looper&, SPGLContext&&, const SPWindow&, const UPMainProc&)> {
using base = ThreadL<void (Looper&, SPGLContext&&, const SPWindow&, const UPMainProc&)>;
int _state = 0;
uint64_t _accum = 0;
mutable Mutex _mutex;
protected:
void runL(Looper& mainLooper, SPGLContext&& ctx_b, const SPWindow& w, const UPMainProc& mp) override;
void setState(int s);
public:
int getState() const;
};
using UPDrawTh = UPtr<DrawThread>;
class MainThread : public ThreadL<void (Looper&,const SPWindow&)> {
using base = ThreadL<void (Looper&, const SPWindow&)>;
MPCreate _mcr;
protected:
void runL(Looper& guiLooper, const SPWindow& w) override;
public:
MainThread(MPCreate mcr);
};
using UPMainTh = UPtr<MainThread>;
const uint32_t EVID_SIGNAL = SDL_RegisterEvents(1);
int GameLoop(MPCreate mcr, spn::To8Str title, int w, int h, uint32_t flag, int major=2, int minor=0, int depth=16);
}
<commit_msg>gameloop: インタフェースのデストラクタを仮想化<commit_after>#pragma once
#include "event.hpp"
#include "sdlwrap.hpp"
#include "spinner/abstbuff.hpp"
namespace rs {
template <class T>
using UPtr = std::unique_ptr<T>;
namespace msg {
struct DrawInit : MsgBase {};
struct MainInit : MsgBase {};
//! 描画リクエスト
struct DrawReq : MsgBase {};
//! スレッド終了リクエスト
struct QuitReq : MsgBase {};
//! スレッド状態値更新
struct State : MsgBase {
int state;
State(int st): state(st) {}
};
}
struct IDrawProc {
//! 描画コールバック
/*! 描画スレッドから呼ばれる */
/*! \param[in] accum 累積フレーム数
\return backbufferのswapをかける時はtrue */
virtual bool runU(uint64_t accum) = 0;
virtual ~IDrawProc() {}
};
using UPDrawProc = UPtr<IDrawProc>;
struct IMainProc {
//! ゲームアップデートコールバック
/*! メインスレッドから呼ばれる */
/*! \return ゲーム終了時にfalseを返す */
virtual bool runU() = 0;
//! 描画コールバックインタフェースを作成
/*! 描画スレッドから呼ばれる */
virtual IDrawProc* initDraw() = 0;
virtual ~IMainProc() {}
};
using UPMainProc = UPtr<IMainProc>;
using MPCreate = std::function<IMainProc* ()>;
class DrawThread : public ThreadL<void (Looper&, SPGLContext&&, const SPWindow&, const UPMainProc&)> {
using base = ThreadL<void (Looper&, SPGLContext&&, const SPWindow&, const UPMainProc&)>;
int _state = 0;
uint64_t _accum = 0;
mutable Mutex _mutex;
protected:
void runL(Looper& mainLooper, SPGLContext&& ctx_b, const SPWindow& w, const UPMainProc& mp) override;
void setState(int s);
public:
int getState() const;
};
using UPDrawTh = UPtr<DrawThread>;
class MainThread : public ThreadL<void (Looper&,const SPWindow&)> {
using base = ThreadL<void (Looper&, const SPWindow&)>;
MPCreate _mcr;
protected:
void runL(Looper& guiLooper, const SPWindow& w) override;
public:
MainThread(MPCreate mcr);
};
using UPMainTh = UPtr<MainThread>;
const uint32_t EVID_SIGNAL = SDL_RegisterEvents(1);
int GameLoop(MPCreate mcr, spn::To8Str title, int w, int h, uint32_t flag, int major=2, int minor=0, int depth=16);
}
<|endoftext|> |
<commit_before>#include "AlignmentInfo.h"
#include "PhrasePairFeature.h"
#include "TargetPhrase.h"
using namespace std;
namespace Moses {
PhrasePairFeature::PhrasePairFeature
(FactorType sourceFactorId, FactorType targetFactorId) :
StatelessFeatureFunction("pp", ScoreProducer::unlimited),
m_sourceFactorId(sourceFactorId),
m_targetFactorId(targetFactorId) {}
string PhrasePairFeature::GetScoreProducerWeightShortName(unsigned) const
{
return "pp";
}
size_t PhrasePairFeature::GetNumInputScores() const
{
return 0;
}
void PhrasePairFeature::Evaluate(const TargetPhrase& target, ScoreComponentCollection* accumulator) const {
const Phrase& source = target.GetSourcePhrase();
/* const AlignmentInfo& align = cur_hypo.GetAlignmentInfo();
for (AlignmentInfo::const_iterator i = align.begin(); i != align.end(); ++i) {
const Factor* sourceFactor = source.GetWord(i->first).GetFactor(m_sourceFactorId);
const Factor* targetFactor = cur_hypo.GetWord(i->second).GetFactor(m_targetFactorId);
ostringstream namestr;
namestr << sourceFactor->GetString();
namestr << ":";
namestr << targetFactor->GetString();
accumulator->PlusEquals(this,namestr.str(),1);
}*/
ostringstream namestr;
namestr << source.GetWord(0).GetFactor(m_sourceFactorId)->GetString();
for (size_t i = 1; i < source.GetSize(); ++i) {
const Factor* sourceFactor = source.GetWord(i).GetFactor(m_sourceFactorId);
namestr << ",";
namestr << sourceFactor->GetString();
}
namestr << "~";
namestr << target.GetWord(0).GetFactor(m_targetFactorId)->GetString();
for (size_t i = 1; i < target.GetSize(); ++i) {
const Factor* targetFactor = target.GetWord(i).GetFactor(m_targetFactorId);
namestr << ",";
namestr << targetFactor->GetString();
}
accumulator->PlusEquals(this,namestr.str(),1);
}
bool PhrasePairFeature::ComputeValueInTranslationOption() const {
return false;
}
}
<commit_msg>add comment<commit_after>#include "AlignmentInfo.h"
#include "PhrasePairFeature.h"
#include "TargetPhrase.h"
using namespace std;
namespace Moses {
PhrasePairFeature::PhrasePairFeature
(FactorType sourceFactorId, FactorType targetFactorId) :
StatelessFeatureFunction("pp", ScoreProducer::unlimited),
m_sourceFactorId(sourceFactorId),
m_targetFactorId(targetFactorId) {
std::cerr << "Creating phrase pair feature.. " << endl;
}
string PhrasePairFeature::GetScoreProducerWeightShortName(unsigned) const
{
return "pp";
}
size_t PhrasePairFeature::GetNumInputScores() const
{
return 0;
}
void PhrasePairFeature::Evaluate(const TargetPhrase& target, ScoreComponentCollection* accumulator) const {
const Phrase& source = target.GetSourcePhrase();
/* const AlignmentInfo& align = cur_hypo.GetAlignmentInfo();
for (AlignmentInfo::const_iterator i = align.begin(); i != align.end(); ++i) {
const Factor* sourceFactor = source.GetWord(i->first).GetFactor(m_sourceFactorId);
const Factor* targetFactor = cur_hypo.GetWord(i->second).GetFactor(m_targetFactorId);
ostringstream namestr;
namestr << sourceFactor->GetString();
namestr << ":";
namestr << targetFactor->GetString();
accumulator->PlusEquals(this,namestr.str(),1);
}*/
ostringstream namestr;
namestr << source.GetWord(0).GetFactor(m_sourceFactorId)->GetString();
for (size_t i = 1; i < source.GetSize(); ++i) {
const Factor* sourceFactor = source.GetWord(i).GetFactor(m_sourceFactorId);
namestr << ",";
namestr << sourceFactor->GetString();
}
namestr << "~";
namestr << target.GetWord(0).GetFactor(m_targetFactorId)->GetString();
for (size_t i = 1; i < target.GetSize(); ++i) {
const Factor* targetFactor = target.GetWord(i).GetFactor(m_targetFactorId);
namestr << ",";
namestr << targetFactor->GetString();
}
accumulator->PlusEquals(this,namestr.str(),1);
}
bool PhrasePairFeature::ComputeValueInTranslationOption() const {
return false;
}
}
<|endoftext|> |
<commit_before>#include <string>
#include "ccspec/core.h"
#include "ccspec/expectation.h"
#include "ccspec/matchers.h"
using std::string;
using ccspec::core::before;
using ccspec::core::context;
using ccspec::core::describe;
using ccspec::core::it;
using ccspec::expect;
using ccspec::matchers::be_falsey;
using ccspec::matchers::be_truthy;
using ccspec::matchers::eq;
namespace spec {
namespace matchers {
auto eq_spec = describe("Eq", [] {
it("matches if two const temp bools are equal", [] {
expect(eq(false).match(false)).to(be_truthy);
});
it("matches if two bools are equal", [] {
bool b0, b1;
b0 = b1 = true;
expect(eq(b0).match(b1)).to(be_truthy);
});
it("does not match if two bools are not equal", [] {
bool b0 = true, b1 = false;
expect(eq(b0).match(b1)).to(be_falsey);
});
it("matches if two const temp chars are equal", [] {
expect(eq('x').match('x')).to(be_truthy);
});
it("matches if two chars are equal", [] {
char c0, c1;
c0 = c1 = 'z';
expect(eq(c0).match(c1)).to(be_truthy);
});
it("does not match if two chars are not equal", [] {
char c0 = 'x', c1 = 'y';
expect(eq(c0).match(c1)).to(be_falsey);
});
it("matches if two const temp ints are equal", [] {
expect(eq(42).match(42)).to(be_truthy);
});
it("matches if two ints are equal", [] {
int i0, i1;
i0 = i1 = 42;
expect(eq(i0).match(i1)).to(be_truthy);
});
it("does not match if two ints are not equal", [] {
int i0 = 42, i1 = 43;
expect(eq(i0).match(i1)).to(be_falsey);
});
it("matches if two const temp doubles are equal", [] {
expect(eq(3.14).match(3.14)).to(be_truthy);
});
it("matches if two doubles are equal", [] {
double d0, d1;
d0 = d1 = 2.718;
expect(eq(d0).match(d1)).to(be_truthy);
});
it("does not match if two doubles are not equal", [] {
double d0 = 3.14, d1 = 2.718;
expect(eq(d0).match(d1)).to(be_falsey);
});
it("matches if two const temp char* point to the same string", [] {
expect(eq("foo").match("foo")).to(be_truthy);
});
it("matches if two char* point to the same string", [] {
const char* str0 = "test";
const char* str1 = "test";
expect(eq(str0).match(str1)).to(be_truthy);
});
it("does not match if two char* point to different string", [] {
const char* str0 = "test";
const char* str1 = "spec";
expect(eq(str0).match(str1)).to(be_falsey);
});
it("does not match if two char* point to different copies of the same string",
[] {
const char* str0 = "test";
char str1[] = "test";
expect(eq(str0).match(str1)).to(be_falsey);
});
it("matches if two const temp strings are equal", [] {
expect(eq(string("test")).match(string("test"))).to(be_truthy);
});
it("matches if two strings are equal", [] {
string str0 = "test";
string str1 = "test";
expect(eq(str0).match(str1)).to(be_truthy);
});
it("does not match if two strings are not equal", [] {
string str0 = "test";
string str1 = "spec";
expect(eq(str0).match(str1)).to(be_falsey);
});
context("when used for arbitrary types", [] {
class T {
public:
explicit T(int i) : i_(i) {}
bool operator ==(const T& t) const {
return i_ == t.i_;
}
private:
int i_;
} t0(0), t1(2), t3(0);
it("matches if two const temp instances of them are equal", [] {
expect(eq(T(3)).match(T(3))).to(be_truthy);
});
it("matches if two instances of them are equal", [t0, t3] {
expect(eq(t0).match(t3)).to(be_truthy);
});
it("does not match if two instances of them are not equal", [t1, t3] {
expect(eq(t1).match(t3)).to(be_falsey);
});
});
describe("#desc", [] {
it("says 'equal $b' when expecting bool", [] {
expect(eq(true).desc()).to(eq("equal true"));
});
it("says 'equal $c' when expecting char", [] {
expect(eq('x').desc()).to(eq("equal x"));
});
it("says 'equal $i' when expecting int", [] {
expect(eq(42).desc()).to(eq("equal 42"));
});
it("says 'equal $d' when expecting double", [] {
expect(eq(3.14).desc()).to(eq("equal 3.14"));
});
it("says 'equal $s' when expecting char*", [] {
expect(eq("test").desc()).to(eq("equal test"));
});
it("says 'equal $s' when expecting string", [] {
expect(eq(string("test")).desc()).to(eq("equal test"));
});
});
});
} // namespace matchers
} // namespace spec
<commit_msg>Fix plural of words in spec description<commit_after>#include <string>
#include "ccspec/core.h"
#include "ccspec/expectation.h"
#include "ccspec/matchers.h"
using std::string;
using ccspec::core::before;
using ccspec::core::context;
using ccspec::core::describe;
using ccspec::core::it;
using ccspec::expect;
using ccspec::matchers::be_falsey;
using ccspec::matchers::be_truthy;
using ccspec::matchers::eq;
namespace spec {
namespace matchers {
auto eq_spec = describe("Eq", [] {
it("matches if two const temp bools are equal", [] {
expect(eq(false).match(false)).to(be_truthy);
});
it("matches if two bools are equal", [] {
bool b0, b1;
b0 = b1 = true;
expect(eq(b0).match(b1)).to(be_truthy);
});
it("does not match if two bools are not equal", [] {
bool b0 = true, b1 = false;
expect(eq(b0).match(b1)).to(be_falsey);
});
it("matches if two const temp chars are equal", [] {
expect(eq('x').match('x')).to(be_truthy);
});
it("matches if two chars are equal", [] {
char c0, c1;
c0 = c1 = 'z';
expect(eq(c0).match(c1)).to(be_truthy);
});
it("does not match if two chars are not equal", [] {
char c0 = 'x', c1 = 'y';
expect(eq(c0).match(c1)).to(be_falsey);
});
it("matches if two const temp ints are equal", [] {
expect(eq(42).match(42)).to(be_truthy);
});
it("matches if two ints are equal", [] {
int i0, i1;
i0 = i1 = 42;
expect(eq(i0).match(i1)).to(be_truthy);
});
it("does not match if two ints are not equal", [] {
int i0 = 42, i1 = 43;
expect(eq(i0).match(i1)).to(be_falsey);
});
it("matches if two const temp doubles are equal", [] {
expect(eq(3.14).match(3.14)).to(be_truthy);
});
it("matches if two doubles are equal", [] {
double d0, d1;
d0 = d1 = 2.718;
expect(eq(d0).match(d1)).to(be_truthy);
});
it("does not match if two doubles are not equal", [] {
double d0 = 3.14, d1 = 2.718;
expect(eq(d0).match(d1)).to(be_falsey);
});
it("matches if two const temp char* point to the same string", [] {
expect(eq("foo").match("foo")).to(be_truthy);
});
it("matches if two char* point to the same string", [] {
const char* str0 = "test";
const char* str1 = "test";
expect(eq(str0).match(str1)).to(be_truthy);
});
it("does not match if two char* point to different strings", [] {
const char* str0 = "test";
const char* str1 = "spec";
expect(eq(str0).match(str1)).to(be_falsey);
});
it("does not match if two char* point to different copies of the same string",
[] {
const char* str0 = "test";
char str1[] = "test";
expect(eq(str0).match(str1)).to(be_falsey);
});
it("matches if two const temp strings are equal", [] {
expect(eq(string("test")).match(string("test"))).to(be_truthy);
});
it("matches if two strings are equal", [] {
string str0 = "test";
string str1 = "test";
expect(eq(str0).match(str1)).to(be_truthy);
});
it("does not match if two strings are not equal", [] {
string str0 = "test";
string str1 = "spec";
expect(eq(str0).match(str1)).to(be_falsey);
});
context("when used for arbitrary types", [] {
class T {
public:
explicit T(int i) : i_(i) {}
bool operator ==(const T& t) const {
return i_ == t.i_;
}
private:
int i_;
} t0(0), t1(2), t3(0);
it("matches if two const temp instances of them are equal", [] {
expect(eq(T(3)).match(T(3))).to(be_truthy);
});
it("matches if two instances of them are equal", [t0, t3] {
expect(eq(t0).match(t3)).to(be_truthy);
});
it("does not match if two instances of them are not equal", [t1, t3] {
expect(eq(t1).match(t3)).to(be_falsey);
});
});
describe("#desc", [] {
it("says 'equal $b' when expecting bool", [] {
expect(eq(true).desc()).to(eq("equal true"));
});
it("says 'equal $c' when expecting char", [] {
expect(eq('x').desc()).to(eq("equal x"));
});
it("says 'equal $i' when expecting int", [] {
expect(eq(42).desc()).to(eq("equal 42"));
});
it("says 'equal $d' when expecting double", [] {
expect(eq(3.14).desc()).to(eq("equal 3.14"));
});
it("says 'equal $s' when expecting char*", [] {
expect(eq("test").desc()).to(eq("equal test"));
});
it("says 'equal $s' when expecting string", [] {
expect(eq(string("test")).desc()).to(eq("equal test"));
});
});
});
} // namespace matchers
} // namespace spec
<|endoftext|> |
<commit_before>/*
* Copyright (C) [2004, 2005, 2006], Hyperic, Inc.
* This file is part of SIGAR.
*
* SIGAR is free software; you can redistribute it and/or modify
* it under the terms version 2 of the GNU General Public License as
* published by the Free Software Foundation. This program is distributed
* in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA.
*/
#ifdef WIN32
#include "win32bindings.h"
#include "javasigar.h"
#ifdef __cplusplus
extern "C" {
#endif
JNIEXPORT jint SIGAR_JNI(win32_LocaleInfo_getSystemDefaultLCID)
(JNIEnv *env, jclass objcls)
{
return GetSystemDefaultLCID();
}
JNIEXPORT jstring SIGAR_JNI(win32_LocaleInfo_getAttribute)
(JNIEnv *env, jclass objcls, jint lcid, jint attr)
{
char value[8192];
int retval =
GetLocaleInfo(lcid,
attr,
value, sizeof(value));
if (retval) {
return env->NewStringUTF(value);
}
else {
return NULL;
}
}
#ifdef __cplusplus
}
#endif
#endif /* WIN32 */
<commit_msg>unicode-ize<commit_after>/*
* Copyright (C) [2004, 2005, 2006], Hyperic, Inc.
* This file is part of SIGAR.
*
* SIGAR is free software; you can redistribute it and/or modify
* it under the terms version 2 of the GNU General Public License as
* published by the Free Software Foundation. This program is distributed
* in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA.
*/
#ifdef WIN32
#define UNICODE
#define _UNICODE
#include "win32bindings.h"
#include "javasigar.h"
#ifdef __cplusplus
extern "C" {
#endif
JNIEXPORT jint SIGAR_JNI(win32_LocaleInfo_getSystemDefaultLCID)
(JNIEnv *env, jclass objcls)
{
return GetSystemDefaultLCID();
}
JNIEXPORT jstring SIGAR_JNI(win32_LocaleInfo_getAttribute)
(JNIEnv *env, jclass objcls, jint lcid, jint attr)
{
TCHAR value[8192];
int retval =
GetLocaleInfo(lcid,
attr,
value, sizeof(value));
if (retval) {
int len = lstrlen(value);
return env->NewString((const jchar *)value, len);
}
else {
return NULL;
}
}
#ifdef __cplusplus
}
#endif
#endif /* WIN32 */
<|endoftext|> |
<commit_before>//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2016, Image Engine Design Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// * Neither the name of Image Engine Design nor the names of any
// other contributors to this software may be used to endorse or
// promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////
#include "boost/interprocess/smart_ptr/unique_ptr.hpp"
#include "IECore/MessageHandler.h"
#include "IECore/SimpleTypedData.h"
#include "IECore/DespatchTypedData.h"
#include "IECoreArnold/ParameterAlgo.h"
using namespace std;
using namespace IECore;
using namespace IECoreArnold;
//////////////////////////////////////////////////////////////////////////
// Internal utilities
//////////////////////////////////////////////////////////////////////////
namespace
{
typedef boost::interprocess::unique_ptr<AtArray, void (*)( AtArray *)> ArrayPtr;
template<typename T>
inline const T *dataCast( const char *name, const IECore::Data *data )
{
const T *result = runTimeCast<const T>( data );
if( result )
{
return result;
}
msg( Msg::Warning, "setParameter", boost::format( "Unsupported value type \"%s\" for parameter \"%s\" (expected %s)." ) % data->typeName() % name % T::staticTypeName() );
return NULL;
}
void setParameterInternal( AtNode *node, const char *name, int parameterType, bool array, const IECore::Data *value )
{
if( array )
{
AtArray *a = ParameterAlgo::dataToArray( value );
if( !a )
{
msg( Msg::Warning, "setParameter", boost::format( "Unable to create array from data of type \"%s\" for parameter \"%s\"" ) % value->typeName() % name );
return;
}
if( a->type != parameterType )
{
msg( Msg::Warning, "setParameter", boost::format( "Unable to create array of type %s from data of type \"%s\" for parameter \"%s\"" ) % AiParamGetTypeName( parameterType ) % value->typeName() % name );
return;
}
AiNodeSetArray( node, name, a );
}
else
{
switch( parameterType )
{
case AI_TYPE_INT :
if( const IntData *data = dataCast<IntData>( name, value ) )
{
AiNodeSetInt( node, name, data->readable() );
}
break;
case AI_TYPE_BYTE :
if( const IntData *data = dataCast<IntData>( name, value ) )
{
AiNodeSetByte( node, name, data->readable() );
}
break;
case AI_TYPE_FLOAT :
if( const FloatData *data = dataCast<FloatData>( name, value ) )
{
AiNodeSetFlt( node, name, data->readable() );
}
break;
case AI_TYPE_STRING :
if( const StringData *data = dataCast<StringData>( name, value ) )
{
AiNodeSetStr( node, name, data->readable().c_str() );
}
break;
case AI_TYPE_RGB :
if( const Color3fData *data = dataCast<Color3fData>( name, value ) )
{
const Imath::Color3f &c = data->readable();
AiNodeSetRGB( node, name, c[0], c[1], c[2] );
}
break;
case AI_TYPE_RGBA :
if( const Color4fData *data = dataCast<Color4fData>( name, value ) )
{
const Imath::Color4f &c = data->readable();
AiNodeSetRGBA( node, name, c[0], c[1], c[2], c[3] );
}
break;
case AI_TYPE_ENUM :
if( const StringData *data = dataCast<StringData>( name, value ) )
{
AiNodeSetStr( node, name, data->readable().c_str() );
}
break;
case AI_TYPE_BOOLEAN :
if( const BoolData *data = dataCast<BoolData>( name, value ) )
{
AiNodeSetBool( node, name, data->readable() );
}
break;
case AI_TYPE_POINT2 :
if( const V2fData *data = dataCast<V2fData>( name, value ) )
{
const Imath::V2f &v = data->readable();
AiNodeSetPnt2( node, name, v.x, v.y );
}
break;
default :
{
msg( Msg::Warning, "setParameter", boost::format( "Arnold parameter \"%s\" has unsupported type \"%s\"." ) % name % AiParamGetTypeName( parameterType ) );
}
}
}
}
template<typename T, typename F>
IECore::DataPtr arrayToDataInternal( AtArray *array, F f )
{
typedef vector<T> VectorType;
typedef IECore::TypedData<vector<T> > DataType;
typename DataType::Ptr data = new DataType;
VectorType &v = data->writable();
v.reserve( array->nelements );
for( size_t i = 0; i < array->nelements; ++i )
{
v.push_back( f( array, i, __AI_FILE__, __AI_LINE__ ) );
}
return data;
}
/// \todo Flesh this out to support more types and then
/// consider exposing it in the public API.
IECore::DataPtr arrayToData( AtArray *array )
{
if( array->nkeys > 1 )
{
/// \todo Decide how to deal with more
/// than one key - is it more useful to return multiple Data
/// objects or to put it all in one?
return NULL;
}
switch( array->type )
{
case AI_TYPE_BOOLEAN :
return arrayToDataInternal<bool>( array, AiArrayGetBoolFunc );
case AI_TYPE_INT :
return arrayToDataInternal<int>( array, AiArrayGetIntFunc );
case AI_TYPE_FLOAT :
return arrayToDataInternal<float>( array, AiArrayGetFltFunc );
case AI_TYPE_STRING :
return arrayToDataInternal<string>( array, AiArrayGetStrFunc );
default :
return NULL;
}
}
IECore::DataPtr getParameterInternal( AtNode *node, const char *name, int parameterType )
{
switch( parameterType )
{
case AI_TYPE_BOOLEAN :
return new BoolData( AiNodeGetBool( node, name ) );
case AI_TYPE_INT :
return new IntData( AiNodeGetInt( node, name ) );
case AI_TYPE_FLOAT :
return new FloatData( AiNodeGetFlt( node, name ) );
case AI_TYPE_STRING :
return new StringData( AiNodeGetStr( node, name ) );
case AI_TYPE_ARRAY :
return arrayToData( AiNodeGetArray( node, name ) );
}
return NULL;
}
} // namespace
//////////////////////////////////////////////////////////////////////////
// Implementation of public API.
//////////////////////////////////////////////////////////////////////////
namespace IECoreArnold
{
namespace ParameterAlgo
{
void setParameter( AtNode *node, const AtParamEntry *parameter, const IECore::Data *value )
{
bool isArray = false;
int type = AiParamGetType( parameter );
if( type == AI_TYPE_ARRAY )
{
type = AiParamGetDefault( parameter )->ARRAY->type;
isArray = true;
}
setParameterInternal( node, AiParamGetName( parameter ), type, isArray, value );
}
void setParameter( AtNode *node, const char *name, const IECore::Data *value )
{
const AtParamEntry *parameter = AiNodeEntryLookUpParameter( AiNodeGetNodeEntry( node ), name );
if( parameter )
{
setParameter( node, parameter, value );
}
else
{
bool array = false;
int type = parameterType( value->typeId(), array );
if( type != AI_TYPE_NONE )
{
std::string typeString = "constant ";
if( array )
{
typeString += "ARRAY ";
}
typeString += AiParamGetTypeName( type );
AiNodeDeclare( node, name, typeString.c_str() );
setParameterInternal( node, name, type, array, value );
}
else
{
msg(
Msg::Warning,
"setParameter",
boost::format( "Unsupported data type \"%s\" for name \"%s\"" ) % value->typeName() % name
);
}
}
}
void setParameters( AtNode *node, const IECore::CompoundDataMap &values )
{
for( CompoundDataMap::const_iterator it=values.begin(); it!=values.end(); it++ )
{
setParameter( node, it->first.value().c_str(), it->second.get() );
}
}
IECore::DataPtr getParameter( AtNode *node, const AtParamEntry *parameter )
{
return getParameterInternal( node, AiParamGetName( parameter ), AiParamGetType( parameter ) );
}
IECore::DataPtr getParameter( AtNode *node, const AtUserParamEntry *parameter )
{
return getParameterInternal( node, AiUserParamGetName( parameter ), AiUserParamGetType( parameter ) );
}
IECore::DataPtr getParameter( AtNode *node, const char *name )
{
const AtParamEntry *parameter = AiNodeEntryLookUpParameter( AiNodeGetNodeEntry( node ), name );
if( parameter )
{
return getParameter( node, parameter );
}
else
{
const AtUserParamEntry *userParameter = AiNodeLookUpUserParameter( node, name );
if( userParameter )
{
return getParameter( node, userParameter );
}
}
return NULL;
}
void getParameters( AtNode *node, IECore::CompoundDataMap &values )
{
/// \todo Non-user parameters
AtUserParamIterator *it = AiNodeGetUserParamIterator( node );
while( const AtUserParamEntry *param = AiUserParamIteratorGetNext( it ) )
{
DataPtr d = getParameter( node, param );
if( d )
{
values[AiUserParamGetName( param )] = d;
}
else
{
msg(
Msg::Warning,
"getParameters",
boost::format( "Unable to convert user parameter \"%s\"" ) % AiUserParamGetName( param )
);
}
}
AiUserParamIteratorDestroy( it );
}
int parameterType( IECore::TypeId dataType, bool &array )
{
switch( dataType )
{
// non-array types
case IntDataTypeId :
array = false;
return AI_TYPE_INT;
case FloatDataTypeId :
array = false;
return AI_TYPE_FLOAT;
case StringDataTypeId :
array = false;
return AI_TYPE_STRING;
case Color3fDataTypeId :
array = false;
return AI_TYPE_RGB;
case BoolDataTypeId :
array = false;
return AI_TYPE_BOOLEAN;
// array types
case IntVectorDataTypeId :
array = true;
return AI_TYPE_INT;
case FloatVectorDataTypeId :
array = true;
return AI_TYPE_FLOAT;
case StringVectorDataTypeId :
array = true;
return AI_TYPE_STRING;
case Color3fVectorDataTypeId :
array = true;
return AI_TYPE_RGB;
case BoolVectorDataTypeId :
array = true;
return AI_TYPE_BOOLEAN;
case V3fVectorDataTypeId :
array = true;
return AI_TYPE_VECTOR;
default :
return AI_TYPE_NONE;
}
}
AtArray *dataToArray( const IECore::Data *data, int aiType )
{
if( aiType == AI_TYPE_NONE )
{
bool isArray = false;
aiType = parameterType( data->typeId(), isArray );
if( aiType == AI_TYPE_NONE || !isArray )
{
return NULL;
}
}
const void *dataAddress = despatchTypedData<TypedDataAddress, TypeTraits::IsTypedData, DespatchTypedDataIgnoreError>( const_cast<Data *>( data ) );
size_t dataSize = despatchTypedData<TypedDataSize, TypeTraits::IsTypedData, DespatchTypedDataIgnoreError>( const_cast<Data *>( data ) );
return AiArrayConvert( dataSize, 1, aiType, dataAddress );
}
IECOREARNOLD_API AtArray *dataToArray( const std::vector<const IECore::Data *> &samples, int aiType )
{
if( aiType == AI_TYPE_NONE )
{
bool isArray = false;
aiType = parameterType( samples.front()->typeId(), isArray );
if( aiType == AI_TYPE_NONE || !isArray )
{
return NULL;
}
}
size_t arraySize = despatchTypedData<TypedDataSize, TypeTraits::IsTypedData, DespatchTypedDataIgnoreError>( const_cast<Data *>( samples.front() ) );
ArrayPtr array(
AiArrayAllocate( arraySize, samples.size(), aiType ),
AiArrayDestroy
);
for( vector<const IECore::Data *>::const_iterator it = samples.begin(), eIt = samples.end(); it != eIt; ++it )
{
if( (*it)->typeId() != samples.front()->typeId() )
{
throw IECore::Exception( "ParameterAlgo::dataToArray() : Mismatched sample types." );
}
const size_t dataSize = despatchTypedData<TypedDataSize, TypeTraits::IsTypedData, DespatchTypedDataIgnoreError>( const_cast<Data *>( *it ) );
if( dataSize != arraySize )
{
throw IECore::Exception( "ParameterAlgo::dataToArray() : Mismatched sample lengths." );
}
const void *dataAddress = despatchTypedData<TypedDataAddress, TypeTraits::IsTypedData, DespatchTypedDataIgnoreError>( const_cast<Data *>( *it ) );
AiArraySetKey( array.get(), /* key = */ it - samples.begin(), dataAddress );
}
return array.release();
}
} // namespace ParameterAlgo
} // namespace IECoreArnold
<commit_msg>IECoreArnold : Added support for matrix parameters<commit_after>//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2016, Image Engine Design Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// * Neither the name of Image Engine Design nor the names of any
// other contributors to this software may be used to endorse or
// promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////
#include "boost/interprocess/smart_ptr/unique_ptr.hpp"
#include "IECore/MessageHandler.h"
#include "IECore/SimpleTypedData.h"
#include "IECore/DespatchTypedData.h"
#include "IECoreArnold/ParameterAlgo.h"
using namespace std;
using namespace IECore;
using namespace IECoreArnold;
//////////////////////////////////////////////////////////////////////////
// Internal utilities
//////////////////////////////////////////////////////////////////////////
namespace
{
typedef boost::interprocess::unique_ptr<AtArray, void (*)( AtArray *)> ArrayPtr;
template<typename T>
inline const T *dataCast( const char *name, const IECore::Data *data )
{
const T *result = runTimeCast<const T>( data );
if( result )
{
return result;
}
msg( Msg::Warning, "setParameter", boost::format( "Unsupported value type \"%s\" for parameter \"%s\" (expected %s)." ) % data->typeName() % name % T::staticTypeName() );
return NULL;
}
void setParameterInternal( AtNode *node, const char *name, int parameterType, bool array, const IECore::Data *value )
{
if( array )
{
AtArray *a = ParameterAlgo::dataToArray( value );
if( !a )
{
msg( Msg::Warning, "setParameter", boost::format( "Unable to create array from data of type \"%s\" for parameter \"%s\"" ) % value->typeName() % name );
return;
}
if( a->type != parameterType )
{
msg( Msg::Warning, "setParameter", boost::format( "Unable to create array of type %s from data of type \"%s\" for parameter \"%s\"" ) % AiParamGetTypeName( parameterType ) % value->typeName() % name );
return;
}
AiNodeSetArray( node, name, a );
}
else
{
switch( parameterType )
{
case AI_TYPE_INT :
if( const IntData *data = dataCast<IntData>( name, value ) )
{
AiNodeSetInt( node, name, data->readable() );
}
break;
case AI_TYPE_BYTE :
if( const IntData *data = dataCast<IntData>( name, value ) )
{
AiNodeSetByte( node, name, data->readable() );
}
break;
case AI_TYPE_FLOAT :
if( const FloatData *data = dataCast<FloatData>( name, value ) )
{
AiNodeSetFlt( node, name, data->readable() );
}
break;
case AI_TYPE_STRING :
if( const StringData *data = dataCast<StringData>( name, value ) )
{
AiNodeSetStr( node, name, data->readable().c_str() );
}
break;
case AI_TYPE_RGB :
if( const Color3fData *data = dataCast<Color3fData>( name, value ) )
{
const Imath::Color3f &c = data->readable();
AiNodeSetRGB( node, name, c[0], c[1], c[2] );
}
break;
case AI_TYPE_RGBA :
if( const Color4fData *data = dataCast<Color4fData>( name, value ) )
{
const Imath::Color4f &c = data->readable();
AiNodeSetRGBA( node, name, c[0], c[1], c[2], c[3] );
}
break;
case AI_TYPE_ENUM :
if( const StringData *data = dataCast<StringData>( name, value ) )
{
AiNodeSetStr( node, name, data->readable().c_str() );
}
break;
case AI_TYPE_BOOLEAN :
if( const BoolData *data = dataCast<BoolData>( name, value ) )
{
AiNodeSetBool( node, name, data->readable() );
}
break;
case AI_TYPE_POINT2 :
if( const V2fData *data = dataCast<V2fData>( name, value ) )
{
const Imath::V2f &v = data->readable();
AiNodeSetPnt2( node, name, v.x, v.y );
}
break;
case AI_TYPE_MATRIX :
if( const M44fData *data = dataCast<M44fData>( name, value ) )
{
const Imath::M44f &v = data->readable();
// Can't see any reason why AiNodeSetMatrix couldn't have been declared const,
// this const_cast seems safe
AiNodeSetMatrix( node, name, const_cast<float (*)[4]>( v.x ) );
}
break;
default :
{
msg( Msg::Warning, "setParameter", boost::format( "Arnold parameter \"%s\" has unsupported type \"%s\"." ) % name % AiParamGetTypeName( parameterType ) );
}
}
}
}
template<typename T, typename F>
IECore::DataPtr arrayToDataInternal( AtArray *array, F f )
{
typedef vector<T> VectorType;
typedef IECore::TypedData<vector<T> > DataType;
typename DataType::Ptr data = new DataType;
VectorType &v = data->writable();
v.reserve( array->nelements );
for( size_t i = 0; i < array->nelements; ++i )
{
v.push_back( f( array, i, __AI_FILE__, __AI_LINE__ ) );
}
return data;
}
/// \todo Flesh this out to support more types and then
/// consider exposing it in the public API.
IECore::DataPtr arrayToData( AtArray *array )
{
if( array->nkeys > 1 )
{
/// \todo Decide how to deal with more
/// than one key - is it more useful to return multiple Data
/// objects or to put it all in one?
return NULL;
}
switch( array->type )
{
case AI_TYPE_BOOLEAN :
return arrayToDataInternal<bool>( array, AiArrayGetBoolFunc );
case AI_TYPE_INT :
return arrayToDataInternal<int>( array, AiArrayGetIntFunc );
case AI_TYPE_FLOAT :
return arrayToDataInternal<float>( array, AiArrayGetFltFunc );
case AI_TYPE_STRING :
return arrayToDataInternal<string>( array, AiArrayGetStrFunc );
default :
return NULL;
}
}
IECore::DataPtr getParameterInternal( AtNode *node, const char *name, int parameterType )
{
switch( parameterType )
{
case AI_TYPE_BOOLEAN :
return new BoolData( AiNodeGetBool( node, name ) );
case AI_TYPE_INT :
return new IntData( AiNodeGetInt( node, name ) );
case AI_TYPE_FLOAT :
return new FloatData( AiNodeGetFlt( node, name ) );
case AI_TYPE_STRING :
return new StringData( AiNodeGetStr( node, name ) );
case AI_TYPE_ARRAY :
return arrayToData( AiNodeGetArray( node, name ) );
}
return NULL;
}
} // namespace
//////////////////////////////////////////////////////////////////////////
// Implementation of public API.
//////////////////////////////////////////////////////////////////////////
namespace IECoreArnold
{
namespace ParameterAlgo
{
void setParameter( AtNode *node, const AtParamEntry *parameter, const IECore::Data *value )
{
bool isArray = false;
int type = AiParamGetType( parameter );
if( type == AI_TYPE_ARRAY )
{
type = AiParamGetDefault( parameter )->ARRAY->type;
isArray = true;
}
setParameterInternal( node, AiParamGetName( parameter ), type, isArray, value );
}
void setParameter( AtNode *node, const char *name, const IECore::Data *value )
{
const AtParamEntry *parameter = AiNodeEntryLookUpParameter( AiNodeGetNodeEntry( node ), name );
if( parameter )
{
setParameter( node, parameter, value );
}
else
{
bool array = false;
int type = parameterType( value->typeId(), array );
if( type != AI_TYPE_NONE )
{
std::string typeString = "constant ";
if( array )
{
typeString += "ARRAY ";
}
typeString += AiParamGetTypeName( type );
AiNodeDeclare( node, name, typeString.c_str() );
setParameterInternal( node, name, type, array, value );
}
else
{
msg(
Msg::Warning,
"setParameter",
boost::format( "Unsupported data type \"%s\" for name \"%s\"" ) % value->typeName() % name
);
}
}
}
void setParameters( AtNode *node, const IECore::CompoundDataMap &values )
{
for( CompoundDataMap::const_iterator it=values.begin(); it!=values.end(); it++ )
{
setParameter( node, it->first.value().c_str(), it->second.get() );
}
}
IECore::DataPtr getParameter( AtNode *node, const AtParamEntry *parameter )
{
return getParameterInternal( node, AiParamGetName( parameter ), AiParamGetType( parameter ) );
}
IECore::DataPtr getParameter( AtNode *node, const AtUserParamEntry *parameter )
{
return getParameterInternal( node, AiUserParamGetName( parameter ), AiUserParamGetType( parameter ) );
}
IECore::DataPtr getParameter( AtNode *node, const char *name )
{
const AtParamEntry *parameter = AiNodeEntryLookUpParameter( AiNodeGetNodeEntry( node ), name );
if( parameter )
{
return getParameter( node, parameter );
}
else
{
const AtUserParamEntry *userParameter = AiNodeLookUpUserParameter( node, name );
if( userParameter )
{
return getParameter( node, userParameter );
}
}
return NULL;
}
void getParameters( AtNode *node, IECore::CompoundDataMap &values )
{
/// \todo Non-user parameters
AtUserParamIterator *it = AiNodeGetUserParamIterator( node );
while( const AtUserParamEntry *param = AiUserParamIteratorGetNext( it ) )
{
DataPtr d = getParameter( node, param );
if( d )
{
values[AiUserParamGetName( param )] = d;
}
else
{
msg(
Msg::Warning,
"getParameters",
boost::format( "Unable to convert user parameter \"%s\"" ) % AiUserParamGetName( param )
);
}
}
AiUserParamIteratorDestroy( it );
}
int parameterType( IECore::TypeId dataType, bool &array )
{
switch( dataType )
{
// non-array types
case IntDataTypeId :
array = false;
return AI_TYPE_INT;
case FloatDataTypeId :
array = false;
return AI_TYPE_FLOAT;
case StringDataTypeId :
array = false;
return AI_TYPE_STRING;
case Color3fDataTypeId :
array = false;
return AI_TYPE_RGB;
case BoolDataTypeId :
array = false;
return AI_TYPE_BOOLEAN;
case M44fDataTypeId :
array = false;
return AI_TYPE_MATRIX;
// array types
case IntVectorDataTypeId :
array = true;
return AI_TYPE_INT;
case FloatVectorDataTypeId :
array = true;
return AI_TYPE_FLOAT;
case StringVectorDataTypeId :
array = true;
return AI_TYPE_STRING;
case Color3fVectorDataTypeId :
array = true;
return AI_TYPE_RGB;
case BoolVectorDataTypeId :
array = true;
return AI_TYPE_BOOLEAN;
case V3fVectorDataTypeId :
array = true;
return AI_TYPE_VECTOR;
case M44fVectorDataTypeId :
array = true;
return AI_TYPE_MATRIX;
default :
return AI_TYPE_NONE;
}
}
AtArray *dataToArray( const IECore::Data *data, int aiType )
{
if( aiType == AI_TYPE_NONE )
{
bool isArray = false;
aiType = parameterType( data->typeId(), isArray );
if( aiType == AI_TYPE_NONE || !isArray )
{
return NULL;
}
}
const void *dataAddress = despatchTypedData<TypedDataAddress, TypeTraits::IsTypedData, DespatchTypedDataIgnoreError>( const_cast<Data *>( data ) );
size_t dataSize = despatchTypedData<TypedDataSize, TypeTraits::IsTypedData, DespatchTypedDataIgnoreError>( const_cast<Data *>( data ) );
return AiArrayConvert( dataSize, 1, aiType, dataAddress );
}
IECOREARNOLD_API AtArray *dataToArray( const std::vector<const IECore::Data *> &samples, int aiType )
{
if( aiType == AI_TYPE_NONE )
{
bool isArray = false;
aiType = parameterType( samples.front()->typeId(), isArray );
if( aiType == AI_TYPE_NONE || !isArray )
{
return NULL;
}
}
size_t arraySize = despatchTypedData<TypedDataSize, TypeTraits::IsTypedData, DespatchTypedDataIgnoreError>( const_cast<Data *>( samples.front() ) );
ArrayPtr array(
AiArrayAllocate( arraySize, samples.size(), aiType ),
AiArrayDestroy
);
for( vector<const IECore::Data *>::const_iterator it = samples.begin(), eIt = samples.end(); it != eIt; ++it )
{
if( (*it)->typeId() != samples.front()->typeId() )
{
throw IECore::Exception( "ParameterAlgo::dataToArray() : Mismatched sample types." );
}
const size_t dataSize = despatchTypedData<TypedDataSize, TypeTraits::IsTypedData, DespatchTypedDataIgnoreError>( const_cast<Data *>( *it ) );
if( dataSize != arraySize )
{
throw IECore::Exception( "ParameterAlgo::dataToArray() : Mismatched sample lengths." );
}
const void *dataAddress = despatchTypedData<TypedDataAddress, TypeTraits::IsTypedData, DespatchTypedDataIgnoreError>( const_cast<Data *>( *it ) );
AiArraySetKey( array.get(), /* key = */ it - samples.begin(), dataAddress );
}
return array.release();
}
} // namespace ParameterAlgo
} // namespace IECoreArnold
<|endoftext|> |
<commit_before>#include <cstring>
#include <iostream>
#include <memory>
#include <string>
#include <utility>
#include <Python.h>
#include "string.hh"
#include "py.hh"
#include "text.hh"
#include "base.hh"
using namespace py;
//------------------------------------------------------------------------------
namespace {
class String
: public ExtensionType
{
std::unique_ptr<fixfmt::String> fmt_;
static int tp_init(String* self, PyObject* args, PyObject* kw_args)
{
static char const* arg_names[]
= {"size", "ellipsis", "pad", "position", "pad_left", nullptr};
int size;
char const* ellipsis = "...";
char pad = ' ';
double position = 1.0;
bool pad_left = false;
if (PyArg_ParseTupleAndKeywords(
args, kw_args, "i|sCdb", (char**) arg_names,
&size, &ellipsis, &pad, &position, &pad_left)) {
// FIXME: Validate args.
self->fmt_ = std::unique_ptr<fixfmt::String>(
new fixfmt::String(size, ellipsis, pad, position, pad_left));
return 0;
}
else
return -1;
}
static PyObject* tp_call(String* self, PyObject* args, PyObject* kw_args)
{
static char const* arg_names[] = {"str", nullptr};
char* val;
if (PyArg_ParseTupleAndKeywords(
args, kw_args, "s", (char**) arg_names, &val))
return Unicode::from((*self->fmt_)(val)).release();
else
return nullptr;
}
static PyMethodDef const tp_methods[];
public:
static PyTypeObject type;
};
PyMethodDef const String::tp_methods[] = {
METHODDEF_END
};
PyTypeObject String::type = {
PyVarObject_HEAD_INIT(nullptr, 0)
"fixfmt.String", // tp_name
sizeof(String), // tp_basicsize
0, // tp_itemsize
nullptr, // tp_dealloc
nullptr, // tp_print
nullptr, // tp_getattr
nullptr, // tp_setattr
nullptr, // tp_reserved
nullptr, // tp_repr
nullptr, // tp_as_number
nullptr, // tp_as_sequence
nullptr, // tp_as_mapping
nullptr, // tp_hash
(ternaryfunc) tp_call, // tp_call
nullptr, // tp_str
nullptr, // tp_getattro
nullptr, // tp_setattro
nullptr, // tp_as_buffer
Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_BASETYPE, // tp_flags
nullptr, // tp_doc
nullptr, // tp_traverse
nullptr, // tp_clear
nullptr, // tp_richcompare
0, // tp_weaklistoffset
nullptr, // tp_iter
nullptr, // tp_iternext
(PyMethodDef*) tp_methods, // tp_methods
nullptr, // tp_members
nullptr, // tp_getset
nullptr, // tp_base
nullptr, // tp_dict
nullptr, // tp_descr_get
nullptr, // tp_descr_set
0, // tp_dictoffset
(initproc) tp_init, // tp_init
nullptr, // tp_alloc
PyType_GenericNew, // tp_new
};
} // anonymous namespace
PyTypeObject* get_String()
{
int result = PyType_Ready(&String::type);
assert(result == 0); unused(result);
return &String::type;
}
<commit_msg>Order imports.<commit_after>#include <cstring>
#include <iostream>
#include <memory>
#include <string>
#include <utility>
#include <Python.h>
#include "base.hh"
#include "py.hh"
#include "string.hh"
#include "text.hh"
using namespace py;
//------------------------------------------------------------------------------
namespace {
class String
: public ExtensionType
{
std::unique_ptr<fixfmt::String> fmt_;
static int tp_init(String* self, PyObject* args, PyObject* kw_args)
{
static char const* arg_names[]
= {"size", "ellipsis", "pad", "position", "pad_left", nullptr};
int size;
char const* ellipsis = "...";
char pad = ' ';
double position = 1.0;
bool pad_left = false;
if (PyArg_ParseTupleAndKeywords(
args, kw_args, "i|sCdb", (char**) arg_names,
&size, &ellipsis, &pad, &position, &pad_left)) {
// FIXME: Validate args.
self->fmt_ = std::unique_ptr<fixfmt::String>(
new fixfmt::String(size, ellipsis, pad, position, pad_left));
return 0;
}
else
return -1;
}
static PyObject* tp_call(String* self, PyObject* args, PyObject* kw_args)
{
static char const* arg_names[] = {"str", nullptr};
char* val;
if (PyArg_ParseTupleAndKeywords(
args, kw_args, "s", (char**) arg_names, &val))
return Unicode::from((*self->fmt_)(val)).release();
else
return nullptr;
}
static PyMethodDef const tp_methods[];
public:
static PyTypeObject type;
};
PyMethodDef const String::tp_methods[] = {
METHODDEF_END
};
PyTypeObject String::type = {
PyVarObject_HEAD_INIT(nullptr, 0)
"fixfmt.String", // tp_name
sizeof(String), // tp_basicsize
0, // tp_itemsize
nullptr, // tp_dealloc
nullptr, // tp_print
nullptr, // tp_getattr
nullptr, // tp_setattr
nullptr, // tp_reserved
nullptr, // tp_repr
nullptr, // tp_as_number
nullptr, // tp_as_sequence
nullptr, // tp_as_mapping
nullptr, // tp_hash
(ternaryfunc) tp_call, // tp_call
nullptr, // tp_str
nullptr, // tp_getattro
nullptr, // tp_setattro
nullptr, // tp_as_buffer
Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_BASETYPE, // tp_flags
nullptr, // tp_doc
nullptr, // tp_traverse
nullptr, // tp_clear
nullptr, // tp_richcompare
0, // tp_weaklistoffset
nullptr, // tp_iter
nullptr, // tp_iternext
(PyMethodDef*) tp_methods, // tp_methods
nullptr, // tp_members
nullptr, // tp_getset
nullptr, // tp_base
nullptr, // tp_dict
nullptr, // tp_descr_get
nullptr, // tp_descr_set
0, // tp_dictoffset
(initproc) tp_init, // tp_init
nullptr, // tp_alloc
PyType_GenericNew, // tp_new
};
} // anonymous namespace
PyTypeObject* get_String()
{
int result = PyType_Ready(&String::type);
assert(result == 0); unused(result);
return &String::type;
}
<|endoftext|> |
<commit_before>#include "ResourceView.hpp"
#include <Engine/Geometry/Model.hpp>
#include <Engine/Texture/TextureAsset.hpp>
#include <Engine/Audio/SoundBuffer.hpp>
#include <Engine/Script/ScriptFile.hpp>
#include <Engine/Util/FileSystem.hpp>
#include <Engine/Hymn.hpp>
#include <DefaultAlbedo.png.hpp>
#include <Engine/MainWindow.hpp>
#include <imgui.h>
#include <limits>
#include "../ImGui/Splitter.hpp"
#include <Engine/Manager/Managers.hpp>
#include <Engine/Manager/ResourceManager.hpp>
#include <cstdio>
#include <Utility/Log.hpp>
using namespace GUI;
using namespace std;
ResourceView::ResourceView() {
folderNameWindow.SetClosedCallback(std::bind(&ResourceView::FileNameWindowClosed, this, placeholders::_1));
}
void ResourceView::Show() {
ImVec2 size(MainWindow::GetInstance()->GetSize().x, MainWindow::GetInstance()->GetSize().y);
// Splitter.
ImGui::VerticalSplitter(ImVec2(sceneWidth, size.y - resourceHeight), size.x - sceneWidth - editorWidth, splitterSize, resourceHeight, resourceResize, 20, size.y - 20);
if (resourceResize)
resourceHeight = size.y - resourceHeight;
ImGui::SetNextWindowPos(ImVec2(sceneWidth, size.y - resourceHeight));
ImGui::SetNextWindowSize(ImVec2(size.x - sceneWidth - editorWidth, resourceHeight));
ImGui::Begin("Resources", nullptr, ImGuiWindowFlags_NoResize | ImGuiWindowFlags_ShowBorders);
// Show resources.
scriptPressed = false;
texturePressed = false;
modelPressed = false;
soundPressed = false;
ShowResourceFolder(Resources().resourceFolder, Resources().resourceFolder.name);
// Change scene.
if (changeScene) {
if (Hymn().GetPath() != "") {
savePromptWindow.SetVisible(true);
savePromptWindow.Show();
switch (savePromptWindow.GetDecision()) {
case 0:
sceneEditor.Save();
sceneEditor.SetVisible(true);
sceneEditor.SetScene(resourcePath, scene);
Resources().activeScene = resourcePath + "/" + *scene;
sceneEditor.entityEditor.SetVisible(false);
Hymn().world.Clear();
Hymn().world.Load(Hymn().GetPath() + "/" + Resources().activeScene + ".json");
changeScene = false;
savePromptWindow.SetVisible(false);
savePromptWindow.ResetDecision();
break;
case 1:
sceneEditor.SetVisible(true);
sceneEditor.SetScene(resourcePath, scene);
Resources().activeScene = resourcePath + "/" + *scene;
sceneEditor.entityEditor.SetVisible(false);
Hymn().world.Clear();
Hymn().world.Load(Hymn().GetPath() + "/" + Resources().activeScene + ".json");
changeScene = false;
savePromptWindow.SetVisible(false);
savePromptWindow.ResetDecision();
break;
case 2:
changeScene = false;
savePromptWindow.ResetDecision();
savePromptWindow.SetVisible(false);
break;
default:
break;
}
}
}
// Create folder.
if (folderNameWindow.IsVisible())
folderNameWindow.Show();
if (sceneEditor.entityPressed || scriptPressed || texturePressed || modelPressed || soundPressed) {
sceneEditor.entityEditor.SetVisible(sceneEditor.entityPressed);
scriptEditor.SetVisible(scriptPressed);
textureEditor.SetVisible(texturePressed);
modelEditor.SetVisible(modelPressed);
soundEditor.SetVisible(soundPressed);
}
if (sceneEditor.IsVisible()) {
ImGui::HorizontalSplitter(ImVec2(sceneWidth, 20), size.y - 20, splitterSize, sceneWidth, sceneResize, 20, size.x - editorWidth - 20);
ImGui::SetNextWindowPos(ImVec2(0, 20));
ImGui::SetNextWindowSize(ImVec2(sceneWidth, size.y - 20));
sceneEditor.Show();
}
if (sceneEditor.entityEditor.IsVisible() || scriptEditor.IsVisible() || textureEditor.IsVisible() || modelEditor.IsVisible() || soundEditor.IsVisible()) {
editorWidth = size.x - editorWidth;
ImGui::HorizontalSplitter(ImVec2(editorWidth, 20), size.y - 20, splitterSize, editorWidth, editorResize, sceneWidth + 20, size.x - 20);
editorWidth = size.x - editorWidth;
ImGui::SetNextWindowPos(ImVec2(size.x - editorWidth, 20));
ImGui::SetNextWindowSize(ImVec2(editorWidth, size.y - 20));
}
if (sceneEditor.entityEditor.IsVisible())
sceneEditor.entityEditor.Show();
if (scriptEditor.IsVisible())
scriptEditor.Show();
if (textureEditor.IsVisible())
textureEditor.Show();
if (modelEditor.IsVisible())
modelEditor.Show();
if (soundEditor.IsVisible())
soundEditor.Show();
ImGui::End();
}
bool ResourceView::IsVisible() const {
return visible;
}
void ResourceView::SetVisible(bool visible) {
this->visible = visible;
}
void ResourceView::HideEditors() {
sceneEditor.SetVisible(false);
sceneEditor.entityEditor.SetVisible(false);
scriptEditor.SetVisible(false);
modelEditor.SetVisible(false);
textureEditor.SetVisible(false);
soundEditor.SetVisible(false);
}
void ResourceView::SaveScene() const {
sceneEditor.Save();
}
#undef max
void ResourceView::ResetScene() {
sceneEditor.SetScene("", nullptr);
sceneEditor.SetVisible(false);
}
SceneEditor& ResourceView::GetScene() {
return sceneEditor;
}
void ResourceView::ShowResourceFolder(ResourceList::ResourceFolder& folder, const std::string& path) {
bool opened = ImGui::TreeNode(folder.name.c_str());
if (ImGui::BeginPopupContextItem(folder.name.c_str())) {
// Add subfolder.
if (ImGui::Selectable("Add folder")) {
resourcePath = path;
parentFolder = &folder;
folderNameWindow.SetVisible(true);
return;
}
// Add scene.
if (ImGui::Selectable("Add scene")) {
ResourceList::Resource resource;
resource.type = ResourceList::Resource::SCENE;
resource.scene = "Scene #" + std::to_string(Resources().sceneNumber++);
folder.resources.push_back(resource);
return;
}
// Add model.
if (ImGui::Selectable("Add model")) {
ResourceList::Resource resource;
resource.type = ResourceList::Resource::MODEL;
resource.model = new Geometry::Model();
resource.model->path = path + "/";
resource.model->name = "Model #" + std::to_string(Resources().modelNumber++);
folder.resources.push_back(resource);
return;
}
// Add texture.
if (ImGui::Selectable("Add texture")) {
ResourceList::Resource resource;
resource.type = ResourceList::Resource::TEXTURE;
string name = path + "/Texture #" + std::to_string(Resources().textureNumber++);
resource.texture = Managers().resourceManager->CreateTextureAsset(name, Managers().resourceManager->CreateTexture2D(DEFAULTALBEDO_PNG, DEFAULTALBEDO_PNG_LENGTH));
folder.resources.push_back(resource);
return;
}
// Add script.
if (ImGui::Selectable("Add script")) {
ResourceList::Resource resource;
resource.type = ResourceList::Resource::SCRIPT;
resource.script = new ScriptFile();
resource.script->path = path + "/";
resource.script->name = "Script #" + std::to_string(Hymn().scriptNumber++);
Hymn().scripts.push_back(resource.script);
folder.resources.push_back(resource);
return;
}
// Add sound.
if (ImGui::Selectable("Add sound")) {
ResourceList::Resource resource;
resource.type = ResourceList::Resource::SOUND;
resource.sound = new Audio::SoundBuffer();
resource.sound->path = path + "/";
resource.sound->name = "Sound #" + std::to_string(Resources().soundNumber++);
folder.resources.push_back(resource);
return;
}
/// @todo Remove folder.
ImGui::EndPopup();
}
if (opened) {
// Show subfolders.
for (ResourceList::ResourceFolder& subfolder : folder.subfolders) {
ShowResourceFolder(subfolder, path + "/" + subfolder.name);
}
// Show resources.
for (auto it = folder.resources.begin(); it != folder.resources.end(); ++it) {
if (ShowResource(*it, path)) {
folder.resources.erase(it);
return;
}
}
ImGui::TreePop();
}
}
bool ResourceView::ShowResource(ResourceList::Resource& resource, const std::string& path) {
// Scene.
if (resource.type == ResourceList::Resource::SCENE) {
if (ImGui::Selectable(resource.scene.c_str())) {
// Sets to don't save when opening first scene.
if (scene == nullptr) {
changeScene = true;
resourcePath = path;
scene = &resource.scene;
savePromptWindow.SetVisible(false);
savePromptWindow.SetDecision(1);
} else {
// Does so that the prompt window won't show if you select active scene.
if (resource.scene != Resources().activeScene) {
changeScene = true;
resourcePath = path;
scene = &resource.scene;
savePromptWindow.SetTitle("Save before you switch scene?");
}
}
}
// Delete scene.
if (ImGui::BeginPopupContextItem(resource.scene.c_str())) {
if (ImGui::Selectable("Delete")) {
if (Resources().activeScene == resource.scene) {
Resources().activeScene = "";
sceneEditor.SetScene("", nullptr);
}
ImGui::EndPopup();
return true;
}
ImGui::EndPopup();
}
}
// Model.
if (resource.type == ResourceList::Resource::MODEL) {
if (ImGui::Selectable(resource.model->name.c_str())) {
modelPressed = true;
modelEditor.SetModel(resource.model);
}
if (ImGui::BeginPopupContextItem(resource.model->name.c_str())) {
if (ImGui::Selectable("Delete")) {
if (modelEditor.GetModel() == resource.model)
modelEditor.SetVisible(false);
Managers().resourceManager->FreeModel(resource.model);
ImGui::EndPopup();
return true;
}
ImGui::EndPopup();
}
}
// Textures.
if (resource.type == ResourceList::Resource::TEXTURE) {
if (ImGui::Selectable(resource.texture->name.c_str())) {
texturePressed = true;
textureEditor.SetTexture(resource.texture);
}
if (ImGui::BeginPopupContextItem(resource.texture->name.c_str())) {
if (ImGui::Selectable("Delete")) {
if (Managers().resourceManager->GetTextureAssetInstanceCount(resource.texture) > 1) {
Log() << "This texture is in use. Remove all references to the texture first.\n";
} else {
if (textureEditor.GetTexture() == resource.texture)
textureEditor.SetVisible(false);
// Remove files.
remove((Hymn().GetPath() + "/" + path + "/" + resource.texture->name + ".png").c_str());
remove((Hymn().GetPath() + "/" + path + "/" + resource.texture->name + ".json").c_str());
Managers().resourceManager->FreeTextureAsset(resource.texture);
ImGui::EndPopup();
return true;
}
}
ImGui::EndPopup();
}
}
/*
// Scripts.
bool scriptPressed = false;
if (ImGui::TreeNode("Scripts")) {
for (auto it = Hymn().scripts.begin(); it != Hymn().scripts.end(); ++it) {
ScriptFile* script = *it;
std::string name = script->name;
if (ImGui::Selectable(name.c_str())) {
scriptPressed = true;
scriptEditor.SetScript(script);
}
if (ImGui::BeginPopupContextItem(name.c_str())) {
if (ImGui::Selectable("Delete")) {
if (scriptEditor.GetScript() == script)
scriptEditor.SetVisible(false);
delete script;
Hymn().scripts.erase(it);
ImGui::EndPopup();
break;
}
ImGui::EndPopup();
}
}
ImGui::TreePop();
}
// Sounds.
bool soundPressed = false;
if (ImGui::TreeNode("Sounds")) {
for (auto it = Resources().sounds.begin(); it != Resources().sounds.end(); ++it) {
Audio::SoundBuffer* sound = *it;
if (ImGui::Selectable(sound->name.c_str())) {
soundPressed = true;
soundEditor.SetSound(sound);
}
if (ImGui::BeginPopupContextItem(sound->name.c_str())) {
if (ImGui::Selectable("Delete")) {
if (soundEditor.GetSound() == sound)
soundEditor.SetVisible(false);
delete sound;
Resources().sounds.erase(it);
ImGui::EndPopup();
break;
}
ImGui::EndPopup();
}
}
ImGui::TreePop();
}*/
return false;
}
void ResourceView::FileNameWindowClosed(const std::string& name) {
if (!name.empty()) {
ResourceList::ResourceFolder folder;
folder.name = name;
parentFolder->subfolders.push_back(folder);
FileSystem::CreateDirectory((Hymn().GetPath() + "/" + resourcePath + "/" + name).c_str());
}
}
<commit_msg>Show scripts<commit_after>#include "ResourceView.hpp"
#include <Engine/Geometry/Model.hpp>
#include <Engine/Texture/TextureAsset.hpp>
#include <Engine/Audio/SoundBuffer.hpp>
#include <Engine/Script/ScriptFile.hpp>
#include <Engine/Util/FileSystem.hpp>
#include <Engine/Hymn.hpp>
#include <DefaultAlbedo.png.hpp>
#include <Engine/MainWindow.hpp>
#include <imgui.h>
#include <limits>
#include "../ImGui/Splitter.hpp"
#include <Engine/Manager/Managers.hpp>
#include <Engine/Manager/ResourceManager.hpp>
#include <cstdio>
#include <Utility/Log.hpp>
using namespace GUI;
using namespace std;
ResourceView::ResourceView() {
folderNameWindow.SetClosedCallback(std::bind(&ResourceView::FileNameWindowClosed, this, placeholders::_1));
}
void ResourceView::Show() {
ImVec2 size(MainWindow::GetInstance()->GetSize().x, MainWindow::GetInstance()->GetSize().y);
// Splitter.
ImGui::VerticalSplitter(ImVec2(sceneWidth, size.y - resourceHeight), size.x - sceneWidth - editorWidth, splitterSize, resourceHeight, resourceResize, 20, size.y - 20);
if (resourceResize)
resourceHeight = size.y - resourceHeight;
ImGui::SetNextWindowPos(ImVec2(sceneWidth, size.y - resourceHeight));
ImGui::SetNextWindowSize(ImVec2(size.x - sceneWidth - editorWidth, resourceHeight));
ImGui::Begin("Resources", nullptr, ImGuiWindowFlags_NoResize | ImGuiWindowFlags_ShowBorders);
// Show resources.
scriptPressed = false;
texturePressed = false;
modelPressed = false;
soundPressed = false;
ShowResourceFolder(Resources().resourceFolder, Resources().resourceFolder.name);
// Change scene.
if (changeScene) {
if (Hymn().GetPath() != "") {
savePromptWindow.SetVisible(true);
savePromptWindow.Show();
switch (savePromptWindow.GetDecision()) {
case 0:
sceneEditor.Save();
sceneEditor.SetVisible(true);
sceneEditor.SetScene(resourcePath, scene);
Resources().activeScene = resourcePath + "/" + *scene;
sceneEditor.entityEditor.SetVisible(false);
Hymn().world.Clear();
Hymn().world.Load(Hymn().GetPath() + "/" + Resources().activeScene + ".json");
changeScene = false;
savePromptWindow.SetVisible(false);
savePromptWindow.ResetDecision();
break;
case 1:
sceneEditor.SetVisible(true);
sceneEditor.SetScene(resourcePath, scene);
Resources().activeScene = resourcePath + "/" + *scene;
sceneEditor.entityEditor.SetVisible(false);
Hymn().world.Clear();
Hymn().world.Load(Hymn().GetPath() + "/" + Resources().activeScene + ".json");
changeScene = false;
savePromptWindow.SetVisible(false);
savePromptWindow.ResetDecision();
break;
case 2:
changeScene = false;
savePromptWindow.ResetDecision();
savePromptWindow.SetVisible(false);
break;
default:
break;
}
}
}
// Create folder.
if (folderNameWindow.IsVisible())
folderNameWindow.Show();
if (sceneEditor.entityPressed || scriptPressed || texturePressed || modelPressed || soundPressed) {
sceneEditor.entityEditor.SetVisible(sceneEditor.entityPressed);
scriptEditor.SetVisible(scriptPressed);
textureEditor.SetVisible(texturePressed);
modelEditor.SetVisible(modelPressed);
soundEditor.SetVisible(soundPressed);
}
if (sceneEditor.IsVisible()) {
ImGui::HorizontalSplitter(ImVec2(sceneWidth, 20), size.y - 20, splitterSize, sceneWidth, sceneResize, 20, size.x - editorWidth - 20);
ImGui::SetNextWindowPos(ImVec2(0, 20));
ImGui::SetNextWindowSize(ImVec2(sceneWidth, size.y - 20));
sceneEditor.Show();
}
if (sceneEditor.entityEditor.IsVisible() || scriptEditor.IsVisible() || textureEditor.IsVisible() || modelEditor.IsVisible() || soundEditor.IsVisible()) {
editorWidth = size.x - editorWidth;
ImGui::HorizontalSplitter(ImVec2(editorWidth, 20), size.y - 20, splitterSize, editorWidth, editorResize, sceneWidth + 20, size.x - 20);
editorWidth = size.x - editorWidth;
ImGui::SetNextWindowPos(ImVec2(size.x - editorWidth, 20));
ImGui::SetNextWindowSize(ImVec2(editorWidth, size.y - 20));
}
if (sceneEditor.entityEditor.IsVisible())
sceneEditor.entityEditor.Show();
if (scriptEditor.IsVisible())
scriptEditor.Show();
if (textureEditor.IsVisible())
textureEditor.Show();
if (modelEditor.IsVisible())
modelEditor.Show();
if (soundEditor.IsVisible())
soundEditor.Show();
ImGui::End();
}
bool ResourceView::IsVisible() const {
return visible;
}
void ResourceView::SetVisible(bool visible) {
this->visible = visible;
}
void ResourceView::HideEditors() {
sceneEditor.SetVisible(false);
sceneEditor.entityEditor.SetVisible(false);
scriptEditor.SetVisible(false);
modelEditor.SetVisible(false);
textureEditor.SetVisible(false);
soundEditor.SetVisible(false);
}
void ResourceView::SaveScene() const {
sceneEditor.Save();
}
#undef max
void ResourceView::ResetScene() {
sceneEditor.SetScene("", nullptr);
sceneEditor.SetVisible(false);
}
SceneEditor& ResourceView::GetScene() {
return sceneEditor;
}
void ResourceView::ShowResourceFolder(ResourceList::ResourceFolder& folder, const std::string& path) {
bool opened = ImGui::TreeNode(folder.name.c_str());
if (ImGui::BeginPopupContextItem(folder.name.c_str())) {
// Add subfolder.
if (ImGui::Selectable("Add folder")) {
resourcePath = path;
parentFolder = &folder;
folderNameWindow.SetVisible(true);
return;
}
// Add scene.
if (ImGui::Selectable("Add scene")) {
ResourceList::Resource resource;
resource.type = ResourceList::Resource::SCENE;
resource.scene = "Scene #" + std::to_string(Resources().sceneNumber++);
folder.resources.push_back(resource);
return;
}
// Add model.
if (ImGui::Selectable("Add model")) {
ResourceList::Resource resource;
resource.type = ResourceList::Resource::MODEL;
resource.model = new Geometry::Model();
resource.model->path = path + "/";
resource.model->name = "Model #" + std::to_string(Resources().modelNumber++);
folder.resources.push_back(resource);
return;
}
// Add texture.
if (ImGui::Selectable("Add texture")) {
ResourceList::Resource resource;
resource.type = ResourceList::Resource::TEXTURE;
string name = path + "/Texture #" + std::to_string(Resources().textureNumber++);
resource.texture = Managers().resourceManager->CreateTextureAsset(name, Managers().resourceManager->CreateTexture2D(DEFAULTALBEDO_PNG, DEFAULTALBEDO_PNG_LENGTH));
folder.resources.push_back(resource);
return;
}
// Add script.
if (ImGui::Selectable("Add script")) {
ResourceList::Resource resource;
resource.type = ResourceList::Resource::SCRIPT;
resource.script = new ScriptFile();
resource.script->path = path + "/";
resource.script->name = "Script #" + std::to_string(Hymn().scriptNumber++);
Hymn().scripts.push_back(resource.script);
folder.resources.push_back(resource);
return;
}
// Add sound.
if (ImGui::Selectable("Add sound")) {
ResourceList::Resource resource;
resource.type = ResourceList::Resource::SOUND;
resource.sound = new Audio::SoundBuffer();
resource.sound->path = path + "/";
resource.sound->name = "Sound #" + std::to_string(Resources().soundNumber++);
folder.resources.push_back(resource);
return;
}
/// @todo Remove folder.
ImGui::EndPopup();
}
if (opened) {
// Show subfolders.
for (ResourceList::ResourceFolder& subfolder : folder.subfolders) {
ShowResourceFolder(subfolder, path + "/" + subfolder.name);
}
// Show resources.
for (auto it = folder.resources.begin(); it != folder.resources.end(); ++it) {
if (ShowResource(*it, path)) {
folder.resources.erase(it);
return;
}
}
ImGui::TreePop();
}
}
bool ResourceView::ShowResource(ResourceList::Resource& resource, const std::string& path) {
// Scene.
if (resource.type == ResourceList::Resource::SCENE) {
if (ImGui::Selectable(resource.scene.c_str())) {
// Sets to don't save when opening first scene.
if (scene == nullptr) {
changeScene = true;
resourcePath = path;
scene = &resource.scene;
savePromptWindow.SetVisible(false);
savePromptWindow.SetDecision(1);
} else {
// Does so that the prompt window won't show if you select active scene.
if (resource.scene != Resources().activeScene) {
changeScene = true;
resourcePath = path;
scene = &resource.scene;
savePromptWindow.SetTitle("Save before you switch scene?");
}
}
}
// Delete scene.
if (ImGui::BeginPopupContextItem(resource.scene.c_str())) {
if (ImGui::Selectable("Delete")) {
if (Resources().activeScene == resource.scene) {
Resources().activeScene = "";
sceneEditor.SetScene("", nullptr);
}
ImGui::EndPopup();
return true;
}
ImGui::EndPopup();
}
}
// Model.
if (resource.type == ResourceList::Resource::MODEL) {
if (ImGui::Selectable(resource.model->name.c_str())) {
modelPressed = true;
modelEditor.SetModel(resource.model);
}
if (ImGui::BeginPopupContextItem(resource.model->name.c_str())) {
if (ImGui::Selectable("Delete")) {
if (modelEditor.GetModel() == resource.model)
modelEditor.SetVisible(false);
Managers().resourceManager->FreeModel(resource.model);
ImGui::EndPopup();
return true;
}
ImGui::EndPopup();
}
}
// Textures.
if (resource.type == ResourceList::Resource::TEXTURE) {
if (ImGui::Selectable(resource.texture->name.c_str())) {
texturePressed = true;
textureEditor.SetTexture(resource.texture);
}
if (ImGui::BeginPopupContextItem(resource.texture->name.c_str())) {
if (ImGui::Selectable("Delete")) {
if (Managers().resourceManager->GetTextureAssetInstanceCount(resource.texture) > 1) {
Log() << "This texture is in use. Remove all references to the texture first.\n";
} else {
if (textureEditor.GetTexture() == resource.texture)
textureEditor.SetVisible(false);
// Remove files.
remove((Hymn().GetPath() + "/" + path + "/" + resource.texture->name + ".png").c_str());
remove((Hymn().GetPath() + "/" + path + "/" + resource.texture->name + ".json").c_str());
Managers().resourceManager->FreeTextureAsset(resource.texture);
ImGui::EndPopup();
return true;
}
}
ImGui::EndPopup();
}
}
// Scripts.
if (resource.type == ResourceList::Resource::SCRIPT) {
std::string name = resource.script->name;
if (ImGui::Selectable(name.c_str())) {
scriptPressed = true;
scriptEditor.SetScript(resource.script);
}
if (ImGui::BeginPopupContextItem(name.c_str())) {
if (ImGui::Selectable("Delete")) {
if (scriptEditor.GetScript() == resource.script)
scriptEditor.SetVisible(false);
Managers().resourceManager->FreeScriptFile(resource.script);
for (auto it = Hymn().scripts.begin(); it != Hymn().scripts.end(); ++it) {
if (*it == resource.script) {
Hymn().scripts.erase(it);
break;
}
}
ImGui::EndPopup();
return true;
}
ImGui::EndPopup();
}
}
/*
// Sounds.
bool soundPressed = false;
if (ImGui::TreeNode("Sounds")) {
for (auto it = Resources().sounds.begin(); it != Resources().sounds.end(); ++it) {
Audio::SoundBuffer* sound = *it;
if (ImGui::Selectable(sound->name.c_str())) {
soundPressed = true;
soundEditor.SetSound(sound);
}
if (ImGui::BeginPopupContextItem(sound->name.c_str())) {
if (ImGui::Selectable("Delete")) {
if (soundEditor.GetSound() == sound)
soundEditor.SetVisible(false);
delete sound;
Resources().sounds.erase(it);
ImGui::EndPopup();
break;
}
ImGui::EndPopup();
}
}
ImGui::TreePop();
}*/
return false;
}
void ResourceView::FileNameWindowClosed(const std::string& name) {
if (!name.empty()) {
ResourceList::ResourceFolder folder;
folder.name = name;
parentFolder->subfolders.push_back(folder);
FileSystem::CreateDirectory((Hymn().GetPath() + "/" + resourcePath + "/" + name).c_str());
}
}
<|endoftext|> |
<commit_before>/**********************************************************************
Copyright (c) 2016 Advanced Micro Devices, Inc. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
********************************************************************/
#include "scene_io.h"
#include "image_io.h"
#include "SceneGraph/scene1.h"
#include "SceneGraph/shape.h"
#include "SceneGraph/material.h"
#include "SceneGraph/light.h"
#include "SceneGraph/texture.h"
#include "math/mathutils.h"
#include "SceneGraph/uberv2material.h"
#include "SceneGraph/inputmaps.h"
#include <string>
#include <map>
#include <set>
#include <cassert>
#include "Utils/tiny_obj_loader.h"
#include "Utils/log.h"
namespace Baikal
{
// Obj scene loader
class SceneIoObj : public SceneIo::Loader
{
public:
// Load scene from file
Scene1::Ptr LoadScene(std::string const& filename, std::string const& basepath) const override;
SceneIoObj() : SceneIo::Loader("obj", this)
{
SceneIo::RegisterLoader("objm", this);
}
~SceneIoObj()
{
SceneIo::UnregisterLoader("objm");
}
private:
Material::Ptr TranslateMaterialUberV2(ImageIo const& image_io, tinyobj::material_t const& mat, std::string const& basepath, Scene1& scene) const;
mutable std::map<std::string, Material::Ptr> m_material_cache;
};
// Create static object to register loader. This object will be used as loader
static SceneIoObj obj_loader;
Scene1::Ptr SceneIoObj::LoadScene(std::string const& filename, std::string const& basepath) const
{
using namespace tinyobj;
auto image_io(ImageIo::CreateImageIo());
// Loader data
std::vector<shape_t> objshapes;
std::vector<material_t> objmaterials;
// Try loading file
LogInfo("Loading a scene from OBJ: ", filename, " ... ");
std::string err;
auto res = LoadObj(objshapes, objmaterials, err, filename.c_str(), basepath.c_str(), triangulation|calculate_normals);
if (!res)
{
throw std::runtime_error(err);
}
LogInfo("Success\n");
// Allocate scene
auto scene = Scene1::Create();
// Enumerate and translate materials
// Keep track of emissive subset
std::set<Material::Ptr> emissives;
std::vector<Material::Ptr> materials(objmaterials.size());
for (int i = 0; i < (int)objmaterials.size(); ++i)
{
// Translate material
materials[i] = TranslateMaterialUberV2(*image_io, objmaterials[i], basepath, *scene);
// Add to emissive subset if needed
if (materials[i]->HasEmission())
{
emissives.insert(materials[i]);
}
}
// Enumerate all shapes in the scene
for (int s = 0; s < (int)objshapes.size(); ++s)
{
const auto& shape = objshapes[s];
// Find all materials used by this shape.
std::set<int> used_materials(std::begin(shape.mesh.material_ids), std::end(shape.mesh.material_ids));
// Split the mesh into multiple meshes, each with only one material.
for (int used_material : used_materials)
{
// Map from old index to new index.
std::map<unsigned int, unsigned int> used_indices;
// Remapped indices.
std::vector<unsigned int> indices;
// Collected vertex/normal/texcoord data.
std::vector<float> vertices, normals, texcoords;
// Go through each face in the mesh.
for (size_t i = 0; i < shape.mesh.material_ids.size(); ++i)
{
// Skip faces which don't use the current material.
if (shape.mesh.material_ids[i] != used_material) continue;
const int num_face_vertices = shape.mesh.num_vertices[i];
assert(num_face_vertices == 3 && "expected triangles");
// For each vertex index of this face.
for (int j = 0; j < num_face_vertices; ++j)
{
const unsigned int old_index = shape.mesh.indices[num_face_vertices * i + j];
// Collect vertex/normal/texcoord data. Avoid inserting the same data twice.
auto result = used_indices.emplace(old_index, (unsigned int)(vertices.size() / 3));
if (result.second) // Did insert?
{
// Push the new data.
for (int k = 0; k < 3; ++k)
vertices.push_back(shape.mesh.positions[3 * old_index + k]);
for (int k = 0; k < 3; ++k)
normals.push_back(shape.mesh.normals[3 * old_index + k]);
if (!shape.mesh.texcoords.empty())
for (int k = 0; k < 2; ++k)
texcoords.push_back(shape.mesh.texcoords[2 * old_index + k]);
}
const unsigned int new_index = result.first->second;
indices.push_back(new_index);
}
}
// Create empty mesh
auto mesh = Mesh::Create();
// Set vertex and index data
auto num_vertices = vertices.size() / 3;
mesh->SetVertices(&vertices[0], num_vertices);
auto num_normals = normals.size() / 3;
mesh->SetNormals(&normals[0], num_normals);
auto num_uvs = texcoords.size() / 2;
// If we do not have UVs, generate zeroes
if (num_uvs)
{
mesh->SetUVs(&texcoords[0], num_uvs);
}
else
{
std::vector<RadeonRays::float2> zero(num_vertices);
std::fill(zero.begin(), zero.end(), RadeonRays::float2(0, 0));
mesh->SetUVs(&zero[0], num_vertices);
}
// Set indices
auto num_indices = indices.size();
mesh->SetIndices(reinterpret_cast<std::uint32_t const*>(&indices[0]), num_indices);
// Set material
if (used_material >= 0)
{
mesh->SetMaterial(materials[used_material]);
}
// Attach to the scene
scene->AttachShape(mesh);
// If the mesh has emissive material we need to add area light for it
if (used_material >= 0 && emissives.find(materials[used_material]) != emissives.cend())
{
// Add area light for each polygon of emissive mesh
for (std::size_t l = 0; l < mesh->GetNumIndices() / 3; ++l)
{
auto light = AreaLight::Create(mesh, l);
scene->AttachLight(light);
}
}
}
}
// TODO: temporary code, add IBL
auto ibl_texture = image_io->LoadImage("../Resources/Textures/studio015.hdr");
//auto ibl_texture1 = image_io->LoadImage("../Resources/Textures/sky.hdr");
auto ibl = ImageBasedLight::Create();
ibl->SetTexture(ibl_texture);
//ibl->SetReflectionTexture(ibl_texture1);
//ibl->SetBackgroundTexture(ibl_texture);
ibl->SetMultiplier(1.f);
// TODO: temporary code to add directional light
auto light = DirectionalLight::Create();
light->SetDirection(RadeonRays::float3(.1f, -1.f, -.1f));
light->SetEmittedRadiance(RadeonRays::float3(1.f, 1.f, 1.f));
/*auto light1 = DirectionalLight::Create();
auto d = RadeonRays::float3(-0.1f, -1.f, -1.f);
d.normalize();
light1->SetDirection(d);
light1->SetEmittedRadiance(3.f * RadeonRays::float3(1.f, 0.8f, 0.65f));*/
scene->AttachLight(light);
//scene->AttachLight(light1);
scene->AttachLight(ibl);
return scene;
}
Material::Ptr SceneIoObj::TranslateMaterialUberV2(ImageIo const& image_io, tinyobj::material_t const& mat, std::string const& basepath, Scene1& scene) const
{
auto iter = m_material_cache.find(mat.name);
if (iter != m_material_cache.cend())
{
return iter->second;
}
UberV2Material::Ptr material = UberV2Material::Create();
RadeonRays::float3 emission(mat.emission[0], mat.emission[1], mat.emission[2]);
bool apply_gamma = false;
uint32_t material_layers = 0;
auto uberv2_set_texture = [](UberV2Material::Ptr material, const std::string input_name, Texture::Ptr texture, bool apply_gamma)
{
if (apply_gamma)
{
material->SetInputValue(input_name.c_str(),
InputMap_Pow::Create(
InputMap_Sampler::Create(texture),
InputMap_ConstantFloat::Create(2.2f)));
}
else
{
material->SetInputValue(input_name.c_str(), InputMap_Sampler::Create(texture));
}
};
auto uberv2_set_bump_texture = [](UberV2Material::Ptr material, Texture::Ptr texture)
{
auto bump_sampler = InputMap_SamplerBumpMap::Create(texture);
auto bump_remap = Baikal::InputMap_Remap::Create(
Baikal::InputMap_ConstantFloat3::Create(RadeonRays::float3(0.f, 1.f, 0.f)),
Baikal::InputMap_ConstantFloat3::Create(RadeonRays::float3(-1.f, 1.f, 0.f)),
bump_sampler);
material->SetInputValue("uberv2.shading_normal", bump_remap);
};
// Check emission layer
if (emission.sqnorm() > 0)
{
material_layers |= UberV2Material::Layers::kEmissionLayer;
if (!mat.diffuse_texname.empty())
{
auto texture = LoadTexture(image_io, scene, basepath, mat.diffuse_texname);
uberv2_set_texture(material, "uberv2.emission.color", texture, apply_gamma);
}
else
{
material->SetInputValue("uberv2.emission.color", InputMap_ConstantFloat3::Create(emission));
}
}
auto s = RadeonRays::float3(mat.specular[0], mat.specular[1], mat.specular[2]);
auto r = RadeonRays::float3(mat.transmittance[0], mat.transmittance[1], mat.transmittance[2]);
auto d = RadeonRays::float3(mat.diffuse[0], mat.diffuse[1], mat.diffuse[2]);
auto default_ior = Baikal::InputMap_ConstantFloat::Create(3.0f);
auto default_roughness = Baikal::InputMap_ConstantFloat::Create(0.01f);
auto default_one = Baikal::InputMap_ConstantFloat::Create(1.0f);
// Check refraction layer
if (r.sqnorm() > 0)
{
material_layers |= UberV2Material::Layers::kRefractionLayer;
material->SetInputValue("uberv2.refraction.ior", default_ior);
material->SetInputValue("uberv2.refraction.roughness", default_roughness);
material->SetInputValue("uberv2.refraction.color", InputMap_ConstantFloat3::Create(r));
}
// Check reflection layer
if (s.sqnorm() > 0)
{
material_layers |= UberV2Material::Layers::kReflectionLayer;
material->SetInputValue("uberv2.reflection.ior", default_ior);
material->SetInputValue("uberv2.reflection.roughness", default_roughness);
material->SetInputValue("uberv2.reflection.metalness", default_one);
if (!mat.specular_texname.empty())
{
auto texture = LoadTexture(image_io, scene, basepath, mat.specular_texname);
uberv2_set_texture(material, "uberv2.reflection.color", texture, apply_gamma);
}
else
{
material->SetInputValue("uberv2.reflection.color", InputMap_ConstantFloat3::Create(s));
}
}
// Check if we have bump map
if (!mat.bump_texname.empty())
{
material_layers |= UberV2Material::Layers::kShadingNormalLayer;
auto texture = LoadTexture(image_io, scene, basepath, mat.bump_texname);
uberv2_set_bump_texture(material, texture);
}
// Finally add diffuse layer
{
material_layers |= UberV2Material::Layers::kDiffuseLayer;
if (!mat.diffuse_texname.empty())
{
auto texture = LoadTexture(image_io, scene, basepath, mat.diffuse_texname);
uberv2_set_texture(material, "uberv2.diffuse.color", texture, apply_gamma);
}
else
{
material->SetInputValue("uberv2.diffuse.color", InputMap_ConstantFloat3::Create(d));
}
}
// Set material name
material->SetName(mat.name);
material->SetLayers(material_layers);
m_material_cache.emplace(std::make_pair(mat.name, material));
return material;
}
}
<commit_msg>Apply gamma by default<commit_after>/**********************************************************************
Copyright (c) 2016 Advanced Micro Devices, Inc. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
********************************************************************/
#include "scene_io.h"
#include "image_io.h"
#include "SceneGraph/scene1.h"
#include "SceneGraph/shape.h"
#include "SceneGraph/material.h"
#include "SceneGraph/light.h"
#include "SceneGraph/texture.h"
#include "math/mathutils.h"
#include "SceneGraph/uberv2material.h"
#include "SceneGraph/inputmaps.h"
#include <string>
#include <map>
#include <set>
#include <cassert>
#include "Utils/tiny_obj_loader.h"
#include "Utils/log.h"
namespace Baikal
{
// Obj scene loader
class SceneIoObj : public SceneIo::Loader
{
public:
// Load scene from file
Scene1::Ptr LoadScene(std::string const& filename, std::string const& basepath) const override;
SceneIoObj() : SceneIo::Loader("obj", this)
{
SceneIo::RegisterLoader("objm", this);
}
~SceneIoObj()
{
SceneIo::UnregisterLoader("objm");
}
private:
Material::Ptr TranslateMaterialUberV2(ImageIo const& image_io, tinyobj::material_t const& mat, std::string const& basepath, Scene1& scene) const;
mutable std::map<std::string, Material::Ptr> m_material_cache;
};
// Create static object to register loader. This object will be used as loader
static SceneIoObj obj_loader;
Scene1::Ptr SceneIoObj::LoadScene(std::string const& filename, std::string const& basepath) const
{
using namespace tinyobj;
auto image_io(ImageIo::CreateImageIo());
// Loader data
std::vector<shape_t> objshapes;
std::vector<material_t> objmaterials;
// Try loading file
LogInfo("Loading a scene from OBJ: ", filename, " ... ");
std::string err;
auto res = LoadObj(objshapes, objmaterials, err, filename.c_str(), basepath.c_str(), triangulation|calculate_normals);
if (!res)
{
throw std::runtime_error(err);
}
LogInfo("Success\n");
// Allocate scene
auto scene = Scene1::Create();
// Enumerate and translate materials
// Keep track of emissive subset
std::set<Material::Ptr> emissives;
std::vector<Material::Ptr> materials(objmaterials.size());
for (int i = 0; i < (int)objmaterials.size(); ++i)
{
// Translate material
materials[i] = TranslateMaterialUberV2(*image_io, objmaterials[i], basepath, *scene);
// Add to emissive subset if needed
if (materials[i]->HasEmission())
{
emissives.insert(materials[i]);
}
}
// Enumerate all shapes in the scene
for (int s = 0; s < (int)objshapes.size(); ++s)
{
const auto& shape = objshapes[s];
// Find all materials used by this shape.
std::set<int> used_materials(std::begin(shape.mesh.material_ids), std::end(shape.mesh.material_ids));
// Split the mesh into multiple meshes, each with only one material.
for (int used_material : used_materials)
{
// Map from old index to new index.
std::map<unsigned int, unsigned int> used_indices;
// Remapped indices.
std::vector<unsigned int> indices;
// Collected vertex/normal/texcoord data.
std::vector<float> vertices, normals, texcoords;
// Go through each face in the mesh.
for (size_t i = 0; i < shape.mesh.material_ids.size(); ++i)
{
// Skip faces which don't use the current material.
if (shape.mesh.material_ids[i] != used_material) continue;
const int num_face_vertices = shape.mesh.num_vertices[i];
assert(num_face_vertices == 3 && "expected triangles");
// For each vertex index of this face.
for (int j = 0; j < num_face_vertices; ++j)
{
const unsigned int old_index = shape.mesh.indices[num_face_vertices * i + j];
// Collect vertex/normal/texcoord data. Avoid inserting the same data twice.
auto result = used_indices.emplace(old_index, (unsigned int)(vertices.size() / 3));
if (result.second) // Did insert?
{
// Push the new data.
for (int k = 0; k < 3; ++k)
vertices.push_back(shape.mesh.positions[3 * old_index + k]);
for (int k = 0; k < 3; ++k)
normals.push_back(shape.mesh.normals[3 * old_index + k]);
if (!shape.mesh.texcoords.empty())
for (int k = 0; k < 2; ++k)
texcoords.push_back(shape.mesh.texcoords[2 * old_index + k]);
}
const unsigned int new_index = result.first->second;
indices.push_back(new_index);
}
}
// Create empty mesh
auto mesh = Mesh::Create();
// Set vertex and index data
auto num_vertices = vertices.size() / 3;
mesh->SetVertices(&vertices[0], num_vertices);
auto num_normals = normals.size() / 3;
mesh->SetNormals(&normals[0], num_normals);
auto num_uvs = texcoords.size() / 2;
// If we do not have UVs, generate zeroes
if (num_uvs)
{
mesh->SetUVs(&texcoords[0], num_uvs);
}
else
{
std::vector<RadeonRays::float2> zero(num_vertices);
std::fill(zero.begin(), zero.end(), RadeonRays::float2(0, 0));
mesh->SetUVs(&zero[0], num_vertices);
}
// Set indices
auto num_indices = indices.size();
mesh->SetIndices(reinterpret_cast<std::uint32_t const*>(&indices[0]), num_indices);
// Set material
if (used_material >= 0)
{
mesh->SetMaterial(materials[used_material]);
}
// Attach to the scene
scene->AttachShape(mesh);
// If the mesh has emissive material we need to add area light for it
if (used_material >= 0 && emissives.find(materials[used_material]) != emissives.cend())
{
// Add area light for each polygon of emissive mesh
for (std::size_t l = 0; l < mesh->GetNumIndices() / 3; ++l)
{
auto light = AreaLight::Create(mesh, l);
scene->AttachLight(light);
}
}
}
}
// TODO: temporary code, add IBL
auto ibl_texture = image_io->LoadImage("../Resources/Textures/studio015.hdr");
//auto ibl_texture1 = image_io->LoadImage("../Resources/Textures/sky.hdr");
auto ibl = ImageBasedLight::Create();
ibl->SetTexture(ibl_texture);
//ibl->SetReflectionTexture(ibl_texture1);
//ibl->SetBackgroundTexture(ibl_texture);
ibl->SetMultiplier(1.f);
// TODO: temporary code to add directional light
auto light = DirectionalLight::Create();
light->SetDirection(RadeonRays::float3(.1f, -1.f, -.1f));
light->SetEmittedRadiance(RadeonRays::float3(1.f, 1.f, 1.f));
/*auto light1 = DirectionalLight::Create();
auto d = RadeonRays::float3(-0.1f, -1.f, -1.f);
d.normalize();
light1->SetDirection(d);
light1->SetEmittedRadiance(3.f * RadeonRays::float3(1.f, 0.8f, 0.65f));*/
scene->AttachLight(light);
//scene->AttachLight(light1);
scene->AttachLight(ibl);
return scene;
}
Material::Ptr SceneIoObj::TranslateMaterialUberV2(ImageIo const& image_io, tinyobj::material_t const& mat, std::string const& basepath, Scene1& scene) const
{
auto iter = m_material_cache.find(mat.name);
if (iter != m_material_cache.cend())
{
return iter->second;
}
UberV2Material::Ptr material = UberV2Material::Create();
RadeonRays::float3 emission(mat.emission[0], mat.emission[1], mat.emission[2]);
bool apply_gamma = true;
uint32_t material_layers = 0;
auto uberv2_set_texture = [](UberV2Material::Ptr material, const std::string input_name, Texture::Ptr texture, bool apply_gamma)
{
if (apply_gamma)
{
material->SetInputValue(input_name.c_str(),
InputMap_Pow::Create(
InputMap_Sampler::Create(texture),
InputMap_ConstantFloat::Create(2.2f)));
}
else
{
material->SetInputValue(input_name.c_str(), InputMap_Sampler::Create(texture));
}
};
auto uberv2_set_bump_texture = [](UberV2Material::Ptr material, Texture::Ptr texture)
{
auto bump_sampler = InputMap_SamplerBumpMap::Create(texture);
auto bump_remap = Baikal::InputMap_Remap::Create(
Baikal::InputMap_ConstantFloat3::Create(RadeonRays::float3(0.f, 1.f, 0.f)),
Baikal::InputMap_ConstantFloat3::Create(RadeonRays::float3(-1.f, 1.f, 0.f)),
bump_sampler);
material->SetInputValue("uberv2.shading_normal", bump_remap);
};
// Check emission layer
if (emission.sqnorm() > 0)
{
material_layers |= UberV2Material::Layers::kEmissionLayer;
if (!mat.diffuse_texname.empty())
{
auto texture = LoadTexture(image_io, scene, basepath, mat.diffuse_texname);
uberv2_set_texture(material, "uberv2.emission.color", texture, apply_gamma);
}
else
{
material->SetInputValue("uberv2.emission.color", InputMap_ConstantFloat3::Create(emission));
}
}
auto s = RadeonRays::float3(mat.specular[0], mat.specular[1], mat.specular[2]);
auto r = RadeonRays::float3(mat.transmittance[0], mat.transmittance[1], mat.transmittance[2]);
auto d = RadeonRays::float3(mat.diffuse[0], mat.diffuse[1], mat.diffuse[2]);
auto default_ior = Baikal::InputMap_ConstantFloat::Create(3.0f);
auto default_roughness = Baikal::InputMap_ConstantFloat::Create(0.01f);
auto default_one = Baikal::InputMap_ConstantFloat::Create(1.0f);
// Check refraction layer
if (r.sqnorm() > 0)
{
material_layers |= UberV2Material::Layers::kRefractionLayer;
material->SetInputValue("uberv2.refraction.ior", default_ior);
material->SetInputValue("uberv2.refraction.roughness", default_roughness);
material->SetInputValue("uberv2.refraction.color", InputMap_ConstantFloat3::Create(r));
}
// Check reflection layer
if (s.sqnorm() > 0)
{
material_layers |= UberV2Material::Layers::kReflectionLayer;
material->SetInputValue("uberv2.reflection.ior", default_ior);
material->SetInputValue("uberv2.reflection.roughness", default_roughness);
material->SetInputValue("uberv2.reflection.metalness", default_one);
if (!mat.specular_texname.empty())
{
auto texture = LoadTexture(image_io, scene, basepath, mat.specular_texname);
uberv2_set_texture(material, "uberv2.reflection.color", texture, apply_gamma);
}
else
{
material->SetInputValue("uberv2.reflection.color", InputMap_ConstantFloat3::Create(s));
}
}
// Check if we have bump map
if (!mat.bump_texname.empty())
{
material_layers |= UberV2Material::Layers::kShadingNormalLayer;
auto texture = LoadTexture(image_io, scene, basepath, mat.bump_texname);
uberv2_set_bump_texture(material, texture);
}
// Finally add diffuse layer
{
material_layers |= UberV2Material::Layers::kDiffuseLayer;
if (!mat.diffuse_texname.empty())
{
auto texture = LoadTexture(image_io, scene, basepath, mat.diffuse_texname);
uberv2_set_texture(material, "uberv2.diffuse.color", texture, apply_gamma);
}
else
{
material->SetInputValue("uberv2.diffuse.color", InputMap_ConstantFloat3::Create(d));
}
}
// Set material name
material->SetName(mat.name);
material->SetLayers(material_layers);
m_material_cache.emplace(std::make_pair(mat.name, material));
return material;
}
}
<|endoftext|> |
<commit_before>#ifndef STAN_MATH_PRIM_FUN_UNIT_VECTOR_CONSTRAIN_HPP
#define STAN_MATH_PRIM_FUN_UNIT_VECTOR_CONSTRAIN_HPP
#include <stan/math/prim/err.hpp>
#include <stan/math/prim/fun/Eigen.hpp>
#include <stan/math/prim/fun/dot_self.hpp>
#include <stan/math/prim/fun/sqrt.hpp>
#include <cmath>
namespace stan {
namespace math {
/**
* Return the unit length vector corresponding to the free vector y.
*
* See <a
* href="https://en.wikipedia.org/wiki/N-sphere#Generating_random_points">the
* Wikipedia page on generating random points on an N-sphere</a>.
*
* @tparam EigMat type inheriting from `EigenBase` that does not have an fvar
* scalar type.
* @param y vector of K unrestricted variables
* @return Unit length vector of dimension K
*/
template <typename T, require_eigen_col_vector_t<T>* = nullptr,
require_not_vt_autodiff<T>* = nullptr>
inline auto unit_vector_constrain(const T& y) {
using std::sqrt;
check_nonzero_size("unit_vector_constrain", "y", y);
return make_holder(
[](const auto& y_ref) {
value_type_t<T> SN = dot_self(y_ref);
check_positive_finite("unit_vector_constrain", "norm", SN);
return y_ref / sqrt(SN);
},
to_ref(y));
}
/**
* Return the unit length vector corresponding to the free vector y.
* See https://en.wikipedia.org/wiki/N-sphere#Generating_random_points
*
* @tparam EigMat type inheriting from `EigenBase` that does not have an fvar
* scalar type.
*
* @param y vector of K unrestricted variables
* @return Unit length vector of dimension K
* @param lp Log probability reference to increment.
*/
template <typename T1, typename T2, require_eigen_col_vector_t<T1>* = nullptr,
require_all_not_vt_autodiff<T1, T2>* = nullptr>
inline plain_type_t<T1> unit_vector_constrain(const T1& y, T2& lp) {
using std::sqrt;
check_nonzero_size("unit_vector_constrain", "y", y);
return make_holder(
[](const auto& y_ref, const auto& lp) {
value_type_t<T1> SN = dot_self(y_ref);
check_positive_finite("unit_vector_constrain", "norm", SN);
lp -= 0.5 * SN;
return y_ref / sqrt(SN);
},
to_ref(y), lp);
}
} // namespace math
} // namespace stan
#endif
<commit_msg>fix unit vector constrain<commit_after>#ifndef STAN_MATH_PRIM_FUN_UNIT_VECTOR_CONSTRAIN_HPP
#define STAN_MATH_PRIM_FUN_UNIT_VECTOR_CONSTRAIN_HPP
#include <stan/math/prim/err.hpp>
#include <stan/math/prim/fun/Eigen.hpp>
#include <stan/math/prim/fun/dot_self.hpp>
#include <stan/math/prim/fun/sqrt.hpp>
#include <cmath>
namespace stan {
namespace math {
/**
* Return the unit length vector corresponding to the free vector y.
*
* See <a
* href="https://en.wikipedia.org/wiki/N-sphere#Generating_random_points">the
* Wikipedia page on generating random points on an N-sphere</a>.
*
* @tparam EigMat type inheriting from `EigenBase` that does not have an fvar
* scalar type.
* @param y vector of K unrestricted variables
* @return Unit length vector of dimension K
*/
template <typename T, require_eigen_col_vector_t<T>* = nullptr,
require_not_vt_autodiff<T>* = nullptr>
inline auto unit_vector_constrain(const T& y) {
using std::sqrt;
check_nonzero_size("unit_vector_constrain", "y", y);
return make_holder(
[](const auto& y_ref) {
value_type_t<T> SN = dot_self(y_ref);
check_positive_finite("unit_vector_constrain", "norm", SN);
return y_ref / sqrt(SN);
},
to_ref(y));
}
/**
* Return the unit length vector corresponding to the free vector y.
* See https://en.wikipedia.org/wiki/N-sphere#Generating_random_points
*
* @tparam EigMat type inheriting from `EigenBase` that does not have an fvar
* scalar type.
*
* @param y vector of K unrestricted variables
* @return Unit length vector of dimension K
* @param lp Log probability reference to increment.
*/
template <typename T1, typename T2, require_eigen_col_vector_t<T1>* = nullptr,
require_all_not_vt_autodiff<T1, T2>* = nullptr>
inline plain_type_t<T1> unit_vector_constrain(const T1& y, T2& lp) {
using std::sqrt;
check_nonzero_size("unit_vector_constrain", "y", y);
return make_holder(
[](const auto& y_ref, auto& lp) {
value_type_t<T1> SN = dot_self(y_ref);
check_positive_finite("unit_vector_constrain", "norm", SN);
lp -= 0.5 * SN;
return y_ref / sqrt(SN);
},
to_ref(y), lp);
}
} // namespace math
} // namespace stan
#endif
<|endoftext|> |
<commit_before>//////////////////////////////////////////////////////////////////////////////
// oxygentransitionwidget.cpp
// stores event filters and maps widgets to transitions for transitions
// -------------------
//
// Copyright (c) 2009 Hugo Pereira Da Costa <hugo.pereira@free.fr>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//////////////////////////////////////////////////////////////////////////////
#include "oxygentransitionwidget.h"
#include <cassert>
#include <QtGui/QPainter>
#include <QtGui/QPaintEvent>
#include <QStyleOption>
#include <QtCore/QCoreApplication>
#include <QtCore/QTextStream>
namespace Oxygen
{
//________________________________________________
bool TransitionWidget::_paintEnabled = true;
bool TransitionWidget::paintEnabled( void )
{ return _paintEnabled; }
int TransitionWidget::_steps = 0;
//________________________________________________
TransitionWidget::TransitionWidget( QWidget* parent, int duration ):
QWidget( parent ),
_flags( None ),
_animation( new Animation( duration, this ) ),
_opacity( 0 )
{
// background flags
setAttribute(Qt::WA_NoSystemBackground );
setAutoFillBackground( false );
// setup animation
_animation.data()->setStartValue( 0 );
_animation.data()->setEndValue( 1.0 );
_animation.data()->setTargetObject( this );
_animation.data()->setPropertyName( "opacity" );
// setup connections
connect( _animation.data(), SIGNAL(finished()), SIGNAL(finished()) );
}
//________________________________________________
QPixmap TransitionWidget::grab( QWidget* widget, QRect rect )
{
// change rect
if( !rect.isValid() ) rect = widget->rect();
if( !rect.isValid() ) return QPixmap();
// initialize pixmap
QPixmap out( rect.size() );
out.fill( Qt::transparent );
_paintEnabled = false;
if( testFlag( GrabFromWindow ) )
{
rect = rect.translated( widget->mapTo( widget->window(), widget->rect().topLeft() ) );
widget = widget->window();
out = QPixmap::grabWidget( widget, rect );
} else {
if( !testFlag( Transparent ) ) { grabBackground( out, widget, rect ); }
grabWidget( out, widget, rect );
}
_paintEnabled = true;
return out;
}
//________________________________________________
void TransitionWidget::paintEvent( QPaintEvent* event )
{
// fully transparent case
if( opacity() >= 1.0 && endPixmap().isNull() ) return;
if( !_paintEnabled ) return;
// get rect
QRect rect = event->rect();
if( !rect.isValid() ) rect = this->rect();
// local pixmap
const bool paintOnWidget( testFlag( PaintOnWidget ) && !testFlag( Transparent ) );
if( !paintOnWidget )
{
if( _currentPixmap.isNull() || _currentPixmap.size() != size() )
{ _currentPixmap = QPixmap( size() ); }
}
// fill
_currentPixmap.fill( Qt::transparent );
// copy local pixmap to current
{
QPainter p;
// draw end pixmap first, provided that opacity is small enough
if( opacity() >= 0.004 && !_endPixmap.isNull() )
{
// faded endPixmap if parent target is transparent and opacity is
if( opacity() <= 0.996 && testFlag( Transparent ) )
{
fade( _endPixmap, _currentPixmap, opacity(), rect );
p.begin( &_currentPixmap );
p.setClipRect( event->rect() );
} else {
if( paintOnWidget ) p.begin( this );
else p.begin( &_currentPixmap );
p.setClipRect( event->rect() );
p.drawPixmap( QPoint(), _endPixmap );
}
} else {
if( paintOnWidget ) p.begin( this );
else p.begin( &_currentPixmap );
p.setClipRect( event->rect() );
}
// draw fading start pixmap
if( opacity() <= 0.996 && !_startPixmap.isNull() )
{
if( opacity() >= 0.004 )
{
fade( _startPixmap, _localStartPixmap, 1.0-opacity(), rect );
p.drawPixmap( QPoint(), _localStartPixmap );
} else p.drawPixmap( QPoint(), _startPixmap );
}
p.end();
}
// copy current pixmap on widget
if( !paintOnWidget )
{
QPainter p( this );
p.setClipRect( event->rect() );
p.drawPixmap( QPoint(0,0), _currentPixmap );
p.end();
}
}
//________________________________________________
void TransitionWidget::grabBackground( QPixmap& pixmap, QWidget* widget, QRect& rect ) const
{
if( !widget ) return;
QWidgetList widgets;
if( widget->autoFillBackground() )
{ widgets.push_back( widget ); }
QWidget *parent(0);
// get highest level parent
for( parent = widget->parentWidget(); parent; parent = parent->parentWidget() )
{
if( !( parent->isVisible() && parent->rect().isValid() ) ) continue;
// store in list
widgets.push_back( parent );
// stop at topLevel
if( parent->isTopLevel() || parent->autoFillBackground() ) break;
}
if( !parent ) parent = widget;
// painting
QPainter p(&pixmap);
p.setClipRect( rect );
const QBrush backgroundBrush = parent->palette().brush( parent->backgroundRole());
if( backgroundBrush.style() == Qt::TexturePattern)
{
p.drawTiledPixmap( rect, backgroundBrush.texture(), widget->mapTo( parent, rect.topLeft() ) );
} else {
p.fillRect( pixmap.rect(), backgroundBrush );
}
if( parent->isTopLevel() && parent->testAttribute(Qt::WA_StyledBackground))
{
QStyleOption option;
option.initFrom(parent);
option.rect = rect;
option.rect.translate( widget->mapTo( parent, rect.topLeft() ) );
p.translate(-option.rect.topLeft());
parent->style()->drawPrimitive ( QStyle::PE_Widget, &option, &p, parent );
}
p.end();
// draw all widgets in parent list
// backward
QPaintEvent event(rect);
for( int i = widgets.size() - 1; i>=0; i-- )
{
QWidget* w = widgets.at(i);
QPainter::setRedirected( w, &pixmap, widget->mapTo(w, rect.topLeft() ) );
event = QPaintEvent(QRect( QPoint(), rect.size()));
QCoreApplication::sendEvent(w, &event);
QPainter::restoreRedirected(w);
}
}
//________________________________________________
void TransitionWidget::grabWidget( QPixmap& pixmap, QWidget* widget, QRect& rect ) const
{ widget->render( &pixmap, pixmap.rect().topLeft(), rect, QWidget::DrawChildren ); }
//________________________________________________
void TransitionWidget::fade( const QPixmap& source, QPixmap& target, qreal opacity, const QRect& rect ) const
{
if( target.isNull() || target.size() != size() )
{ target = QPixmap( size() ); }
// erase target
target.fill( Qt::transparent );
// check opacity
if( opacity*255 < 1 ) return;
QPainter p( &target );
p.setClipRect( rect );
// draw pixmap
p.drawPixmap( QPoint(0,0), source );
// opacity mask (0.996 corresponds to 254/255)
if( opacity <= 0.996 )
{
p.setCompositionMode(QPainter::CompositionMode_DestinationIn);
QColor color( Qt::black );
color.setAlphaF( opacity );
p.fillRect(rect, color );
}
p.end();
return;
}
}
<commit_msg>Replace deprecated in Qt4 and ignored in Qt5 setRedirected() call with render()<commit_after>//////////////////////////////////////////////////////////////////////////////
// oxygentransitionwidget.cpp
// stores event filters and maps widgets to transitions for transitions
// -------------------
//
// Copyright (c) 2009 Hugo Pereira Da Costa <hugo.pereira@free.fr>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//////////////////////////////////////////////////////////////////////////////
#include "oxygentransitionwidget.h"
#include <cassert>
#include <QtGui/QPainter>
#include <QtGui/QPaintEvent>
#include <QStyleOption>
#include <QtCore/QCoreApplication>
#include <QtCore/QTextStream>
namespace Oxygen
{
//________________________________________________
bool TransitionWidget::_paintEnabled = true;
bool TransitionWidget::paintEnabled( void )
{ return _paintEnabled; }
int TransitionWidget::_steps = 0;
//________________________________________________
TransitionWidget::TransitionWidget( QWidget* parent, int duration ):
QWidget( parent ),
_flags( None ),
_animation( new Animation( duration, this ) ),
_opacity( 0 )
{
// background flags
setAttribute(Qt::WA_NoSystemBackground );
setAutoFillBackground( false );
// setup animation
_animation.data()->setStartValue( 0 );
_animation.data()->setEndValue( 1.0 );
_animation.data()->setTargetObject( this );
_animation.data()->setPropertyName( "opacity" );
// setup connections
connect( _animation.data(), SIGNAL(finished()), SIGNAL(finished()) );
}
//________________________________________________
QPixmap TransitionWidget::grab( QWidget* widget, QRect rect )
{
// change rect
if( !rect.isValid() ) rect = widget->rect();
if( !rect.isValid() ) return QPixmap();
// initialize pixmap
QPixmap out( rect.size() );
out.fill( Qt::transparent );
_paintEnabled = false;
if( testFlag( GrabFromWindow ) )
{
rect = rect.translated( widget->mapTo( widget->window(), widget->rect().topLeft() ) );
widget = widget->window();
out = QPixmap::grabWidget( widget, rect );
} else {
if( !testFlag( Transparent ) ) { grabBackground( out, widget, rect ); }
grabWidget( out, widget, rect );
}
_paintEnabled = true;
return out;
}
//________________________________________________
void TransitionWidget::paintEvent( QPaintEvent* event )
{
// fully transparent case
if( opacity() >= 1.0 && endPixmap().isNull() ) return;
if( !_paintEnabled ) return;
// get rect
QRect rect = event->rect();
if( !rect.isValid() ) rect = this->rect();
// local pixmap
const bool paintOnWidget( testFlag( PaintOnWidget ) && !testFlag( Transparent ) );
if( !paintOnWidget )
{
if( _currentPixmap.isNull() || _currentPixmap.size() != size() )
{ _currentPixmap = QPixmap( size() ); }
}
// fill
_currentPixmap.fill( Qt::transparent );
// copy local pixmap to current
{
QPainter p;
// draw end pixmap first, provided that opacity is small enough
if( opacity() >= 0.004 && !_endPixmap.isNull() )
{
// faded endPixmap if parent target is transparent and opacity is
if( opacity() <= 0.996 && testFlag( Transparent ) )
{
fade( _endPixmap, _currentPixmap, opacity(), rect );
p.begin( &_currentPixmap );
p.setClipRect( event->rect() );
} else {
if( paintOnWidget ) p.begin( this );
else p.begin( &_currentPixmap );
p.setClipRect( event->rect() );
p.drawPixmap( QPoint(), _endPixmap );
}
} else {
if( paintOnWidget ) p.begin( this );
else p.begin( &_currentPixmap );
p.setClipRect( event->rect() );
}
// draw fading start pixmap
if( opacity() <= 0.996 && !_startPixmap.isNull() )
{
if( opacity() >= 0.004 )
{
fade( _startPixmap, _localStartPixmap, 1.0-opacity(), rect );
p.drawPixmap( QPoint(), _localStartPixmap );
} else p.drawPixmap( QPoint(), _startPixmap );
}
p.end();
}
// copy current pixmap on widget
if( !paintOnWidget )
{
QPainter p( this );
p.setClipRect( event->rect() );
p.drawPixmap( QPoint(0,0), _currentPixmap );
p.end();
}
}
//________________________________________________
void TransitionWidget::grabBackground( QPixmap& pixmap, QWidget* widget, QRect& rect ) const
{
if( !widget ) return;
QWidgetList widgets;
if( widget->autoFillBackground() )
{ widgets.push_back( widget ); }
QWidget *parent(0);
// get highest level parent
for( parent = widget->parentWidget(); parent; parent = parent->parentWidget() )
{
if( !( parent->isVisible() && parent->rect().isValid() ) ) continue;
// store in list
widgets.push_back( parent );
// stop at topLevel
if( parent->isTopLevel() || parent->autoFillBackground() ) break;
}
if( !parent ) parent = widget;
// painting
QPainter p(&pixmap);
p.setClipRect( rect );
const QBrush backgroundBrush = parent->palette().brush( parent->backgroundRole());
if( backgroundBrush.style() == Qt::TexturePattern)
{
p.drawTiledPixmap( rect, backgroundBrush.texture(), widget->mapTo( parent, rect.topLeft() ) );
} else {
p.fillRect( pixmap.rect(), backgroundBrush );
}
if( parent->isTopLevel() && parent->testAttribute(Qt::WA_StyledBackground))
{
QStyleOption option;
option.initFrom(parent);
option.rect = rect;
option.rect.translate( widget->mapTo( parent, rect.topLeft() ) );
p.translate(-option.rect.topLeft());
parent->style()->drawPrimitive ( QStyle::PE_Widget, &option, &p, parent );
p.translate(option.rect.topLeft());
}
// draw all widgets in parent list
// backward
QPaintEvent event(rect);
for( int i = widgets.size() - 1; i>=0; i-- )
{
QWidget* w = widgets.at(i);
w->render(&p,-widget->mapTo(w,rect.topLeft()),rect,0);
}
}
//________________________________________________
void TransitionWidget::grabWidget( QPixmap& pixmap, QWidget* widget, QRect& rect ) const
{ widget->render( &pixmap, pixmap.rect().topLeft(), rect, QWidget::DrawChildren ); }
//________________________________________________
void TransitionWidget::fade( const QPixmap& source, QPixmap& target, qreal opacity, const QRect& rect ) const
{
if( target.isNull() || target.size() != size() )
{ target = QPixmap( size() ); }
// erase target
target.fill( Qt::transparent );
// check opacity
if( opacity*255 < 1 ) return;
QPainter p( &target );
p.setClipRect( rect );
// draw pixmap
p.drawPixmap( QPoint(0,0), source );
// opacity mask (0.996 corresponds to 254/255)
if( opacity <= 0.996 )
{
p.setCompositionMode(QPainter::CompositionMode_DestinationIn);
QColor color( Qt::black );
color.setAlphaF( opacity );
p.fillRect(rect, color );
}
p.end();
return;
}
}
<|endoftext|> |
<commit_before>/*
* This program source code file is part of KICAD, a free EDA CAD application.
*
* Copyright (C) 1992-2010 jean-pierre.charras
* Copyright (C) 1992-2010 Kicad Developers, see change_log.txt for contributors.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, you may find one here:
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
* or you may search the http://www.gnu.org website for the version 2 license,
* or you may write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
*/
#include "wx/wx.h"
#include "wx/config.h"
#include "bitmap2cmp_gui_base.h"
#include "potracelib.h"
#include "bitmap_io.h"
#include "bitmap2component.xpm"
#define KEYWORD_FRAME_POSX wxT( "bmconverter_Pos_x" )
#define KEYWORD_FRAME_POSY wxT( "bmconverter_Pos_y" )
#define KEYWORD_FRAME_SIZEX wxT( "bmconverter_Size_x" )
#define KEYWORD_FRAME_SIZEY wxT( "bmconverter_Size_y" )
extern int bitmap2component( potrace_bitmap_t* aPotrace_bitmap, FILE* aOutfile, int aFormat );
/* Class BM2CMP_FRAME_BASE
This is the main frame for this application
*/
class BM2CMP_FRAME : public BM2CMP_FRAME_BASE
{
private:
wxImage m_Pict_Image;
wxBitmap m_Pict_Bitmap;
wxImage m_Greyscale_Image;
wxBitmap m_Greyscale_Bitmap;
wxImage m_NB_Image;
wxBitmap m_BN_Bitmap;
wxString m_ImgFileName;
wxSize m_FrameSize;
wxPoint m_FramePos;
wxConfig * m_Config;
public:
BM2CMP_FRAME();
~BM2CMP_FRAME();
private:
// Event handlers
void OnPaint( wxPaintEvent& event );
void OnLoadFile( wxCommandEvent& event );
void OnExportEeschema( wxCommandEvent& event );
void OnExportPcbnew( wxCommandEvent& event );
void Binarize( int aThreshold );
void OnOptionsSelection( wxCommandEvent& event );
void OnThresholdChange( wxScrollEvent& event );
void NegateGreyscaleImage( );
void ExportFile( FILE* aOutfile, int aFormat );
};
BM2CMP_FRAME::BM2CMP_FRAME() : BM2CMP_FRAME_BASE( NULL )
{
m_Config = new wxConfig();
m_Config->Read( KEYWORD_FRAME_POSX, & m_FramePos.x, -1 );
m_Config->Read( KEYWORD_FRAME_POSY, & m_FramePos.y, -1 );
m_Config->Read( KEYWORD_FRAME_SIZEX, & m_FrameSize.x, -1 );
m_Config->Read( KEYWORD_FRAME_SIZEY, & m_FrameSize.y, -1 );
#ifdef __WINDOWS__
SetIcon( wxICON( bitmap2component_icon ) );
#else
SetIcon( wxICON( bitmap2component ) );
#endif
wxString msg( wxT( "000000" ) );
m_gridInfo->SetCellValue( 1, 0, msg );
m_gridInfo->SetCellValue( 2, 0, msg );
if( GetSizer() )
{
GetSizer()->SetSizeHints( this );
}
SetSize( m_FramePos.x, m_FramePos.y, m_FrameSize.x, m_FrameSize.y );
if ( m_FramePos == wxDefaultPosition )
Centre();
}
BM2CMP_FRAME::~BM2CMP_FRAME()
{
if( ( m_Config == NULL ) || IsIconized() )
return;
m_FrameSize = GetSize();
m_FramePos = GetPosition();
m_Config->Write( KEYWORD_FRAME_POSX, (long) m_FramePos.x );
m_Config->Write( KEYWORD_FRAME_POSY, (long) m_FramePos.y );
m_Config->Write( KEYWORD_FRAME_SIZEX, (long) m_FrameSize.x );
m_Config->Write( KEYWORD_FRAME_SIZEY, (long) m_FrameSize.y );
delete m_Config;
/* This needed for OSX: avoids furter OnDraw processing after this
* destructor and before the native window is destroyed
*/
this->Freeze( );
}
void BM2CMP_FRAME::OnPaint( wxPaintEvent& event )
{
wxPaintDC pict_dc( m_InitialPicturePanel );
wxPaintDC greyscale_dc( m_GreyscalePicturePanel );
wxPaintDC nb_dc( m_BNPicturePanel );
m_InitialPicturePanel->PrepareDC( pict_dc );
m_GreyscalePicturePanel->PrepareDC( greyscale_dc );
m_BNPicturePanel->PrepareDC( nb_dc );
pict_dc.DrawBitmap( m_Pict_Bitmap, 0, 0, false );
greyscale_dc.DrawBitmap( m_Greyscale_Bitmap, 0, 0, false );
nb_dc.DrawBitmap( m_BN_Bitmap, 0, 0, false );
}
/* Called to load a bitmap file
*/
void BM2CMP_FRAME::OnLoadFile( wxCommandEvent& event )
{
wxFileDialog FileDlg( this, _( "Choose Image" ), ::wxGetCwd(), wxEmptyString,
_( "Image Files " ) + wxImage::GetImageExtWildcard(),
wxFD_OPEN );
int diag = FileDlg.ShowModal();
if( diag != wxID_OK )
return;
m_ImgFileName = FileDlg.GetPath();
if( !m_Pict_Image.LoadFile( m_ImgFileName ) )
{
wxMessageBox( _( "Couldn't load image from '%s'." ), m_ImgFileName.c_str() );
return;
}
m_Pict_Bitmap = wxBitmap( m_Pict_Image );
int h = m_Pict_Bitmap.GetHeight();
int w = m_Pict_Bitmap.GetWidth();
int nb = m_Pict_Bitmap.GetDepth();
wxString msg;
msg.Printf( wxT( "%d" ), h );
m_gridInfo->SetCellValue( 0, 0, msg );
msg.Printf( wxT( "%d" ), w );
m_gridInfo->SetCellValue( 1, 0, msg );
msg.Printf( wxT( "%d" ), nb );
m_gridInfo->SetCellValue( 2, 0, msg );
m_InitialPicturePanel->SetVirtualSize( w, h );
m_GreyscalePicturePanel->SetVirtualSize( w, h );
m_BNPicturePanel->SetVirtualSize( w, h );
m_Greyscale_Image.Destroy();
m_Greyscale_Image = m_Pict_Image.ConvertToGreyscale( );
if( m_rbOptions->GetSelection() > 0 )
NegateGreyscaleImage( );
m_Greyscale_Bitmap = wxBitmap( m_Greyscale_Image );
m_NB_Image = m_Greyscale_Image;
Binarize( m_sliderThreshold->GetValue() );
Refresh();
}
void BM2CMP_FRAME::Binarize( int aThreshold )
{
unsigned int pixin;
unsigned char pixout;
int h = m_Greyscale_Image.GetHeight();
int w = m_Greyscale_Image.GetWidth();
unsigned int threshold = (aThreshold * 256) / 10;
for( int y = 1; y < h; y++ )
for( int x = 1; x < w; x++ )
{
pixin = m_Greyscale_Image.GetGreen( x, y );
if( pixin < threshold )
pixout = 0;
else
pixout = 255;
m_NB_Image.SetRGB( x, y, pixout, pixout, pixout );
}
m_BN_Bitmap = wxBitmap( m_NB_Image );
}
void BM2CMP_FRAME::NegateGreyscaleImage( )
{
unsigned char pix;
int h = m_Greyscale_Image.GetHeight();
int w = m_Greyscale_Image.GetWidth();
for( int y = 1; y < h; y++ )
for( int x = 1; x < w; x++ )
{
pix = m_Greyscale_Image.GetGreen( x, y );
pix = ~pix;
m_Greyscale_Image.SetRGB( x, y, pix, pix, pix );
}
}
/* Called on Normal/Negative change option */
void BM2CMP_FRAME::OnOptionsSelection( wxCommandEvent& event )
{
NegateGreyscaleImage( );
m_Greyscale_Bitmap = wxBitmap( m_Greyscale_Image );
Binarize( m_sliderThreshold->GetValue() );
Refresh();
}
void BM2CMP_FRAME::OnThresholdChange( wxScrollEvent& event )
{
Binarize( m_sliderThreshold->GetValue() );
Refresh();
}
void BM2CMP_FRAME::OnExportEeschema( wxCommandEvent& event )
{
wxString msg = _( "Schematic lib file (*.lib)|*.lib" );
wxFileDialog FileDlg( this, _( "Create lib file" ), ::wxGetCwd(), wxEmptyString,
msg,
wxFD_SAVE | wxFD_OVERWRITE_PROMPT );
int diag = FileDlg.ShowModal();
if( diag != wxID_OK )
return;
wxString filename = FileDlg.GetPath();
FILE* outfile;
outfile = wxFopen( filename, wxT( "w" ) );
if( outfile == NULL )
{
wxString msg;
msg.Printf( _( "File %s could not be created" ), filename.c_str() );
wxMessageBox( msg );
return;
}
ExportFile( outfile, 1 );
fclose( outfile );
}
void BM2CMP_FRAME::OnExportPcbnew( wxCommandEvent& event )
{
wxString msg = _( "Footprint export file (*.emp)|*.emp" );
wxFileDialog FileDlg( this, _( "Create footprint export file" ), ::wxGetCwd(), wxEmptyString,
msg,
wxFD_SAVE | wxFD_OVERWRITE_PROMPT );
int diag = FileDlg.ShowModal();
if( diag != wxID_OK )
return;
wxString filename = FileDlg.GetPath();
FILE* outfile;
outfile = wxFopen( filename, wxT( "w" ) );
if( outfile == NULL )
{
wxString msg;
msg.Printf( _( "File %s could not be created" ), filename.c_str() );
wxMessageBox( msg );
return;
}
ExportFile( outfile, 0 );
fclose( outfile );
}
void BM2CMP_FRAME::ExportFile( FILE* aOutfile, int aFormat )
{
// Create a potrace bitmap
int h = m_NB_Image.GetHeight();
int w = m_NB_Image.GetWidth();
potrace_bitmap_t* potrace_bitmap = bm_new( w, h );
if( !potrace_bitmap )
{
wxString msg;
msg.Printf( wxT( "Error allocating memory for potrace bitmap" ) );
wxMessageBox( msg );
return;
}
/* fill the bitmap with data */
for( int y = 0; y<h; y++ )
{
for( int x = 0; x<w; x++ )
{
unsigned char pix = m_NB_Image.GetGreen( x, y );
BM_PUT( potrace_bitmap, x, y, pix ? 1 : 0 );
}
}
bitmap2component( potrace_bitmap, aOutfile, aFormat );
}
// BM_TO_CMP_APP
class BM_TO_CMP_APP : public wxApp
{
public:
virtual bool OnInit();
};
IMPLEMENT_APP( BM_TO_CMP_APP )
///-----------------------------------------------------------------------------
// BM_TO_CMP_APP
// main program
//-----------------------------------------------------------------------------
bool BM_TO_CMP_APP::OnInit()
{
wxInitAllImageHandlers();
SetVendorName( wxT( "kicad" ) );
wxFrame* frame = new BM2CMP_FRAME();
frame->Show( true );
return true;
}
<commit_msg>minor enhancement<commit_after>/*
* This program source code file is part of KICAD, a free EDA CAD application.
*
* Copyright (C) 1992-2010 jean-pierre.charras
* Copyright (C) 1992-2010 Kicad Developers, see change_log.txt for contributors.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, you may find one here:
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
* or you may search the http://www.gnu.org website for the version 2 license,
* or you may write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
*/
#include "wx/wx.h"
#include "wx/config.h"
#include "wx/filename.h"
#include "bitmap2cmp_gui_base.h"
#include "potracelib.h"
#include "bitmap_io.h"
#include "bitmap2component.xpm"
#define KEYWORD_FRAME_POSX wxT( "Bmconverter_Pos_x" )
#define KEYWORD_FRAME_POSY wxT( "Bmconverter_Pos_y" )
#define KEYWORD_FRAME_SIZEX wxT( "Bmconverter_Size_x" )
#define KEYWORD_FRAME_SIZEY wxT( "Bmconverter_Size_y" )
#define KEYWORD_LAST_INPUT_FILE wxT( "Last_input" )
#define KEYWORD_LAST_OUTPUT_FILE wxT( "Last_output" )
extern int bitmap2component( potrace_bitmap_t* aPotrace_bitmap, FILE* aOutfile, int aFormat );
/* Class BM2CMP_FRAME_BASE
This is the main frame for this application
*/
class BM2CMP_FRAME : public BM2CMP_FRAME_BASE
{
private:
wxImage m_Pict_Image;
wxBitmap m_Pict_Bitmap;
wxImage m_Greyscale_Image;
wxBitmap m_Greyscale_Bitmap;
wxImage m_NB_Image;
wxBitmap m_BN_Bitmap;
wxString m_BitmapFileName;
wxString m_ConvertedFileName;
wxSize m_FrameSize;
wxPoint m_FramePos;
wxConfig * m_Config;
public:
BM2CMP_FRAME();
~BM2CMP_FRAME();
private:
// Event handlers
void OnPaint( wxPaintEvent& event );
void OnLoadFile( wxCommandEvent& event );
void OnExportEeschema( wxCommandEvent& event );
void OnExportPcbnew( wxCommandEvent& event );
void Binarize( int aThreshold );
void OnOptionsSelection( wxCommandEvent& event );
void OnThresholdChange( wxScrollEvent& event );
void NegateGreyscaleImage( );
void ExportFile( FILE* aOutfile, int aFormat );
};
BM2CMP_FRAME::BM2CMP_FRAME() : BM2CMP_FRAME_BASE( NULL )
{
m_Config = new wxConfig();
m_Config->Read( KEYWORD_FRAME_POSX, & m_FramePos.x, -1 );
m_Config->Read( KEYWORD_FRAME_POSY, & m_FramePos.y, -1 );
m_Config->Read( KEYWORD_FRAME_SIZEX, & m_FrameSize.x, -1 );
m_Config->Read( KEYWORD_FRAME_SIZEY, & m_FrameSize.y, -1 );
m_Config->Read( KEYWORD_LAST_INPUT_FILE, &m_BitmapFileName );
m_Config->Read( KEYWORD_LAST_OUTPUT_FILE, &m_ConvertedFileName );
#ifdef __WINDOWS__
SetIcon( wxICON( bitmap2component_icon ) );
#else
SetIcon( wxICON( bitmap2component ) );
#endif
wxString msg( wxT( "000000" ) );
m_gridInfo->SetCellValue( 0, 0, msg );
m_gridInfo->SetCellValue( 1, 0, msg );
if( GetSizer() )
{
GetSizer()->SetSizeHints( this );
}
SetSize( m_FramePos.x, m_FramePos.y, m_FrameSize.x, m_FrameSize.y );
if ( m_FramePos == wxDefaultPosition )
Centre();
}
BM2CMP_FRAME::~BM2CMP_FRAME()
{
if( ( m_Config == NULL ) || IsIconized() )
return;
m_FrameSize = GetSize();
m_FramePos = GetPosition();
m_Config->Write( KEYWORD_FRAME_POSX, (long) m_FramePos.x );
m_Config->Write( KEYWORD_FRAME_POSY, (long) m_FramePos.y );
m_Config->Write( KEYWORD_FRAME_SIZEX, (long) m_FrameSize.x );
m_Config->Write( KEYWORD_FRAME_SIZEY, (long) m_FrameSize.y );
m_Config->Write( KEYWORD_LAST_INPUT_FILE, m_BitmapFileName );
m_Config->Write( KEYWORD_LAST_OUTPUT_FILE, m_ConvertedFileName );
delete m_Config;
/* This needed for OSX: avoids furter OnDraw processing after this
* destructor and before the native window is destroyed
*/
this->Freeze( );
}
void BM2CMP_FRAME::OnPaint( wxPaintEvent& event )
{
wxPaintDC pict_dc( m_InitialPicturePanel );
wxPaintDC greyscale_dc( m_GreyscalePicturePanel );
wxPaintDC nb_dc( m_BNPicturePanel );
m_InitialPicturePanel->PrepareDC( pict_dc );
m_GreyscalePicturePanel->PrepareDC( greyscale_dc );
m_BNPicturePanel->PrepareDC( nb_dc );
pict_dc.DrawBitmap( m_Pict_Bitmap, 0, 0, false );
greyscale_dc.DrawBitmap( m_Greyscale_Bitmap, 0, 0, false );
nb_dc.DrawBitmap( m_BN_Bitmap, 0, 0, false );
}
/* Called to load a bitmap file
*/
void BM2CMP_FRAME::OnLoadFile( wxCommandEvent& event )
{
wxFileName fn(m_BitmapFileName);
wxString path = fn.GetPath();
if( path.IsEmpty() || !wxDirExists(path) )
path = wxGetCwd();
wxFileDialog FileDlg( this, _( "Choose Image" ), path, wxEmptyString,
_( "Image Files " ) + wxImage::GetImageExtWildcard(),
wxFD_OPEN );
int diag = FileDlg.ShowModal();
if( diag != wxID_OK )
return;
m_BitmapFileName = FileDlg.GetPath();
if( !m_Pict_Image.LoadFile( m_BitmapFileName ) )
{
wxMessageBox( _( "Couldn't load image from <%s>" ), m_BitmapFileName.c_str() );
return;
}
m_Pict_Bitmap = wxBitmap( m_Pict_Image );
int h = m_Pict_Bitmap.GetHeight();
int w = m_Pict_Bitmap.GetWidth();
int nb = m_Pict_Bitmap.GetDepth();
wxString msg;
msg.Printf( wxT( "%d" ), h );
m_gridInfo->SetCellValue( 0, 0, msg );
msg.Printf( wxT( "%d" ), w );
m_gridInfo->SetCellValue( 1, 0, msg );
msg.Printf( wxT( "%d" ), nb );
m_gridInfo->SetCellValue( 2, 0, msg );
m_InitialPicturePanel->SetVirtualSize( w, h );
m_GreyscalePicturePanel->SetVirtualSize( w, h );
m_BNPicturePanel->SetVirtualSize( w, h );
m_Greyscale_Image.Destroy();
m_Greyscale_Image = m_Pict_Image.ConvertToGreyscale( );
if( m_rbOptions->GetSelection() > 0 )
NegateGreyscaleImage( );
m_Greyscale_Bitmap = wxBitmap( m_Greyscale_Image );
m_NB_Image = m_Greyscale_Image;
Binarize( m_sliderThreshold->GetValue() );
Refresh();
}
void BM2CMP_FRAME::Binarize( int aThreshold )
{
unsigned int pixin;
unsigned char pixout;
int h = m_Greyscale_Image.GetHeight();
int w = m_Greyscale_Image.GetWidth();
unsigned int threshold = (aThreshold * 256) / 10;
for( int y = 1; y < h; y++ )
for( int x = 1; x < w; x++ )
{
pixin = m_Greyscale_Image.GetGreen( x, y );
if( pixin < threshold )
pixout = 0;
else
pixout = 255;
m_NB_Image.SetRGB( x, y, pixout, pixout, pixout );
}
m_BN_Bitmap = wxBitmap( m_NB_Image );
}
void BM2CMP_FRAME::NegateGreyscaleImage( )
{
unsigned char pix;
int h = m_Greyscale_Image.GetHeight();
int w = m_Greyscale_Image.GetWidth();
for( int y = 1; y < h; y++ )
for( int x = 1; x < w; x++ )
{
pix = m_Greyscale_Image.GetGreen( x, y );
pix = ~pix;
m_Greyscale_Image.SetRGB( x, y, pix, pix, pix );
}
}
/* Called on Normal/Negative change option */
void BM2CMP_FRAME::OnOptionsSelection( wxCommandEvent& event )
{
NegateGreyscaleImage( );
m_Greyscale_Bitmap = wxBitmap( m_Greyscale_Image );
Binarize( m_sliderThreshold->GetValue() );
Refresh();
}
void BM2CMP_FRAME::OnThresholdChange( wxScrollEvent& event )
{
Binarize( m_sliderThreshold->GetValue() );
Refresh();
}
void BM2CMP_FRAME::OnExportEeschema( wxCommandEvent& event )
{
wxFileName fn(m_ConvertedFileName);
wxString path = fn.GetPath();
if( path.IsEmpty() || !wxDirExists(path) )
path = ::wxGetCwd();
wxString msg = _( "Schematic lib file (*.lib)|*.lib" );
wxFileDialog FileDlg( this, _( "Create lib file" ), path, wxEmptyString,
msg,
wxFD_SAVE | wxFD_OVERWRITE_PROMPT );
int diag = FileDlg.ShowModal();
if( diag != wxID_OK )
return;
m_ConvertedFileName = FileDlg.GetPath();
FILE* outfile;
outfile = wxFopen( m_ConvertedFileName, wxT( "w" ) );
if( outfile == NULL )
{
wxString msg;
msg.Printf( _( "File %s could not be created" ), m_ConvertedFileName.c_str() );
wxMessageBox( msg );
return;
}
ExportFile( outfile, 1 );
fclose( outfile );
}
void BM2CMP_FRAME::OnExportPcbnew( wxCommandEvent& event )
{
wxFileName fn(m_ConvertedFileName);
wxString path = fn.GetPath();
if( path.IsEmpty() || !wxDirExists(path) )
path = ::wxGetCwd();
wxString msg = _( "Footprint export file (*.emp)|*.emp" );
wxFileDialog FileDlg( this, _( "Create footprint export file" ), path, wxEmptyString,
msg,
wxFD_SAVE | wxFD_OVERWRITE_PROMPT );
int diag = FileDlg.ShowModal();
if( diag != wxID_OK )
return;
m_ConvertedFileName = FileDlg.GetPath();
FILE* outfile;
outfile = wxFopen( m_ConvertedFileName, wxT( "w" ) );
if( outfile == NULL )
{
wxString msg;
msg.Printf( _( "File %s could not be created" ), m_ConvertedFileName.c_str() );
wxMessageBox( msg );
return;
}
ExportFile( outfile, 0 );
fclose( outfile );
}
void BM2CMP_FRAME::ExportFile( FILE* aOutfile, int aFormat )
{
// Create a potrace bitmap
int h = m_NB_Image.GetHeight();
int w = m_NB_Image.GetWidth();
potrace_bitmap_t* potrace_bitmap = bm_new( w, h );
if( !potrace_bitmap )
{
wxString msg;
msg.Printf( wxT( "Error allocating memory for potrace bitmap" ) );
wxMessageBox( msg );
return;
}
/* fill the bitmap with data */
for( int y = 0; y<h; y++ )
{
for( int x = 0; x<w; x++ )
{
unsigned char pix = m_NB_Image.GetGreen( x, y );
BM_PUT( potrace_bitmap, x, y, pix ? 1 : 0 );
}
}
bitmap2component( potrace_bitmap, aOutfile, aFormat );
}
// BM_TO_CMP_APP
class BM_TO_CMP_APP : public wxApp
{
public:
virtual bool OnInit();
};
IMPLEMENT_APP( BM_TO_CMP_APP )
///-----------------------------------------------------------------------------
// BM_TO_CMP_APP
// main program
//-----------------------------------------------------------------------------
bool BM_TO_CMP_APP::OnInit()
{
wxInitAllImageHandlers();
SetVendorName( wxT( "kicad" ) );
wxFrame* frame = new BM2CMP_FRAME();
frame->Show( true );
return true;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: partwnd.cxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: as $ $Date: 2001-11-28 11:22:48 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
// includes ******************************************************************
#ifndef _COM_SUN_STAR_AWT_XWINDOW_HPP_
#include <com/sun/star/awt/XWindow.hpp>
#endif
#ifndef _COM_SUN_STAR_TASK_XSTATUSINDICATOR_HPP_
#include <com/sun/star/task/XStatusIndicator.hpp>
#endif
#ifndef _COM_SUN_STAR_UNO_REFERENCE_H_
#include <com/sun/star/uno/Reference.h>
#endif
#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_
#include <com/sun/star/uno/Sequence.hxx>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_URL_HPP_
#include <com/sun/star/util/URL.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XFRAME_HPP_
#include <com/sun/star/frame/XFrame.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XCONTROLLER_HPP_
#include <com/sun/star/frame/XController.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_POSSIZE_HPP_
#include <com/sun/star/awt/PosSize.hpp>
#endif
#ifndef _UNOTOOLS_PROCESSFACTORY_HXX
#include <comphelper/processfactory.hxx>
#endif
#include <toolkit/helper/vclunohelper.hxx>
#include "sfxsids.hrc"
#include "partwnd.hxx"
#include "bindings.hxx"
#include "dispatch.hxx"
#include "viewfrm.hxx"
#include "frame.hxx"
#include "sfxuno.hxx"
/*
// class SfxPartwinFrame_Impl ------------------------------------------
class SfxPartwinFrame_Impl : public SfxUnoFrame
{
public:
SfxPopupStatusIndicator* pIndicator;
SfxPartDockWnd_Impl* pBeamer;
virtual void SAL_CALL initialize(const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindow > & aPeer) throw ( ::com::sun::star::uno::RuntimeException );
virtual SfxFrame* CreateFrame( Window* pParent );
virtual ::com::sun::star::uno::Reference< ::com::sun::star::task::XStatusIndicator > SAL_CALL getStatusIndicator(void) throw ( ::com::sun::star::uno::RuntimeException );
void dispatch_Impl( const ::com::sun::star::util::URL& aURL, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& aArgs );
};
// -----------------------------------------------------------------------
::com::sun::star::uno::Reference< ::com::sun::star::task::XStatusIndicator > SAL_CALL SfxPartwinFrame_Impl::getStatusIndicator(void) throw ( ::com::sun::star::uno::RuntimeException )
{
return pIndicator->GetInterface();
}
void SfxPartwinFrame_Impl::dispatch_Impl( const ::com::sun::star::util::URL& rURL, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& rArgs )
{
if ( !pBeamer )
return;
if ( rURL.Protocol.compareToAscii(".uno:") == 0 )
{
if ( rURL.Path.compareToAscii("Reload") == 0)
{
SfxUnoFrame::dispatch_Impl( rURL, rArgs );
if ( pBeamer->IsAutoHide_Impl() )
pBeamer->AutoShow_Impl( sal_True );
return;
}
}
else
SfxUnoFrame::dispatch_Impl( rURL, rArgs );
if ( rURL.Complete.len() )
{
if ( pBeamer->IsAutoHide_Impl() )
pBeamer->AutoShow_Impl( sal_True );
}
else
{
::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame > xTmp( this );
SfxApplication* pApp = SFX_APP();
pApp->SetChildWindow( SID_BROWSER, sal_False );
pApp->GetBindings().Invalidate( SID_BROWSER );
}
}
// -----------------------------------------------------------------------
void SAL_CALL SfxPartwinFrame_Impl::initialize( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindow > & aWindow ) throw ( ::com::sun::star::uno::RuntimeException )
{
setName( rtl::OUString::createFromAscii("_partwindow") );
SetContainerWindow_Impl( aWindow );
}
// -----------------------------------------------------------------------
SfxFrame* SfxPartwinFrame_Impl::CreateFrame( Window* pParent )
{
return NULL;
}
*/
//****************************************************************************
// SfxPartChildWnd_Impl
//****************************************************************************
SFX_IMPL_DOCKINGWINDOW( SfxPartChildWnd_Impl, SID_BROWSER );
SfxPartChildWnd_Impl::SfxPartChildWnd_Impl
(
Window* pParent,
sal_uInt16 nId,
SfxBindings* pBindings,
SfxChildWinInfo* pInfo
)
: SfxChildWindow( pParent, nId )
{
// Window erzeugen
pWindow = new SfxPartDockWnd_Impl( pBindings, this, pParent, WB_STDDOCKWIN | WB_CLIPCHILDREN | WB_SIZEABLE | WB_3DLOOK );
eChildAlignment = SFX_ALIGN_TOP;
((SfxDockingWindow*)pWindow)->SetFloatingSize( Size( 240, 240 ) );
pWindow->SetSizePixel( Size( 240, 240 ) );
( ( SfxDockingWindow* ) pWindow )->Initialize( pInfo );
}
SfxPartChildWnd_Impl::~SfxPartChildWnd_Impl()
{
::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame > xFrame = GetFrame();
// If xFrame=NULL release pMgr! Because this window lives longer then the manager!
// In these case we got a xFrame->dispose() call from outside ... and has release our
// frame reference in our own DisposingListener.
// But don't do it, if xFrame already exist. Then dispose() must come from inside ...
// and we need a valid pMgr for further operations ...
SfxPartDockWnd_Impl* pWin = (SfxPartDockWnd_Impl*) pWindow;
if( pWin != NULL && !xFrame.is() )
pWin->ReleaseChildWindow_Impl();
// Release frame and window.
// If frame reference is valid here ... start dieing from inside by calling dispose().
SetFrame( NULL );
pWindow = NULL;
if( xFrame.is() )
xFrame->dispose();
}
sal_Bool SfxPartChildWnd_Impl::QueryClose()
{
return ( (SfxPartDockWnd_Impl*)pWindow )->QueryClose();
}
//****************************************************************************
// SfxPartDockWnd_Impl
//****************************************************************************
SfxPartDockWnd_Impl::SfxPartDockWnd_Impl
(
SfxBindings* pBindings,
SfxChildWindow* pChildWin,
Window* pParent,
WinBits nBits
)
: SfxDockingWindow( pBindings, pChildWin, pParent, nBits )
{
::com::sun::star::uno::Reference < ::com::sun::star::frame::XFrame > xFrame(
::comphelper::getProcessServiceFactory()->createInstance(
DEFINE_CONST_UNICODE("com.sun.star.frame.Frame") ), ::com::sun::star::uno::UNO_QUERY );
xFrame->initialize( VCLUnoHelper::GetInterface ( this ) );
pChildWin->SetFrame( xFrame );
if ( pBindings->GetDispatcher() )
{
::com::sun::star::uno::Reference < ::com::sun::star::frame::XFramesSupplier >
xSupp ( pBindings->GetDispatcher()->GetFrame()->GetFrame()->GetFrameInterface(), ::com::sun::star::uno::UNO_QUERY );
if ( xSupp.is() )
xSupp->getFrames()->append( xFrame );
}
else
DBG_ERROR("Bindings without Dispatcher!");
}
//****************************************************************************
SfxPartDockWnd_Impl::~SfxPartDockWnd_Impl()
{
}
//****************************************************************************
Rectangle impl_Rectangle_Struct2Object( const ::com::sun::star::awt::Rectangle& aRectangleStruct )
{
return Rectangle(aRectangleStruct.X,aRectangleStruct.Y,aRectangleStruct.Width,aRectangleStruct.Height);
}
void SfxPartDockWnd_Impl::Resize()
/* [Beschreibung]
Anpassung der Gr"osse der Controls an die neue Windowgr"osse
*/
{
SfxDockingWindow::Resize();
}
//****************************************************************************
sal_Bool SfxPartDockWnd_Impl::QueryClose()
{
sal_Bool bClose = sal_True;
SfxChildWindow* pChild = GetChildWindow_Impl();
if( pChild )
{
::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame > xFrame = pChild->GetFrame();
if( xFrame.is() )
{
::com::sun::star::uno::Reference< ::com::sun::star::frame::XController > xCtrl = xFrame->getController();
if( xCtrl.is() )
bClose = xCtrl->suspend( sal_True );
}
}
return bClose;
}
//****************************************************************************
long SfxPartDockWnd_Impl::Notify( NotifyEvent& rEvt )
{
if( rEvt.GetType() == EVENT_GETFOCUS )
{
SfxChildWindow* pChild = GetChildWindow_Impl();
if( pChild )
{
::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame > xFrame = pChild->GetFrame();
if( xFrame.is() )
xFrame->activate();
}
}
return SfxDockingWindow::Notify( rEvt );
}
void SfxPartDockWnd_Impl::FillInfo( SfxChildWinInfo& rInfo ) const
{
SfxDockingWindow::FillInfo( rInfo );
rInfo.bVisible = sal_False;
}
<commit_msg>#96252# 'better' beamer dispose<commit_after>/*************************************************************************
*
* $RCSfile: partwnd.cxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: as $ $Date: 2002-01-07 12:12:09 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
// includes ******************************************************************
#ifndef _COM_SUN_STAR_AWT_XWINDOW_HPP_
#include <com/sun/star/awt/XWindow.hpp>
#endif
#ifndef _COM_SUN_STAR_TASK_XSTATUSINDICATOR_HPP_
#include <com/sun/star/task/XStatusIndicator.hpp>
#endif
#ifndef _COM_SUN_STAR_UNO_REFERENCE_H_
#include <com/sun/star/uno/Reference.h>
#endif
#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_
#include <com/sun/star/uno/Sequence.hxx>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_URL_HPP_
#include <com/sun/star/util/URL.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XFRAME_HPP_
#include <com/sun/star/frame/XFrame.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XCONTROLLER_HPP_
#include <com/sun/star/frame/XController.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_POSSIZE_HPP_
#include <com/sun/star/awt/PosSize.hpp>
#endif
#ifndef _UNOTOOLS_PROCESSFACTORY_HXX
#include <comphelper/processfactory.hxx>
#endif
#include <toolkit/helper/vclunohelper.hxx>
#include "sfxsids.hrc"
#include "partwnd.hxx"
#include "bindings.hxx"
#include "dispatch.hxx"
#include "viewfrm.hxx"
#include "frame.hxx"
#include "sfxuno.hxx"
/*
// class SfxPartwinFrame_Impl ------------------------------------------
class SfxPartwinFrame_Impl : public SfxUnoFrame
{
public:
SfxPopupStatusIndicator* pIndicator;
SfxPartDockWnd_Impl* pBeamer;
virtual void SAL_CALL initialize(const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindow > & aPeer) throw ( ::com::sun::star::uno::RuntimeException );
virtual SfxFrame* CreateFrame( Window* pParent );
virtual ::com::sun::star::uno::Reference< ::com::sun::star::task::XStatusIndicator > SAL_CALL getStatusIndicator(void) throw ( ::com::sun::star::uno::RuntimeException );
void dispatch_Impl( const ::com::sun::star::util::URL& aURL, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& aArgs );
};
// -----------------------------------------------------------------------
::com::sun::star::uno::Reference< ::com::sun::star::task::XStatusIndicator > SAL_CALL SfxPartwinFrame_Impl::getStatusIndicator(void) throw ( ::com::sun::star::uno::RuntimeException )
{
return pIndicator->GetInterface();
}
void SfxPartwinFrame_Impl::dispatch_Impl( const ::com::sun::star::util::URL& rURL, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& rArgs )
{
if ( !pBeamer )
return;
if ( rURL.Protocol.compareToAscii(".uno:") == 0 )
{
if ( rURL.Path.compareToAscii("Reload") == 0)
{
SfxUnoFrame::dispatch_Impl( rURL, rArgs );
if ( pBeamer->IsAutoHide_Impl() )
pBeamer->AutoShow_Impl( sal_True );
return;
}
}
else
SfxUnoFrame::dispatch_Impl( rURL, rArgs );
if ( rURL.Complete.len() )
{
if ( pBeamer->IsAutoHide_Impl() )
pBeamer->AutoShow_Impl( sal_True );
}
else
{
::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame > xTmp( this );
SfxApplication* pApp = SFX_APP();
pApp->SetChildWindow( SID_BROWSER, sal_False );
pApp->GetBindings().Invalidate( SID_BROWSER );
}
}
// -----------------------------------------------------------------------
void SAL_CALL SfxPartwinFrame_Impl::initialize( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindow > & aWindow ) throw ( ::com::sun::star::uno::RuntimeException )
{
setName( rtl::OUString::createFromAscii("_partwindow") );
SetContainerWindow_Impl( aWindow );
}
// -----------------------------------------------------------------------
SfxFrame* SfxPartwinFrame_Impl::CreateFrame( Window* pParent )
{
return NULL;
}
*/
//****************************************************************************
// SfxPartChildWnd_Impl
//****************************************************************************
SFX_IMPL_DOCKINGWINDOW( SfxPartChildWnd_Impl, SID_BROWSER );
SfxPartChildWnd_Impl::SfxPartChildWnd_Impl
(
Window* pParent,
sal_uInt16 nId,
SfxBindings* pBindings,
SfxChildWinInfo* pInfo
)
: SfxChildWindow( pParent, nId )
{
// Window erzeugen
pWindow = new SfxPartDockWnd_Impl( pBindings, this, pParent, WB_STDDOCKWIN | WB_CLIPCHILDREN | WB_SIZEABLE | WB_3DLOOK );
eChildAlignment = SFX_ALIGN_TOP;
((SfxDockingWindow*)pWindow)->SetFloatingSize( Size( 240, 240 ) );
pWindow->SetSizePixel( Size( 240, 240 ) );
( ( SfxDockingWindow* ) pWindow )->Initialize( pInfo );
}
SfxPartChildWnd_Impl::~SfxPartChildWnd_Impl()
{
::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame > xFrame = GetFrame();
// If xFrame=NULL release pMgr! Because this window lives longer then the manager!
// In these case we got a xFrame->dispose() call from outside ... and has release our
// frame reference in our own DisposingListener.
// But don't do it, if xFrame already exist. Then dispose() must come from inside ...
// and we need a valid pMgr for further operations ...
SfxPartDockWnd_Impl* pWin = (SfxPartDockWnd_Impl*) pWindow;
if( pWin != NULL && !xFrame.is() )
pWin->ReleaseChildWindow_Impl();
// Release frame and window.
// If frame reference is valid here ... start dieing from inside by calling dispose().
SetFrame( NULL );
pWindow = NULL;
if ( pWin && xFrame == pWin->GetBindings().GetActiveFrame() )
pWin->GetBindings().SetActiveFrame( GetFrame() );
if( xFrame.is() )
xFrame->dispose();
}
sal_Bool SfxPartChildWnd_Impl::QueryClose()
{
return ( (SfxPartDockWnd_Impl*)pWindow )->QueryClose();
}
//****************************************************************************
// SfxPartDockWnd_Impl
//****************************************************************************
SfxPartDockWnd_Impl::SfxPartDockWnd_Impl
(
SfxBindings* pBindings,
SfxChildWindow* pChildWin,
Window* pParent,
WinBits nBits
)
: SfxDockingWindow( pBindings, pChildWin, pParent, nBits )
{
::com::sun::star::uno::Reference < ::com::sun::star::frame::XFrame > xFrame(
::comphelper::getProcessServiceFactory()->createInstance(
DEFINE_CONST_UNICODE("com.sun.star.frame.Frame") ), ::com::sun::star::uno::UNO_QUERY );
xFrame->initialize( VCLUnoHelper::GetInterface ( this ) );
pChildWin->SetFrame( xFrame );
if ( pBindings->GetDispatcher() )
{
::com::sun::star::uno::Reference < ::com::sun::star::frame::XFramesSupplier >
xSupp ( pBindings->GetDispatcher()->GetFrame()->GetFrame()->GetFrameInterface(), ::com::sun::star::uno::UNO_QUERY );
if ( xSupp.is() )
xSupp->getFrames()->append( xFrame );
}
else
DBG_ERROR("Bindings without Dispatcher!");
}
//****************************************************************************
SfxPartDockWnd_Impl::~SfxPartDockWnd_Impl()
{
}
//****************************************************************************
Rectangle impl_Rectangle_Struct2Object( const ::com::sun::star::awt::Rectangle& aRectangleStruct )
{
return Rectangle(aRectangleStruct.X,aRectangleStruct.Y,aRectangleStruct.Width,aRectangleStruct.Height);
}
void SfxPartDockWnd_Impl::Resize()
/* [Beschreibung]
Anpassung der Gr"osse der Controls an die neue Windowgr"osse
*/
{
SfxDockingWindow::Resize();
}
//****************************************************************************
sal_Bool SfxPartDockWnd_Impl::QueryClose()
{
sal_Bool bClose = sal_True;
SfxChildWindow* pChild = GetChildWindow_Impl();
if( pChild )
{
::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame > xFrame = pChild->GetFrame();
if( xFrame.is() )
{
::com::sun::star::uno::Reference< ::com::sun::star::frame::XController > xCtrl = xFrame->getController();
if( xCtrl.is() )
bClose = xCtrl->suspend( sal_True );
}
}
return bClose;
}
//****************************************************************************
long SfxPartDockWnd_Impl::Notify( NotifyEvent& rEvt )
{
if( rEvt.GetType() == EVENT_GETFOCUS )
{
SfxChildWindow* pChild = GetChildWindow_Impl();
if( pChild )
{
::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame > xFrame = pChild->GetFrame();
if( xFrame.is() )
xFrame->activate();
}
}
return SfxDockingWindow::Notify( rEvt );
}
void SfxPartDockWnd_Impl::FillInfo( SfxChildWinInfo& rInfo ) const
{
SfxDockingWindow::FillInfo( rInfo );
rInfo.bVisible = sal_False;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2019 The Bitcoin developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <chain.h>
#include <chainparams.h>
#include <consensus/activation.h>
#include <util/system.h>
#include <test/util/setup_common.h>
#include <boost/test/unit_test.hpp>
BOOST_FIXTURE_TEST_SUITE(activation_tests, BasicTestingSetup)
static void SetMTP(std::array<CBlockIndex, 12> &blocks, int64_t mtp) {
size_t len = blocks.size();
for (size_t i = 0; i < len; ++i) {
blocks[i].nTime = mtp + (i - (len / 2));
}
BOOST_CHECK_EQUAL(blocks.back().GetMedianTimePast(), mtp);
}
BOOST_AUTO_TEST_CASE(isgravitonenabled) {
const auto params = CreateChainParams(CBaseChainParams::MAIN);
const auto &consensus = params->GetConsensus();
BOOST_CHECK(!IsGravitonEnabled(consensus, nullptr));
std::array<CBlockIndex, 4> blocks;
blocks[0].nHeight = consensus.gravitonHeight - 2;
for (size_t i = 1; i < blocks.size(); ++i) {
blocks[i].pprev = &blocks[i - 1];
blocks[i].nHeight = blocks[i - 1].nHeight + 1;
}
BOOST_CHECK(!IsGravitonEnabled(consensus, &blocks[0]));
BOOST_CHECK(!IsGravitonEnabled(consensus, &blocks[1]));
BOOST_CHECK(IsGravitonEnabled(consensus, &blocks[2]));
BOOST_CHECK(IsGravitonEnabled(consensus, &blocks[3]));
}
BOOST_AUTO_TEST_CASE(isphononenabled) {
const Consensus::Params &consensus = Params().GetConsensus();
BOOST_CHECK(!IsPhononEnabled(consensus, nullptr));
std::array<CBlockIndex, 4> blocks;
blocks[0].nHeight = consensus.phononHeight - 2;
for (size_t i = 1; i < blocks.size(); ++i) {
blocks[i].pprev = &blocks[i - 1];
blocks[i].nHeight = blocks[i - 1].nHeight + 1;
}
BOOST_CHECK(!IsPhononEnabled(consensus, &blocks[0]));
BOOST_CHECK(!IsPhononEnabled(consensus, &blocks[1]));
BOOST_CHECK(IsPhononEnabled(consensus, &blocks[2]));
BOOST_CHECK(IsPhononEnabled(consensus, &blocks[3]));
}
BOOST_AUTO_TEST_CASE(isaxionenabled) {
const Consensus::Params ¶ms = Params().GetConsensus();
const auto activation =
gArgs.GetArg("-axionactivationtime", params.axionActivationTime);
SetMockTime(activation - 1000000);
BOOST_CHECK(!IsAxionEnabled(params, nullptr));
std::array<CBlockIndex, 12> blocks;
for (size_t i = 1; i < blocks.size(); ++i) {
blocks[i].pprev = &blocks[i - 1];
}
BOOST_CHECK(!IsAxionEnabled(params, &blocks.back()));
SetMTP(blocks, activation - 1);
BOOST_CHECK(!IsAxionEnabled(params, &blocks.back()));
SetMTP(blocks, activation);
BOOST_CHECK(IsAxionEnabled(params, &blocks.back()));
SetMTP(blocks, activation + 1);
BOOST_CHECK(IsAxionEnabled(params, &blocks.back()));
}
BOOST_AUTO_TEST_SUITE_END()
<commit_msg>[refactor] extract function for past activation tests<commit_after>// Copyright (c) 2019 The Bitcoin developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <chain.h>
#include <chainparams.h>
#include <consensus/activation.h>
#include <util/system.h>
#include <test/util/setup_common.h>
#include <boost/test/unit_test.hpp>
BOOST_FIXTURE_TEST_SUITE(activation_tests, BasicTestingSetup)
static void SetMTP(std::array<CBlockIndex, 12> &blocks, int64_t mtp) {
size_t len = blocks.size();
for (size_t i = 0; i < len; ++i) {
blocks[i].nTime = mtp + (i - (len / 2));
}
BOOST_CHECK_EQUAL(blocks.back().GetMedianTimePast(), mtp);
}
static void testPastActivation(
std::function<bool(const Consensus::Params &, const CBlockIndex *)> func,
const Consensus::Params ¶ms, int activationHeight) {
BOOST_CHECK(!func(params, nullptr));
std::array<CBlockIndex, 4> blocks;
blocks[0].nHeight = activationHeight - 2;
for (size_t i = 1; i < blocks.size(); ++i) {
blocks[i].pprev = &blocks[i - 1];
blocks[i].nHeight = blocks[i - 1].nHeight + 1;
}
BOOST_CHECK(!func(params, &blocks[0]));
BOOST_CHECK(!func(params, &blocks[1]));
BOOST_CHECK(func(params, &blocks[2]));
BOOST_CHECK(func(params, &blocks[3]));
}
BOOST_AUTO_TEST_CASE(test_previous_activations_by_height) {
const auto params = CreateChainParams(CBaseChainParams::MAIN);
const auto consensus = params->GetConsensus();
testPastActivation(IsGravitonEnabled, consensus, consensus.gravitonHeight);
testPastActivation(IsPhononEnabled, consensus, consensus.phononHeight);
}
BOOST_AUTO_TEST_CASE(isaxionenabled) {
const Consensus::Params ¶ms = Params().GetConsensus();
const auto activation =
gArgs.GetArg("-axionactivationtime", params.axionActivationTime);
SetMockTime(activation - 1000000);
BOOST_CHECK(!IsAxionEnabled(params, nullptr));
std::array<CBlockIndex, 12> blocks;
for (size_t i = 1; i < blocks.size(); ++i) {
blocks[i].pprev = &blocks[i - 1];
}
BOOST_CHECK(!IsAxionEnabled(params, &blocks.back()));
SetMTP(blocks, activation - 1);
BOOST_CHECK(!IsAxionEnabled(params, &blocks.back()));
SetMTP(blocks, activation);
BOOST_CHECK(IsAxionEnabled(params, &blocks.back()));
SetMTP(blocks, activation + 1);
BOOST_CHECK(IsAxionEnabled(params, &blocks.back()));
}
BOOST_AUTO_TEST_SUITE_END()
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qgstreamercaptureservice_maemo.h"
#include "qgstreamercapturesession_maemo.h"
#include "qgstreamerrecordercontrol_maemo.h"
#include "qgstreamermediacontainercontrol_maemo.h"
#include "qgstreameraudioencode_maemo.h"
#include "qgstreamervideoencode_maemo.h"
#include "qgstreamerbushelper.h"
#include "qgstreamercapturemetadatacontrol_maemo.h"
#include "qgstreameraudioinputendpointselector.h"
#include "qgstreamervideoinputdevicecontrol.h"
#include "qgstreamervideooverlay.h"
#include "qgstreamervideorenderer.h"
#include "qgstreamervideowidget.h"
#include <qmediaserviceprovider.h>
#include <QtCore/qdebug.h>
class QGstreamerVideoRendererWrapper : public QGstreamerElementFactory
{
public:
QGstreamerVideoRendererWrapper(QGstreamerVideoRendererInterface *videoRenderer)
:m_videoRenderer(videoRenderer),
m_bin(0),
m_element(0),
m_colorspace(0)
{
}
virtual ~QGstreamerVideoRendererWrapper()
{
if (m_bin)
gst_object_unref(GST_OBJECT(m_bin));
}
GstElement *buildElement()
{
#ifdef Q_WS_MAEMO_5
return m_element = m_videoRenderer->videoSink();
#endif
if (m_bin == NULL) {
GstBin * bin = GST_BIN(gst_bin_new(NULL));
m_colorspace = gst_element_factory_make("ffmpegcolorspace", NULL);
m_element = m_videoRenderer->videoSink();
gst_bin_add(bin, m_colorspace);
gst_bin_add(bin, m_element);
gst_element_link(m_colorspace, m_element);
// add ghostpads
GstPad *pad = gst_element_get_static_pad(m_colorspace, "sink");
gst_element_add_pad(GST_ELEMENT(bin), gst_ghost_pad_new("sink", pad));
gst_object_unref(GST_OBJECT(pad));
m_bin = GST_ELEMENT(bin);
}
m_videoRenderer->precessNewStream();
gst_object_ref(GST_OBJECT(m_bin));
return m_bin;
}
void prepareWinId()
{
m_videoRenderer->precessNewStream();
}
private:
QGstreamerVideoRendererInterface *m_videoRenderer;
GstElement *m_bin;
GstElement *m_element;
GstElement *m_colorspace;
};
QGstreamerCaptureService::QGstreamerCaptureService(const QString &service, QObject *parent):
QMediaService(parent)
{
static bool initialized = false;
if (!initialized) {
initialized = true;
gst_init(NULL, NULL);
}
m_captureSession = 0;
m_cameraControl = 0;
m_metaDataControl = 0;
m_audioInputEndpointSelector = 0;
m_videoInputDevice = 0;
m_videoRenderer = 0;
m_videoRendererFactory = 0;
m_videoWindow = 0;
m_videoWindowFactory = 0;
m_videoWidgetControl = 0;
m_videoWidgetFactory = 0;
m_imageCaptureControl = 0;
if (service == Q_MEDIASERVICE_AUDIOSOURCE) {
m_captureSession = new QGstreamerCaptureSession(QGstreamerCaptureSession::Audio, this);
}
bool captureVideo = false;
if (captureVideo) {
m_captureSession = new QGstreamerCaptureSession(QGstreamerCaptureSession::AudioAndVideo, this);
//TODO:m_captureSession->setVideoInput(m_cameraControl);
m_videoInputDevice = new QGstreamerVideoInputDeviceControl(m_captureSession);
//TODO:connect(m_videoInputDevice, SIGNAL(selectedDeviceChanged(QString)),
// m_cameraControl, SLOT(setDevice(QString)));
//TODO:if (m_videoInputDevice->deviceCount())
// m_cameraControl->setDevice(m_videoInputDevice->deviceName(m_videoInputDevice->selectedDevice()));
m_videoRenderer = new QGstreamerVideoRenderer(this);
m_videoRendererFactory = new QGstreamerVideoRendererWrapper(m_videoRenderer);
m_videoWindow = new QGstreamerVideoOverlay(this);
m_videoWindowFactory = new QGstreamerVideoRendererWrapper(m_videoWindow);
m_videoWidgetControl = new QGstreamerVideoWidgetControl(this);
m_videoWidgetFactory = new QGstreamerVideoRendererWrapper(m_videoWidgetControl);
}
if (!m_captureSession) {
qWarning() << "Service type is not supported:" << service;
return;
}
m_audioInputEndpointSelector = new QGstreamerAudioInputEndpointSelector(this);
connect(m_audioInputEndpointSelector, SIGNAL(activeEndpointChanged(QString)), m_captureSession, SLOT(setCaptureDevice(QString)));
if (m_captureSession && m_audioInputEndpointSelector->availableEndpoints().size() > 0)
m_captureSession->setCaptureDevice(m_audioInputEndpointSelector->defaultEndpoint());
m_metaDataControl = new QGstreamerCaptureMetaDataControl(this);
connect(m_metaDataControl, SIGNAL(metaDataChanged(QMap<QByteArray,QVariant>)),
m_captureSession, SLOT(setMetaData(QMap<QByteArray,QVariant>)));
}
QGstreamerCaptureService::~QGstreamerCaptureService()
{
}
QMediaControl *QGstreamerCaptureService::requestControl(const char *name)
{
if (qstrcmp(name, QVideoRendererControl_iid) == 0)
return m_videoRenderer;
if (qstrcmp(name, QVideoWindowControl_iid) == 0)
return m_videoWindow;
if (qstrcmp(name, QVideoWidgetControl_iid) == 0)
return m_videoWidgetControl;
if (qstrcmp(name,QAudioEndpointSelector_iid) == 0)
return m_audioInputEndpointSelector;
if (qstrcmp(name,QVideoDeviceControl_iid) == 0)
return m_videoInputDevice;
if (qstrcmp(name,QMediaRecorderControl_iid) == 0)
return m_captureSession->recorderControl();
if (qstrcmp(name,QAudioEncoderControl_iid) == 0)
return m_captureSession->audioEncodeControl();
if (qstrcmp(name,QVideoEncoderControl_iid) == 0)
return m_captureSession->videoEncodeControl();
if (qstrcmp(name,QMediaContainerControl_iid) == 0)
return m_captureSession->mediaContainerControl();
if (qstrcmp(name,QMetaDataWriterControl_iid) == 0)
return m_metaDataControl;
return 0;
}
void QGstreamerCaptureService::releaseControl(QMediaControl *control)
{
if (control && control == m_videoOutput) {
m_videoOutput = 0;
m_captureSession->setVideoPreview(0);
}
}
<commit_msg>Updated maemo capture service with controls API changes.<commit_after>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qgstreamercaptureservice_maemo.h"
#include "qgstreamercapturesession_maemo.h"
#include "qgstreamerrecordercontrol_maemo.h"
#include "qgstreamermediacontainercontrol_maemo.h"
#include "qgstreameraudioencode_maemo.h"
#include "qgstreamervideoencode_maemo.h"
#include "qgstreamerbushelper.h"
#include "qgstreamercapturemetadatacontrol_maemo.h"
#include "qgstreameraudioinputendpointselector.h"
#include "qgstreamervideoinputdevicecontrol.h"
#include "qgstreamervideooverlay.h"
#include "qgstreamervideorenderer.h"
#include "qgstreamervideowidget.h"
#include <qmediaserviceprovider.h>
#include <QtCore/qdebug.h>
class QGstreamerVideoRendererWrapper : public QGstreamerElementFactory
{
public:
QGstreamerVideoRendererWrapper(QGstreamerVideoRendererInterface *videoRenderer)
:m_videoRenderer(videoRenderer),
m_bin(0),
m_element(0),
m_colorspace(0)
{
}
virtual ~QGstreamerVideoRendererWrapper()
{
if (m_bin)
gst_object_unref(GST_OBJECT(m_bin));
}
GstElement *buildElement()
{
#ifdef Q_WS_MAEMO_5
return m_element = m_videoRenderer->videoSink();
#endif
if (m_bin == NULL) {
GstBin * bin = GST_BIN(gst_bin_new(NULL));
m_colorspace = gst_element_factory_make("ffmpegcolorspace", NULL);
m_element = m_videoRenderer->videoSink();
gst_bin_add(bin, m_colorspace);
gst_bin_add(bin, m_element);
gst_element_link(m_colorspace, m_element);
// add ghostpads
GstPad *pad = gst_element_get_static_pad(m_colorspace, "sink");
gst_element_add_pad(GST_ELEMENT(bin), gst_ghost_pad_new("sink", pad));
gst_object_unref(GST_OBJECT(pad));
m_bin = GST_ELEMENT(bin);
}
m_videoRenderer->precessNewStream();
gst_object_ref(GST_OBJECT(m_bin));
return m_bin;
}
void prepareWinId()
{
m_videoRenderer->precessNewStream();
}
private:
QGstreamerVideoRendererInterface *m_videoRenderer;
GstElement *m_bin;
GstElement *m_element;
GstElement *m_colorspace;
};
QGstreamerCaptureService::QGstreamerCaptureService(const QString &service, QObject *parent):
QMediaService(parent)
{
static bool initialized = false;
if (!initialized) {
initialized = true;
gst_init(NULL, NULL);
}
m_captureSession = 0;
m_cameraControl = 0;
m_metaDataControl = 0;
m_audioInputEndpointSelector = 0;
m_videoInputDevice = 0;
m_videoRenderer = 0;
m_videoRendererFactory = 0;
m_videoWindow = 0;
m_videoWindowFactory = 0;
m_videoWidgetControl = 0;
m_videoWidgetFactory = 0;
m_imageCaptureControl = 0;
if (service == Q_MEDIASERVICE_AUDIOSOURCE) {
m_captureSession = new QGstreamerCaptureSession(QGstreamerCaptureSession::Audio, this);
}
bool captureVideo = false;
if (captureVideo) {
m_captureSession = new QGstreamerCaptureSession(QGstreamerCaptureSession::AudioAndVideo, this);
//TODO:m_captureSession->setVideoInput(m_cameraControl);
m_videoInputDevice = new QGstreamerVideoInputDeviceControl(m_captureSession);
//TODO:connect(m_videoInputDevice, SIGNAL(selectedDeviceChanged(QString)),
// m_cameraControl, SLOT(setDevice(QString)));
//TODO:if (m_videoInputDevice->deviceCount())
// m_cameraControl->setDevice(m_videoInputDevice->deviceName(m_videoInputDevice->selectedDevice()));
m_videoRenderer = new QGstreamerVideoRenderer(this);
m_videoRendererFactory = new QGstreamerVideoRendererWrapper(m_videoRenderer);
m_videoWindow = new QGstreamerVideoOverlay(this);
m_videoWindowFactory = new QGstreamerVideoRendererWrapper(m_videoWindow);
m_videoWidgetControl = new QGstreamerVideoWidgetControl(this);
m_videoWidgetFactory = new QGstreamerVideoRendererWrapper(m_videoWidgetControl);
}
if (!m_captureSession) {
qWarning() << "Service type is not supported:" << service;
return;
}
m_audioInputEndpointSelector = new QGstreamerAudioInputEndpointSelector(this);
connect(m_audioInputEndpointSelector, SIGNAL(activeEndpointChanged(QString)), m_captureSession, SLOT(setCaptureDevice(QString)));
if (m_captureSession && m_audioInputEndpointSelector->availableEndpoints().size() > 0)
m_captureSession->setCaptureDevice(m_audioInputEndpointSelector->defaultEndpoint());
m_metaDataControl = new QGstreamerCaptureMetaDataControl(this);
connect(m_metaDataControl, SIGNAL(metaDataChanged(QMap<QByteArray,QVariant>)),
m_captureSession, SLOT(setMetaData(QMap<QByteArray,QVariant>)));
}
QGstreamerCaptureService::~QGstreamerCaptureService()
{
}
QMediaControl *QGstreamerCaptureService::requestControl(const char *name)
{
if (!m_captureSession)
return 0;
if (!m_videoOutput) {
if (qstrcmp(name, QVideoRendererControl_iid) == 0) {
m_videoOutput = m_videoRenderer;
m_captureSession->setVideoPreview(m_videoRendererFactory);
} else if (qstrcmp(name, QVideoWindowControl_iid) == 0) {
m_videoOutput = m_videoWindow;
m_captureSession->setVideoPreview(m_videoWindowFactory);
} else if (qstrcmp(name, QVideoWidgetControl_iid) == 0) {
m_captureSession->setVideoPreview(m_videoWidgetFactory);
m_videoOutput = m_videoWidgetControl;
}
if (m_videoOutput)
return m_videoOutput;
}
if (qstrcmp(name,QAudioEndpointSelector_iid) == 0)
return m_audioInputEndpointSelector;
if (qstrcmp(name,QVideoDeviceControl_iid) == 0)
return m_videoInputDevice;
if (qstrcmp(name,QMediaRecorderControl_iid) == 0)
return m_captureSession->recorderControl();
if (qstrcmp(name,QAudioEncoderControl_iid) == 0)
return m_captureSession->audioEncodeControl();
if (qstrcmp(name,QVideoEncoderControl_iid) == 0)
return m_captureSession->videoEncodeControl();
if (qstrcmp(name,QMediaContainerControl_iid) == 0)
return m_captureSession->mediaContainerControl();
if (qstrcmp(name,QMetaDataWriterControl_iid) == 0)
return m_metaDataControl;
return 0;
}
void QGstreamerCaptureService::releaseControl(QMediaControl *control)
{
if (control && control == m_videoOutput) {
m_videoOutput = 0;
m_captureSession->setVideoPreview(0);
}
}
<|endoftext|> |
<commit_before>#include <stdlib.h>
#include <stdio.h>
#include <boost/version.hpp>
#include <fstream>
#include <stdint.h>
#include "task_manager_lib/TaskServerInterface.h"
#include <ros/ros.h>
#include <ros/package.h>
using namespace boost::posix_time;
using namespace std;
using namespace task_manager_lib;
std::string TaskServerInterface::package_name = "task_manager_turtlesim";
TaskServerInterface::TaskServerInterface(task_manager_lib::TaskScheduler &ts_ref)
{
saveBasicMissionSrv = ts_ref.getNodeHandle().advertiseService("save_basic_mission", &TaskServerInterface::saveBasicMission,this);
saveComplexMissionSrv = ts_ref.getNodeHandle().advertiseService("save_complex_mission", &TaskServerInterface::saveComplexMission,this);
executeComplexMissionsSrv= ts_ref.getNodeHandle().advertiseService("execute_complex_mission", &TaskServerInterface::executeComplexMission,this);
stopComplexMissionsSrv= ts_ref.getNodeHandle().advertiseService("abord_complex_mission", &TaskServerInterface::stopComplexMission,this);
listMissionsSrv=ts_ref.getNodeHandle().advertiseService("list_mission", &TaskServerInterface::listMissions,this);
}
//callback
bool TaskServerInterface::saveBasicMission(task_manager_lib::SaveBasicMission::Request &req, task_manager_lib::SaveBasicMission::Response &res )
{
createBasicMissionFile(req.basic_mission,res.filename);
return true;
}
bool TaskServerInterface::saveComplexMission(task_manager_lib::SaveComplexMission::Request &req, task_manager_lib::SaveComplexMission::Response &res )
{
createComplexMissionFile(req.complex_mission,res.filename);
return true;
}
bool TaskServerInterface::executeComplexMission(task_manager_lib::ExeComplexMission::Request &req, task_manager_lib::ExeComplexMission::Response &res )
{
launchComplexMission(req.mission_name, res.pid);
return true;
}
bool TaskServerInterface::stopComplexMission(task_manager_lib::StopComplexMission::Request &req, task_manager_lib::StopComplexMission::Response &res )
{
abordComplexMission(req.pid);
return true;
}
bool TaskServerInterface::listMissions(task_manager_lib::ListMissions::Request &req, task_manager_lib::ListMissions::Response &res )
{
parseMissionDirectory(res.basic_missions,res.complex_missions);
return true;
}
void TaskServerInterface::createBasicMissionFile(std::vector<task_manager_msgs::TaskDescriptionLight> &basic_mission, std::string &filename) const
{
std::vector<task_manager_msgs::TaskDescriptionLight> tasklist=basic_mission;
try
{
stringstream path(ros::package::getPath(TaskServerInterface::package_name));
stringstream msg;
if (path.str().length() >0)
{
boost::filesystem::path mission_path(path.str()+"/missions");
if (boost::filesystem::exists(mission_path))
{
time_facet *facet = new time_facet("%d-%b-%Y-%H_%M_%S");
stringstream pathName;
pathName.imbue(locale(pathName.getloc(), facet));
pathName<<mission_path.string()<<"/mission_"<<second_clock::local_time() << ".mission";
boost::filesystem::path output_boost_path(pathName.str());
ofstream outputFile (pathName.str().c_str()) ;
//write mission file
//Mission task
for (unsigned int i = 0;i<tasklist.size();i++)
{
outputFile<<"---"<<"\n";
outputFile<<tasklist[i].name<<"\n";
if (tasklist[i].parameters.size()==0)
{
outputFile<<"empty"<<"\n";
}
else
{
for (unsigned int j = 0;j<tasklist[i].parameters.size();j++)
{
outputFile<<tasklist[i].parameters[j].name;
outputFile<<";";
outputFile<<tasklist[i].parameters[j].value;
outputFile<<"|";
}
outputFile<<"\n";
}
outputFile.close();
}
#if (BOOST_VERSION > 104200)
filename=output_boost_path.filename().string();
#else
filename=output_boost_path.filename();
#endif
}
else
{
#if (BOOST_VERSION > 104200)
PRINTF(1,"%s does not exist\n",mission_path.c_str());
#else
PRINTF(1,"%s does not exist\n",mission_path.string().c_str());
#endif
}
}
else
{
PRINTF(1,"%s does not exist\n",path.str().c_str());
}
}
catch (char * str)
{
PRINTF(1,"%s",str);
filename="Error creating Basic Mission file";
}
}
void TaskServerInterface::createComplexMissionFile(std::string &complex_mission, std::string &filename)
{
std::string tasklist=complex_mission;
stringstream msg;
try
{
std::stringstream path(ros::package::getPath(TaskServerInterface::package_name));
if (path.str().length() >0)
{
boost::filesystem::path mission_path(path.str()+"/missions");
if (boost::filesystem::exists(mission_path))
{
time_facet *facet = new time_facet("%d-%b-%Y-%H_%M_%S");
std::stringstream pathName;
pathName.imbue(locale(pathName.getloc(), facet));
pathName<<mission_path.string()<<"/mission_"<<second_clock::local_time() << ".py";
boost::filesystem::path output_boost_path(pathName.str());
if (boost::filesystem::exists(output_boost_path))
{
//replace
}
else
{
//write mission file
try
{
ofstream outputFile (pathName.str().c_str()) ;
outputFile<<tasklist<<endl;
outputFile.close();
std::stringstream command_line;
command_line<<"chmod 775 "<<pathName.str();
int result=system(command_line.str().c_str());
if (result!=0)
{
PRINTF(1,"Error %d setting execution permission to %s",result,command_line.str().c_str());
}
}
catch(char * str)
{
PRINTF(1,"%s",str);
}
}
#if BOOST_VERSION > 104200
filename=output_boost_path.filename().string();
#else
filename=output_boost_path.filename();
#endif
//update list of complex filename
task_manager_msgs::ComplexMission current_mission;
current_mission.name=filename;
current_mission.complex_mission=tasklist;
ComplexMissions.push_back(current_mission);
}
else
{
#if (BOOST_VERSION > 104200)
PRINTF(1,"%s does not exist\n",mission_path.c_str());
#else
PRINTF(1,"%s does not exist\n",mission_path.string().c_str());
#endif
}
}
else
{
PRINTF(1," %s does not exist\n",path.str().c_str());
}
}
catch (char * str)
{
PRINTF(1,"%s",str);
filename="error creating file";
}
}
void TaskServerInterface::parseBasicMissionFile(boost::filesystem::path &mission_file_path, std::vector<task_manager_msgs::BasicMission>& basic_missions)
{
if (boost::filesystem::exists(mission_file_path))
{
stringstream pathName(mission_file_path.string());
ifstream MisssionFile(pathName.str().c_str());
std::string line;
task_manager_msgs::BasicMission mission_elem;
std::vector<task_manager_msgs::TaskDescriptionLight> tasks;
if (MisssionFile.is_open())
{
task_manager_msgs::TaskDescriptionLight current_task;
std::vector<task_manager_msgs::TaskParameter> parameters;
unsigned int current_line(0), task_line(0);
while ( getline(MisssionFile,line))
{
current_line ++;
if (line=="---")
{
task_line=current_line;
current_task=task_manager_msgs::TaskDescriptionLight();
parameters.clear();
}
else
{
if (current_line>0)
{
if (current_line==task_line+1)//name
{
current_task.name=line;
}
else if (current_line==task_line+2)//params
{
if (line!="empty")
{
std::vector<std::string> params;
split(line,'|',params);
for (unsigned int j=0;j<params.size();j++)
{
std::vector<std::string> name_value;
split(params[j],';',name_value);
task_manager_msgs::TaskParameter current_param;
current_param.name=name_value[0];
current_param.value=name_value[1];
parameters.push_back(current_param);
}
current_task.parameters=parameters;
tasks.push_back(current_task);
}
}
else
{
//error
}
}
}
}
}
#if BOOST_VERSION > 104200
mission_elem.name=mission_file_path.filename().string();
#else
mission_elem.name=mission_file_path.filename();
#endif
mission_elem.basic_mission=tasks;
//store in taskserverinterface BasicMissions
BasicMissions.push_back(mission_elem);
//response
basic_missions.push_back(mission_elem);
}
}
void TaskServerInterface::parseComplexMissionFile(boost::filesystem::path &mission_file_path, std::vector<task_manager_msgs::ComplexMission>& complex_missions)
{
if (boost::filesystem::exists(mission_file_path))
{
stringstream pathName(mission_file_path.string());
ifstream MisssionFile(pathName.str().c_str());
std::string line;
task_manager_msgs::ComplexMission mission_elem;
stringstream current_complex_mission;
if (MisssionFile.is_open())
{
while ( getline(MisssionFile,line))
{
current_complex_mission<<line<<endl;
}
}
#if BOOST_VERSION > 104200
mission_elem.name=mission_file_path.filename().string();
#else
mission_elem.name=mission_file_path.filename();
#endif
mission_elem.complex_mission= current_complex_mission.str();
//store
ComplexMissions.push_back(mission_elem);
//in response
complex_missions.push_back(mission_elem);
}
}
void TaskServerInterface::parseMissionDirectory(std::vector<task_manager_msgs::BasicMission>& basic_missions,std::vector<task_manager_msgs::ComplexMission>& complex_missions )
{
try
{
//todo for all package
std::stringstream path(ros::package::getPath(TaskServerInterface::package_name));
if (path.str().length() >0)
{
boost::filesystem::path mission_path(path.str()+"/missions");
if (boost::filesystem::exists(mission_path))
{
boost::filesystem::directory_iterator end;
for( boost::filesystem::directory_iterator iter(mission_path) ; iter != end ;iter++ )
{
if ( !boost::filesystem::is_directory( *iter ) )
{
#if BOOST_VERSION > 104200
boost::filesystem::path current_path(boost::filesystem::absolute(iter-> path()));
#else
//char * cwd = get_current_dir_name();
//boost::filesystem::path current_path(std::string(cwd) + iter-> path().string());
//free(cwd);
boost::filesystem::path current_path(iter-> path().string());
#endif
if (current_path.extension() ==".py")
{
parseComplexMissionFile(current_path,complex_missions);
}
else if (current_path.extension() ==".mission")
{
parseBasicMissionFile(current_path,basic_missions);
}
}
}
}
else
{
PRINTF(1,"Can't find missions directory in %s \n",path.str().c_str());
}
}
}
catch(char * str)
{
PRINTF(1,"%s",str);
}
}
void TaskServerInterface::launchComplexMission(std::string & mission_name, int &pid) const
{
int id(-1);
for (unsigned int i=0;i<ComplexMissions.size();i++)
{
if (ComplexMissions[i].name==mission_name)
{
id=i;
}
}
std::string full_name=saveBasicMissionSrv.getService();
size_t pos=full_name.find("save_basic_mission");
std::string node_name=full_name.substr(0,pos-1);
stringstream parameter;
parameter<<" _server:="<<node_name;
stringstream rosrun_path;
rosrun_path<<getenv("ROS_ROOT")<<"/bin/rosrun";
//WARNING adding fork in service
stringstream msg;
if (id>-1)
{
int current_pid = fork();
if (current_pid ==-1)
{
PRINTF(1,"Fork failed");
}
else if (current_pid ==0)//in child
{
execl (rosrun_path.str().c_str(),"rosrun", package_name.c_str(), mission_name.c_str(),parameter.str().c_str(),(char *) 0);
//msg<<"Error running the following command :"<<"rosrun "<<package_name.c_str()<<" "<<mission_name.c_str()<<" "<<parameter.str().c_str()<<"\n";
PRINTF(1,"Error running the following command : 'rosrun %s %s %s' \n",package_name.c_str(),mission_name.c_str(),parameter.str().c_str());
}
else //in parent
{
pid=current_pid;
}
}
else
{
PRINTF(1,"Complex Mission %s not found\n",mission_name.c_str());
}
}
void TaskServerInterface::abordComplexMission(int &pid)
{
kill( pid, SIGKILL );
}
void TaskServerInterface::split(const std::string &s, char delim, std::vector<std::string> &elems) {
std::stringstream ss(s);
std::string item;
while(std::getline(ss, item, delim)) {
elems.push_back(item);
}
}
<commit_msg>Execute complex mission using bash to avoid rosrun path issue<commit_after>#include <stdlib.h>
#include <stdio.h>
#include <boost/version.hpp>
#include <fstream>
#include <stdint.h>
#include "task_manager_lib/TaskServerInterface.h"
#include <ros/ros.h>
#include <ros/package.h>
using namespace boost::posix_time;
using namespace std;
using namespace task_manager_lib;
std::string TaskServerInterface::package_name = "task_manager_turtlesim";
TaskServerInterface::TaskServerInterface(task_manager_lib::TaskScheduler &ts_ref)
{
saveBasicMissionSrv = ts_ref.getNodeHandle().advertiseService("save_basic_mission", &TaskServerInterface::saveBasicMission,this);
saveComplexMissionSrv = ts_ref.getNodeHandle().advertiseService("save_complex_mission", &TaskServerInterface::saveComplexMission,this);
executeComplexMissionsSrv= ts_ref.getNodeHandle().advertiseService("execute_complex_mission", &TaskServerInterface::executeComplexMission,this);
stopComplexMissionsSrv= ts_ref.getNodeHandle().advertiseService("abord_complex_mission", &TaskServerInterface::stopComplexMission,this);
listMissionsSrv=ts_ref.getNodeHandle().advertiseService("list_mission", &TaskServerInterface::listMissions,this);
}
//callback
bool TaskServerInterface::saveBasicMission(task_manager_lib::SaveBasicMission::Request &req, task_manager_lib::SaveBasicMission::Response &res )
{
createBasicMissionFile(req.basic_mission,res.filename);
return true;
}
bool TaskServerInterface::saveComplexMission(task_manager_lib::SaveComplexMission::Request &req, task_manager_lib::SaveComplexMission::Response &res )
{
createComplexMissionFile(req.complex_mission,res.filename);
return true;
}
bool TaskServerInterface::executeComplexMission(task_manager_lib::ExeComplexMission::Request &req, task_manager_lib::ExeComplexMission::Response &res )
{
launchComplexMission(req.mission_name, res.pid);
return true;
}
bool TaskServerInterface::stopComplexMission(task_manager_lib::StopComplexMission::Request &req, task_manager_lib::StopComplexMission::Response &res )
{
abordComplexMission(req.pid);
return true;
}
bool TaskServerInterface::listMissions(task_manager_lib::ListMissions::Request &req, task_manager_lib::ListMissions::Response &res )
{
parseMissionDirectory(res.basic_missions,res.complex_missions);
return true;
}
void TaskServerInterface::createBasicMissionFile(std::vector<task_manager_msgs::TaskDescriptionLight> &basic_mission, std::string &filename) const
{
std::vector<task_manager_msgs::TaskDescriptionLight> tasklist=basic_mission;
try
{
stringstream path(ros::package::getPath(TaskServerInterface::package_name));
stringstream msg;
if (path.str().length() >0)
{
boost::filesystem::path mission_path(path.str()+"/missions");
if (boost::filesystem::exists(mission_path))
{
time_facet *facet = new time_facet("%d-%b-%Y-%H_%M_%S");
stringstream pathName;
pathName.imbue(locale(pathName.getloc(), facet));
pathName<<mission_path.string()<<"/mission_"<<second_clock::local_time() << ".mission";
boost::filesystem::path output_boost_path(pathName.str());
ofstream outputFile (pathName.str().c_str()) ;
//write mission file
//Mission task
for (unsigned int i = 0;i<tasklist.size();i++)
{
outputFile<<"---"<<"\n";
outputFile<<tasklist[i].name<<"\n";
if (tasklist[i].parameters.size()==0)
{
outputFile<<"empty"<<"\n";
}
else
{
for (unsigned int j = 0;j<tasklist[i].parameters.size();j++)
{
outputFile<<tasklist[i].parameters[j].name;
outputFile<<";";
outputFile<<tasklist[i].parameters[j].value;
outputFile<<"|";
}
outputFile<<"\n";
}
outputFile.close();
}
#if (BOOST_VERSION > 104200)
filename=output_boost_path.filename().string();
#else
filename=output_boost_path.filename();
#endif
}
else
{
#if (BOOST_VERSION > 104200)
PRINTF(1,"%s does not exist\n",mission_path.c_str());
#else
PRINTF(1,"%s does not exist\n",mission_path.string().c_str());
#endif
}
}
else
{
PRINTF(1,"%s does not exist\n",path.str().c_str());
}
}
catch (char * str)
{
PRINTF(1,"%s",str);
filename="Error creating Basic Mission file";
}
}
void TaskServerInterface::createComplexMissionFile(std::string &complex_mission, std::string &filename)
{
std::string tasklist=complex_mission;
stringstream msg;
try
{
std::stringstream path(ros::package::getPath(TaskServerInterface::package_name));
if (path.str().length() >0)
{
boost::filesystem::path mission_path(path.str()+"/missions");
if (boost::filesystem::exists(mission_path))
{
time_facet *facet = new time_facet("%d-%b-%Y-%H_%M_%S");
std::stringstream pathName;
pathName.imbue(locale(pathName.getloc(), facet));
pathName<<mission_path.string()<<"/mission_"<<second_clock::local_time() << ".py";
boost::filesystem::path output_boost_path(pathName.str());
if (boost::filesystem::exists(output_boost_path))
{
//replace
}
else
{
//write mission file
try
{
ofstream outputFile (pathName.str().c_str()) ;
outputFile<<tasklist<<endl;
outputFile.close();
std::stringstream command_line;
command_line<<"chmod 775 "<<pathName.str();
int result=system(command_line.str().c_str());
if (result!=0)
{
PRINTF(1,"Error %d setting execution permission to %s",result,command_line.str().c_str());
}
}
catch(char * str)
{
PRINTF(1,"%s",str);
}
}
#if BOOST_VERSION > 104200
filename=output_boost_path.filename().string();
#else
filename=output_boost_path.filename();
#endif
//update list of complex filename
task_manager_msgs::ComplexMission current_mission;
current_mission.name=filename;
current_mission.complex_mission=tasklist;
ComplexMissions.push_back(current_mission);
}
else
{
#if (BOOST_VERSION > 104200)
PRINTF(1,"%s does not exist\n",mission_path.c_str());
#else
PRINTF(1,"%s does not exist\n",mission_path.string().c_str());
#endif
}
}
else
{
PRINTF(1," %s does not exist\n",path.str().c_str());
}
}
catch (char * str)
{
PRINTF(1,"%s",str);
filename="error creating file";
}
}
void TaskServerInterface::parseBasicMissionFile(boost::filesystem::path &mission_file_path, std::vector<task_manager_msgs::BasicMission>& basic_missions)
{
if (boost::filesystem::exists(mission_file_path))
{
stringstream pathName(mission_file_path.string());
ifstream MisssionFile(pathName.str().c_str());
std::string line;
task_manager_msgs::BasicMission mission_elem;
std::vector<task_manager_msgs::TaskDescriptionLight> tasks;
if (MisssionFile.is_open())
{
task_manager_msgs::TaskDescriptionLight current_task;
std::vector<task_manager_msgs::TaskParameter> parameters;
unsigned int current_line(0), task_line(0);
while ( getline(MisssionFile,line))
{
current_line ++;
if (line=="---")
{
task_line=current_line;
current_task=task_manager_msgs::TaskDescriptionLight();
parameters.clear();
}
else
{
if (current_line>0)
{
if (current_line==task_line+1)//name
{
current_task.name=line;
}
else if (current_line==task_line+2)//params
{
if (line!="empty")
{
std::vector<std::string> params;
split(line,'|',params);
for (unsigned int j=0;j<params.size();j++)
{
std::vector<std::string> name_value;
split(params[j],';',name_value);
task_manager_msgs::TaskParameter current_param;
current_param.name=name_value[0];
current_param.value=name_value[1];
parameters.push_back(current_param);
}
current_task.parameters=parameters;
tasks.push_back(current_task);
}
}
else
{
//error
}
}
}
}
}
#if BOOST_VERSION > 104200
mission_elem.name=mission_file_path.filename().string();
#else
mission_elem.name=mission_file_path.filename();
#endif
mission_elem.basic_mission=tasks;
//store in taskserverinterface BasicMissions
BasicMissions.push_back(mission_elem);
//response
basic_missions.push_back(mission_elem);
}
}
void TaskServerInterface::parseComplexMissionFile(boost::filesystem::path &mission_file_path, std::vector<task_manager_msgs::ComplexMission>& complex_missions)
{
if (boost::filesystem::exists(mission_file_path))
{
stringstream pathName(mission_file_path.string());
ifstream MisssionFile(pathName.str().c_str());
std::string line;
task_manager_msgs::ComplexMission mission_elem;
stringstream current_complex_mission;
if (MisssionFile.is_open())
{
while ( getline(MisssionFile,line))
{
current_complex_mission<<line<<endl;
}
}
#if BOOST_VERSION > 104200
mission_elem.name=mission_file_path.filename().string();
#else
mission_elem.name=mission_file_path.filename();
#endif
mission_elem.complex_mission= current_complex_mission.str();
//store
ComplexMissions.push_back(mission_elem);
//in response
complex_missions.push_back(mission_elem);
}
}
void TaskServerInterface::parseMissionDirectory(std::vector<task_manager_msgs::BasicMission>& basic_missions,std::vector<task_manager_msgs::ComplexMission>& complex_missions )
{
try
{
//todo for all package
std::stringstream path(ros::package::getPath(TaskServerInterface::package_name));
if (path.str().length() >0)
{
boost::filesystem::path mission_path(path.str()+"/missions");
if (boost::filesystem::exists(mission_path))
{
boost::filesystem::directory_iterator end;
for( boost::filesystem::directory_iterator iter(mission_path) ; iter != end ;iter++ )
{
if ( !boost::filesystem::is_directory( *iter ) )
{
#if BOOST_VERSION > 104200
boost::filesystem::path current_path(boost::filesystem::absolute(iter-> path()));
#else
//char * cwd = get_current_dir_name();
//boost::filesystem::path current_path(std::string(cwd) + iter-> path().string());
//free(cwd);
boost::filesystem::path current_path(iter-> path().string());
#endif
if (current_path.extension() ==".py")
{
parseComplexMissionFile(current_path,complex_missions);
}
else if (current_path.extension() ==".mission")
{
parseBasicMissionFile(current_path,basic_missions);
}
}
}
}
else
{
PRINTF(1,"Can't find missions directory in %s \n",path.str().c_str());
}
}
}
catch(char * str)
{
PRINTF(1,"%s",str);
}
}
void TaskServerInterface::launchComplexMission(std::string & mission_name, int &pid) const
{
int id(-1);
for (unsigned int i=0;i<ComplexMissions.size();i++)
{
if (ComplexMissions[i].name==mission_name)
{
id=i;
}
}
std::string full_name=saveBasicMissionSrv.getService();
size_t pos=full_name.find("save_basic_mission");
std::string node_name=full_name.substr(0,pos-1);
stringstream parameter;
parameter<<"_server:="<<node_name;
stringstream command_line;
command_line<<"rosrun "<<package_name<<" "<<mission_name<<" "<<parameter.str();
//WARNING adding fork in service
stringstream msg;
if (id>-1)
{
int current_pid = fork();
if (current_pid ==-1)
{
PRINTF(1,"Fork failed");
}
else if (current_pid ==0)//in child
{
execl ("/bin/bash","bash","-i","-c",command_line.str().c_str(),(char *) 0);
//msg<<"Error running the following command :"<<"rosrun "<<package_name.c_str()<<" "<<mission_name.c_str()<<" "<<parameter.str().c_str()<<"\n";
PRINTF(1,"Error running the following command : 'bash -i -c %s ' \n",command_line.str().c_str());
}
else //in parent
{
pid=current_pid;
}
}
else
{
PRINTF(1,"Complex Mission %s not found\n",mission_name.c_str());
}
}
void TaskServerInterface::abordComplexMission(int &pid)
{
kill( pid, SIGKILL );
}
void TaskServerInterface::split(const std::string &s, char delim, std::vector<std::string> &elems) {
std::stringstream ss(s);
std::string item;
while(std::getline(ss, item, delim)) {
elems.push_back(item);
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/meta_table_helper.h"
#include "base/logging.h"
#include "base/string_util.h"
#include "chrome/common/sqlite_utils.h"
// Key used in our meta table for version numbers.
static const char kVersionKey[] = "version";
static const char kCompatibleVersionKey[] = "last_compatible_version";
// static
void MetaTableHelper::PrimeCache(const std::string& db_name, sqlite3* db) {
// A statement must be open for the preload command to work. If the meta
// table doesn't exist, it probably means this is a new database and there
// is nothing to preload (so it's OK we do nothing).
SQLStatement dummy;
if (!DoesSqliteTableExist(db, db_name.c_str(), "meta"))
return;
std::string sql("SELECT * from ");
appendMetaTableName(db_name, &sql);
if (dummy.prepare(db, sql.c_str()) != SQLITE_OK)
return;
if (dummy.step() != SQLITE_ROW)
return;
sqlite3Preload(db);
}
MetaTableHelper::MetaTableHelper() : db_(NULL) {
}
MetaTableHelper::~MetaTableHelper() {
}
bool MetaTableHelper::Init(const std::string& db_name,
int version,
int compatible_version,
sqlite3* db) {
DCHECK(!db_ && db);
db_ = db;
db_name_ = db_name;
if (!DoesSqliteTableExist(db_, db_name.c_str(), "meta")) {
// Build the sql.
std::string sql("CREATE TABLE ");
appendMetaTableName(db_name, &sql);
sql.append("(key LONGVARCHAR NOT NULL UNIQUE PRIMARY KEY,"
"value LONGVARCHAR)");
if (sqlite3_exec(db_, sql.c_str(), NULL, NULL, NULL) != SQLITE_OK)
return false;
// Note: there is no index over the meta table. We currently only have a
// couple of keys, so it doesn't matter. If we start storing more stuff in
// there, we should create an index.
SetVersionNumber(version);
SetCompatibleVersionNumber(compatible_version);
}
return true;
}
bool MetaTableHelper::SetValue(const std::string& key,
const std::wstring& value) {
SQLStatement s;
if (!PrepareSetStatement(&s, key))
return false;
s.bind_wstring(1, value);
return s.step() == SQLITE_DONE;
}
bool MetaTableHelper::GetValue(const std::string& key,
std::wstring* value) {
DCHECK(value);
SQLStatement s;
if (!PrepareGetStatement(&s, key))
return false;
s.column_wstring(0, value);
return true;
}
bool MetaTableHelper::SetValue(const std::string& key,
int value) {
SQLStatement s;
if (!PrepareSetStatement(&s, key))
return false;
s.bind_int(1, value);
return s.step() == SQLITE_DONE;
}
bool MetaTableHelper::GetValue(const std::string& key,
int* value) {
DCHECK(value);
SQLStatement s;
if (!PrepareGetStatement(&s, key))
return false;
*value = s.column_int(0);
return true;
}
bool MetaTableHelper::SetValue(const std::string& key,
int64 value) {
SQLStatement s;
if (!PrepareSetStatement(&s, key))
return false;
s.bind_int64(1, value);
return s.step() == SQLITE_DONE;
}
bool MetaTableHelper::GetValue(const std::string& key,
int64* value) {
DCHECK(value);
SQLStatement s;
if (!PrepareGetStatement(&s, key))
return false;
*value = s.column_int64(0);
return true;
}
void MetaTableHelper::SetVersionNumber(int version) {
SetValue(kVersionKey, version);
}
int MetaTableHelper::GetVersionNumber() {
int version;
if (!GetValue(kVersionKey, &version))
return 0;
return version;
}
void MetaTableHelper::SetCompatibleVersionNumber(int version) {
SetValue(kCompatibleVersionKey, version);
}
int MetaTableHelper::GetCompatibleVersionNumber() {
int version;
if (!GetValue(kCompatibleVersionKey, &version))
return 0;
return version;
}
// static
void MetaTableHelper::appendMetaTableName(const std::string& db_name,
std::string* sql) {
if (!db_name.empty()) {
sql->append(db_name);
sql->push_back('.');
}
sql->append("meta");
}
bool MetaTableHelper::PrepareSetStatement(SQLStatement* statement,
const std::string& key) {
DCHECK(db_ && statement);
std::string sql("INSERT OR REPLACE INTO ");
appendMetaTableName(db_name_, &sql);
sql.append("(key,value) VALUES(?,?)");
if (statement->prepare(db_, sql.c_str()) != SQLITE_OK) {
NOTREACHED() << sqlite3_errmsg(db_);
return false;
}
statement->bind_text(0, key.c_str());
return true;
}
bool MetaTableHelper::PrepareGetStatement(SQLStatement* statement,
const std::string& key) {
DCHECK(db_ && statement);
std::string sql("SELECT value FROM ");
appendMetaTableName(db_name_, &sql);
sql.append(" WHERE key = ?");
if (statement->prepare(db_, sql.c_str()) != SQLITE_OK) {
NOTREACHED() << sqlite3_errmsg(db_);
return false;
}
statement->bind_string(0, key);
if (statement->step() != SQLITE_ROW)
return false;
return true;
}
<commit_msg>Fix gcc warning about possible unused variable experienced with Apple gcc 4.2 in an -O3 experiment. Review URL: http://codereview.chromium.org/173124<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/meta_table_helper.h"
#include "base/logging.h"
#include "base/string_util.h"
#include "chrome/common/sqlite_utils.h"
// Key used in our meta table for version numbers.
static const char kVersionKey[] = "version";
static const char kCompatibleVersionKey[] = "last_compatible_version";
// static
void MetaTableHelper::PrimeCache(const std::string& db_name, sqlite3* db) {
// A statement must be open for the preload command to work. If the meta
// table doesn't exist, it probably means this is a new database and there
// is nothing to preload (so it's OK we do nothing).
SQLStatement dummy;
if (!DoesSqliteTableExist(db, db_name.c_str(), "meta"))
return;
std::string sql("SELECT * from ");
appendMetaTableName(db_name, &sql);
if (dummy.prepare(db, sql.c_str()) != SQLITE_OK)
return;
if (dummy.step() != SQLITE_ROW)
return;
sqlite3Preload(db);
}
MetaTableHelper::MetaTableHelper() : db_(NULL) {
}
MetaTableHelper::~MetaTableHelper() {
}
bool MetaTableHelper::Init(const std::string& db_name,
int version,
int compatible_version,
sqlite3* db) {
DCHECK(!db_ && db);
db_ = db;
db_name_ = db_name;
if (!DoesSqliteTableExist(db_, db_name.c_str(), "meta")) {
// Build the sql.
std::string sql("CREATE TABLE ");
appendMetaTableName(db_name, &sql);
sql.append("(key LONGVARCHAR NOT NULL UNIQUE PRIMARY KEY,"
"value LONGVARCHAR)");
if (sqlite3_exec(db_, sql.c_str(), NULL, NULL, NULL) != SQLITE_OK)
return false;
// Note: there is no index over the meta table. We currently only have a
// couple of keys, so it doesn't matter. If we start storing more stuff in
// there, we should create an index.
SetVersionNumber(version);
SetCompatibleVersionNumber(compatible_version);
}
return true;
}
bool MetaTableHelper::SetValue(const std::string& key,
const std::wstring& value) {
SQLStatement s;
if (!PrepareSetStatement(&s, key))
return false;
s.bind_wstring(1, value);
return s.step() == SQLITE_DONE;
}
bool MetaTableHelper::GetValue(const std::string& key,
std::wstring* value) {
DCHECK(value);
SQLStatement s;
if (!PrepareGetStatement(&s, key))
return false;
s.column_wstring(0, value);
return true;
}
bool MetaTableHelper::SetValue(const std::string& key,
int value) {
SQLStatement s;
if (!PrepareSetStatement(&s, key))
return false;
s.bind_int(1, value);
return s.step() == SQLITE_DONE;
}
bool MetaTableHelper::GetValue(const std::string& key,
int* value) {
DCHECK(value);
SQLStatement s;
if (!PrepareGetStatement(&s, key))
return false;
*value = s.column_int(0);
return true;
}
bool MetaTableHelper::SetValue(const std::string& key,
int64 value) {
SQLStatement s;
if (!PrepareSetStatement(&s, key))
return false;
s.bind_int64(1, value);
return s.step() == SQLITE_DONE;
}
bool MetaTableHelper::GetValue(const std::string& key,
int64* value) {
DCHECK(value);
SQLStatement s;
if (!PrepareGetStatement(&s, key))
return false;
*value = s.column_int64(0);
return true;
}
void MetaTableHelper::SetVersionNumber(int version) {
SetValue(kVersionKey, version);
}
int MetaTableHelper::GetVersionNumber() {
int version = 0;
if (!GetValue(kVersionKey, &version))
return 0;
return version;
}
void MetaTableHelper::SetCompatibleVersionNumber(int version) {
SetValue(kCompatibleVersionKey, version);
}
int MetaTableHelper::GetCompatibleVersionNumber() {
int version = 0;
if (!GetValue(kCompatibleVersionKey, &version))
return 0;
return version;
}
// static
void MetaTableHelper::appendMetaTableName(const std::string& db_name,
std::string* sql) {
if (!db_name.empty()) {
sql->append(db_name);
sql->push_back('.');
}
sql->append("meta");
}
bool MetaTableHelper::PrepareSetStatement(SQLStatement* statement,
const std::string& key) {
DCHECK(db_ && statement);
std::string sql("INSERT OR REPLACE INTO ");
appendMetaTableName(db_name_, &sql);
sql.append("(key,value) VALUES(?,?)");
if (statement->prepare(db_, sql.c_str()) != SQLITE_OK) {
NOTREACHED() << sqlite3_errmsg(db_);
return false;
}
statement->bind_text(0, key.c_str());
return true;
}
bool MetaTableHelper::PrepareGetStatement(SQLStatement* statement,
const std::string& key) {
DCHECK(db_ && statement);
std::string sql("SELECT value FROM ");
appendMetaTableName(db_name_, &sql);
sql.append(" WHERE key = ?");
if (statement->prepare(db_, sql.c_str()) != SQLITE_OK) {
NOTREACHED() << sqlite3_errmsg(db_);
return false;
}
statement->bind_string(0, key);
if (statement->step() != SQLITE_ROW)
return false;
return true;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/file_util.h"
#include "base/path_service.h"
#include "base/platform_thread.h"
#include "base/string_util.h"
#include "base/test_file_util.h"
#include "base/time.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/test/ui/ui_test.h"
#include "net/base/net_util.h"
using base::TimeDelta;
using base::TimeTicks;
namespace {
class StartupTest : public UITest {
public:
StartupTest() {
show_window_ = true;
pages_ = "about:blank";
}
void SetUp() {}
void TearDown() {}
void RunStartupTest(const char* graph, const char* trace,
bool test_cold, bool important, int profile_type) {
profile_type_ = profile_type;
// Sets the profile data for the run. For now, this is only used for
// the non-default themes test.
if (profile_type != UITest::DEFAULT_THEME) {
set_template_user_data(UITest::ComputeTypicalUserDataSource(
profile_type).ToWStringHack());
}
const int kNumCyclesMax = 20;
int numCycles = kNumCyclesMax;
// It's ok for unit test code to use getenv(), isn't it?
#if defined(OS_WIN)
#pragma warning( disable : 4996 )
#endif
const char* numCyclesEnv = getenv("STARTUP_TESTS_NUMCYCLES");
if (numCyclesEnv && StringToInt(numCyclesEnv, &numCycles))
LOG(INFO) << "STARTUP_TESTS_NUMCYCLES set in environment, "
<< "so setting numCycles to " << numCycles;
TimeDelta timings[kNumCyclesMax];
for (int i = 0; i < numCycles; ++i) {
if (test_cold) {
FilePath dir_app;
ASSERT_TRUE(PathService::Get(chrome::DIR_APP, &dir_app));
FilePath chrome_exe(dir_app.Append(
FilePath::FromWStringHack(chrome::kBrowserProcessExecutablePath)));
ASSERT_TRUE(EvictFileFromSystemCacheWrapper(chrome_exe));
#if defined(OS_WIN)
// chrome.dll is windows specific.
FilePath chrome_dll(dir_app.Append(FILE_PATH_LITERAL("chrome.dll")));
ASSERT_TRUE(EvictFileFromSystemCacheWrapper(chrome_dll));
#endif
#if defined(OS_WIN)
// TODO(port): Re-enable once gears is working on mac/linux.
FilePath gears_dll;
ASSERT_TRUE(PathService::Get(chrome::FILE_GEARS_PLUGIN, &gears_dll));
ASSERT_TRUE(EvictFileFromSystemCacheWrapper(gears_dll));
#else
NOTIMPLEMENTED() << "gears not enabled yet";
#endif
}
UITest::SetUp();
TimeTicks end_time = TimeTicks::Now();
timings[i] = end_time - browser_launch_time_;
// TODO(beng): Can't shut down so quickly. Figure out why, and fix. If we
// do, we crash.
PlatformThread::Sleep(50);
UITest::TearDown();
if (i == 0) {
// Re-use the profile data after first run so that the noise from
// creating databases doesn't impact all the runs.
clear_profile_ = false;
// Destroy template_user_data_ for complex/gtk themes so we don't try
// to rewrite each time through.
if (profile_type != UITest::DEFAULT_THEME)
set_template_user_data(L"");
}
}
std::string times;
for (int i = 0; i < numCycles; ++i)
StringAppendF(×, "%.2f,", timings[i].InMillisecondsF());
PrintResultList(graph, "", trace, times, "ms", important);
}
protected:
std::string pages_;
};
class StartupReferenceTest : public StartupTest {
public:
// override the browser directory that is used by UITest::SetUp to cause it
// to use the reference build instead.
void SetUp() {
FilePath dir;
PathService::Get(chrome::DIR_TEST_TOOLS, &dir);
dir = dir.AppendASCII("reference_build");
#if defined(OS_WIN)
dir = dir.AppendASCII("chrome");
#elif defined(OS_LINUX)
dir = dir.AppendASCII("chrome_linux");
#elif defined(OS_MACOSX)
dir = dir.AppendASCII("chrome_mac");
#endif
browser_directory_ = dir;
}
};
class StartupFileTest : public StartupTest {
public:
// Load a file on startup rather than about:blank. This tests a longer
// startup path, including resource loading and the loading of gears.dll.
void SetUp() {
FilePath file_url;
ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &file_url));
file_url = file_url.AppendASCII("empty.html");
ASSERT_TRUE(file_util::PathExists(file_url));
launch_arguments_.AppendLooseValue(file_url.ToWStringHack());
pages_ = WideToUTF8(file_url.ToWStringHack());
}
};
TEST_F(StartupTest, Perf) {
RunStartupTest("warm", "t", false /* not cold */, true /* important */,
UITest::DEFAULT_THEME);
}
// TODO(port): We need a mac reference build checked in for this.
TEST_F(StartupReferenceTest, Perf) {
RunStartupTest("warm", "t_ref", false /* not cold */,
true /* important */, UITest::DEFAULT_THEME);
}
// TODO(mpcomplete): Should we have reference timings for all these?
TEST_F(StartupTest, PerfCold) {
RunStartupTest("cold", "t", true /* cold */, false /* not important */,
UITest::DEFAULT_THEME);
}
#if defined(OS_WIN)
// TODO(port): Enable gears tests on linux/mac once gears is working.
TEST_F(StartupFileTest, PerfGears) {
RunStartupTest("warm", "gears", false /* not cold */,
false /* not important */, UITest::DEFAULT_THEME);
}
TEST_F(StartupFileTest, PerfColdGears) {
RunStartupTest("cold", "gears", true /* cold */,
false /* not important */, UITest::DEFAULT_THEME);
}
#endif
TEST_F(StartupTest, PerfColdComplexTheme) {
RunStartupTest("warm", "t-theme", false /* warm */,
false /* not important */, UITest::COMPLEX_THEME);
}
#if defined(OS_LINUX)
TEST_F(StartupTest, PerfColdGtkTheme) {
RunStartupTest("warm", "gtk-theme", false /* warm */,
false /* not important */, UITest::NATIVE_THEME);
}
#endif
} // namespace
<commit_msg>Enable startup tests for custom frame. I meant to do this with the last change, but missed it.<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/file_util.h"
#include "base/path_service.h"
#include "base/platform_thread.h"
#include "base/string_util.h"
#include "base/test_file_util.h"
#include "base/time.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/test/ui/ui_test.h"
#include "net/base/net_util.h"
using base::TimeDelta;
using base::TimeTicks;
namespace {
class StartupTest : public UITest {
public:
StartupTest() {
show_window_ = true;
pages_ = "about:blank";
}
void SetUp() {}
void TearDown() {}
void RunStartupTest(const char* graph, const char* trace,
bool test_cold, bool important, int profile_type) {
profile_type_ = profile_type;
// Sets the profile data for the run. For now, this is only used for
// the non-default themes test.
if (profile_type != UITest::DEFAULT_THEME) {
set_template_user_data(UITest::ComputeTypicalUserDataSource(
profile_type).ToWStringHack());
}
const int kNumCyclesMax = 20;
int numCycles = kNumCyclesMax;
// It's ok for unit test code to use getenv(), isn't it?
#if defined(OS_WIN)
#pragma warning( disable : 4996 )
#endif
const char* numCyclesEnv = getenv("STARTUP_TESTS_NUMCYCLES");
if (numCyclesEnv && StringToInt(numCyclesEnv, &numCycles))
LOG(INFO) << "STARTUP_TESTS_NUMCYCLES set in environment, "
<< "so setting numCycles to " << numCycles;
TimeDelta timings[kNumCyclesMax];
for (int i = 0; i < numCycles; ++i) {
if (test_cold) {
FilePath dir_app;
ASSERT_TRUE(PathService::Get(chrome::DIR_APP, &dir_app));
FilePath chrome_exe(dir_app.Append(
FilePath::FromWStringHack(chrome::kBrowserProcessExecutablePath)));
ASSERT_TRUE(EvictFileFromSystemCacheWrapper(chrome_exe));
#if defined(OS_WIN)
// chrome.dll is windows specific.
FilePath chrome_dll(dir_app.Append(FILE_PATH_LITERAL("chrome.dll")));
ASSERT_TRUE(EvictFileFromSystemCacheWrapper(chrome_dll));
#endif
#if defined(OS_WIN)
// TODO(port): Re-enable once gears is working on mac/linux.
FilePath gears_dll;
ASSERT_TRUE(PathService::Get(chrome::FILE_GEARS_PLUGIN, &gears_dll));
ASSERT_TRUE(EvictFileFromSystemCacheWrapper(gears_dll));
#else
NOTIMPLEMENTED() << "gears not enabled yet";
#endif
}
UITest::SetUp();
TimeTicks end_time = TimeTicks::Now();
timings[i] = end_time - browser_launch_time_;
// TODO(beng): Can't shut down so quickly. Figure out why, and fix. If we
// do, we crash.
PlatformThread::Sleep(50);
UITest::TearDown();
if (i == 0) {
// Re-use the profile data after first run so that the noise from
// creating databases doesn't impact all the runs.
clear_profile_ = false;
// Destroy template_user_data_ for complex/gtk themes so we don't try
// to rewrite each time through.
if (profile_type != UITest::DEFAULT_THEME)
set_template_user_data(L"");
}
}
std::string times;
for (int i = 0; i < numCycles; ++i)
StringAppendF(×, "%.2f,", timings[i].InMillisecondsF());
PrintResultList(graph, "", trace, times, "ms", important);
}
protected:
std::string pages_;
};
class StartupReferenceTest : public StartupTest {
public:
// override the browser directory that is used by UITest::SetUp to cause it
// to use the reference build instead.
void SetUp() {
FilePath dir;
PathService::Get(chrome::DIR_TEST_TOOLS, &dir);
dir = dir.AppendASCII("reference_build");
#if defined(OS_WIN)
dir = dir.AppendASCII("chrome");
#elif defined(OS_LINUX)
dir = dir.AppendASCII("chrome_linux");
#elif defined(OS_MACOSX)
dir = dir.AppendASCII("chrome_mac");
#endif
browser_directory_ = dir;
}
};
class StartupFileTest : public StartupTest {
public:
// Load a file on startup rather than about:blank. This tests a longer
// startup path, including resource loading and the loading of gears.dll.
void SetUp() {
FilePath file_url;
ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &file_url));
file_url = file_url.AppendASCII("empty.html");
ASSERT_TRUE(file_util::PathExists(file_url));
launch_arguments_.AppendLooseValue(file_url.ToWStringHack());
pages_ = WideToUTF8(file_url.ToWStringHack());
}
};
TEST_F(StartupTest, Perf) {
RunStartupTest("warm", "t", false /* not cold */, true /* important */,
UITest::DEFAULT_THEME);
}
// TODO(port): We need a mac reference build checked in for this.
TEST_F(StartupReferenceTest, Perf) {
RunStartupTest("warm", "t_ref", false /* not cold */,
true /* important */, UITest::DEFAULT_THEME);
}
// TODO(mpcomplete): Should we have reference timings for all these?
TEST_F(StartupTest, PerfCold) {
RunStartupTest("cold", "t", true /* cold */, false /* not important */,
UITest::DEFAULT_THEME);
}
#if defined(OS_WIN)
// TODO(port): Enable gears tests on linux/mac once gears is working.
TEST_F(StartupFileTest, PerfGears) {
RunStartupTest("warm", "gears", false /* not cold */,
false /* not important */, UITest::DEFAULT_THEME);
}
TEST_F(StartupFileTest, PerfColdGears) {
RunStartupTest("cold", "gears", true /* cold */,
false /* not important */, UITest::DEFAULT_THEME);
}
#endif
TEST_F(StartupTest, PerfColdComplexTheme) {
RunStartupTest("warm", "t-theme", false /* warm */,
false /* not important */, UITest::COMPLEX_THEME);
}
#if defined(OS_LINUX)
TEST_F(StartupTest, PerfColdGtkTheme) {
RunStartupTest("warm", "gtk-theme", false /* warm */,
false /* not important */, UITest::NATIVE_THEME);
}
TEST_F(StartupTest, PrefColdNativeFrame) {
RunStartupTest("warm", "custom-frame", false /* warm */,
false /* not important */, UITest::CUSTOM_FRAME);
}
TEST_F(StartupTest, PerfColdNativeFrameGtkTheme) {
RunStartupTest("warm", "custom-frame-gtk-theme", false /* warm */,
false /* not important */, UITest::CUSTOM_FRAME_NATIVE_THEME);
}
#endif
} // namespace
<|endoftext|> |
<commit_before>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: lex.hxx,v $
* $Revision: 1.4 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef _LEX_HXX
#define _LEX_HXX
#include <hash.hxx>
#include <tools/gen.hxx>
#include <tools/stream.hxx>
/******************** enum ***********************************************/
enum SVTOKEN_ENUM { SVTOKEN_EMPTY, SVTOKEN_COMMENT,
SVTOKEN_INTEGER, SVTOKEN_STRING,
SVTOKEN_BOOL, SVTOKEN_IDENTIFIER,
SVTOKEN_CHAR, SVTOKEN_RTTIBASE,
SVTOKEN_EOF, SVTOKEN_HASHID };
/******************** class SvToken **************************************/
class BigInt;
class SvToken
{
friend class SvTokenStream;
ULONG nLine, nColumn;
SVTOKEN_ENUM nType;
ByteString aString;
union
{
ULONG nLong;
BOOL bBool;
char cChar;
// SvRttiBase * pComplexObj;
SvStringHashEntry * pHash;
};
public:
SvToken();
SvToken( const SvToken & rObj );
SvToken( ULONG n );
SvToken( SVTOKEN_ENUM nTypeP, BOOL b );
SvToken( char c );
SvToken( SVTOKEN_ENUM nTypeP, const ByteString & rStr );
// SvToken( SvRttiBase * pComplexObj );
SvToken( SVTOKEN_ENUM nTypeP );
SvToken & operator = ( const SvToken & rObj );
ByteString GetTokenAsString() const;
ByteString Print() const;
SVTOKEN_ENUM GetType() const { return nType; }
void SetLine( ULONG nLineP ) { nLine = nLineP; }
ULONG GetLine() const { return nLine; }
void SetColumn( ULONG nColumnP ) { nColumn = nColumnP; }
ULONG GetColumn() const { return nColumn; }
BOOL IsEmpty() const { return nType == SVTOKEN_EMPTY; }
BOOL IsComment() const { return nType == SVTOKEN_COMMENT; }
BOOL IsInteger() const { return nType == SVTOKEN_INTEGER; }
BOOL IsString() const { return nType == SVTOKEN_STRING; }
BOOL IsBool() const { return nType == SVTOKEN_BOOL; }
BOOL IsIdentifierHash() const
{ return nType == SVTOKEN_HASHID; }
BOOL IsIdentifier() const
{
return nType == SVTOKEN_IDENTIFIER
|| nType == SVTOKEN_HASHID;
}
BOOL IsChar() const { return nType == SVTOKEN_CHAR; }
BOOL IsRttiBase() const { return nType == SVTOKEN_RTTIBASE; }
BOOL IsEof() const { return nType == SVTOKEN_EOF; }
const ByteString & GetString() const
{
return IsIdentifierHash()
? pHash->GetName()
: aString;
}
ULONG GetNumber() const { return nLong; }
BOOL GetBool() const { return bBool; }
char GetChar() const { return cChar; }
// SvRttiBase *GetObject() const { return pComplexObj; }
void SetHash( SvStringHashEntry * pHashP )
{ pHash = pHashP; nType = SVTOKEN_HASHID; }
BOOL HasHash() const
{ return nType == SVTOKEN_HASHID; }
SvStringHashEntry * GetHash() const { return pHash; }
BOOL Is( SvStringHashEntry * pEntry ) const
{ return IsIdentifierHash() && pHash == pEntry; }
};
inline SvToken::SvToken()
: nType( SVTOKEN_EMPTY ) {}
inline SvToken::SvToken( ULONG n )
: nType( SVTOKEN_INTEGER ), nLong( n ) {}
inline SvToken::SvToken( SVTOKEN_ENUM nTypeP, BOOL b )
: nType( nTypeP ), bBool( b ) {}
inline SvToken::SvToken( char c )
: nType( SVTOKEN_CHAR ), cChar( c ) {}
inline SvToken::SvToken( SVTOKEN_ENUM nTypeP, const ByteString & rStr )
: nType( nTypeP ), aString( rStr ) {}
/*
inline SvToken::SvToken( SvRttiBase * pObj )
: nType( SVTOKEN_RTTIBASE ), pComplexObj( pObj )
{ pObj->AddRef(); }
*/
inline SvToken::SvToken( SVTOKEN_ENUM nTypeP )
: nType( nTypeP ) {}
DECLARE_LIST( SvTokenList, SvToken * )
/******************** class SvTokenStream ********************************/
class SvTokenStream
{
ULONG nLine, nColumn;
int nBufPos;
int c; // naechstes Zeichen
CharSet nCharSet;
char * pCharTab; // Zeiger auf die Konverierungstabelle
USHORT nTabSize; // Tabulator Laenge
ByteString aStrTrue;
ByteString aStrFalse;
ULONG nMaxPos;
SvFileStream * pInStream;
SvStream & rInStream;
String aFileName;
SvTokenList aTokList;
SvToken * pCurToken;
void InitCtor();
ByteString aBufStr;
int GetNextChar();
int GetFastNextChar()
{
return aBufStr.GetChar((USHORT)nBufPos++);
}
void FillTokenList();
ULONG GetNumber();
BOOL MakeToken( SvToken & );
BOOL IsEof() const { return rInStream.IsEof(); }
void SetMax()
{
ULONG n = Tell();
if( n > nMaxPos )
nMaxPos = n;
}
void CalcColumn()
{
// wenn Zeilenende berechnung sparen
if( 0 != c )
{
USHORT n = 0;
nColumn = 0;
while( n < nBufPos )
nColumn += aBufStr.GetChar(n++) == '\t' ? nTabSize : 1;
}
}
public:
SvTokenStream( const String & rFileName );
SvTokenStream( SvStream & rInStream, const String & rFileName );
~SvTokenStream();
static BOOL GetHexValue( const ByteString & rStr, BigInt * pValue );
const String & GetFileName() const { return aFileName; }
SvStream & GetStream() { return rInStream; }
void SetCharSet( CharSet nSet );
CharSet GetCharSet() const { return nCharSet; }
void SetTabSize( USHORT nTabSizeP )
{ nTabSize = nTabSizeP; }
USHORT GetTabSize() const { return nTabSize; }
SvToken * GetToken_PrevAll()
{
SvToken * pRetToken = pCurToken;
if( NULL == (pCurToken = aTokList.Prev()) )
// Current Zeiger nie Null
pCurToken = pRetToken;
return pRetToken;
}
SvToken * GetToken_NextAll()
{
SvToken * pRetToken = pCurToken;
if( NULL == (pCurToken = aTokList.Next()) )
// Current Zeiger nie Null
pCurToken = pRetToken;
SetMax();
return pRetToken;
}
SvToken * GetToken_Next()
{
// Kommentare werden initial entfernt
return GetToken_NextAll();
}
SvToken * GetToken() const { return pCurToken; }
BOOL Skip( char cStart, char cEnd, UINT32 * pBegin );
BOOL Read( char cChar )
{
if( pCurToken->IsChar()
&& cChar == pCurToken->GetChar() )
{
GetToken_Next();
return TRUE;
}
else
return FALSE;
}
void ReadDelemiter()
{
if( pCurToken->IsChar()
&& (';' == pCurToken->GetChar()
|| ',' == pCurToken->GetChar()) )
{
GetToken_Next();
}
}
UINT32 Tell() const
{ return aTokList.GetCurPos(); }
void Seek( UINT32 nPos )
{
pCurToken = aTokList.Seek( nPos );
SetMax();
}
void SeekRel( INT32 nRelPos )
{
pCurToken = aTokList.Seek( Tell() + nRelPos );
SetMax();
}
void SeekEnd()
{
pCurToken = aTokList.Seek( nMaxPos );
}
};
#endif // _LEX_HXX
<commit_msg>INTEGRATION: CWS mba30patches01 (1.3.36); FILE MERGED 2008/04/23 09:44:58 mba 1.3.36.2: RESYNC: (1.3-1.4); FILE MERGED 2008/03/18 15:40:03 mba 1.3.36.1: #i86353#: remove unused code<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: lex.hxx,v $
* $Revision: 1.5 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef _LEX_HXX
#define _LEX_HXX
#include <hash.hxx>
#include <tools/gen.hxx>
#include <tools/stream.hxx>
/******************** enum ***********************************************/
enum SVTOKEN_ENUM { SVTOKEN_EMPTY, SVTOKEN_COMMENT,
SVTOKEN_INTEGER, SVTOKEN_STRING,
SVTOKEN_BOOL, SVTOKEN_IDENTIFIER,
SVTOKEN_CHAR, SVTOKEN_RTTIBASE,
SVTOKEN_EOF, SVTOKEN_HASHID };
/******************** class SvToken **************************************/
class BigInt;
class SvToken
{
friend class SvTokenStream;
ULONG nLine, nColumn;
SVTOKEN_ENUM nType;
ByteString aString;
union
{
ULONG nLong;
BOOL bBool;
char cChar;
// SvRttiBase * pComplexObj;
SvStringHashEntry * pHash;
};
public:
SvToken();
SvToken( const SvToken & rObj );
SvToken( ULONG n );
SvToken( SVTOKEN_ENUM nTypeP, BOOL b );
SvToken( char c );
SvToken( SVTOKEN_ENUM nTypeP, const ByteString & rStr );
// SvToken( SvRttiBase * pComplexObj );
SvToken( SVTOKEN_ENUM nTypeP );
SvToken & operator = ( const SvToken & rObj );
ByteString GetTokenAsString() const;
SVTOKEN_ENUM GetType() const { return nType; }
void SetLine( ULONG nLineP ) { nLine = nLineP; }
ULONG GetLine() const { return nLine; }
void SetColumn( ULONG nColumnP ) { nColumn = nColumnP; }
ULONG GetColumn() const { return nColumn; }
BOOL IsEmpty() const { return nType == SVTOKEN_EMPTY; }
BOOL IsComment() const { return nType == SVTOKEN_COMMENT; }
BOOL IsInteger() const { return nType == SVTOKEN_INTEGER; }
BOOL IsString() const { return nType == SVTOKEN_STRING; }
BOOL IsBool() const { return nType == SVTOKEN_BOOL; }
BOOL IsIdentifierHash() const
{ return nType == SVTOKEN_HASHID; }
BOOL IsIdentifier() const
{
return nType == SVTOKEN_IDENTIFIER
|| nType == SVTOKEN_HASHID;
}
BOOL IsChar() const { return nType == SVTOKEN_CHAR; }
BOOL IsRttiBase() const { return nType == SVTOKEN_RTTIBASE; }
BOOL IsEof() const { return nType == SVTOKEN_EOF; }
const ByteString & GetString() const
{
return IsIdentifierHash()
? pHash->GetName()
: aString;
}
ULONG GetNumber() const { return nLong; }
BOOL GetBool() const { return bBool; }
char GetChar() const { return cChar; }
// SvRttiBase *GetObject() const { return pComplexObj; }
void SetHash( SvStringHashEntry * pHashP )
{ pHash = pHashP; nType = SVTOKEN_HASHID; }
BOOL HasHash() const
{ return nType == SVTOKEN_HASHID; }
SvStringHashEntry * GetHash() const { return pHash; }
BOOL Is( SvStringHashEntry * pEntry ) const
{ return IsIdentifierHash() && pHash == pEntry; }
};
inline SvToken::SvToken()
: nType( SVTOKEN_EMPTY ) {}
inline SvToken::SvToken( ULONG n )
: nType( SVTOKEN_INTEGER ), nLong( n ) {}
inline SvToken::SvToken( SVTOKEN_ENUM nTypeP, BOOL b )
: nType( nTypeP ), bBool( b ) {}
inline SvToken::SvToken( char c )
: nType( SVTOKEN_CHAR ), cChar( c ) {}
inline SvToken::SvToken( SVTOKEN_ENUM nTypeP, const ByteString & rStr )
: nType( nTypeP ), aString( rStr ) {}
/*
inline SvToken::SvToken( SvRttiBase * pObj )
: nType( SVTOKEN_RTTIBASE ), pComplexObj( pObj )
{ pObj->AddRef(); }
*/
inline SvToken::SvToken( SVTOKEN_ENUM nTypeP )
: nType( nTypeP ) {}
DECLARE_LIST( SvTokenList, SvToken * )
/******************** class SvTokenStream ********************************/
class SvTokenStream
{
ULONG nLine, nColumn;
int nBufPos;
int c; // naechstes Zeichen
CharSet nCharSet;
char * pCharTab; // Zeiger auf die Konverierungstabelle
USHORT nTabSize; // Tabulator Laenge
ByteString aStrTrue;
ByteString aStrFalse;
ULONG nMaxPos;
SvFileStream * pInStream;
SvStream & rInStream;
String aFileName;
SvTokenList aTokList;
SvToken * pCurToken;
void InitCtor();
ByteString aBufStr;
int GetNextChar();
int GetFastNextChar()
{
return aBufStr.GetChar((USHORT)nBufPos++);
}
void FillTokenList();
ULONG GetNumber();
BOOL MakeToken( SvToken & );
BOOL IsEof() const { return rInStream.IsEof(); }
void SetMax()
{
ULONG n = Tell();
if( n > nMaxPos )
nMaxPos = n;
}
void CalcColumn()
{
// wenn Zeilenende berechnung sparen
if( 0 != c )
{
USHORT n = 0;
nColumn = 0;
while( n < nBufPos )
nColumn += aBufStr.GetChar(n++) == '\t' ? nTabSize : 1;
}
}
public:
SvTokenStream( const String & rFileName );
SvTokenStream( SvStream & rInStream, const String & rFileName );
~SvTokenStream();
const String & GetFileName() const { return aFileName; }
SvStream & GetStream() { return rInStream; }
void SetCharSet( CharSet nSet );
CharSet GetCharSet() const { return nCharSet; }
void SetTabSize( USHORT nTabSizeP )
{ nTabSize = nTabSizeP; }
USHORT GetTabSize() const { return nTabSize; }
SvToken * GetToken_PrevAll()
{
SvToken * pRetToken = pCurToken;
if( NULL == (pCurToken = aTokList.Prev()) )
// Current Zeiger nie Null
pCurToken = pRetToken;
return pRetToken;
}
SvToken * GetToken_NextAll()
{
SvToken * pRetToken = pCurToken;
if( NULL == (pCurToken = aTokList.Next()) )
// Current Zeiger nie Null
pCurToken = pRetToken;
SetMax();
return pRetToken;
}
SvToken * GetToken_Next()
{
// Kommentare werden initial entfernt
return GetToken_NextAll();
}
SvToken * GetToken() const { return pCurToken; }
BOOL Read( char cChar )
{
if( pCurToken->IsChar()
&& cChar == pCurToken->GetChar() )
{
GetToken_Next();
return TRUE;
}
else
return FALSE;
}
void ReadDelemiter()
{
if( pCurToken->IsChar()
&& (';' == pCurToken->GetChar()
|| ',' == pCurToken->GetChar()) )
{
GetToken_Next();
}
}
UINT32 Tell() const
{ return aTokList.GetCurPos(); }
void Seek( UINT32 nPos )
{
pCurToken = aTokList.Seek( nPos );
SetMax();
}
void SeekRel( INT32 nRelPos )
{
pCurToken = aTokList.Seek( Tell() + nRelPos );
SetMax();
}
void SeekEnd()
{
pCurToken = aTokList.Seek( nMaxPos );
}
};
#endif // _LEX_HXX
<|endoftext|> |
<commit_before>// $Id$
// vim:tabstop=2
/***********************************************************************
Moses - factored phrase-based language decoder
Copyright (C) 2006 University of Edinburgh
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
***********************************************************************/
#include "util/check.hh"
#include <algorithm>
#include <sstream>
#include <string>
#include "memory.h"
#include "FactorCollection.h"
#include "Phrase.h"
#include "StaticData.h" // GetMaxNumFactors
#include "util/string_piece.hh"
#include "util/tokenize_piece.hh"
using namespace std;
namespace Moses
{
Phrase::Phrase() {}
Phrase::Phrase(size_t reserveSize)
{
m_words.reserve(reserveSize);
}
Phrase::Phrase(const vector< const Word* > &mergeWords)
{
m_words.reserve(mergeWords.size());
for (size_t currPos = 0 ; currPos < mergeWords.size() ; currPos++) {
AddWord(*mergeWords[currPos]);
}
}
Phrase::~Phrase()
{
}
void Phrase::MergeFactors(const Phrase ©)
{
CHECK(GetSize() == copy.GetSize());
size_t size = GetSize();
const size_t maxNumFactors = MAX_NUM_FACTORS;
for (size_t currPos = 0 ; currPos < size ; currPos++) {
for (unsigned int currFactor = 0 ; currFactor < maxNumFactors ; currFactor++) {
FactorType factorType = static_cast<FactorType>(currFactor);
const Factor *factor = copy.GetFactor(currPos, factorType);
if (factor != NULL)
SetFactor(currPos, factorType, factor);
}
}
}
void Phrase::MergeFactors(const Phrase ©, FactorType factorType)
{
CHECK(GetSize() == copy.GetSize());
for (size_t currPos = 0 ; currPos < GetSize() ; currPos++)
SetFactor(currPos, factorType, copy.GetFactor(currPos, factorType));
}
void Phrase::MergeFactors(const Phrase ©, const std::vector<FactorType>& factorVec)
{
CHECK(GetSize() == copy.GetSize());
for (size_t currPos = 0 ; currPos < GetSize() ; currPos++)
for (std::vector<FactorType>::const_iterator i = factorVec.begin();
i != factorVec.end(); ++i) {
SetFactor(currPos, *i, copy.GetFactor(currPos, *i));
}
}
Phrase Phrase::GetSubString(const WordsRange &wordsRange) const
{
Phrase retPhrase(wordsRange.GetNumWordsCovered());
for (size_t currPos = wordsRange.GetStartPos() ; currPos <= wordsRange.GetEndPos() ; currPos++) {
Word &word = retPhrase.AddWord();
word = GetWord(currPos);
}
return retPhrase;
}
Phrase Phrase::GetSubString(const WordsRange &wordsRange, FactorType factorType) const
{
Phrase retPhrase(wordsRange.GetNumWordsCovered());
for (size_t currPos = wordsRange.GetStartPos() ; currPos <= wordsRange.GetEndPos() ; currPos++) {
const Factor* f = GetFactor(currPos, factorType);
Word &word = retPhrase.AddWord();
word.SetFactor(factorType, f);
}
return retPhrase;
}
std::string Phrase::GetStringRep(const vector<FactorType> factorsToPrint) const
{
stringstream strme;
for (size_t pos = 0 ; pos < GetSize() ; pos++) {
strme << GetWord(pos).GetString(factorsToPrint, (pos != GetSize()-1));
}
return strme.str();
}
Word &Phrase::AddWord()
{
m_words.push_back(Word());
return m_words.back();
}
void Phrase::Append(const Phrase &endPhrase)
{
for (size_t i = 0; i < endPhrase.GetSize(); i++) {
AddWord(endPhrase.GetWord(i));
}
}
void Phrase::PrependWord(const Word &newWord)
{
AddWord();
// shift
for (size_t pos = GetSize() - 1; pos >= 1; --pos) {
const Word &word = m_words[pos - 1];
m_words[pos] = word;
}
m_words[0] = newWord;
}
void Phrase::CreateFromString(FactorDirection direction
,const std::vector<FactorType> &factorOrder
,const StringPiece &phraseString
,const StringPiece &factorDelimiter
,Word **lhs)
{
// parse
vector<StringPiece> annotatedWordVector;
for (util::TokenIter<util::AnyCharacter, true> it(phraseString, "\t "); it; ++it) {
annotatedWordVector.push_back(*it);
}
if (annotatedWordVector.size() == 0) {
if (lhs) {
(*lhs) = NULL;
}
return;
}
// KOMMA|none ART|Def.Z NN|Neut.NotGen.Sg VVFIN|none
// to
// "KOMMA|none" "ART|Def.Z" "NN|Neut.NotGen.Sg" "VVFIN|none"
size_t numWords;
const StringPiece &annotatedWord = annotatedWordVector.back();
if (annotatedWord.size() >= 2
&& *annotatedWord.data() == '['
&& annotatedWord.data()[annotatedWord.size() - 1] == ']') {
// hiero/syntax rule
numWords = annotatedWordVector.size()-1;
// lhs
assert(lhs);
(*lhs) = new Word(true);
(*lhs)->CreateFromString(direction, factorOrder, annotatedWord.substr(1, annotatedWord.size() - 2), true);
assert((*lhs)->IsNonTerminal());
} else {
numWords = annotatedWordVector.size();
//CHECK(lhs == NULL);
if (lhs) {
(*lhs) = NULL;
}
}
// parse each word
m_words.reserve(numWords);
for (size_t phrasePos = 0 ; phrasePos < numWords; phrasePos++) {
StringPiece &annotatedWord = annotatedWordVector[phrasePos];
bool isNonTerminal;
if (annotatedWord.size() >= 2 && *annotatedWord.data() == '[' && annotatedWord.data()[annotatedWord.size() - 1] == ']') {
// non-term
isNonTerminal = true;
size_t nextPos = annotatedWord.find('[', 1);
CHECK(nextPos != string::npos);
if (direction == Input)
annotatedWord = annotatedWord.substr(1, nextPos - 2);
else
annotatedWord = annotatedWord.substr(nextPos + 1, annotatedWord.size() - nextPos - 2);
} else {
isNonTerminal = false;
}
Word &word = AddWord();
word.CreateFromString(direction, factorOrder, annotatedWord, isNonTerminal);
}
}
int Phrase::Compare(const Phrase &other) const
{
#ifdef min
#undef min
#endif
size_t thisSize = GetSize()
,compareSize = other.GetSize();
if (thisSize != compareSize) {
return (thisSize < compareSize) ? -1 : 1;
}
for (size_t pos = 0 ; pos < thisSize ; pos++) {
const Word &thisWord = GetWord(pos)
,&otherWord = other.GetWord(pos);
int ret = Word::Compare(thisWord, otherWord);
if (ret != 0)
return ret;
}
return 0;
}
bool Phrase::Contains(const vector< vector<string> > &subPhraseVector
, const vector<FactorType> &inputFactor) const
{
const size_t subSize = subPhraseVector.size()
,thisSize= GetSize();
if (subSize > thisSize)
return false;
// try to match word-for-word
for (size_t currStartPos = 0 ; currStartPos < (thisSize - subSize + 1) ; currStartPos++) {
bool match = true;
for (size_t currFactorIndex = 0 ; currFactorIndex < inputFactor.size() ; currFactorIndex++) {
FactorType factorType = inputFactor[currFactorIndex];
for (size_t currSubPos = 0 ; currSubPos < subSize ; currSubPos++) {
size_t currThisPos = currSubPos + currStartPos;
const string &subStr = subPhraseVector[currSubPos][currFactorIndex];
StringPiece thisStr = GetFactor(currThisPos, factorType)->GetString();
if (subStr != thisStr) {
match = false;
break;
}
}
if (!match)
break;
}
if (match)
return true;
}
return false;
}
bool Phrase::IsCompatible(const Phrase &inputPhrase) const
{
if (inputPhrase.GetSize() != GetSize()) {
return false;
}
const size_t size = GetSize();
const size_t maxNumFactors = MAX_NUM_FACTORS;
for (size_t currPos = 0 ; currPos < size ; currPos++) {
for (unsigned int currFactor = 0 ; currFactor < maxNumFactors ; currFactor++) {
FactorType factorType = static_cast<FactorType>(currFactor);
const Factor *thisFactor = GetFactor(currPos, factorType)
,*inputFactor = inputPhrase.GetFactor(currPos, factorType);
if (thisFactor != NULL && inputFactor != NULL && thisFactor != inputFactor)
return false;
}
}
return true;
}
bool Phrase::IsCompatible(const Phrase &inputPhrase, FactorType factorType) const
{
if (inputPhrase.GetSize() != GetSize()) {
return false;
}
for (size_t currPos = 0 ; currPos < GetSize() ; currPos++) {
if (GetFactor(currPos, factorType) != inputPhrase.GetFactor(currPos, factorType))
return false;
}
return true;
}
bool Phrase::IsCompatible(const Phrase &inputPhrase, const std::vector<FactorType>& factorVec) const
{
if (inputPhrase.GetSize() != GetSize()) {
return false;
}
for (size_t currPos = 0 ; currPos < GetSize() ; currPos++) {
for (std::vector<FactorType>::const_iterator i = factorVec.begin();
i != factorVec.end(); ++i) {
if (GetFactor(currPos, *i) != inputPhrase.GetFactor(currPos, *i))
return false;
}
}
return true;
}
size_t Phrase::GetNumTerminals() const
{
size_t ret = 0;
for (size_t pos = 0; pos < GetSize(); ++pos) {
if (!GetWord(pos).IsNonTerminal())
ret++;
}
return ret;
}
void Phrase::InitializeMemPool()
{
}
void Phrase::FinalizeMemPool()
{
}
void Phrase::OnlyTheseFactors(const FactorMask &factors)
{
for (unsigned int currFactor = 0 ; currFactor < MAX_NUM_FACTORS ; currFactor++) {
if (!factors[currFactor]) {
for (size_t pos = 0; pos < GetSize(); ++pos) {
SetFactor(pos, currFactor, NULL);
}
}
}
}
void Phrase::InitStartEndWord()
{
FactorCollection &factorCollection = FactorCollection::Instance();
Word startWord(Input);
const Factor *factor = factorCollection.AddFactor(Input, 0, BOS_); // TODO - non-factored
startWord.SetFactor(0, factor);
PrependWord(startWord);
Word endWord(Input);
factor = factorCollection.AddFactor(Input, 0, EOS_); // TODO - non-factored
endWord.SetFactor(0, factor);
AddWord(endWord);
}
bool Phrase::Contains(const Phrase &sought) const
{
}
TO_STRING_BODY(Phrase);
// friend
ostream& operator<<(ostream& out, const Phrase& phrase)
{
// out << "(size " << phrase.GetSize() << ") ";
for (size_t pos = 0 ; pos < phrase.GetSize() ; pos++) {
const Word &word = phrase.GetWord(pos);
out << word;
}
return out;
}
}
<commit_msg>Phrase::Contains(const Phrase& sought) throws exception, since it's not implemented yet. Added return value to make the compiler shut up.<commit_after>// $Id$
// vim:tabstop=2
/***********************************************************************
Moses - factored phrase-based language decoder
Copyright (C) 2006 University of Edinburgh
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
***********************************************************************/
#include "util/check.hh"
#include <algorithm>
#include <sstream>
#include <string>
#include "memory.h"
#include "FactorCollection.h"
#include "Phrase.h"
#include "StaticData.h" // GetMaxNumFactors
#include "util/string_piece.hh"
#include "util/tokenize_piece.hh"
using namespace std;
namespace Moses
{
Phrase::Phrase() {}
Phrase::Phrase(size_t reserveSize)
{
m_words.reserve(reserveSize);
}
Phrase::Phrase(const vector< const Word* > &mergeWords)
{
m_words.reserve(mergeWords.size());
for (size_t currPos = 0 ; currPos < mergeWords.size() ; currPos++) {
AddWord(*mergeWords[currPos]);
}
}
Phrase::~Phrase()
{
}
void Phrase::MergeFactors(const Phrase ©)
{
CHECK(GetSize() == copy.GetSize());
size_t size = GetSize();
const size_t maxNumFactors = MAX_NUM_FACTORS;
for (size_t currPos = 0 ; currPos < size ; currPos++) {
for (unsigned int currFactor = 0 ; currFactor < maxNumFactors ; currFactor++) {
FactorType factorType = static_cast<FactorType>(currFactor);
const Factor *factor = copy.GetFactor(currPos, factorType);
if (factor != NULL)
SetFactor(currPos, factorType, factor);
}
}
}
void Phrase::MergeFactors(const Phrase ©, FactorType factorType)
{
CHECK(GetSize() == copy.GetSize());
for (size_t currPos = 0 ; currPos < GetSize() ; currPos++)
SetFactor(currPos, factorType, copy.GetFactor(currPos, factorType));
}
void Phrase::MergeFactors(const Phrase ©, const std::vector<FactorType>& factorVec)
{
CHECK(GetSize() == copy.GetSize());
for (size_t currPos = 0 ; currPos < GetSize() ; currPos++)
for (std::vector<FactorType>::const_iterator i = factorVec.begin();
i != factorVec.end(); ++i) {
SetFactor(currPos, *i, copy.GetFactor(currPos, *i));
}
}
Phrase Phrase::GetSubString(const WordsRange &wordsRange) const
{
Phrase retPhrase(wordsRange.GetNumWordsCovered());
for (size_t currPos = wordsRange.GetStartPos() ; currPos <= wordsRange.GetEndPos() ; currPos++) {
Word &word = retPhrase.AddWord();
word = GetWord(currPos);
}
return retPhrase;
}
Phrase Phrase::GetSubString(const WordsRange &wordsRange, FactorType factorType) const
{
Phrase retPhrase(wordsRange.GetNumWordsCovered());
for (size_t currPos = wordsRange.GetStartPos() ; currPos <= wordsRange.GetEndPos() ; currPos++) {
const Factor* f = GetFactor(currPos, factorType);
Word &word = retPhrase.AddWord();
word.SetFactor(factorType, f);
}
return retPhrase;
}
std::string Phrase::GetStringRep(const vector<FactorType> factorsToPrint) const
{
stringstream strme;
for (size_t pos = 0 ; pos < GetSize() ; pos++) {
strme << GetWord(pos).GetString(factorsToPrint, (pos != GetSize()-1));
}
return strme.str();
}
Word &Phrase::AddWord()
{
m_words.push_back(Word());
return m_words.back();
}
void Phrase::Append(const Phrase &endPhrase)
{
for (size_t i = 0; i < endPhrase.GetSize(); i++) {
AddWord(endPhrase.GetWord(i));
}
}
void Phrase::PrependWord(const Word &newWord)
{
AddWord();
// shift
for (size_t pos = GetSize() - 1; pos >= 1; --pos) {
const Word &word = m_words[pos - 1];
m_words[pos] = word;
}
m_words[0] = newWord;
}
void Phrase::CreateFromString(FactorDirection direction
,const std::vector<FactorType> &factorOrder
,const StringPiece &phraseString
,const StringPiece &factorDelimiter
,Word **lhs)
{
// parse
vector<StringPiece> annotatedWordVector;
for (util::TokenIter<util::AnyCharacter, true> it(phraseString, "\t "); it; ++it) {
annotatedWordVector.push_back(*it);
}
if (annotatedWordVector.size() == 0) {
if (lhs) {
(*lhs) = NULL;
}
return;
}
// KOMMA|none ART|Def.Z NN|Neut.NotGen.Sg VVFIN|none
// to
// "KOMMA|none" "ART|Def.Z" "NN|Neut.NotGen.Sg" "VVFIN|none"
size_t numWords;
const StringPiece &annotatedWord = annotatedWordVector.back();
if (annotatedWord.size() >= 2
&& *annotatedWord.data() == '['
&& annotatedWord.data()[annotatedWord.size() - 1] == ']') {
// hiero/syntax rule
numWords = annotatedWordVector.size()-1;
// lhs
assert(lhs);
(*lhs) = new Word(true);
(*lhs)->CreateFromString(direction, factorOrder, annotatedWord.substr(1, annotatedWord.size() - 2), true);
assert((*lhs)->IsNonTerminal());
} else {
numWords = annotatedWordVector.size();
//CHECK(lhs == NULL);
if (lhs) {
(*lhs) = NULL;
}
}
// parse each word
m_words.reserve(numWords);
for (size_t phrasePos = 0 ; phrasePos < numWords; phrasePos++) {
StringPiece &annotatedWord = annotatedWordVector[phrasePos];
bool isNonTerminal;
if (annotatedWord.size() >= 2 && *annotatedWord.data() == '[' && annotatedWord.data()[annotatedWord.size() - 1] == ']') {
// non-term
isNonTerminal = true;
size_t nextPos = annotatedWord.find('[', 1);
CHECK(nextPos != string::npos);
if (direction == Input)
annotatedWord = annotatedWord.substr(1, nextPos - 2);
else
annotatedWord = annotatedWord.substr(nextPos + 1, annotatedWord.size() - nextPos - 2);
} else {
isNonTerminal = false;
}
Word &word = AddWord();
word.CreateFromString(direction, factorOrder, annotatedWord, isNonTerminal);
}
}
int Phrase::Compare(const Phrase &other) const
{
#ifdef min
#undef min
#endif
size_t thisSize = GetSize()
,compareSize = other.GetSize();
if (thisSize != compareSize) {
return (thisSize < compareSize) ? -1 : 1;
}
for (size_t pos = 0 ; pos < thisSize ; pos++) {
const Word &thisWord = GetWord(pos)
,&otherWord = other.GetWord(pos);
int ret = Word::Compare(thisWord, otherWord);
if (ret != 0)
return ret;
}
return 0;
}
bool Phrase::Contains(const vector< vector<string> > &subPhraseVector
, const vector<FactorType> &inputFactor) const
{
const size_t subSize = subPhraseVector.size()
,thisSize= GetSize();
if (subSize > thisSize)
return false;
// try to match word-for-word
for (size_t currStartPos = 0 ; currStartPos < (thisSize - subSize + 1) ; currStartPos++) {
bool match = true;
for (size_t currFactorIndex = 0 ; currFactorIndex < inputFactor.size() ; currFactorIndex++) {
FactorType factorType = inputFactor[currFactorIndex];
for (size_t currSubPos = 0 ; currSubPos < subSize ; currSubPos++) {
size_t currThisPos = currSubPos + currStartPos;
const string &subStr = subPhraseVector[currSubPos][currFactorIndex];
StringPiece thisStr = GetFactor(currThisPos, factorType)->GetString();
if (subStr != thisStr) {
match = false;
break;
}
}
if (!match)
break;
}
if (match)
return true;
}
return false;
}
bool Phrase::IsCompatible(const Phrase &inputPhrase) const
{
if (inputPhrase.GetSize() != GetSize()) {
return false;
}
const size_t size = GetSize();
const size_t maxNumFactors = MAX_NUM_FACTORS;
for (size_t currPos = 0 ; currPos < size ; currPos++) {
for (unsigned int currFactor = 0 ; currFactor < maxNumFactors ; currFactor++) {
FactorType factorType = static_cast<FactorType>(currFactor);
const Factor *thisFactor = GetFactor(currPos, factorType)
,*inputFactor = inputPhrase.GetFactor(currPos, factorType);
if (thisFactor != NULL && inputFactor != NULL && thisFactor != inputFactor)
return false;
}
}
return true;
}
bool Phrase::IsCompatible(const Phrase &inputPhrase, FactorType factorType) const
{
if (inputPhrase.GetSize() != GetSize()) {
return false;
}
for (size_t currPos = 0 ; currPos < GetSize() ; currPos++) {
if (GetFactor(currPos, factorType) != inputPhrase.GetFactor(currPos, factorType))
return false;
}
return true;
}
bool Phrase::IsCompatible(const Phrase &inputPhrase, const std::vector<FactorType>& factorVec) const
{
if (inputPhrase.GetSize() != GetSize()) {
return false;
}
for (size_t currPos = 0 ; currPos < GetSize() ; currPos++) {
for (std::vector<FactorType>::const_iterator i = factorVec.begin();
i != factorVec.end(); ++i) {
if (GetFactor(currPos, *i) != inputPhrase.GetFactor(currPos, *i))
return false;
}
}
return true;
}
size_t Phrase::GetNumTerminals() const
{
size_t ret = 0;
for (size_t pos = 0; pos < GetSize(); ++pos) {
if (!GetWord(pos).IsNonTerminal())
ret++;
}
return ret;
}
void Phrase::InitializeMemPool()
{
}
void Phrase::FinalizeMemPool()
{
}
void Phrase::OnlyTheseFactors(const FactorMask &factors)
{
for (unsigned int currFactor = 0 ; currFactor < MAX_NUM_FACTORS ; currFactor++) {
if (!factors[currFactor]) {
for (size_t pos = 0; pos < GetSize(); ++pos) {
SetFactor(pos, currFactor, NULL);
}
}
}
}
void Phrase::InitStartEndWord()
{
FactorCollection &factorCollection = FactorCollection::Instance();
Word startWord(Input);
const Factor *factor = factorCollection.AddFactor(Input, 0, BOS_); // TODO - non-factored
startWord.SetFactor(0, factor);
PrependWord(startWord);
Word endWord(Input);
factor = factorCollection.AddFactor(Input, 0, EOS_); // TODO - non-factored
endWord.SetFactor(0, factor);
AddWord(endWord);
}
bool Phrase::Contains(const Phrase &sought) const
{
throw "THIS FUNCTION IS NOT IMPLEMENTED YET!";
return false;
}
TO_STRING_BODY(Phrase);
// friend
ostream& operator<<(ostream& out, const Phrase& phrase)
{
// out << "(size " << phrase.GetSize() << ") ";
for (size_t pos = 0 ; pos < phrase.GetSize() ; pos++) {
const Word &word = phrase.GetWord(pos);
out << word;
}
return out;
}
}
<|endoftext|> |
<commit_before>//===-- MachineFunction.cpp -----------------------------------------------===//
//
// Collect native machine code information for a function. This allows
// target-specific information about the generated code to be stored with each
// function.
//
//===----------------------------------------------------------------------===//
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineInstr.h"
#include "llvm/CodeGen/MachineCodeForInstruction.h"
#include "llvm/CodeGen/SSARegMap.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/MachineFrameInfo.h"
#include "llvm/Target/MachineCacheInfo.h"
#include "llvm/Function.h"
#include "llvm/iOther.h"
#include "llvm/Pass.h"
#include <limits.h>
const int INVALID_FRAME_OFFSET = INT_MAX; // std::numeric_limits<int>::max();
static AnnotationID MF_AID(
AnnotationManager::getID("CodeGen::MachineCodeForFunction"));
//===---------------------------------------------------------------------===//
// Code generation/destruction passes
//===---------------------------------------------------------------------===//
namespace {
class ConstructMachineFunction : public FunctionPass {
TargetMachine &Target;
public:
ConstructMachineFunction(TargetMachine &T) : Target(T) {}
const char *getPassName() const {
return "ConstructMachineFunction";
}
bool runOnFunction(Function &F) {
MachineFunction::construct(&F, Target).CalculateArgSize();
return false;
}
};
struct DestroyMachineFunction : public FunctionPass {
const char *getPassName() const { return "FreeMachineFunction"; }
static void freeMachineCode(Instruction &I) {
MachineCodeForInstruction::destroy(&I);
}
bool runOnFunction(Function &F) {
for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI)
for (BasicBlock::iterator I = FI->begin(), E = FI->end(); I != E; ++I)
MachineCodeForInstruction::get(I).dropAllReferences();
for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI)
for_each(FI->begin(), FI->end(), freeMachineCode);
return false;
}
};
struct Printer : public FunctionPass {
const char *getPassName() const { return "MachineFunction Printer"; }
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
AU.setPreservesAll();
}
bool runOnFunction(Function &F) {
MachineFunction::get(&F).dump();
return false;
}
};
}
Pass *createMachineCodeConstructionPass(TargetMachine &Target) {
return new ConstructMachineFunction(Target);
}
Pass *createMachineCodeDestructionPass() {
return new DestroyMachineFunction();
}
Pass *createMachineFunctionPrinterPass() {
return new Printer();
}
//===---------------------------------------------------------------------===//
// MachineFunction implementation
//===---------------------------------------------------------------------===//
MachineFunction::MachineFunction(const Function *F,
const TargetMachine& target)
: Annotation(MF_AID), Fn(F), Target(target) {
SSARegMapping = new SSARegMap();
// FIXME: move state into another class
staticStackSize = automaticVarsSize = regSpillsSize = 0;
maxOptionalArgsSize = maxOptionalNumArgs = currentTmpValuesSize = 0;
maxTmpValuesSize = 0;
compiledAsLeaf = spillsAreaFrozen = automaticVarsAreaFrozen = false;
}
MachineFunction::~MachineFunction() {
delete SSARegMapping;
}
void MachineFunction::dump() const { print(std::cerr); }
void MachineFunction::print(std::ostream &OS) const {
OS << "\n" << *(Value*)Fn->getReturnType() << " \"" << Fn->getName()<< "\"\n";
for (const_iterator BB = begin(); BB != end(); ++BB) {
BasicBlock *LBB = BB->getBasicBlock();
OS << "\n" << LBB->getName() << " (" << (const void*)LBB << "):\n";
for (MachineBasicBlock::const_iterator I = BB->begin(); I != BB->end();++I){
OS << "\t";
(*I)->print(OS, Target);
}
}
OS << "\nEnd function \"" << Fn->getName() << "\"\n\n";
}
// The next two methods are used to construct and to retrieve
// the MachineCodeForFunction object for the given function.
// construct() -- Allocates and initializes for a given function and target
// get() -- Returns a handle to the object.
// This should not be called before "construct()"
// for a given Function.
//
MachineFunction&
MachineFunction::construct(const Function *Fn, const TargetMachine &Tar)
{
assert(Fn->getAnnotation(MF_AID) == 0 &&
"Object already exists for this function!");
MachineFunction* mcInfo = new MachineFunction(Fn, Tar);
Fn->addAnnotation(mcInfo);
return *mcInfo;
}
void
MachineFunction::destruct(const Function *Fn)
{
bool Deleted = Fn->deleteAnnotation(MF_AID);
assert(Deleted && "Machine code did not exist for function!");
}
MachineFunction& MachineFunction::get(const Function *F)
{
MachineFunction *mc = (MachineFunction*)F->getAnnotation(MF_AID);
assert(mc && "Call construct() method first to allocate the object");
return *mc;
}
void MachineFunction::clearSSARegMap() {
delete SSARegMapping;
SSARegMapping = 0;
}
static unsigned
ComputeMaxOptionalArgsSize(const TargetMachine& target, const Function *F,
unsigned &maxOptionalNumArgs)
{
const MachineFrameInfo& frameInfo = target.getFrameInfo();
unsigned maxSize = 0;
for (Function::const_iterator BB = F->begin(), BBE = F->end(); BB !=BBE; ++BB)
for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
if (const CallInst *callInst = dyn_cast<CallInst>(&*I))
{
unsigned numOperands = callInst->getNumOperands() - 1;
int numExtra = (int)numOperands-frameInfo.getNumFixedOutgoingArgs();
if (numExtra <= 0)
continue;
unsigned int sizeForThisCall;
if (frameInfo.argsOnStackHaveFixedSize())
{
int argSize = frameInfo.getSizeOfEachArgOnStack();
sizeForThisCall = numExtra * (unsigned) argSize;
}
else
{
assert(0 && "UNTESTED CODE: Size per stack argument is not "
"fixed on this architecture: use actual arg sizes to "
"compute MaxOptionalArgsSize");
sizeForThisCall = 0;
for (unsigned i = 0; i < numOperands; ++i)
sizeForThisCall += target.DataLayout.getTypeSize(callInst->
getOperand(i)->getType());
}
if (maxSize < sizeForThisCall)
maxSize = sizeForThisCall;
if ((int)maxOptionalNumArgs < numExtra)
maxOptionalNumArgs = (unsigned) numExtra;
}
return maxSize;
}
// Align data larger than one L1 cache line on L1 cache line boundaries.
// Align all smaller data on the next higher 2^x boundary (4, 8, ...),
// but not higher than the alignment of the largest type we support
// (currently a double word). -- see class TargetData).
//
// This function is similar to the corresponding function in EmitAssembly.cpp
// but they are unrelated. This one does not align at more than a
// double-word boundary whereas that one might.
//
inline unsigned int
SizeToAlignment(unsigned int size, const TargetMachine& target)
{
unsigned short cacheLineSize = target.getCacheInfo().getCacheLineSize(1);
if (size > (unsigned) cacheLineSize / 2)
return cacheLineSize;
else
for (unsigned sz=1; /*no condition*/; sz *= 2)
if (sz >= size || sz >= target.DataLayout.getDoubleAlignment())
return sz;
}
void MachineFunction::CalculateArgSize() {
maxOptionalArgsSize = ComputeMaxOptionalArgsSize(Target, Fn,
maxOptionalNumArgs);
staticStackSize = maxOptionalArgsSize
+ Target.getFrameInfo().getMinStackFrameSize();
}
int
MachineFunction::computeOffsetforLocalVar(const TargetMachine& target,
const Value* val,
unsigned int& getPaddedSize,
unsigned int sizeToUse)
{
if (sizeToUse == 0)
sizeToUse = target.findOptimalStorageSize(val->getType());
unsigned int align = SizeToAlignment(sizeToUse, target);
bool growUp;
int firstOffset = target.getFrameInfo().getFirstAutomaticVarOffset(*this,
growUp);
int offset = growUp? firstOffset + getAutomaticVarsSize()
: firstOffset - (getAutomaticVarsSize() + sizeToUse);
int aligned = target.getFrameInfo().adjustAlignment(offset, growUp, align);
getPaddedSize = sizeToUse + abs(aligned - offset);
return aligned;
}
int
MachineFunction::allocateLocalVar(const TargetMachine& target,
const Value* val,
unsigned int sizeToUse)
{
assert(! automaticVarsAreaFrozen &&
"Size of auto vars area has been used to compute an offset so "
"no more automatic vars should be allocated!");
// Check if we've allocated a stack slot for this value already
//
int offset = getOffset(val);
if (offset == INVALID_FRAME_OFFSET)
{
unsigned int getPaddedSize;
offset = computeOffsetforLocalVar(target, val, getPaddedSize, sizeToUse);
offsets[val] = offset;
incrementAutomaticVarsSize(getPaddedSize);
}
return offset;
}
int
MachineFunction::allocateSpilledValue(const TargetMachine& target,
const Type* type)
{
assert(! spillsAreaFrozen &&
"Size of reg spills area has been used to compute an offset so "
"no more register spill slots should be allocated!");
unsigned int size = target.DataLayout.getTypeSize(type);
unsigned char align = target.DataLayout.getTypeAlignment(type);
bool growUp;
int firstOffset = target.getFrameInfo().getRegSpillAreaOffset(*this, growUp);
int offset = growUp? firstOffset + getRegSpillsSize()
: firstOffset - (getRegSpillsSize() + size);
int aligned = target.getFrameInfo().adjustAlignment(offset, growUp, align);
size += abs(aligned - offset); // include alignment padding in size
incrementRegSpillsSize(size); // update size of reg. spills area
return aligned;
}
int
MachineFunction::pushTempValue(const TargetMachine& target,
unsigned int size)
{
unsigned int align = SizeToAlignment(size, target);
bool growUp;
int firstOffset = target.getFrameInfo().getTmpAreaOffset(*this, growUp);
int offset = growUp? firstOffset + currentTmpValuesSize
: firstOffset - (currentTmpValuesSize + size);
int aligned = target.getFrameInfo().adjustAlignment(offset, growUp, align);
size += abs(aligned - offset); // include alignment padding in size
incrementTmpAreaSize(size); // update "current" size of tmp area
return aligned;
}
void
MachineFunction::popAllTempValues(const TargetMachine& target)
{
resetTmpAreaSize(); // clear tmp area to reuse
}
int
MachineFunction::getOffset(const Value* val) const
{
hash_map<const Value*, int>::const_iterator pair = offsets.find(val);
return (pair == offsets.end()) ? INVALID_FRAME_OFFSET : pair->second;
}
<commit_msg>* A bunch of functionality and data was removed from MachineFunction and put into a new MachineFunctionInfo class * Implement new FunctionFrameInfo class<commit_after>//===-- MachineFunction.cpp -----------------------------------------------===//
//
// Collect native machine code information for a function. This allows
// target-specific information about the generated code to be stored with each
// function.
//
//===----------------------------------------------------------------------===//
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineInstr.h"
#include "llvm/CodeGen/MachineCodeForInstruction.h"
#include "llvm/CodeGen/SSARegMap.h"
#include "llvm/CodeGen/MachineFunctionInfo.h"
#include "llvm/CodeGen/FunctionFrameInfo.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/MachineFrameInfo.h"
#include "llvm/Target/MachineCacheInfo.h"
#include "llvm/Function.h"
#include "llvm/iOther.h"
#include "llvm/Pass.h"
#include <limits.h>
const int INVALID_FRAME_OFFSET = INT_MAX; // std::numeric_limits<int>::max();
static AnnotationID MF_AID(
AnnotationManager::getID("CodeGen::MachineCodeForFunction"));
//===---------------------------------------------------------------------===//
// Code generation/destruction passes
//===---------------------------------------------------------------------===//
namespace {
class ConstructMachineFunction : public FunctionPass {
TargetMachine &Target;
public:
ConstructMachineFunction(TargetMachine &T) : Target(T) {}
const char *getPassName() const {
return "ConstructMachineFunction";
}
bool runOnFunction(Function &F) {
MachineFunction::construct(&F, Target).getInfo()->CalculateArgSize();
return false;
}
};
struct DestroyMachineFunction : public FunctionPass {
const char *getPassName() const { return "FreeMachineFunction"; }
static void freeMachineCode(Instruction &I) {
MachineCodeForInstruction::destroy(&I);
}
bool runOnFunction(Function &F) {
for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI)
for (BasicBlock::iterator I = FI->begin(), E = FI->end(); I != E; ++I)
MachineCodeForInstruction::get(I).dropAllReferences();
for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI)
for_each(FI->begin(), FI->end(), freeMachineCode);
return false;
}
};
struct Printer : public FunctionPass {
const char *getPassName() const { return "MachineFunction Printer"; }
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
AU.setPreservesAll();
}
bool runOnFunction(Function &F) {
MachineFunction::get(&F).dump();
return false;
}
};
}
Pass *createMachineCodeConstructionPass(TargetMachine &Target) {
return new ConstructMachineFunction(Target);
}
Pass *createMachineCodeDestructionPass() {
return new DestroyMachineFunction();
}
Pass *createMachineFunctionPrinterPass() {
return new Printer();
}
//===---------------------------------------------------------------------===//
// MachineFunction implementation
//===---------------------------------------------------------------------===//
MachineFunction::MachineFunction(const Function *F,
const TargetMachine &TM)
: Annotation(MF_AID), Fn(F), Target(TM) {
SSARegMapping = new SSARegMap();
MFInfo = new MachineFunctionInfo(*this);
FrameInfo = new FunctionFrameInfo();
}
MachineFunction::~MachineFunction() {
delete SSARegMapping;
delete MFInfo;
delete FrameInfo;
}
void MachineFunction::dump() const { print(std::cerr); }
void MachineFunction::print(std::ostream &OS) const {
OS << "\n" << *(Value*)Fn->getFunctionType() << " \"" << Fn->getName()
<< "\"\n";
// Print Frame Information
getFrameInfo()->print(OS);
for (const_iterator BB = begin(); BB != end(); ++BB) {
BasicBlock *LBB = BB->getBasicBlock();
OS << "\n" << LBB->getName() << " (" << (const void*)LBB << "):\n";
for (MachineBasicBlock::const_iterator I = BB->begin(); I != BB->end();++I){
OS << "\t";
(*I)->print(OS, Target);
}
}
OS << "\nEnd function \"" << Fn->getName() << "\"\n\n";
}
// The next two methods are used to construct and to retrieve
// the MachineCodeForFunction object for the given function.
// construct() -- Allocates and initializes for a given function and target
// get() -- Returns a handle to the object.
// This should not be called before "construct()"
// for a given Function.
//
MachineFunction&
MachineFunction::construct(const Function *Fn, const TargetMachine &Tar)
{
assert(Fn->getAnnotation(MF_AID) == 0 &&
"Object already exists for this function!");
MachineFunction* mcInfo = new MachineFunction(Fn, Tar);
Fn->addAnnotation(mcInfo);
return *mcInfo;
}
void
MachineFunction::destruct(const Function *Fn)
{
bool Deleted = Fn->deleteAnnotation(MF_AID);
assert(Deleted && "Machine code did not exist for function!");
}
MachineFunction& MachineFunction::get(const Function *F)
{
MachineFunction *mc = (MachineFunction*)F->getAnnotation(MF_AID);
assert(mc && "Call construct() method first to allocate the object");
return *mc;
}
void MachineFunction::clearSSARegMap() {
delete SSARegMapping;
SSARegMapping = 0;
}
//===----------------------------------------------------------------------===//
// FunctionFrameInfo implementation
//===----------------------------------------------------------------------===//
void FunctionFrameInfo::print(std::ostream &OS) const {
for (unsigned i = 0, e = Objects.size(); i != e; ++i) {
const StackObject &SO = Objects[i];
OS << " <fi# " << (int)(i-NumFixedObjects) << "> is ";
if (SO.Size == 0)
OS << "variable sized";
else
OS << SO.Size << " byte" << (SO.Size != 1 ? "s" : " ");
if (i < NumFixedObjects)
OS << " fixed";
if (i < NumFixedObjects || SO.SPOffset != -1) {
OS << " at location [SP";
if (SO.SPOffset > 0)
OS << "+" << SO.SPOffset;
else if (SO.SPOffset < 0)
OS << SO.SPOffset;
OS << "]";
}
OS << "\n";
}
if (HasVarSizedObjects)
OS << " Stack frame contains variable sized objects\n";
}
void FunctionFrameInfo::dump() const { print(std::cerr); }
//===----------------------------------------------------------------------===//
// MachineFunctionInfo implementation
//===----------------------------------------------------------------------===//
static unsigned
ComputeMaxOptionalArgsSize(const TargetMachine& target, const Function *F,
unsigned &maxOptionalNumArgs)
{
const TargetFrameInfo &frameInfo = target.getFrameInfo();
unsigned maxSize = 0;
for (Function::const_iterator BB = F->begin(), BBE = F->end(); BB !=BBE; ++BB)
for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
if (const CallInst *callInst = dyn_cast<CallInst>(&*I))
{
unsigned numOperands = callInst->getNumOperands() - 1;
int numExtra = (int)numOperands-frameInfo.getNumFixedOutgoingArgs();
if (numExtra <= 0)
continue;
unsigned sizeForThisCall;
if (frameInfo.argsOnStackHaveFixedSize())
{
int argSize = frameInfo.getSizeOfEachArgOnStack();
sizeForThisCall = numExtra * (unsigned) argSize;
}
else
{
assert(0 && "UNTESTED CODE: Size per stack argument is not "
"fixed on this architecture: use actual arg sizes to "
"compute MaxOptionalArgsSize");
sizeForThisCall = 0;
for (unsigned i = 0; i < numOperands; ++i)
sizeForThisCall += target.getTargetData().getTypeSize(callInst->
getOperand(i)->getType());
}
if (maxSize < sizeForThisCall)
maxSize = sizeForThisCall;
if ((int)maxOptionalNumArgs < numExtra)
maxOptionalNumArgs = (unsigned) numExtra;
}
return maxSize;
}
// Align data larger than one L1 cache line on L1 cache line boundaries.
// Align all smaller data on the next higher 2^x boundary (4, 8, ...),
// but not higher than the alignment of the largest type we support
// (currently a double word). -- see class TargetData).
//
// This function is similar to the corresponding function in EmitAssembly.cpp
// but they are unrelated. This one does not align at more than a
// double-word boundary whereas that one might.
//
inline unsigned
SizeToAlignment(unsigned size, const TargetMachine& target)
{
unsigned short cacheLineSize = target.getCacheInfo().getCacheLineSize(1);
if (size > (unsigned) cacheLineSize / 2)
return cacheLineSize;
else
for (unsigned sz=1; /*no condition*/; sz *= 2)
if (sz >= size || sz >= target.getTargetData().getDoubleAlignment())
return sz;
}
void MachineFunctionInfo::CalculateArgSize() {
maxOptionalArgsSize = ComputeMaxOptionalArgsSize(MF.getTarget(),
MF.getFunction(),
maxOptionalNumArgs);
staticStackSize = maxOptionalArgsSize
+ MF.getTarget().getFrameInfo().getMinStackFrameSize();
}
int
MachineFunctionInfo::computeOffsetforLocalVar(const Value* val,
unsigned &getPaddedSize,
unsigned sizeToUse)
{
if (sizeToUse == 0)
sizeToUse = MF.getTarget().findOptimalStorageSize(val->getType());
unsigned align = SizeToAlignment(sizeToUse, MF.getTarget());
bool growUp;
int firstOffset = MF.getTarget().getFrameInfo().getFirstAutomaticVarOffset(MF,
growUp);
int offset = growUp? firstOffset + getAutomaticVarsSize()
: firstOffset - (getAutomaticVarsSize() + sizeToUse);
int aligned = MF.getTarget().getFrameInfo().adjustAlignment(offset, growUp, align);
getPaddedSize = sizeToUse + abs(aligned - offset);
return aligned;
}
int
MachineFunctionInfo::allocateLocalVar(const Value* val,
unsigned sizeToUse)
{
assert(! automaticVarsAreaFrozen &&
"Size of auto vars area has been used to compute an offset so "
"no more automatic vars should be allocated!");
// Check if we've allocated a stack slot for this value already
//
int offset = getOffset(val);
if (offset == INVALID_FRAME_OFFSET)
{
unsigned getPaddedSize;
offset = computeOffsetforLocalVar(val, getPaddedSize, sizeToUse);
offsets[val] = offset;
incrementAutomaticVarsSize(getPaddedSize);
}
return offset;
}
int
MachineFunctionInfo::allocateSpilledValue(const Type* type)
{
assert(! spillsAreaFrozen &&
"Size of reg spills area has been used to compute an offset so "
"no more register spill slots should be allocated!");
unsigned size = MF.getTarget().getTargetData().getTypeSize(type);
unsigned char align = MF.getTarget().getTargetData().getTypeAlignment(type);
bool growUp;
int firstOffset = MF.getTarget().getFrameInfo().getRegSpillAreaOffset(MF, growUp);
int offset = growUp? firstOffset + getRegSpillsSize()
: firstOffset - (getRegSpillsSize() + size);
int aligned = MF.getTarget().getFrameInfo().adjustAlignment(offset, growUp, align);
size += abs(aligned - offset); // include alignment padding in size
incrementRegSpillsSize(size); // update size of reg. spills area
return aligned;
}
int
MachineFunctionInfo::pushTempValue(unsigned size)
{
unsigned align = SizeToAlignment(size, MF.getTarget());
bool growUp;
int firstOffset = MF.getTarget().getFrameInfo().getTmpAreaOffset(MF, growUp);
int offset = growUp? firstOffset + currentTmpValuesSize
: firstOffset - (currentTmpValuesSize + size);
int aligned = MF.getTarget().getFrameInfo().adjustAlignment(offset, growUp,
align);
size += abs(aligned - offset); // include alignment padding in size
incrementTmpAreaSize(size); // update "current" size of tmp area
return aligned;
}
void MachineFunctionInfo::popAllTempValues() {
resetTmpAreaSize(); // clear tmp area to reuse
}
int
MachineFunctionInfo::getOffset(const Value* val) const
{
hash_map<const Value*, int>::const_iterator pair = offsets.find(val);
return (pair == offsets.end()) ? INVALID_FRAME_OFFSET : pair->second;
}
<|endoftext|> |
<commit_before>//
// Copyright (C) 2011-2014 Jeff Bush
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Library General Public
// License as published by the Free Software Foundation; either
// version 2 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Library General Public License for more details.
//
// You should have received a copy of the GNU Library General Public
// License along with this library; if not, write to the
// Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
// Boston, MA 02110-1301, USA.
//
#include <stdint.h>
#include <stdlib.h>
#include "Surface.h"
using namespace librender;
Surface::Surface(int width, int height, void *base)
: fWidth(width),
fHeight(height),
fStride(width * kBytesPerPixel),
fBaseAddress((unsigned int) base),
fOwnedPointer(false)
{
initializePointerVec();
}
Surface::Surface(int fbWidth, int fbHeight)
: fWidth(fbWidth),
fHeight(fbHeight),
fStride(fbWidth * kBytesPerPixel),
fOwnedPointer(true)
{
fBaseAddress = (unsigned int) memalign(kCacheLineSize, fbWidth * fbHeight * kBytesPerPixel);
initializePointerVec();
}
Surface::~Surface()
{
if (fOwnedPointer)
::free((void*) fBaseAddress);
}
void Surface::initializePointerVec()
{
f4x4AtOrigin = {
fBaseAddress,
fBaseAddress + 4,
fBaseAddress + 8,
fBaseAddress + 12,
fBaseAddress + (fWidth * 4),
fBaseAddress + (fWidth * 4) + 4,
fBaseAddress + (fWidth * 4) + 8,
fBaseAddress + (fWidth * 4) + 12,
fBaseAddress + (fWidth * 8),
fBaseAddress + (fWidth * 8) + 4,
fBaseAddress + (fWidth * 8) + 8,
fBaseAddress + (fWidth * 8) + 12,
fBaseAddress + (fWidth * 12),
fBaseAddress + (fWidth * 12) + 4,
fBaseAddress + (fWidth * 12) + 8,
fBaseAddress + (fWidth * 12) + 12
};
}
void Surface::clearTileSlow(int left, int top, unsigned int value)
{
veci16_t *ptr = (veci16_t*)(fBaseAddress + (left + top * fWidth) * kBytesPerPixel);
const veci16_t kClearColor = splati(value);
int right = min(kTileSize, fWidth - left);
int bottom = min(kTileSize, fHeight - top);
const int kStride = ((fWidth - right) * kBytesPerPixel / sizeof(veci16_t));
for (int y = 0; y < bottom; y++)
{
// XXX LLVM ends up turning this into memset
for (int x = 0; x < right; x += 16)
*ptr++ = kClearColor;
ptr += kStride;
}
}
// Push a NxN tile from the L2 cache back to system memory
void Surface::flushTile(int left, int top)
{
unsigned int ptr = fBaseAddress + (left + top * fWidth) * kBytesPerPixel;
int right = min(kTileSize, fWidth - left);
int bottom = min(kTileSize, fHeight - top);
const int kStride = (fWidth - right) * kBytesPerPixel;
for (int y = 0; y < bottom; y++)
{
for (int x = 0; x < right; x += 16)
{
asm("dflush %0" : : "s" (ptr));
ptr += kCacheLineSize;
}
ptr += kStride;
}
}
<commit_msg>Fix mixed tabs/spaces<commit_after>//
// Copyright (C) 2011-2014 Jeff Bush
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Library General Public
// License as published by the Free Software Foundation; either
// version 2 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Library General Public License for more details.
//
// You should have received a copy of the GNU Library General Public
// License along with this library; if not, write to the
// Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
// Boston, MA 02110-1301, USA.
//
#include <stdint.h>
#include <stdlib.h>
#include "Surface.h"
using namespace librender;
Surface::Surface(int width, int height, void *base)
: fWidth(width),
fHeight(height),
fStride(width * kBytesPerPixel),
fBaseAddress((unsigned int) base),
fOwnedPointer(false)
{
initializePointerVec();
}
Surface::Surface(int fbWidth, int fbHeight)
: fWidth(fbWidth),
fHeight(fbHeight),
fStride(fbWidth * kBytesPerPixel),
fOwnedPointer(true)
{
fBaseAddress = (unsigned int) memalign(kCacheLineSize, fbWidth * fbHeight * kBytesPerPixel);
initializePointerVec();
}
Surface::~Surface()
{
if (fOwnedPointer)
::free((void*) fBaseAddress);
}
void Surface::initializePointerVec()
{
f4x4AtOrigin = {
fBaseAddress,
fBaseAddress + 4,
fBaseAddress + 8,
fBaseAddress + 12,
fBaseAddress + (fWidth * 4),
fBaseAddress + (fWidth * 4) + 4,
fBaseAddress + (fWidth * 4) + 8,
fBaseAddress + (fWidth * 4) + 12,
fBaseAddress + (fWidth * 8),
fBaseAddress + (fWidth * 8) + 4,
fBaseAddress + (fWidth * 8) + 8,
fBaseAddress + (fWidth * 8) + 12,
fBaseAddress + (fWidth * 12),
fBaseAddress + (fWidth * 12) + 4,
fBaseAddress + (fWidth * 12) + 8,
fBaseAddress + (fWidth * 12) + 12
};
}
void Surface::clearTileSlow(int left, int top, unsigned int value)
{
veci16_t *ptr = (veci16_t*)(fBaseAddress + (left + top * fWidth) * kBytesPerPixel);
const veci16_t kClearColor = splati(value);
int right = min(kTileSize, fWidth - left);
int bottom = min(kTileSize, fHeight - top);
const int kStride = ((fWidth - right) * kBytesPerPixel / sizeof(veci16_t));
for (int y = 0; y < bottom; y++)
{
// XXX LLVM ends up turning this into memset
for (int x = 0; x < right; x += 16)
*ptr++ = kClearColor;
ptr += kStride;
}
}
// Push a NxN tile from the L2 cache back to system memory
void Surface::flushTile(int left, int top)
{
unsigned int ptr = fBaseAddress + (left + top * fWidth) * kBytesPerPixel;
int right = min(kTileSize, fWidth - left);
int bottom = min(kTileSize, fHeight - top);
const int kStride = (fWidth - right) * kBytesPerPixel;
for (int y = 0; y < bottom; y++)
{
for (int x = 0; x < right; x += 16)
{
asm("dflush %0" : : "s" (ptr));
ptr += kCacheLineSize;
}
ptr += kStride;
}
}
<|endoftext|> |
<commit_before>// RUN: %clangxx_asan -O0 %s -o %t -mllvm -asan-detect-invalid-pointer-pair
// RUN: %env_asan_opts=detect_invalid_pointer_pairs=1 %run %t k 2>&1 | FileCheck %s -check-prefix=OK -allow-empty
// RUN: %env_asan_opts=detect_invalid_pointer_pairs=1 not %run %t g 2>&1 | FileCheck %s -check-prefix=CMP -check-prefix=ALL-ERRORS
// RUN: %env_asan_opts=detect_invalid_pointer_pairs=1 not %run %t s 2>&1 | FileCheck %s -check-prefix=SUB -check-prefix=ALL-ERRORS
// RUN: %env_asan_opts=detect_invalid_pointer_pairs=1 not %run %t f 2>&1 | FileCheck %s -check-prefix=FREE -check-prefix=ALL-ERRORS
#include <assert.h>
#include <stdlib.h>
int f(char c, char *p, char *q) {
// ALL-ERRORS: ERROR: AddressSanitizer: invalid-pointer-pair
// [[PTR1:0x[0-9a-f]+]] [[PTR2:0x[0-9a-f]+]]
switch (c) {
case 'g':
// CMP: #0 {{.*}} in f({{char, char\*, char\*|char,char \*,char \*}}) {{.*}}invalid-pointer-pairs.cc:[[@LINE+1]]:14
return p > q;
case 's':
// SUB: #0 {{.*}} in f({{char, char\*, char\*|char,char \*,char \*}}) {{.*}}invalid-pointer-pairs.cc:[[@LINE+1]]:14
return p - q;
case 'k': {
// OK-NOT: ERROR
char *p2 = p + 20;
return p > p2;
}
case 'f': {
char *p3 = p + 20;
free(p);
// FREE: #0 {{.*}} in f({{char, char\*, char\*|char,char \*,char \*}}) {{.*}}invalid-pointer-pairs.cc:[[@LINE+2]]:14
// FREE: freed by thread
return p < p3;
}
}
assert(0);
}
int main(int argc, char **argv) {
char *p = (char *)malloc(42);
char *q = (char *)malloc(42);
assert(argc >= 2);
f(argv[1][0], p, q);
free(p);
free(q);
}
<commit_msg>[asan] Relax a flaky invalid-pointer-pairs test<commit_after>// RUN: %clangxx_asan -O0 %s -o %t -mllvm -asan-detect-invalid-pointer-pair
// RUN: %env_asan_opts=detect_invalid_pointer_pairs=1 %run %t k 2>&1 | FileCheck %s -check-prefix=OK -allow-empty
// RUN: %env_asan_opts=detect_invalid_pointer_pairs=1 not %run %t g 2>&1 | FileCheck %s -check-prefix=CMP -check-prefix=ALL-ERRORS
// RUN: %env_asan_opts=detect_invalid_pointer_pairs=1 not %run %t s 2>&1 | FileCheck %s -check-prefix=SUB -check-prefix=ALL-ERRORS
// RUN: %env_asan_opts=detect_invalid_pointer_pairs=1 not %run %t f 2>&1 | FileCheck %s -check-prefix=FREE -check-prefix=ALL-ERRORS
#include <assert.h>
#include <stdlib.h>
int f(char c, char *p, char *q) {
// ALL-ERRORS: ERROR: AddressSanitizer: invalid-pointer-pair
// [[PTR1:0x[0-9a-f]+]] [[PTR2:0x[0-9a-f]+]]
switch (c) {
case 'g':
// CMP: #{{[0-9]+ .*}} in f({{char, char\*, char\*|char,char \*,char \*}}) {{.*}}invalid-pointer-pairs.cc:[[@LINE+1]]:14
return p > q;
case 's':
// SUB: #{{[0-9]+ .*}} in f({{char, char\*, char\*|char,char \*,char \*}}) {{.*}}invalid-pointer-pairs.cc:[[@LINE+1]]:14
return p - q;
case 'k': {
// OK-NOT: ERROR
char *p2 = p + 20;
return p > p2;
}
case 'f': {
char *p3 = p + 20;
free(p);
// FREE: #{{[0-9]+ .*}} in f({{char, char\*, char\*|char,char \*,char \*}}) {{.*}}invalid-pointer-pairs.cc:[[@LINE+2]]:14
// FREE: freed by thread
return p < p3;
}
}
assert(0);
}
int main(int argc, char **argv) {
char *p = (char *)malloc(42);
char *q = (char *)malloc(42);
assert(argc >= 2);
f(argv[1][0], p, q);
free(p);
free(q);
}
<|endoftext|> |
<commit_before>/**
* Copyright 2017 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <string>
#include "util.hpp"
static constexpr auto external_sensor =
"/xyz/openbmc_project/extsensors/"; // type/
static constexpr auto openbmc_sensor = "/xyz/openbmc_project/"; // type/
static constexpr auto sysfs = "/sys/";
IOInterfaceType GetWriteInterfaceType(const std::string& path)
{
std::string::size_type n;
if (path.empty() || "None" == path)
{
return IOInterfaceType::NONE;
}
if (path.find(sysfs) != std::string::npos)
{
// A sysfs read sensor.
return IOInterfaceType::SYSFS;
}
return IOInterfaceType::UNKNOWN;
}
IOInterfaceType GetReadInterfaceType(const std::string& path)
{
std::string::size_type n;
if (path.empty() || "None" == path)
{
return IOInterfaceType::NONE;
}
if (path.find(external_sensor) != std::string::npos)
{
return IOInterfaceType::EXTERNAL;
}
if (path.find(openbmc_sensor) != std::string::npos)
{
return IOInterfaceType::DBUSPASSIVE;
}
if (path.find(sysfs) != std::string::npos)
{
return IOInterfaceType::SYSFS;
}
return IOInterfaceType::UNKNOWN;
}
<commit_msg>util: remove unused variable<commit_after>/**
* Copyright 2017 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <string>
#include "util.hpp"
static constexpr auto external_sensor =
"/xyz/openbmc_project/extsensors/"; // type/
static constexpr auto openbmc_sensor = "/xyz/openbmc_project/"; // type/
static constexpr auto sysfs = "/sys/";
IOInterfaceType GetWriteInterfaceType(const std::string& path)
{
if (path.empty() || "None" == path)
{
return IOInterfaceType::NONE;
}
if (path.find(sysfs) != std::string::npos)
{
// A sysfs read sensor.
return IOInterfaceType::SYSFS;
}
return IOInterfaceType::UNKNOWN;
}
IOInterfaceType GetReadInterfaceType(const std::string& path)
{
if (path.empty() || "None" == path)
{
return IOInterfaceType::NONE;
}
if (path.find(external_sensor) != std::string::npos)
{
return IOInterfaceType::EXTERNAL;
}
if (path.find(openbmc_sensor) != std::string::npos)
{
return IOInterfaceType::DBUSPASSIVE;
}
if (path.find(sysfs) != std::string::npos)
{
return IOInterfaceType::SYSFS;
}
return IOInterfaceType::UNKNOWN;
}
<|endoftext|> |
<commit_before>/*
* trend: display live data on a trend graph
* Copyright(c) 2003-2004 by wave++ "Yuri D'Elia" <wavexx@users.sf.net>
* Distributed under GNU LGPL WITHOUT ANY WARRANTY.
*/
/*
* Headers
*/
// defaults
#include "defaults.hh"
// system headers
#include <stdexcept>
#include <deque>
using std::deque;
#include <iostream>
using std::cout;
using std::cerr;
using std::cin;
#include <string>
using std::string;
#include <utility>
using std::pair;
#include <cmath>
using std::isnan;
// c system headers
#include <cstdlib>
using std::strtod;
using std::strtoul;
#include <stdio.h>
#include <ctype.h>
#include <unistd.h>
#include <pthread.h>
// OpenGL/GLU
#include <GL/glut.h>
/*
* Data structures
*/
struct Value
{
Value(double value, size_t count)
: value(value), count(count)
{}
double value;
size_t count;
};
/*
* Graph/Program state
*/
namespace
{
// Basic data
const char* fileName;
pthread_mutex_t mutex;
bool damaged = false;
// Data and fixed parameters
deque<Value> data;
double loLimit;
double hiLimit;
size_t history;
size_t divisions;
// Visual/Fixed settings
const char* title = NULL;
// Visual/Changeable settings
bool autoLimit;
bool smooth = Trend::smooth;
bool scroll = Trend::scroll;
bool values = Trend::values;
bool marker = Trend::marker;
bool grid = Trend::grid;
double gridres = Trend::gridres;
}
/*
* I/O and data manipulation
*/
// skip whitespace
void
skipSpc(FILE* fd)
{
char c;
do { c = getc_unlocked(fd); }
while(isspace(c) && c != EOF);
ungetc(c, fd);
}
// skip a space-separated string
void
skipStr(FILE* fd)
{
char c;
do { c = getc_unlocked(fd); }
while(!isspace(c) && c != EOF);
ungetc(c, fd);
}
// read a space-separated string
char*
readStr(FILE* fd, char* buf, size_t len)
{
char* p(buf);
int c;
while(len--)
{
c = getc_unlocked(fd);
if(c == EOF || isspace(c))
{
ungetc(c, fd);
return p;
}
*p++ = c;
}
// overflow
return NULL;
}
// read a number from the stream
double
readNum(FILE* fd)
{
// discard initial whitespace
skipSpc(fd);
if(feof(fd))
return NAN;
// read the number
char buf[Trend::maxNumLen];
char* end = readStr(fd, buf, sizeof(buf));
if(feof(fd))
return NAN;
if(!end)
{
// long string, skip it.
skipStr(fd);
return NAN;
}
// convert the number
double num = strtod(buf, &end);
if(end == buf)
return NAN;
return num;
}
// producer thread
void*
thread(void*)
{
// iostreams under gcc 3.x are completely unusable for advanced tasks such as
// customizable buffering/locking/etc. They also removed the (really
// standard) ->fd() access for "encapsulation"...
FILE* in;
for(size_t pos = 0; fileName;)
{
// open the file and disable buffering
in = fopen(fileName, "r");
if(!in) break;
setvbuf(in, NULL, _IONBF, 0);
// read all data
double num;
while(!isnan(num = readNum(in)) && fileName)
{
// append the value
pthread_mutex_lock(&mutex);
data.push_back(Value(num, pos));
if(data.size() == history + 2)
data.pop_front();
damaged = true;
pthread_mutex_unlock(&mutex);
// wrap pos when possible
if(!(++pos % divisions))
pos = 0;
}
// close the stream
fclose(in);
}
return NULL;
}
/*
* OpenGL functions
*/
// OpenGL state initializer
void
init()
{
// Smoothing
if(smooth)
{
glEnable(GL_LINE_SMOOTH);
glHint(GL_LINE_SMOOTH_HINT, GL_FASTEST);
}
else
glDisable(GL_LINE_SMOOTH);
// Blending should be enabled by default
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
// Clear color
glClearColor(0.0, 0.0, 0.0, 0.0);
}
#if 0
// Write an OpenGL string using glut.
void
drawString(const float scale, const float x, const float y, const char* string)
{
glPushMatrix();
glTranslatef(x, y, 0);
glScalef(scale, scale, 0);
for(const char* p = string; *p; ++p)
glutStrokeCharacter(GLUT_STROKE_ROMAN, *p);
glPopMatrix();
}
#endif
void
drawGrid()
{
glBegin(GL_LINES);
// horizontal scanlines
for(size_t it = 1; it != divisions; ++it)
{
glVertex2f(it, loLimit);
glVertex2f(it, hiLimit);
}
// vertical rasterlines
for(float it = loLimit; it <= hiLimit; it += gridres)
{
glVertex2f(0, it);
glVertex2f(divisions, it);
}
glEnd();
}
void
drawMarker(const float x)
{
glBegin(GL_LINES);
glVertex2f(x, loLimit);
glVertex2f(x, hiLimit);
glEnd();
}
// redraw handler
void
display()
{
glLoadIdentity();
gluOrtho2D(0, divisions, loLimit, hiLimit);
// Clear the device.
pthread_mutex_lock(&mutex);
glClear(GL_COLOR_BUFFER_BIT);
if(grid)
{
glColor3f(0.5, 0., 0.5);
drawGrid();
}
deque<Value>::const_iterator it(data.begin());
size_t pos;
glBegin(GL_LINE_STRIP);
for(size_t i = 0; i != data.size(); ++i, ++it)
{
glColor4f(1., 1., 1., static_cast<float>(i) / data.size());
pos = ((scroll? i: it->count) % divisions);
if(!pos)
{
// Cursor at the end
glVertex2f(divisions, it->value);
glEnd();
glBegin(GL_LINE_STRIP);
glVertex2f(0, it->value);
}
else
glVertex2f(pos, it->value);
}
glEnd();
if(marker)
{
glColor3f(0.5, 0.5, 0.);
drawMarker(pos);
}
// Flush buffers
glutSwapBuffers();
pthread_mutex_unlock(&mutex);
}
// Resize handler
void
reshape(const int w, const int h)
{
glViewport(0, 0, w, h);
glutPostRedisplay();
}
void
setLimits()
{
deque<Value>::const_iterator it(data.begin());
float lo(it->value);
float hi(lo);
for(; it != data.end(); ++it)
{
if(it->value > hi)
hi = it->value;
if(it->value < lo)
lo = it->value;
}
hiLimit = hi + gridres;
loLimit = lo - gridres;
}
void
idle(int)
{
// re-register the callback
glutTimerFunc(1, idle, 0);
// check if a redraw is necessary
pthread_mutex_lock(&mutex);
if(damaged)
{
if(autoLimit)
setLimits();
glutPostRedisplay();
damaged = false;
}
pthread_mutex_unlock(&mutex);
}
/*
* Keyboard interation
*/
void
showToggleStatus(const char* str, bool& var)
{
var = !var;
std::cout << str << ": " << (var? "enabled": "disabled") << std::endl;
}
double
getUnit()
{
cout << "u? ";
double u;
cin >> u;
return u;
}
void
keyboard(const unsigned char key, const int x, const int y)
{
switch(key)
{
case Trend::quitKey:
exit(Trend::success);
break;
// Redraw alteration
case Trend::smoothKey:
showToggleStatus("smoothing", smooth);
init();
break;
case Trend::scrollKey:
showToggleStatus("scrolling", scroll);
break;
case Trend::markerKey:
showToggleStatus("marker", marker);
break;
case Trend::gridKey:
showToggleStatus("grid", grid);
break;
case Trend::valuesKey:
showToggleStatus("values", values);
break;
case Trend::setResKey:
gridres = getUnit();
break;
default:
return;
}
glutPostRedisplay();
}
/*
* CLI and options
*/
// Initialize globals through command line
int
parseOptions(int argc, char* const argv[])
{
// starting options
autoLimit = false;
int arg;
while((arg = getopt(argc, argv, "aSsvmgG:ht:")) != -1)
switch(arg)
{
case 'a':
autoLimit = true;
break;
case 'S':
smooth = true;
break;
case 's':
scroll = true;
break;
case 'v':
values = true;
break;
case 'm':
marker = true;
break;
case 'g':
grid = true;
break;
case 'G':
gridres = strtod(optarg, NULL);
break;
case 't':
title = optarg;
break;
case 'h':
cout << argv[0] << " usage: " <<
argv[0] << " [options] fifo hist-sz x-div [-y +y]\n" <<
argv[0] << " version: $Revision$ $Date$\n";
return 1;
default:
return -1;
}
// main parameters
argc -= optind;
if(argc != 3 && argc != 5)
{
cerr << argv[0] << ": bad parameters\n";
return -1;
}
fileName = argv[1];
history = strtoul(argv[2], NULL, 0);
divisions = strtoul(argv[3], NULL, 0);
// optional limiting factors
if(argc == 5)
{
loLimit = strtod(argv[4], NULL);
hiLimit = strtod(argv[5], NULL);
}
else
autoLimit = true;
return 0;
}
int
main(int argc, char* const argv[]) try
{
// parameters
if(parseOptions(argc, argv))
return Trend::args;
// start the producer thread
pthread_t thrd;
pthread_mutex_init(&mutex, NULL);
pthread_create(&thrd, NULL, thread, NULL);
// display
glutInit(const_cast<int*>(&argc), const_cast<char**>(argv));
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
// main mindow and callbacks
glutCreateWindow(title? title: argv[0]);
glutReshapeFunc(reshape);
glutDisplayFunc(display);
glutKeyboardFunc(keyboard);
// first redraw
init();
idle(0);
// processing
glutMainLoop();
return Trend::success;
}
catch(const std::exception& e)
{
std::cerr << argv[0] << ": " << e.what() << std::endl;
throw;
}
<commit_msg>Colours are configurable. Fixed producer for errors in data stream. Grid is correctly positioned now. Fixed argument parsing.<commit_after>/*
* trend: display live data on a trend graph
* Copyright(c) 2003-2004 by wave++ "Yuri D'Elia" <wavexx@users.sf.net>
* Distributed under GNU LGPL WITHOUT ANY WARRANTY.
*/
/*
* Headers
*/
// defaults
#include "defaults.hh"
#include "color.hh"
// system headers
#include <stdexcept>
#include <deque>
using std::deque;
#include <iostream>
using std::cout;
using std::cerr;
using std::cin;
#include <string>
using std::string;
#include <utility>
using std::pair;
#include <cmath>
using std::isnan;
// c system headers
#include <cstdlib>
using std::strtod;
using std::strtoul;
#include <cstring>
using std::memcpy;
#include <stdio.h>
#include <ctype.h>
#include <unistd.h>
#include <pthread.h>
// OpenGL/GLU
#include <GL/glut.h>
/*
* Data structures
*/
struct Value
{
Value(double value, size_t count)
: value(value), count(count)
{}
double value;
size_t count;
};
/*
* Graph/Program state
*/
namespace
{
// Basic data
const char* fileName;
pthread_mutex_t mutex;
bool damaged = false;
// Data and fixed parameters
deque<Value> data;
double loLimit;
double hiLimit;
size_t history;
size_t divisions;
// Visual/Fixed settings
int width;
int height;
const char* title = NULL;
GLfloat backCol[3];
GLfloat textCol[3];
GLfloat gridCol[3];
GLfloat lineCol[3];
GLfloat markCol[3];
// Visual/Changeable settings
bool autoLimit;
bool smooth = Trend::smooth;
bool scroll = Trend::scroll;
bool values = Trend::values;
bool marker = Trend::marker;
bool grid = Trend::grid;
double gridres = Trend::gridres;
}
/*
* I/O and data manipulation
*/
// skip whitespace
void
skipSpc(FILE* fd)
{
char c;
do { c = getc_unlocked(fd); }
while(isspace(c) && c != EOF);
ungetc(c, fd);
}
// skip a space-separated string
void
skipStr(FILE* fd)
{
char c;
do { c = getc_unlocked(fd); }
while(!isspace(c) && c != EOF);
ungetc(c, fd);
}
// read a space-separated string
char*
readStr(FILE* fd, char* buf, size_t len)
{
char* p(buf);
int c;
while(len--)
{
c = getc_unlocked(fd);
if(c == EOF || isspace(c))
{
ungetc(c, fd);
return p;
}
*p++ = c;
}
// overflow
return NULL;
}
// read a number from the stream
double
readNum(FILE* fd)
{
// discard initial whitespace
skipSpc(fd);
if(feof(fd))
return NAN;
// read the number
char buf[Trend::maxNumLen];
char* end = readStr(fd, buf, sizeof(buf));
if(feof(fd))
return NAN;
if(!end)
{
// long string, skip it.
skipStr(fd);
return NAN;
}
// convert the number
double num = strtod(buf, &end);
if(end == buf)
return NAN;
return num;
}
// producer thread
void*
thread(void*)
{
// iostreams under gcc 3.x are completely unusable for advanced tasks such as
// customizable buffering/locking/etc. They also removed the (really
// standard) ->fd() access for "encapsulation"...
FILE* in;
for(size_t pos = 0; fileName;)
{
// open the file and disable buffering
in = fopen(fileName, "r");
if(!in) break;
setvbuf(in, NULL, _IONBF, 0);
// read all data
double num;
while(fileName)
{
num = readNum(in);
if(isnan(num) && feof(in))
break;
// append the value
pthread_mutex_lock(&mutex);
data.push_back(Value(num, pos));
if(data.size() == history + 2)
data.pop_front();
damaged = true;
pthread_mutex_unlock(&mutex);
// wrap pos when possible
if(!(++pos % divisions))
pos = 0;
}
// close the stream
fclose(in);
}
return NULL;
}
/*
* OpenGL functions
*/
// OpenGL state initializer
void
init()
{
// Smoothing
if(smooth)
{
glEnable(GL_LINE_SMOOTH);
glHint(GL_LINE_SMOOTH_HINT, GL_FASTEST);
}
else
glDisable(GL_LINE_SMOOTH);
// Blending should be enabled by default
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
// Clear color
glClearColor(backCol[0], backCol[1], backCol[2], 0.0);
}
// Resize handler
void
reshape(const int w, const int h)
{
width = w;
height = w;
glViewport(0, 0, w, h);
}
#if 0
// Write an OpenGL string using glut.
void
drawString(const float scale, const float x, const float y, const char* string)
{
glPushMatrix();
glTranslatef(x, y, 0);
glScalef(scale, scale, 0);
for(const char* p = string; *p; ++p)
glutStrokeCharacter(GLUT_STROKE_ROMAN, *p);
glPopMatrix();
}
#endif
void
drawGrid()
{
glColor3fv(gridCol);
glBegin(GL_LINES);
double it;
// horizontal scanlines
for(it = 1; it != divisions; ++it)
{
glVertex2d(it, loLimit);
glVertex2d(it, hiLimit);
}
// vertical rasterlines
it = loLimit + drem(loLimit, gridres);
for(; it <= hiLimit; it += gridres)
{
glVertex2d(0, it);
glVertex2d(divisions, it);
}
glEnd();
}
void
drawMarker(const float x)
{
glColor3fv(markCol);
glBegin(GL_LINES);
glVertex2d(x, loLimit);
glVertex2d(x, hiLimit);
glEnd();
}
size_t
drawLine()
{
deque<Value>::const_iterator it(data.begin());
size_t pos;
glBegin(GL_LINE_STRIP);
for(size_t i = 0; i != data.size(); ++i, ++it)
{
// shade the color
glColor4f(lineCol[0], lineCol[1], lineCol[2],
static_cast<float>(i) / data.size());
pos = ((scroll? i: it->count) % divisions);
if(!pos)
{
// Cursor at the end
glVertex2f(divisions, it->value);
glEnd();
glBegin(GL_LINE_STRIP);
glVertex2d(0, it->value);
}
else
glVertex2d(pos, it->value);
}
glEnd();
return pos;
}
// redraw handler
void
display()
{
// setup model coordinates
glClear(GL_COLOR_BUFFER_BIT);
glLoadIdentity();
gluOrtho2D(0, divisions, loLimit, hiLimit);
// background grid
if(grid)
drawGrid();
// data
pthread_mutex_lock(&mutex);
size_t pos(drawLine());
pthread_mutex_unlock(&mutex);
// marker
if(marker)
drawMarker(pos);
// flush buffers
glutSwapBuffers();
}
void
setLimits()
{
deque<Value>::const_iterator it(data.begin());
float lo(it->value);
float hi(lo);
for(; it != data.end(); ++it)
{
if(it->value > hi)
hi = it->value;
if(it->value < lo)
lo = it->value;
}
// some vertical bounds
hiLimit = hi + gridres;
loLimit = lo - gridres;
}
void
idle(int)
{
// re-register the callback
glutTimerFunc(1, idle, 0);
// check if a redraw is really necessary
pthread_mutex_lock(&mutex);
if(damaged)
{
// recalculate limits seldom
if(autoLimit)
setLimits();
glutPostRedisplay();
damaged = false;
}
pthread_mutex_unlock(&mutex);
}
/*
* Keyboard interation
*/
void
toggleStatus(const char* str, bool& var)
{
var = !var;
std::cout << str << ": " << (var? "enabled": "disabled") << std::endl;
}
double
getUnit(const char* str)
{
cout << str << "? ";
double u;
cin >> u;
return u;
}
void
keyboard(const unsigned char key, const int x, const int y)
{
switch(key)
{
case Trend::quitKey:
exit(Trend::success);
break;
// redraw alteration
case Trend::autolimKey:
toggleStatus("autolimit", autoLimit);
break;
case Trend::smoothKey:
toggleStatus("smoothing", smooth);
init();
break;
case Trend::scrollKey:
toggleStatus("scrolling", scroll);
break;
case Trend::valuesKey:
toggleStatus("values", values);
break;
case Trend::markerKey:
toggleStatus("marker", marker);
break;
case Trend::gridKey:
toggleStatus("grid", grid);
break;
case Trend::setResKey:
gridres = getUnit("grid resolution");
break;
default:
return;
}
glutPostRedisplay();
}
/*
* CLI and options
*/
// Initialize globals through command line
int
parseOptions(int argc, char* const argv[])
{
// starting options
autoLimit = false;
memcpy(backCol, Trend::backCol, sizeof(backCol));
memcpy(textCol, Trend::textCol, sizeof(textCol));
memcpy(gridCol, Trend::gridCol, sizeof(gridCol));
memcpy(lineCol, Trend::lineCol, sizeof(lineCol));
memcpy(markCol, Trend::markCol, sizeof(markCol));
int arg;
while((arg = getopt(argc, argv, "aSsvmgG:ht:A:E:R:I:M:")) != -1)
switch(arg)
{
case 'a':
autoLimit = true;
break;
case 'S':
smooth = true;
break;
case 's':
scroll = true;
break;
case 'v':
values = true;
break;
case 'm':
marker = true;
break;
case 'g':
grid = true;
break;
case 'G':
gridres = strtod(optarg, NULL);
break;
case 't':
title = optarg;
break;
case 'A':
parseColor(backCol, optarg);
break;
case 'E':
parseColor(textCol, optarg);
break;
case 'R':
parseColor(gridCol, optarg);
break;
case 'I':
parseColor(lineCol, optarg);
break;
case 'M':
parseColor(markCol, optarg);
break;
case 'h':
cout << argv[0] << " usage: " <<
argv[0] << " [options] fifo hist-sz x-div [-y +y]\n" <<
argv[0] << " version: $Revision$ $Date$\n";
return 1;
default:
return -1;
}
// main parameters
argc -= optind;
if(argc != 3 && argc != 5)
{
cerr << argv[0] << ": bad parameters\n";
return -1;
}
fileName = argv[optind++];
history = strtoul(argv[optind++], NULL, 0);
divisions = strtoul(argv[optind++], NULL, 0);
// optional limiting factors
if(argc == 5)
{
loLimit = strtod(argv[optind++], NULL);
hiLimit = strtod(argv[optind++], NULL);
}
else
autoLimit = true;
return 0;
}
int
main(int argc, char* const argv[]) try
{
// parameters
if(parseOptions(argc, argv))
return Trend::args;
// start the producer thread
pthread_t thrd;
pthread_mutex_init(&mutex, NULL);
pthread_create(&thrd, NULL, thread, NULL);
// display
glutInit(const_cast<int*>(&argc), const_cast<char**>(argv));
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
// main mindow and callbacks
glutCreateWindow(title? title: argv[0]);
glutReshapeFunc(reshape);
glutDisplayFunc(display);
glutKeyboardFunc(keyboard);
// first redraw
init();
idle(0);
// processing
glutMainLoop();
return Trend::success;
}
catch(const std::exception& e)
{
std::cerr << argv[0] << ": " << e.what() << std::endl;
throw;
}
<|endoftext|> |
<commit_before>#include "nuclear_burn.hpp"
extern "C" {
void burn_step_(int* indexeos,
double* density,
double* energy,
double* tburn,
double* xn,
double* atomw,
double* atomn,
double* dedtmp,
int* matters,
double* dt,
double* qrec,
int* nse,
double* tmp_nse,
int* key_done,
char* screen_type);
}
namespace {
pair<double,vector<double> > burn_step_wrapper(double density,
double energy,
double tburn,
vector<double> xn,
pair<double,double> az,
double dt)
{
int indexeos = 0;
double dedtmp = 0;
int matters = static_cast<int>(xn.size());
double qrec = 0;
int nse = 0;
double tmp_nse = 1e10;
char screen_type[80] = "default";
int key_done = 0;
burn_step_(&indexeos,
&density,
&energy,
&tburn,
&xn[0],
&az.first,
&az.second,
&dedtmp,
&matters,
&dt,
&qrec,
&nse,
&tmp_nse,
&key_done,
screen_type);
assert(key_done==1);
return pair<double,vector<double> >(qrec,xn);
}
template<class S, class T> const T& safe_retrieve(const map<S,T>& m,
const S& s)
{
/*
map<S,T>::const_iterator it = m.find(s);
assert(it!=m.end());
return it->second;
*/
assert(m.find(s)!=m.end());
return m.find(s)->second;
}
pair<double,double> calc_average_atomic_properties
(const map<string,pair<double,double> >& atomic_properties,
const map<string,double>& compositions)
{
double total = 0;
double aa = 0;
double zz = 0;
for(map<string,pair<double,double> >::const_iterator it=
atomic_properties.begin();
it!=atomic_properties.end();
++it){
const double mass_frac = safe_retrieve(compositions,it->first);
const double A = it->second.first;
const double Z = it->second.second;
total += mass_frac;
aa += mass_frac/A;
zz += mass_frac*Z/A;
}
return pair<double,double>(total/aa,zz/aa);
}
}
NuclearBurn::NuclearBurn
(const map<string,pair<double,double> >& atomic_properties,
const string& ignore_label,
const FermiTable& eos):
atomic_properties_(atomic_properties),
t_prev_(0),
ignore_label_(ignore_label),
eos_(eos) {}
void NuclearBurn::operator()(hdsim& sim)
{
const double dt = sim.getTime() - t_prev_;
vector<ComputationalCell>& cells = sim.getAllCells();
for(size_t i=0;i<cells.size();++i){
ComputationalCell& cell = cells[i];
if(safe_retrieve(cell.stickers,ignore_label_))
continue;
}
sim.recalculateExtensives();
}
<commit_msg>fix compiler errors<commit_after>#include "nuclear_burn.hpp"
extern "C" {
void burn_step_(int* indexeos,
double* density,
double* energy,
double* tburn,
double* xn,
double* atomw,
double* atomn,
double* dedtmp,
int* matters,
double* dt,
double* qrec,
int* nse,
double* tmp_nse,
int* key_done,
char* screen_type);
}
namespace {
pair<double,vector<double> > burn_step_wrapper(double density,
double energy,
double tburn,
vector<double> xn,
pair<double,double> az,
double dt)
{
int indexeos = 0;
double dedtmp = 0;
int matters = static_cast<int>(xn.size());
double qrec = 0;
int nse = 0;
double tmp_nse = 1e10;
char screen_type[80] = "default";
int key_done = 0;
burn_step_(&indexeos,
&density,
&energy,
&tburn,
&xn[0],
&az.first,
&az.second,
&dedtmp,
&matters,
&dt,
&qrec,
&nse,
&tmp_nse,
&key_done,
screen_type);
assert(key_done==1);
return pair<double,vector<double> >(qrec,xn);
}
template<class S, class T> const T& safe_retrieve(const map<S,T>& m,
const S& s)
{
/*
map<S,T>::const_iterator it = m.find(s);
assert(it!=m.end());
return it->second;
*/
assert(m.find(s)!=m.end());
return m.find(s)->second;
}
vector<double> serialize_tracers(const map<string,double>& tracers)
{
vector<double> res;
for(map<string,double>::const_iterator it=tracers.begin();
it!=tracers.end();
++it)
res.push_back(it->second);
return res;
}
map<string,double> reassemble_tracers(const vector<double>& compositions,
const map<string,double>& old)
{
map<string,double> res;
for(pair<size_t,map<string,double>::const_iterator> index(0,old.begin());
index.second!=old.end();
++index.first,++index.second)
res[index.second->first] = compositions[index.first];
return res;
}
}
NuclearBurn::NuclearBurn
(const map<string,pair<double,double> >& atomic_properties,
const string& ignore_label,
const FermiTable& eos):
atomic_properties_(atomic_properties),
t_prev_(0),
ignore_label_(ignore_label),
eos_(eos) {}
void NuclearBurn::operator()(hdsim& sim)
{
const double dt = sim.getTime() - t_prev_;
vector<ComputationalCell>& cells = sim.getAllCells();
for(size_t i=0;i<cells.size();++i){
ComputationalCell& cell = cells[i];
if(safe_retrieve(cell.stickers,ignore_label_))
continue;
// const double temperature = eos_.
}
sim.recalculateExtensives();
}
<|endoftext|> |
<commit_before>/* -*- mode:c++; tab-width:4; c-basic-offset:4; -*- */
/**
* \file cryptoki_config.cpp
* \brief Configuration for the certman library
*/
#include "cryptoki_config.h"
#include <maemosec_common.h>
#include "c_xmldoc.h"
#include <string>
#include <vector>
typedef struct int_slot_info {
CK_SLOT_ID nr;
string label;
string domain;
bool is_shared;
bool is_writable;
}* I_SLOT_INFO;
static vector<I_SLOT_INFO> slots;
extern "C" {
const char config_file_name[] = "/etc/maemosec-certman-cryptoki.conf";
static void
strbcpy(CK_UTF8CHAR* to, const char* from, const unsigned blen)
{
unsigned slen = strlen(from);
if (slen < blen) {
memcpy((char*)to, from, slen);
memset((char*)to + slen, ' ', blen - slen);
} else {
memcpy((char*)to, from, blen);
}
// This is not necessary
// *(to + blen - 1) = '\0';
}
CK_RV
read_config(CK_ULONG* nrof_slots,
CK_SLOT_ID_PTR slot_list,
CK_ULONG max_slots)
{
c_xmldoc cfile;
c_xmlnode* cnode;
string cfilename;
string appname;
string tagname;
process_name(appname);
MAEMOSEC_DEBUG(1, "Init PKCS11 for '%s'", appname.c_str());
cfile.parse_file(config_file_name);
cnode = cfile.root();
if (!cnode) {
*nrof_slots = 0;
goto end;
}
for (int i = 0; i < cnode->nbrof_children(); i++) {
tagname = string(cnode->child(i)->attribute("path", true, ""));
if ("application" == string(cnode->child(i)->name())
&& (appname == tagname || "*" == tagname))
{
MAEMOSEC_DEBUG(1, "config '%s' applied to '%s'",
tagname.c_str(), appname.c_str());
cnode = cnode->child(i);
for (int j = 0; j < cnode->nbrof_children(); j++) {
if ("slot" == string(cnode->child(j)->name())) {
c_xmlnode* lnode = cnode->child(j);
I_SLOT_INFO islot = new(struct int_slot_info);
islot->nr = atoi(lnode->attribute("nbr", true, ""));
islot->label = lnode->attribute("label", false, "");
islot->domain = lnode->attribute("domain", false, "");
islot->is_shared =
("shared" == string(lnode->attribute("type",true,"")));
islot->is_writable =
("y" == string(lnode->attribute("writable",true,"")));
slots.push_back(islot);
if (slots.size() == max_slots) {
MAEMOSEC_DEBUG(1, "All slots filled");
goto done;
}
}
}
}
}
done:
MAEMOSEC_DEBUG(1, "found %d slots for this application", slots.size());
*nrof_slots = slots.size();
for (int i = 0; i < slots.size(); i++) {
slot_list[i] = slots[i]->nr;
MAEMOSEC_DEBUG(1, "Slot %d=%d", i, slot_list[i]);
}
end:
return(CKR_OK);
}
void
release_config(void)
{
for (int i = 0; i < slots.size(); i++) {
slots.erase(slots.begin() + i);
delete(slots[i]);
}
}
extern CK_RV get_slot_info(CK_SLOT_ID slotID,
CK_SLOT_INFO_PTR pInfo)
{
I_SLOT_INFO sinfo = NULL;
MAEMOSEC_DEBUG(1, "%d", slotID);
for (int i = 0; i < slots.size(); i++) {
if (slots[i]->nr == slotID) {
sinfo = slots[i];
break;
}
}
if (sinfo && pInfo) {
strbcpy(pInfo->slotDescription,
"Maemo secure certificate store",
sizeof(pInfo->slotDescription));
strbcpy(pInfo->manufacturerID,
"Nokia corporation",
sizeof(pInfo->manufacturerID));
pInfo->flags = CKF_TOKEN_PRESENT;
pInfo->hardwareVersion.major = 0;
pInfo->hardwareVersion.minor = 1;
pInfo->firmwareVersion.major = 0;
pInfo->firmwareVersion.minor = 1;
return(CKR_OK);
} else
return(CKR_ARGUMENTS_BAD);
}
extern CK_RV get_token_info(CK_SLOT_ID slotID,
CK_TOKEN_INFO_PTR pInfo)
{
I_SLOT_INFO sinfo = NULL;
MAEMOSEC_DEBUG(1, "%d", slotID);
for (int i = 0; i < slots.size(); i++) {
if (slots[i]->nr == slotID) {
sinfo = slots[i];
break;
}
}
if (sinfo && pInfo) {
strbcpy(pInfo->label,
sinfo->label.c_str(),
sizeof(pInfo->label));
strbcpy(pInfo->manufacturerID,
"Nokia corporation",
sizeof(pInfo->manufacturerID));
strbcpy(pInfo->model,
"certman",
sizeof(pInfo->model));
strbcpy(pInfo->serialNumber,
"0000000000000000",
sizeof(pInfo->serialNumber));
pInfo->flags = CKF_TOKEN_INITIALIZED;
if (!sinfo->is_writable) {
pInfo->flags |= CKF_WRITE_PROTECTED;
pInfo->ulMaxRwSessionCount = 0;
} else
pInfo->ulMaxRwSessionCount = 1;
pInfo->ulMaxSessionCount = 1;
pInfo->ulSessionCount = 1;
pInfo->ulRwSessionCount = 0;
pInfo->ulMaxPinLen = 0;
pInfo->ulMinPinLen = 0;
pInfo->ulTotalPublicMemory = CK_UNAVAILABLE_INFORMATION;
pInfo->ulFreePublicMemory = CK_UNAVAILABLE_INFORMATION;
pInfo->ulTotalPrivateMemory = CK_UNAVAILABLE_INFORMATION;
pInfo->ulFreePrivateMemory = CK_UNAVAILABLE_INFORMATION;
pInfo->hardwareVersion.major = 0;
pInfo->hardwareVersion.minor = 1;
pInfo->firmwareVersion.major = 0;
pInfo->firmwareVersion.minor = 1;
strncpy((char*)pInfo->utcTime,
" ",
sizeof(pInfo->utcTime));
return(CKR_OK);
} else
return(CKR_ARGUMENTS_BAD);
}
static CK_SESSION_HANDLE last_session = 0;
static vector<SESSION> sessions;
typedef vector<SESSION>::iterator siter;
CK_SESSION_HANDLE
open_session(CK_SLOT_ID slot_id)
{
SESSION new_session;
I_SLOT_INFO slot_info = NULL;
domain_handle domain;
int rc;
for (size_t i = 0; i < slots.size(); i++) {
if (slots[i]->nr == slot_id) {
slot_info = slots[i];
}
}
if (!slot_info)
return(CKR_SLOT_ID_INVALID);
MAEMOSEC_DEBUG(1, "open %s domain %s",
slot_info->is_shared
?"shared":"private",
slot_info->domain.c_str());
rc = maemosec_certman_open_domain(slot_info->domain.c_str(),
slot_info->is_shared
?MAEMOSEC_CERTMAN_DOMAIN_SHARED
:MAEMOSEC_CERTMAN_DOMAIN_PRIVATE,
&domain);
if (rc != 0) {
return(CKR_SLOT_ID_INVALID);
}
new_session = new(struct session);
memset(new_session, '\0', sizeof(struct session));
/*
* Don't start from zero as zero is an invalid session handle
*/
new_session->session_id = ++last_session;
new_session->slot = slot_id;
new_session->cmdomain = domain;
new_session->domain_name = strdup(slot_info->domain.c_str());
new_session->read_only = !slot_info->is_writable;
new_session->state = sstat_base;
sessions.push_back(new_session);
return(new_session->session_id);
}
SESSION
find_session(CK_SESSION_HANDLE sess_id)
{
for (size_t i = 0; i < sessions.size(); i++) {
if (sessions[i]->session_id == sess_id)
return(sessions[i]);
}
return(NULL);
}
typedef vector<X509*> cstore;
static int
cb_copy_cert(int ordnr, X509* cert, void* sh)
{
cstore* certs = (cstore*)sh;
certs->push_back(cert);
MAEMOSEC_DEBUG(1, "Read certificate");
return(-1);
}
X509*
get_cert(SESSION sess, int ord_nbr)
{
cstore* certs;
if (sess->certs == NULL) {
certs = new(cstore);
sess->certs = certs;
maemosec_certman_iterate_certs(sess->cmdomain,
cb_copy_cert,
sess->certs);
} else {
certs = (cstore*)sess->certs;
}
if (ord_nbr < certs->size()) {
return((*certs)[(size_t)ord_nbr]);
} else {
MAEMOSEC_ERROR("invalid object nbr %d", ord_nbr);
return(NULL);
}
}
CK_RV
add_cert(SESSION sess, X509* cert, int* ord_nbr)
{
int rv;
cstore* certs;
if ( !sess
|| MAEMOSEC_CERTMAN_DOMAIN_NONE == sess->cmdomain)
{
MAEMOSEC_DEBUG(1, "sess %p, sess->cmdomain %p",
sess, sess->cmdomain);
return(CKR_SESSION_HANDLE_INVALID);
}
if (sess->certs == NULL) {
certs = new(cstore);
sess->certs = certs;
} else {
certs = (cstore*)sess->certs;
}
certs->push_back(cert);
*ord_nbr = certs->size() - 1;
rv = maemosec_certman_add_cert(sess->cmdomain, cert);
if (0 != rv) {
MAEMOSEC_ERROR("maemosec_certman_add_cert ret %d", rv);
return(CKR_FUNCTION_FAILED);
}
return(CKR_OK);
}
CK_RV
close_session(CK_SESSION_HANDLE sess_id)
{
for (size_t i = 0; i < sessions.size(); i++) {
if (sessions[i]->session_id == sess_id) {
SESSION sess = sessions[i];
sessions.erase(sessions.begin() + i);
if (sess->certs) {
cstore* certs = (cstore*)sess->certs;
for (size_t j = 0; j < certs->size(); j++) {
X509_free((*certs)[j]);
}
delete(certs);
}
if (sess->cmdomain != MAEMOSEC_CERTMAN_DOMAIN_NONE)
maemosec_certman_close_domain(sess->cmdomain);
if (sess->domain_name)
free((void*)sess->domain_name);
delete(sess);
MAEMOSEC_DEBUG(1, "exit, closed session %d", sess_id);
return(CKR_OK);
}
}
MAEMOSEC_DEBUG(1, "exit, session_not_found");
return(CKR_SESSION_HANDLE_INVALID);
}
CK_RV
close_all_sessions(CK_SLOT_ID slot_id)
{
for (size_t i = 0; i < sessions.size(); i++) {
if (sessions[i]->slot == slot_id) {
close_session(sessions[i]->session_id);
}
}
MAEMOSEC_DEBUG(1, "closed all sessions for slot %d", slot_id);
return(CKR_OK);
}
} /* extern C */
<commit_msg>Added include<cstring> to cryptoki_config.c as required by gcc 4.3.x<commit_after>/* -*- mode:c++; tab-width:4; c-basic-offset:4; -*- */
/**
* \file cryptoki_config.cpp
* \brief Configuration for the certman library
*/
#include "cryptoki_config.h"
#include <maemosec_common.h>
#include "c_xmldoc.h"
#include <cstring>
#include <string>
#include <vector>
typedef struct int_slot_info {
CK_SLOT_ID nr;
string label;
string domain;
bool is_shared;
bool is_writable;
}* I_SLOT_INFO;
static vector<I_SLOT_INFO> slots;
extern "C" {
const char config_file_name[] = "/etc/maemosec-certman-cryptoki.conf";
static void
strbcpy(CK_UTF8CHAR* to, const char* from, const unsigned blen)
{
unsigned slen = strlen(from);
if (slen < blen) {
memcpy((char*)to, from, slen);
memset((char*)to + slen, ' ', blen - slen);
} else {
memcpy((char*)to, from, blen);
}
// This is not necessary
// *(to + blen - 1) = '\0';
}
CK_RV
read_config(CK_ULONG* nrof_slots,
CK_SLOT_ID_PTR slot_list,
CK_ULONG max_slots)
{
c_xmldoc cfile;
c_xmlnode* cnode;
string cfilename;
string appname;
string tagname;
process_name(appname);
MAEMOSEC_DEBUG(1, "Init PKCS11 for '%s'", appname.c_str());
cfile.parse_file(config_file_name);
cnode = cfile.root();
if (!cnode) {
*nrof_slots = 0;
goto end;
}
for (int i = 0; i < cnode->nbrof_children(); i++) {
tagname = string(cnode->child(i)->attribute("path", true, ""));
if ("application" == string(cnode->child(i)->name())
&& (appname == tagname || "*" == tagname))
{
MAEMOSEC_DEBUG(1, "config '%s' applied to '%s'",
tagname.c_str(), appname.c_str());
cnode = cnode->child(i);
for (int j = 0; j < cnode->nbrof_children(); j++) {
if ("slot" == string(cnode->child(j)->name())) {
c_xmlnode* lnode = cnode->child(j);
I_SLOT_INFO islot = new(struct int_slot_info);
islot->nr = atoi(lnode->attribute("nbr", true, ""));
islot->label = lnode->attribute("label", false, "");
islot->domain = lnode->attribute("domain", false, "");
islot->is_shared =
("shared" == string(lnode->attribute("type",true,"")));
islot->is_writable =
("y" == string(lnode->attribute("writable",true,"")));
slots.push_back(islot);
if (slots.size() == max_slots) {
MAEMOSEC_DEBUG(1, "All slots filled");
goto done;
}
}
}
}
}
done:
MAEMOSEC_DEBUG(1, "found %d slots for this application", slots.size());
*nrof_slots = slots.size();
for (int i = 0; i < slots.size(); i++) {
slot_list[i] = slots[i]->nr;
MAEMOSEC_DEBUG(1, "Slot %d=%d", i, slot_list[i]);
}
end:
return(CKR_OK);
}
void
release_config(void)
{
for (int i = 0; i < slots.size(); i++) {
slots.erase(slots.begin() + i);
delete(slots[i]);
}
}
extern CK_RV get_slot_info(CK_SLOT_ID slotID,
CK_SLOT_INFO_PTR pInfo)
{
I_SLOT_INFO sinfo = NULL;
MAEMOSEC_DEBUG(1, "%d", slotID);
for (int i = 0; i < slots.size(); i++) {
if (slots[i]->nr == slotID) {
sinfo = slots[i];
break;
}
}
if (sinfo && pInfo) {
strbcpy(pInfo->slotDescription,
"Maemo secure certificate store",
sizeof(pInfo->slotDescription));
strbcpy(pInfo->manufacturerID,
"Nokia corporation",
sizeof(pInfo->manufacturerID));
pInfo->flags = CKF_TOKEN_PRESENT;
pInfo->hardwareVersion.major = 0;
pInfo->hardwareVersion.minor = 1;
pInfo->firmwareVersion.major = 0;
pInfo->firmwareVersion.minor = 1;
return(CKR_OK);
} else
return(CKR_ARGUMENTS_BAD);
}
extern CK_RV get_token_info(CK_SLOT_ID slotID,
CK_TOKEN_INFO_PTR pInfo)
{
I_SLOT_INFO sinfo = NULL;
MAEMOSEC_DEBUG(1, "%d", slotID);
for (int i = 0; i < slots.size(); i++) {
if (slots[i]->nr == slotID) {
sinfo = slots[i];
break;
}
}
if (sinfo && pInfo) {
strbcpy(pInfo->label,
sinfo->label.c_str(),
sizeof(pInfo->label));
strbcpy(pInfo->manufacturerID,
"Nokia corporation",
sizeof(pInfo->manufacturerID));
strbcpy(pInfo->model,
"certman",
sizeof(pInfo->model));
strbcpy(pInfo->serialNumber,
"0000000000000000",
sizeof(pInfo->serialNumber));
pInfo->flags = CKF_TOKEN_INITIALIZED;
if (!sinfo->is_writable) {
pInfo->flags |= CKF_WRITE_PROTECTED;
pInfo->ulMaxRwSessionCount = 0;
} else
pInfo->ulMaxRwSessionCount = 1;
pInfo->ulMaxSessionCount = 1;
pInfo->ulSessionCount = 1;
pInfo->ulRwSessionCount = 0;
pInfo->ulMaxPinLen = 0;
pInfo->ulMinPinLen = 0;
pInfo->ulTotalPublicMemory = CK_UNAVAILABLE_INFORMATION;
pInfo->ulFreePublicMemory = CK_UNAVAILABLE_INFORMATION;
pInfo->ulTotalPrivateMemory = CK_UNAVAILABLE_INFORMATION;
pInfo->ulFreePrivateMemory = CK_UNAVAILABLE_INFORMATION;
pInfo->hardwareVersion.major = 0;
pInfo->hardwareVersion.minor = 1;
pInfo->firmwareVersion.major = 0;
pInfo->firmwareVersion.minor = 1;
strncpy((char*)pInfo->utcTime,
" ",
sizeof(pInfo->utcTime));
return(CKR_OK);
} else
return(CKR_ARGUMENTS_BAD);
}
static CK_SESSION_HANDLE last_session = 0;
static vector<SESSION> sessions;
typedef vector<SESSION>::iterator siter;
CK_SESSION_HANDLE
open_session(CK_SLOT_ID slot_id)
{
SESSION new_session;
I_SLOT_INFO slot_info = NULL;
domain_handle domain;
int rc;
for (size_t i = 0; i < slots.size(); i++) {
if (slots[i]->nr == slot_id) {
slot_info = slots[i];
}
}
if (!slot_info)
return(CKR_SLOT_ID_INVALID);
MAEMOSEC_DEBUG(1, "open %s domain %s",
slot_info->is_shared
?"shared":"private",
slot_info->domain.c_str());
rc = maemosec_certman_open_domain(slot_info->domain.c_str(),
slot_info->is_shared
?MAEMOSEC_CERTMAN_DOMAIN_SHARED
:MAEMOSEC_CERTMAN_DOMAIN_PRIVATE,
&domain);
if (rc != 0) {
return(CKR_SLOT_ID_INVALID);
}
new_session = new(struct session);
memset(new_session, '\0', sizeof(struct session));
/*
* Don't start from zero as zero is an invalid session handle
*/
new_session->session_id = ++last_session;
new_session->slot = slot_id;
new_session->cmdomain = domain;
new_session->domain_name = strdup(slot_info->domain.c_str());
new_session->read_only = !slot_info->is_writable;
new_session->state = sstat_base;
sessions.push_back(new_session);
return(new_session->session_id);
}
SESSION
find_session(CK_SESSION_HANDLE sess_id)
{
for (size_t i = 0; i < sessions.size(); i++) {
if (sessions[i]->session_id == sess_id)
return(sessions[i]);
}
return(NULL);
}
typedef vector<X509*> cstore;
static int
cb_copy_cert(int ordnr, X509* cert, void* sh)
{
cstore* certs = (cstore*)sh;
certs->push_back(cert);
MAEMOSEC_DEBUG(1, "Read certificate");
return(-1);
}
X509*
get_cert(SESSION sess, int ord_nbr)
{
cstore* certs;
if (sess->certs == NULL) {
certs = new(cstore);
sess->certs = certs;
maemosec_certman_iterate_certs(sess->cmdomain,
cb_copy_cert,
sess->certs);
} else {
certs = (cstore*)sess->certs;
}
if (ord_nbr < certs->size()) {
return((*certs)[(size_t)ord_nbr]);
} else {
MAEMOSEC_ERROR("invalid object nbr %d", ord_nbr);
return(NULL);
}
}
CK_RV
add_cert(SESSION sess, X509* cert, int* ord_nbr)
{
int rv;
cstore* certs;
if ( !sess
|| MAEMOSEC_CERTMAN_DOMAIN_NONE == sess->cmdomain)
{
MAEMOSEC_DEBUG(1, "sess %p, sess->cmdomain %p",
sess, sess->cmdomain);
return(CKR_SESSION_HANDLE_INVALID);
}
if (sess->certs == NULL) {
certs = new(cstore);
sess->certs = certs;
} else {
certs = (cstore*)sess->certs;
}
certs->push_back(cert);
*ord_nbr = certs->size() - 1;
rv = maemosec_certman_add_cert(sess->cmdomain, cert);
if (0 != rv) {
MAEMOSEC_ERROR("maemosec_certman_add_cert ret %d", rv);
return(CKR_FUNCTION_FAILED);
}
return(CKR_OK);
}
CK_RV
close_session(CK_SESSION_HANDLE sess_id)
{
for (size_t i = 0; i < sessions.size(); i++) {
if (sessions[i]->session_id == sess_id) {
SESSION sess = sessions[i];
sessions.erase(sessions.begin() + i);
if (sess->certs) {
cstore* certs = (cstore*)sess->certs;
for (size_t j = 0; j < certs->size(); j++) {
X509_free((*certs)[j]);
}
delete(certs);
}
if (sess->cmdomain != MAEMOSEC_CERTMAN_DOMAIN_NONE)
maemosec_certman_close_domain(sess->cmdomain);
if (sess->domain_name)
free((void*)sess->domain_name);
delete(sess);
MAEMOSEC_DEBUG(1, "exit, closed session %d", sess_id);
return(CKR_OK);
}
}
MAEMOSEC_DEBUG(1, "exit, session_not_found");
return(CKR_SESSION_HANDLE_INVALID);
}
CK_RV
close_all_sessions(CK_SLOT_ID slot_id)
{
for (size_t i = 0; i < sessions.size(); i++) {
if (sessions[i]->slot == slot_id) {
close_session(sessions[i]->session_id);
}
}
MAEMOSEC_DEBUG(1, "closed all sessions for slot %d", slot_id);
return(CKR_OK);
}
} /* extern C */
<|endoftext|> |
<commit_before>#include "imzb/reader.hpp"
#include "blosc.h"
#include <ios>
#include <cassert>
#include <algorithm>
#include <stdexcept>
#include <sstream>
imzb::ImzbReader::ImzbReader(const std::string& filename) :
fn_(filename),
in_(filename, std::ios::binary), block_idx_(0), peaks_(imzb::ImzbWriter::BLOCK_SIZE),
n_peaks_(0), pos_(0), empty_(false)
{
std::ifstream in_idx(filename + ".idx", std::ios::binary);
if (!in_.is_open())
throw std::runtime_error("couldn't open the file");
if (!in_idx.is_open())
throw std::runtime_error("couldn't open the index file");
index_ = std::make_shared<Index>();
index_->read(in_idx);
in_.seekg(0, in_.end);
index_->offsets.push_back(in_.tellg());
in_.seekg(0, in_.beg);
}
size_t imzb::ImzbReader::decompressBlock(size_t block_idx,
std::ifstream& in,
std::vector<char>& inbuf,
std::vector<ims::Peak>& outbuf) const
{
assert(block_idx + 1 < index_->offsets.size());
uint64_t start = index_->offsets[block_idx];
uint64_t end = index_->offsets[block_idx + 1];
assert(start > 0);
assert(start < end);
inbuf.resize(end - start);
in.seekg(start);
in.read(&inbuf[0], end - start);
int result = blosc_decompress_ctx(&inbuf[0], &outbuf[0],
outbuf.size() * sizeof(ims::Peak), 1);
assert(result > 0);
return result / sizeof(ims::Peak);
}
bool imzb::ImzbReader::readNextBlock()
{
++block_idx_;
if (block_idx_ == index_->mzs.size()) {
n_peaks_ = 0;
return false;
}
n_peaks_ = decompressBlock(block_idx_, in_, buffer_, peaks_);
pos_ = 0;
return true;
}
bool imzb::ImzbReader::readNext(ims::Peak& peak)
{
if (empty_)
return false;
if (pos_ >= n_peaks_) {
if (!readNextBlock()) {
empty_ = true;
return false;
}
}
peak = peaks_[pos_];
++pos_;
return true;
}
void imzb::ImzbReader::reset()
{
in_.seekg(0, in_.beg);
n_peaks_ = pos_ = block_idx_ = 0;
empty_ = false;
}
std::vector<ims::Peak> imzb::ImzbReader::slice(double min_mz, double max_mz) const
{
assert(min_mz < max_mz);
std::vector<char> inbuf;
std::vector<ims::Peak> result, outbuf{imzb::ImzbWriter::BLOCK_SIZE};
size_t start_block = index_->startBlock(min_mz);
size_t end_block = index_->endBlock(max_mz);
std::ifstream in{fn_, std::ios::binary};
for (size_t i = start_block; i < end_block; ++i) {
size_t n = decompressBlock(i, in, inbuf, outbuf);
auto beg = outbuf.cbegin(), end = outbuf.cbegin() + n;
if (outbuf.front().mz < min_mz)
beg = std::lower_bound(beg, end, min_mz,
[](const ims::Peak& p, double mz) { return p.mz < mz; });
if (outbuf.back().mz > max_mz)
end = std::upper_bound(beg, end, max_mz,
[](double mz, const ims::Peak& p) { return mz < p.mz; });
result.insert(result.end(), beg, end);
}
return result;
}
ims::Image<float> imzb::ImzbReader::image(double mz, double ppm) const
{
assert(ppm > 0);
ims::Image<float> img(height(), width());
readImage(mz, ppm, img.rawPtr());
return img;
}
#define unlikely(x) __builtin_expect(!!(x), 0)
static void initImage(float* image, const imzb::Mask& mask) {
for (size_t i = 0; i < mask.height; ++i)
for (size_t j = 0; j < mask.width; ++j) {
auto idx = ims::pixelIndex(i, j, mask.width);
if (!mask.hasSpectrumAt(i, j))
image[idx] = -1.0;
else
image[idx] = 0.0;
}
}
void imzb::ImzbReader::readImage(double mz, double ppm, float* image) const
{
initImage(image, index_->header.mask);
auto peaks = slice(mz - mz * ppm * 1e-6, mz + mz * ppm * 1e-6);
for (auto& peak: peaks) {
if (unlikely(!index_->header.mask.hasSpectrumAt(peak.coords.x, peak.coords.y))) {
std::stringstream ss;
ss << "peak at x=" << peak.coords.x
<< ", y=" << peak.coords.y << ", m/z=" << peak.mz
<< " is outside the spatial mask";
throw std::runtime_error(ss.str());
}
if (unlikely(peak.intensity < 0)) {
std::stringstream ss;
ss << "negative intensity peak at x=" << peak.coords.x
<< ", y=" << peak.coords.y << ", m/z=" << peak.mz;
throw std::runtime_error(ss.str());
}
auto idx = ims::pixelIndex(peak.coords.x, peak.coords.y, width());
image[idx] += peak.intensity;
}
}
void imzb::ImzbReader::readCentroidedImage(double mz, double ppm, float* image) const
{
initImage(image, index_->header.mask);
auto peaks = slice(mz - mz * ppm * 1e-6, mz + mz * ppm * 1e-6);
auto n = height() * width();
auto float_inf = std::numeric_limits<float>::infinity();
std::vector<double> m_prev(n), m_curr(n), m_next(n);
std::vector<float> i_prev(n, float_inf), i_curr(n, float_inf), i_next(n, float_inf);
for (auto& peak: peaks) {
auto i = ims::pixelIndex(peak.coords.x, peak.coords.y, width());
m_prev[i] = m_curr[i], i_prev[i] = i_curr[i];
m_curr[i] = m_next[i], i_curr[i] = i_next[i];
m_next[i] = peak.mz, i_next[i] = peak.intensity;
if (i_prev[i] < i_curr[i] && i_curr[i] >= i_next[i]) {
image[i] += i_curr[i];
}
}
}
<commit_msg>removed old assert<commit_after>#include "imzb/reader.hpp"
#include "blosc.h"
#include <ios>
#include <cassert>
#include <algorithm>
#include <stdexcept>
#include <sstream>
imzb::ImzbReader::ImzbReader(const std::string& filename) :
fn_(filename),
in_(filename, std::ios::binary), block_idx_(0), peaks_(imzb::ImzbWriter::BLOCK_SIZE),
n_peaks_(0), pos_(0), empty_(false)
{
std::ifstream in_idx(filename + ".idx", std::ios::binary);
if (!in_.is_open())
throw std::runtime_error("couldn't open the file");
if (!in_idx.is_open())
throw std::runtime_error("couldn't open the index file");
index_ = std::make_shared<Index>();
index_->read(in_idx);
in_.seekg(0, in_.end);
index_->offsets.push_back(in_.tellg());
in_.seekg(0, in_.beg);
}
size_t imzb::ImzbReader::decompressBlock(size_t block_idx,
std::ifstream& in,
std::vector<char>& inbuf,
std::vector<ims::Peak>& outbuf) const
{
assert(block_idx + 1 < index_->offsets.size());
uint64_t start = index_->offsets[block_idx];
uint64_t end = index_->offsets[block_idx + 1];
assert(start < end);
inbuf.resize(end - start);
in.seekg(start);
in.read(&inbuf[0], end - start);
int result = blosc_decompress_ctx(&inbuf[0], &outbuf[0],
outbuf.size() * sizeof(ims::Peak), 1);
assert(result > 0);
return result / sizeof(ims::Peak);
}
bool imzb::ImzbReader::readNextBlock()
{
++block_idx_;
if (block_idx_ == index_->mzs.size()) {
n_peaks_ = 0;
return false;
}
n_peaks_ = decompressBlock(block_idx_, in_, buffer_, peaks_);
pos_ = 0;
return true;
}
bool imzb::ImzbReader::readNext(ims::Peak& peak)
{
if (empty_)
return false;
if (pos_ >= n_peaks_) {
if (!readNextBlock()) {
empty_ = true;
return false;
}
}
peak = peaks_[pos_];
++pos_;
return true;
}
void imzb::ImzbReader::reset()
{
in_.seekg(0, in_.beg);
n_peaks_ = pos_ = block_idx_ = 0;
empty_ = false;
}
std::vector<ims::Peak> imzb::ImzbReader::slice(double min_mz, double max_mz) const
{
assert(min_mz < max_mz);
std::vector<char> inbuf;
std::vector<ims::Peak> result, outbuf{imzb::ImzbWriter::BLOCK_SIZE};
size_t start_block = index_->startBlock(min_mz);
size_t end_block = index_->endBlock(max_mz);
std::ifstream in{fn_, std::ios::binary};
for (size_t i = start_block; i < end_block; ++i) {
size_t n = decompressBlock(i, in, inbuf, outbuf);
auto beg = outbuf.cbegin(), end = outbuf.cbegin() + n;
if (outbuf.front().mz < min_mz)
beg = std::lower_bound(beg, end, min_mz,
[](const ims::Peak& p, double mz) { return p.mz < mz; });
if (outbuf.back().mz > max_mz)
end = std::upper_bound(beg, end, max_mz,
[](double mz, const ims::Peak& p) { return mz < p.mz; });
result.insert(result.end(), beg, end);
}
return result;
}
ims::Image<float> imzb::ImzbReader::image(double mz, double ppm) const
{
assert(ppm > 0);
ims::Image<float> img(height(), width());
readImage(mz, ppm, img.rawPtr());
return img;
}
#define unlikely(x) __builtin_expect(!!(x), 0)
static void initImage(float* image, const imzb::Mask& mask) {
for (size_t i = 0; i < mask.height; ++i)
for (size_t j = 0; j < mask.width; ++j) {
auto idx = ims::pixelIndex(i, j, mask.width);
if (!mask.hasSpectrumAt(i, j))
image[idx] = -1.0;
else
image[idx] = 0.0;
}
}
void imzb::ImzbReader::readImage(double mz, double ppm, float* image) const
{
initImage(image, index_->header.mask);
auto peaks = slice(mz - mz * ppm * 1e-6, mz + mz * ppm * 1e-6);
for (auto& peak: peaks) {
if (unlikely(!index_->header.mask.hasSpectrumAt(peak.coords.x, peak.coords.y))) {
std::stringstream ss;
ss << "peak at x=" << peak.coords.x
<< ", y=" << peak.coords.y << ", m/z=" << peak.mz
<< " is outside the spatial mask";
throw std::runtime_error(ss.str());
}
if (unlikely(peak.intensity < 0)) {
std::stringstream ss;
ss << "negative intensity peak at x=" << peak.coords.x
<< ", y=" << peak.coords.y << ", m/z=" << peak.mz;
throw std::runtime_error(ss.str());
}
auto idx = ims::pixelIndex(peak.coords.x, peak.coords.y, width());
image[idx] += peak.intensity;
}
}
void imzb::ImzbReader::readCentroidedImage(double mz, double ppm, float* image) const
{
initImage(image, index_->header.mask);
auto peaks = slice(mz - mz * ppm * 1e-6, mz + mz * ppm * 1e-6);
auto n = height() * width();
auto float_inf = std::numeric_limits<float>::infinity();
std::vector<double> m_prev(n), m_curr(n), m_next(n);
std::vector<float> i_prev(n, float_inf), i_curr(n, float_inf), i_next(n, float_inf);
for (auto& peak: peaks) {
auto i = ims::pixelIndex(peak.coords.x, peak.coords.y, width());
m_prev[i] = m_curr[i], i_prev[i] = i_curr[i];
m_curr[i] = m_next[i], i_curr[i] = i_next[i];
m_next[i] = peak.mz, i_next[i] = peak.intensity;
if (i_prev[i] < i_curr[i] && i_curr[i] >= i_next[i]) {
image[i] += i_curr[i];
}
}
}
<|endoftext|> |
<commit_before>#ifndef MUTEXES_H
#define MUTEXES_H
/*
This header file contains "App" versions of the os/thread.hpp
objects.
The "App" versions have the following characteristics:
1. If you -Dsingle_threaded, they are completely empty and
will be removed by a sufficiently-smart compiler.
We even lose the dependency on pthreads, so in theory
we can still work in an environment without pthreads.
2. If you decide to launch hl in single-threaded mode, these
will not bother to do locking, or allocate and create
lock.
*/
#ifndef single_threaded
#include"thread.hpp"
#include<boost/scoped_ptr.hpp>
#endif
#include<boost/noncopyable.hpp>
class AppLock;
class AppTryLock;
class AppCondVar;
class AppMutex : boost::noncopyable {
private:
#ifndef single_threaded
boost::scoped_ptr<Mutex> mp;
#endif
AppMutex(AppMutex const&) : mp() { }
public:
AppMutex(void) {
#ifndef single_threaded
if(!single_threaded) {
mp.reset(new Mutex());
}
#endif
}
friend class AppLock;
friend class AppTryLock;
};
class AppLock : boost::noncopyable {
private:
#ifndef single_threaded
boost::scoped_ptr<Lock> lp;
#endif
AppLock(void); // disallowed!
public:
AppLock(AppMutex& m) {
#ifndef single_threaded
if(!single_threaded) {
lp.reset(new Lock(*m.mp));
}
#endif
}
friend class AppCondVar;
};
class AppTryLock : boost::noncopyable {
private:
#ifndef single_threaded
boost::scoped_ptr<TryLock> lp;
#endif
AppTryLock(void); //disallowed!
public:
AppTryLock(AppMutex& m) {
#ifndef single_threaded
if(!single_threaded) {
lp.reset(new TryLock(*m.mp));
}
#endif
}
/*safe bool idiom*/
inline void unspecified_bool(void) const { }
typedef void (AppTryLock::*unspecified_bool_type)(void) const;
operator unspecified_bool_type(void) const {
#ifndef single_threaded
if(!lp) return &AppTryLock::unspecified_bool;
return (*lp) ? &AppTryLock::unspecified_bool : 0;
#else
return &AppTryLock::unspecified_bool;
#endif
}
friend class AppCondVar;
};
class AppCondVar : boost::noncopyable {
private:
#ifndef single_threaded
boost::scoped_ptr<CondVar> cp;
#endif
public:
AppCondVar(void) {
#ifndef single_threaded
if(!single_threaded) {
cp.reset(new CondVar());
}
#endif
}
void wait(AppLock const& l) const {
#ifndef single_threaded
if(l.lp && cp) {
cp->wait(*l.lp);
}
#endif
}
void wait(AppTryLock const& l) const {
#ifndef single_threaded
if(l.lp && cp) {
cp->wait(*l.lp);
}
#endif
}
void signal(void) {
#ifndef single_threaded
if(cp) {
cp->signal();
}
#endif
}
void broadcast(void) {
#ifndef single_threaded
if(cp) {
cp->broadcast();
}
#endif
}
};
#endif // MUTEXES_H
<commit_msg>inc/mutexes.hpp: Corrected compilation with -Dsingle_threaded option<commit_after>#ifndef MUTEXES_H
#define MUTEXES_H
/*
This header file contains "App" versions of the os/thread.hpp
objects.
The "App" versions have the following characteristics:
1. If you -Dsingle_threaded, they are completely empty and
will be removed by a sufficiently-smart compiler.
We even lose the dependency on pthreads, so in theory
we can still work in an environment without pthreads.
2. If you decide to launch hl in single-threaded mode, these
will not bother to do locking, or allocate and create
lock.
*/
#ifndef single_threaded
#include"thread.hpp"
#include<boost/scoped_ptr.hpp>
#endif
#include<boost/noncopyable.hpp>
class AppLock;
class AppTryLock;
class AppCondVar;
class AppMutex : boost::noncopyable {
private:
#ifndef single_threaded
boost::scoped_ptr<Mutex> mp;
#endif
AppMutex(AppMutex const&)
#ifndef single_threaded
: mp()
#endif
{ }
public:
AppMutex(void) {
#ifndef single_threaded
if(!single_threaded) {
mp.reset(new Mutex());
}
#endif
}
friend class AppLock;
friend class AppTryLock;
};
class AppLock : boost::noncopyable {
private:
#ifndef single_threaded
boost::scoped_ptr<Lock> lp;
#endif
AppLock(void); // disallowed!
public:
AppLock(AppMutex& m) {
#ifndef single_threaded
if(!single_threaded) {
lp.reset(new Lock(*m.mp));
}
#endif
}
friend class AppCondVar;
};
class AppTryLock : boost::noncopyable {
private:
#ifndef single_threaded
boost::scoped_ptr<TryLock> lp;
#endif
AppTryLock(void); //disallowed!
public:
AppTryLock(AppMutex& m) {
#ifndef single_threaded
if(!single_threaded) {
lp.reset(new TryLock(*m.mp));
}
#endif
}
/*safe bool idiom*/
inline void unspecified_bool(void) const { }
typedef void (AppTryLock::*unspecified_bool_type)(void) const;
operator unspecified_bool_type(void) const {
#ifndef single_threaded
if(!lp) return &AppTryLock::unspecified_bool;
return (*lp) ? &AppTryLock::unspecified_bool : 0;
#else
return &AppTryLock::unspecified_bool;
#endif
}
friend class AppCondVar;
};
class AppCondVar : boost::noncopyable {
private:
#ifndef single_threaded
boost::scoped_ptr<CondVar> cp;
#endif
public:
AppCondVar(void) {
#ifndef single_threaded
if(!single_threaded) {
cp.reset(new CondVar());
}
#endif
}
void wait(AppLock const& l) const {
#ifndef single_threaded
if(l.lp && cp) {
cp->wait(*l.lp);
}
#endif
}
void wait(AppTryLock const& l) const {
#ifndef single_threaded
if(l.lp && cp) {
cp->wait(*l.lp);
}
#endif
}
void signal(void) {
#ifndef single_threaded
if(cp) {
cp->signal();
}
#endif
}
void broadcast(void) {
#ifndef single_threaded
if(cp) {
cp->broadcast();
}
#endif
}
};
#endif // MUTEXES_H
<|endoftext|> |
<commit_before><commit_msg>Remove unused variable<commit_after><|endoftext|> |
<commit_before><commit_msg>Increase delay between sysexes<commit_after><|endoftext|> |
<commit_before>//
// LevelManager.cpp
// Created by Matt Kaufmann on 01/10/14.
//
#include "ExampleGame/Components/LevelManager/LevelManager.h"
#include "ExampleGame/Components/ComponentTypes/ComponentTypeIds.h"
#include "ExampleGame/Components/LevelManager/LevelFileTags.h"
#include "ExampleGame/Components/ShadyCamera/ShadyCamera.h"
#include "ExampleGame/GameSingletons/GameSingletons.h"
#include "Vajra/Engine/Components/DerivedComponents/Transform/Transform.h"
// These includes can probably go away once we load objects from prefabs.
#include "ExampleGame/Components/GameScripts/SampleGameScript.h"
#include "ExampleGame/Components/GameScripts/Units/PlayerUnit.h"
#include "ExampleGame/Components/Grid/GridNavigator.h"
#include "ExampleGame/Components/Grid/GridRoom.h"
#include "Vajra/Engine/Components/DerivedComponents/Renderer/MeshRenderer.h"
#include "Vajra/Engine/Core/Engine.h"
#include "Vajra/Engine/SceneGraph/SceneGraph3D.h"
#include "Vajra/Framework/DeviceUtils/FileSystemUtils/FileSystemUtils.h"
#include <fstream>
ComponentIdType LevelManager::componentTypeId = COMPONENT_TYPE_ID_LEVEL_MANAGER;
LevelManager::LevelManager() : Component() {
this->init();
}
LevelManager::LevelManager(Object* object_) : Component(object_) {
this->init();
}
LevelManager::~LevelManager() {
this->destroy();
}
void LevelManager::HandleMessage(MessageChunk messageChunk) {
switch (messageChunk->GetMessageType()) {
case MESSAGE_TYPE_FRAME_EVENT:
this->update();
break;
}
}
void LevelManager::LoadLevelFromFile(std::string levelFilename) {
std::ifstream ifs;
ifs.open(levelFilename, std::ios_base::in);
ASSERT(!ifs.fail(), "Loading level data from file %s", levelFilename.c_str());
std::string tag;
ifs >> tag;
ASSERT(tag == LEVEL_NAME_TAG, "Reading level name from file %s", levelFilename.c_str());
ifs >> this->currentLevelName;
SINGLETONS->GetGridManager()->loadGridDataFromStream(ifs);
this->loadStaticDataFromStream(ifs);
this->loadUnitDataFromStream(ifs);
this->loadCameraDataFromStream(ifs);
ifs.close();
this->isPaused = false;
}
void LevelManager::init() {
//this->shadyCam = nullptr;
this->isPaused = true;
this->currentLevelName = "";
this->addSubscriptionToMessageType(MESSAGE_TYPE_FRAME_EVENT, this->GetTypeId(), false);
}
void LevelManager::destroy() {
this->removeSubscriptionToAllMessageTypes(this->GetTypeId());
}
void LevelManager::update() {
if (!this->isPaused) {
}
}
void LevelManager::loadStaticDataFromStream(std::istream& ifs) {
std::string tag;
// Static Geometry
int nStaticObjs;
ifs >> tag;
ASSERT(tag == NUM_STATIC_TAG, "Loading static objects for level %s", SINGLETONS->GetLevelManager()->GetCurrentLevelName().c_str());
ifs >> nStaticObjs;
for (int i = 0; i < nStaticObjs; ++i) {
std::string prefab;
int objWestBound, objSouthBound, objWidth, objHeight; // Cell bounds
float rotation;
ifs >> prefab >> objWestBound >> objSouthBound >> objWidth >> objHeight >> rotation;
// Temporary code; Eventually we should be doing this by reading from a prefab.
GameObject* staticObj = new GameObject(ENGINE->GetSceneGraph3D());
ENGINE->GetSceneGraph3D()->GetRootGameObject()->AddChild(staticObj->GetId());
// Add the object to the grid
SINGLETONS->GetGridManager()->placeStaticObjectOnGrid(staticObj->GetId(), objWestBound, objSouthBound, objWidth, objHeight);
staticObj->GetTransform()->SetOrientation(rotation, YAXIS);
}
}
void LevelManager::loadUnitDataFromStream(std::istream& ifs) {
std::string tag;
// Player Units
int nPlayerUnits;
ifs >> tag;
ASSERT(tag == NUM_PLAYERS_TAG, "Loading player units for level %s", SINGLETONS->GetLevelManager()->GetCurrentLevelName().c_str());
ifs >> nPlayerUnits;
for (int i = 0; i < nPlayerUnits; ++i) {
std::string unitType; // Unit type
int gX, gZ; // Starting position
float rotation; // Orientation
ifs >> unitType >> gX >> gZ >> rotation;
// Temporary code; Eventually we should be doing this by reading from a prefab.
GameObject* unitObj = new GameObject(ENGINE->GetSceneGraph3D());
ENGINE->GetSceneGraph3D()->GetRootGameObject()->AddChild(unitObj->GetId());
MeshRenderer* unitRenderer = unitObj->AddComponent<MeshRenderer>();
unitRenderer->InitMesh(FRAMEWORK->GetFileSystemUtils()->GetDeviceModelResourcesPath() + "Suzanne.model");
unitObj->AddComponent<SampleGameScript>();
unitObj->AddComponent<GridNavigator>();
unitObj->AddComponent<PlayerUnit>();
// Add the unit to the grid
SINGLETONS->GetGridManager()->placeUnitOnGrid(unitObj->GetId(), gX, gZ);
unitObj->GetTransform()->SetOrientation(rotation, YAXIS);
}
// Enemy Units
int nEnemyUnits;
ifs >> tag;
ASSERT(tag == NUM_ENEMIES_TAG, "Loading enemy units for level %s", SINGLETONS->GetLevelManager()->GetCurrentLevelName().c_str());
ifs >> nEnemyUnits;
for (int i = 0; i < nEnemyUnits; ++i) {
std::string unitType; // Unit type
int gX, gZ; // Starting position
float rotation; // Orientation
int nCommands; // Number of AI commands
ifs >> unitType >> gX >> gZ >> rotation >> nCommands;
for (int j = 0; j < nCommands; ++j) {
std::string command;
ifs >> command;
}
}
}
void LevelManager::loadCameraDataFromStream(std::istream& ifs) {
// The level data file will specify which unit the camera should focus on by default
std::string tag;
std::string startingUnit;
ifs >> tag;
ASSERT(tag == UNIT_START_TAG, "Loading starting unit for level %s", SINGLETONS->GetLevelManager()->GetCurrentLevelName().c_str());
ifs >> startingUnit;
// Create the ShadyCamera; this should possibly be a prefab as well.
GameObject* camera = new GameObject(ENGINE->GetSceneGraph3D());
ENGINE->GetSceneGraph3D()->GetRootGameObject()->AddChild(camera->GetId());
ShadyCamera* cameraComponent = camera->AddComponent<ShadyCamera>();
cameraComponent->SetCameraType(CAMERA_TYPE_PERSPECTIVE);
ENGINE->GetSceneGraph3D()->SetMainCameraId(camera->GetId());
cameraComponent->SetGridManager(SINGLETONS->GetGridManager());
// TODO [Hack] Figure out a better way to do this.
int gX = SINGLETONS->GetGridManager()->gridRooms[0]->westBound;
int gZ = SINGLETONS->GetGridManager()->gridRooms[0]->southBound;
cameraComponent->MoveToRoom(gX, gZ);
}
void LevelManager::endLevel(bool /*success*/) {
this->isPaused = true;
//LevelEnd.EndLevel(success);
}
<commit_msg>Addressed comment on pull request<commit_after>//
// LevelManager.cpp
// Created by Matt Kaufmann on 01/10/14.
//
#include "ExampleGame/Components/LevelManager/LevelManager.h"
#include "ExampleGame/Components/ComponentTypes/ComponentTypeIds.h"
#include "ExampleGame/Components/LevelManager/LevelFileTags.h"
#include "ExampleGame/Components/ShadyCamera/ShadyCamera.h"
#include "ExampleGame/GameSingletons/GameSingletons.h"
#include "Vajra/Engine/Components/DerivedComponents/Transform/Transform.h"
// These includes can probably go away once we load objects from prefabs.
#include "ExampleGame/Components/GameScripts/SampleGameScript.h"
#include "ExampleGame/Components/GameScripts/Units/PlayerUnit.h"
#include "ExampleGame/Components/Grid/GridNavigator.h"
#include "ExampleGame/Components/Grid/GridRoom.h"
#include "Vajra/Engine/Components/DerivedComponents/Renderer/MeshRenderer.h"
#include "Vajra/Engine/Core/Engine.h"
#include "Vajra/Engine/SceneGraph/SceneGraph3D.h"
#include "Vajra/Framework/DeviceUtils/FileSystemUtils/FileSystemUtils.h"
#include <fstream>
ComponentIdType LevelManager::componentTypeId = COMPONENT_TYPE_ID_LEVEL_MANAGER;
LevelManager::LevelManager() : Component() {
this->init();
}
LevelManager::LevelManager(Object* object_) : Component(object_) {
this->init();
}
LevelManager::~LevelManager() {
this->destroy();
}
void LevelManager::HandleMessage(MessageChunk messageChunk) {
switch (messageChunk->GetMessageType()) {
case MESSAGE_TYPE_FRAME_EVENT:
this->update();
break;
}
}
void LevelManager::LoadLevelFromFile(std::string levelFilename) {
std::ifstream ifs;
ifs.open(levelFilename, std::ios_base::in);
ASSERT(!ifs.fail(), "Loading level data from file %s", levelFilename.c_str());
std::string tag;
ifs >> tag;
ASSERT(tag == LEVEL_NAME_TAG, "Reading level name from file %s", levelFilename.c_str());
ifs >> this->currentLevelName;
SINGLETONS->GetGridManager()->loadGridDataFromStream(ifs);
this->loadStaticDataFromStream(ifs);
this->loadUnitDataFromStream(ifs);
this->loadCameraDataFromStream(ifs);
ifs.close();
this->isPaused = false;
}
void LevelManager::init() {
//this->shadyCam = nullptr;
this->isPaused = true;
this->currentLevelName = "";
this->addSubscriptionToMessageType(MESSAGE_TYPE_FRAME_EVENT, this->GetTypeId(), false);
}
void LevelManager::destroy() {
this->removeSubscriptionToAllMessageTypes(this->GetTypeId());
}
void LevelManager::update() {
if (!this->isPaused) {
}
}
void LevelManager::loadStaticDataFromStream(std::istream& ifs) {
std::string tag;
// Static Geometry
int nStaticObjs;
ifs >> tag;
ASSERT(tag == NUM_STATIC_TAG, "Loading static objects for level %s", SINGLETONS->GetLevelManager()->GetCurrentLevelName().c_str());
ifs >> nStaticObjs;
for (int i = 0; i < nStaticObjs; ++i) {
std::string prefab;
int objWestBound, objSouthBound, objWidth, objHeight; // Cell bounds
float rotation;
ifs >> prefab >> objWestBound >> objSouthBound >> objWidth >> objHeight >> rotation;
// Temporary code; Eventually we should be doing this by reading from a prefab.
GameObject* staticObj = new GameObject(ENGINE->GetSceneGraph3D());
ENGINE->GetSceneGraph3D()->GetRootGameObject()->AddChild(staticObj->GetId());
// Add the object to the grid
SINGLETONS->GetGridManager()->placeStaticObjectOnGrid(staticObj->GetId(), objWestBound, objSouthBound, objWidth, objHeight);
staticObj->GetTransform()->SetOrientation(rotation, YAXIS);
}
}
void LevelManager::loadUnitDataFromStream(std::istream& ifs) {
std::string tag;
// Player Units
int nPlayerUnits;
ifs >> tag;
ASSERT(tag == NUM_PLAYERS_TAG, "Loading player units for level %s", SINGLETONS->GetLevelManager()->GetCurrentLevelName().c_str());
ifs >> nPlayerUnits;
for (int i = 0; i < nPlayerUnits; ++i) {
std::string unitType; // Unit type
int gX, gZ; // Starting position
float rotation; // Orientation
ifs >> unitType >> gX >> gZ >> rotation;
// Temporary code; Eventually we should be doing this by reading from a prefab.
GameObject* unitObj = new GameObject(ENGINE->GetSceneGraph3D());
ENGINE->GetSceneGraph3D()->GetRootGameObject()->AddChild(unitObj->GetId());
MeshRenderer* unitRenderer = unitObj->AddComponent<MeshRenderer>();
unitRenderer->InitMesh(FRAMEWORK->GetFileSystemUtils()->GetDeviceModelResourcesPath() + "Suzanne.model");
unitObj->AddComponent<SampleGameScript>();
unitObj->AddComponent<GridNavigator>();
unitObj->AddComponent<PlayerUnit>();
// Add the unit to the grid
SINGLETONS->GetGridManager()->placeUnitOnGrid(unitObj->GetId(), gX, gZ);
unitObj->GetTransform()->SetOrientation(rotation, YAXIS);
}
// Enemy Units
int nEnemyUnits;
ifs >> tag;
ASSERT(tag == NUM_ENEMIES_TAG, "Loading enemy units for level %s", SINGLETONS->GetLevelManager()->GetCurrentLevelName().c_str());
ifs >> nEnemyUnits;
for (int i = 0; i < nEnemyUnits; ++i) {
std::string unitType; // Unit type
int gX, gZ; // Starting position
float rotation; // Orientation
int nCommands; // Number of AI commands
ifs >> unitType >> gX >> gZ >> rotation >> nCommands;
for (int j = 0; j < nCommands; ++j) {
std::string command;
ifs >> command;
}
}
}
void LevelManager::loadCameraDataFromStream(std::istream& ifs) {
// The level data file will specify which unit the camera should focus on by default
std::string tag;
std::string startingUnit;
ifs >> tag;
ASSERT(tag == UNIT_START_TAG, "Loading starting unit for level %s", SINGLETONS->GetLevelManager()->GetCurrentLevelName().c_str());
ifs >> startingUnit;
// Create the ShadyCamera; this should possibly be a prefab as well.
GameObject* camera = new GameObject(ENGINE->GetSceneGraph3D());
ENGINE->GetSceneGraph3D()->GetRootGameObject()->AddChild(camera->GetId());
ShadyCamera* cameraComponent = camera->AddComponent<ShadyCamera>();
ENGINE->GetSceneGraph3D()->SetMainCameraId(camera->GetId());
cameraComponent->SetGridManager(SINGLETONS->GetGridManager());
// TODO [Hack] Figure out a better way to do this.
int gX = SINGLETONS->GetGridManager()->gridRooms[0]->westBound;
int gZ = SINGLETONS->GetGridManager()->gridRooms[0]->southBound;
cameraComponent->MoveToRoom(gX, gZ);
}
void LevelManager::endLevel(bool /*success*/) {
this->isPaused = true;
//LevelEnd.EndLevel(success);
}
<|endoftext|> |
<commit_before>#ifndef PLATEROBJECT_HPP
#define PLATEROBJECT_HPP
#include <wx/wxprec.h>
#ifndef WX_PRECOMP
#include <wx/wx.h>
#endif
#include "ExPolygonCollection.hpp"
#include "Model.hpp"
namespace Slic3r { namespace GUI {
class PlaterObject {
public:
std::string name {""};
size_t identifier {0U};
std::string input_file {""};
int input_file_obj_idx {-1};
bool selected {false};
int selected_instance {-1};
Slic3r::ExPolygonCollection thumbnail;
Slic3r::ExPolygonCollection transformed_thumbnail;
// read only
std::vector<Slic3r::ExPolygonCollection> instance_thumbnails;
Slic3r::ExPolygonCollection& make_thumbnail(const Slic3r::Model model, int obj_idx);
Slic3r::ExPolygonCollection& make_thumbnail(const std::shared_ptr<Slic3r::Model> model, int obj_idx);
Slic3r::ExPolygonCollection& transform_thumbnail(const Slic3r::Model model, int obj_idx);
Slic3r::ExPolygonCollection& transform_thumbnail(const std::shared_ptr<Slic3r::Model> model, int obj_idx);
protected:
const std::string LogChannel {"PlaterObject"};
};
}} // Namespace Slic3r::GUI
#endif
<commit_msg>use integers instead of size_t for object identifiers.<commit_after>#ifndef PLATEROBJECT_HPP
#define PLATEROBJECT_HPP
#include <wx/wxprec.h>
#ifndef WX_PRECOMP
#include <wx/wx.h>
#endif
#include "ExPolygonCollection.hpp"
#include "Model.hpp"
namespace Slic3r { namespace GUI {
class PlaterObject {
public:
std::string name {""};
int identifier {0};
std::string input_file {""};
int input_file_obj_idx {-1};
bool selected {false};
int selected_instance {-1};
Slic3r::ExPolygonCollection thumbnail;
Slic3r::ExPolygonCollection transformed_thumbnail;
// read only
std::vector<Slic3r::ExPolygonCollection> instance_thumbnails;
Slic3r::ExPolygonCollection& make_thumbnail(const Slic3r::Model model, int obj_idx);
Slic3r::ExPolygonCollection& make_thumbnail(const std::shared_ptr<Slic3r::Model> model, int obj_idx);
Slic3r::ExPolygonCollection& transform_thumbnail(const Slic3r::Model model, int obj_idx);
Slic3r::ExPolygonCollection& transform_thumbnail(const std::shared_ptr<Slic3r::Model> model, int obj_idx);
protected:
const std::string LogChannel {"PlaterObject"};
};
}} // Namespace Slic3r::GUI
#endif
<|endoftext|> |
<commit_before><commit_msg>[FlashPy]: check matrix when getting types.<commit_after><|endoftext|> |
<commit_before>// Copyright 2011 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <iostream>
#include <list>
#include "base/at_exit.h"
#include "base/command_line.h"
#include "base/file_util.h"
#include "base/logging.h"
#include "base/process_util.h"
#include "base/utf_string_conversions.h"
#include "pcrecpp.h" // NOLINT
#include "syzygy/wsdump/process_working_set.h"
namespace {
class RegexpProcessFilter: public base::ProcessFilter {
public:
RegexpProcessFilter();
bool Initialize(const std::string& regexpr);
virtual bool Includes(const base::ProcessEntry& entry) const OVERRIDE;
private:
pcrecpp::RE expr_;
};
RegexpProcessFilter::RegexpProcessFilter() : expr_("") {
}
bool RegexpProcessFilter::Initialize(const std::string& regexpr) {
pcrecpp::RE_Options options;
options.set_utf8(true);
options.set_caseless(true);
pcrecpp::RE new_expr(regexpr, options);
if (!new_expr.error().empty()) {
LOG(ERROR) << "Failed to initialize regular expression, error: "
<< new_expr.error();
return false;
}
expr_ = new_expr;
DCHECK_EQ("", new_expr.error());
return true;
}
bool RegexpProcessFilter::Includes(const base::ProcessEntry& entry) const {
return expr_.PartialMatch(WideToUTF8(entry.exe_file()));
}
} // namespace
static const char kUsage[] =
"Usage: wsdump [--process-name=<process_re>]\n"
"\n"
" Captures and outputs working set statistics for all processes,\n"
" or only for processess whose executable name matches <process_re>.\n"
"\n"
" The output is tab-separated, where a process heading starts a line with\n"
" an executable name, followed by the process PID and parent PID.\n"
" Following a process heading is a tab-prefixed line for each module that\n"
" appear in its working set, where the line has the following columns\n"
" * Module path.\n"
" * Total number of pages.\n"
" * Number of shareable pages.\n"
" * Number of shared pages.\n"
" * Number of read-only (non-executable) pages.\n"
" * Number of writable pages.\n"
" * Number of executable pages.\n"
"\n"
"Example output:\n"
"\n"
"notepad++.exe 4648 3600\n"
" Total: 4402 2694 2377 4402 2694 2377 963 1714 1725\n"
" C:\\PROGRA~2\\Sophos\\SOPHOS~1\\SOPHOS~1.DLL 3 3 3 3 3 3 1 0 2\n"
" C:\\Windows\\SysWOW64\\ntdll.dll 84 78 78 84 78 78 1 5 78\n";
static int Usage() {
std::cout << kUsage;
return 1;
}
int main(int argc, char** argv) {
base::AtExitManager at_exit_manager;
CommandLine::Init(argc, argv);
if (!logging::InitLogging(L"", logging::LOG_ONLY_TO_SYSTEM_DEBUG_LOG,
logging::DONT_LOCK_LOG_FILE, logging::APPEND_TO_OLD_LOG_FILE,
logging::ENABLE_DCHECK_FOR_NON_OFFICIAL_RELEASE_BUILDS)) {
return 1;
}
CommandLine* cmd_line = CommandLine::ForCurrentProcess();
DCHECK(cmd_line != NULL);
if (cmd_line->HasSwitch("help") || !cmd_line->args().empty()) {
return Usage();
}
// If the process-name is empty or missing we match all processes.
std::string process_re = cmd_line->GetSwitchValueASCII("process-name");
RegexpProcessFilter filter;
if (!filter.Initialize(process_re)) {
LOG(ERROR) << "Incorrect process filter regular expression.";
return 1;
}
struct ProcessInfo {
ProcessInfo() : pid(0), parent_pid(0) {
}
std::wstring exe_file;
base::ProcessId pid;
base::ProcessId parent_pid;
ProcessWorkingSet ws;
};
typedef std::list<ProcessInfo> WorkingSets;
WorkingSets working_sets;
const base::ProcessEntry* entry = NULL;
base::ProcessIterator process_iterator(&filter);
while (entry = process_iterator.NextProcessEntry()) {
working_sets.push_back(ProcessInfo());
ProcessInfo& info = working_sets.back();
if (info.ws.Initialize(entry->pid())) {
info.exe_file = entry->exe_file();
info.pid = entry->pid();
info.parent_pid = entry->parent_pid();
} else {
LOG(ERROR) << "Unable to capture working set information for pid: "
<< entry->pid();
working_sets.pop_back();
}
}
WorkingSets::const_iterator it = working_sets.begin();
for (; it != working_sets.end(); ++it) {
std::cout << it->exe_file << "\t"
<< it->pid << "\t"
<< it->parent_pid << std::endl;
const ProcessWorkingSet& ws = it->ws;
std::cout << "\tTotal: "
<< "\t" << ws.total_stats().pages
<< "\t" << ws.total_stats().shareable_pages
<< "\t" << ws.total_stats().shared_pages
<< "\t" << ws.total_stats().pages
<< "\t" << ws.total_stats().shareable_pages
<< "\t" << ws.total_stats().shared_pages
<< "\t" << ws.total_stats().read_only_pages
<< "\t" << ws.total_stats().writable_pages
<< "\t" << ws.total_stats().executable_pages << std::endl;
ProcessWorkingSet::ModuleStatsVector::const_iterator jt =
ws.module_stats().begin();
for (; jt != ws.module_stats().end(); ++jt) {
std::cout << "\t" << jt->module_name
<< "\t" << jt->pages
<< "\t" << jt->shareable_pages
<< "\t" << jt->shared_pages
<< "\t" << jt->pages
<< "\t" << jt->shareable_pages
<< "\t" << jt->shared_pages
<< "\t" << jt->read_only_pages
<< "\t" << jt->writable_pages
<< "\t" << jt->executable_pages << std::endl;
}
}
return 1;
}
<commit_msg>Switch wsdump to JSON output.<commit_after>// Copyright 2011 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <iostream>
#include <list>
#include "base/at_exit.h"
#include "base/command_line.h"
#include "base/file_util.h"
#include "base/json/string_escape.h"
#include "base/logging.h"
#include "base/process_util.h"
#include "base/utf_string_conversions.h"
#include "pcrecpp.h" // NOLINT
#include "syzygy/wsdump/process_working_set.h"
namespace {
class RegexpProcessFilter: public base::ProcessFilter {
public:
RegexpProcessFilter();
bool Initialize(const std::string& regexpr);
virtual bool Includes(const base::ProcessEntry& entry) const OVERRIDE;
private:
pcrecpp::RE expr_;
};
RegexpProcessFilter::RegexpProcessFilter() : expr_("") {
}
bool RegexpProcessFilter::Initialize(const std::string& regexpr) {
pcrecpp::RE_Options options;
options.set_utf8(true);
options.set_caseless(true);
pcrecpp::RE new_expr(regexpr, options);
if (!new_expr.error().empty()) {
LOG(ERROR) << "Failed to initialize regular expression, error: "
<< new_expr.error();
return false;
}
expr_ = new_expr;
DCHECK_EQ("", new_expr.error());
return true;
}
bool RegexpProcessFilter::Includes(const base::ProcessEntry& entry) const {
return expr_.PartialMatch(WideToUTF8(entry.exe_file()));
}
const char kUsage[] =
"Usage: wsdump [--process-name=<process_re>]\n"
"\n"
" Captures and outputs working set statistics for all processes,\n"
" or only for processess whose executable name matches <process_re>.\n"
"\n"
" The output is JSON encoded array, where each element of the array\n"
" is a dictionary describing a process. Each process has the following\n"
" items:\n"
" * exe_file - the process' executable file, e.g. \"chrome.exe\".\n"
" * pid - the process ID.\n"
" * parent_pid - the parent process ID.\n"
" * modules - an array of dictionaries, one for each module in the\n"
" process working set.\n"
" Each module has the following keys:\n"
" * module_name - the module file name, e.g. \"C:\\temp\\xyz.dll\"\n"
" * pages - total number of pages from this module in the working set.\n"
" * shareable_pages - shareable pages in the working set.\n"
" * shared_pages - shared pages in the working set.\n"
" * read_only_pages - read-only pages in the working set.\n"
" * writable_pages - writable pages in the working set.\n"
" * executable_pages - executable pages in the working set.\n"
"\n"
"Example Output:\n"
"[\n"
" {\n"
" \"exe_file\": \"devenv.exe\",\n"
" \"pid\": 5772,\n"
" \"parent_pid\": 3804,\n"
" \"modules\": [\n"
" {\n"
" \"module_name\": \"Total\",\n"
" \"pages\": 34145,\n"
" \"shareable_pages\": 10515,\n"
" \"shared_pages\": 4847,\n"
" \"pages\": 34145,\n"
" \"shareable_pages\": 10515,\n"
" \"shared_pages\": 4847,\n"
" \"read_only_pages\": 1951,\n"
" \"writable_pages\": 23235,\n"
" \"executable_pages\": 8959\n"
" },\n"
" {\n"
" ... \n";
int Usage() {
std::cout << kUsage;
return 1;
}
struct ProcessInfo {
ProcessInfo() : pid(0), parent_pid(0) {
}
std::wstring exe_file;
base::ProcessId pid;
base::ProcessId parent_pid;
ProcessWorkingSet ws;
};
void OutputKeyValue(const char* key,
const std::wstring& value,
int indent,
bool trailing_comma) {
std::cout << std::string(indent, ' ')
<< base::GetDoubleQuotedJson(key) << ": "
<< base::GetDoubleQuotedJson(value)
<< (trailing_comma ? "," : "") << "\n";
}
template <class Streamable>
void OutputKeyValue(const char* key,
const Streamable& value,
int indent,
bool trailing_comma) {
std::cout << std::string(indent, ' ')
<< base::GetDoubleQuotedJson(key) << ": "
<< value
<< (trailing_comma ? "," : "") << "\n";
}
void OutputModule(const std::wstring& module_name,
const ProcessWorkingSet::Stats& stats,
bool trailing_comma) {
std::cout << " {\n";
OutputKeyValue("module_name", module_name, 8, true);
OutputKeyValue("pages", stats.pages, 8, true);
OutputKeyValue("shareable_pages", stats.shareable_pages, 8, true);
OutputKeyValue("shared_pages", stats.shared_pages, 8, true);
OutputKeyValue("pages", stats.pages, 8, true);
OutputKeyValue("shareable_pages", stats.shareable_pages, 8, true);
OutputKeyValue("shared_pages", stats.shared_pages, 8, true);
OutputKeyValue("read_only_pages", stats.read_only_pages, 8, true);
OutputKeyValue("writable_pages", stats.writable_pages, 8, true);
OutputKeyValue("executable_pages", stats.executable_pages, 8, false);
std::cout << " }" << (trailing_comma ? "," : "") << "\n";
}
void OutputProcessInfo(const ProcessInfo& info) {
std::cout << " {\n";
OutputKeyValue("exe_file", info.exe_file, 4, true);
OutputKeyValue("pid", info.pid, 4, true);
OutputKeyValue("parent_pid", info.parent_pid, 4, true);
std::cout << " \"modules\": [\n";
OutputModule(L"Total", info.ws.total_stats(), true);
ProcessWorkingSet::ModuleStatsVector::const_iterator it =
info.ws.module_stats().begin();
ProcessWorkingSet::ModuleStatsVector::const_iterator end =
info.ws.module_stats().end();
for (; it != end; ++it)
OutputModule(it->module_name, *it, it + 1 != end);
std::cout << " ]\n";
std::cout << " }\n";
}
} // namespace
int main(int argc, char** argv) {
base::AtExitManager at_exit_manager;
CommandLine::Init(argc, argv);
if (!logging::InitLogging(L"", logging::LOG_ONLY_TO_SYSTEM_DEBUG_LOG,
logging::DONT_LOCK_LOG_FILE, logging::APPEND_TO_OLD_LOG_FILE,
logging::ENABLE_DCHECK_FOR_NON_OFFICIAL_RELEASE_BUILDS)) {
return 1;
}
CommandLine* cmd_line = CommandLine::ForCurrentProcess();
DCHECK(cmd_line != NULL);
if (cmd_line->HasSwitch("help") || !cmd_line->args().empty()) {
return Usage();
}
// If the process-name is empty or missing we match all processes.
std::string process_re = cmd_line->GetSwitchValueASCII("process-name");
RegexpProcessFilter filter;
if (!filter.Initialize(process_re)) {
LOG(ERROR) << "Incorrect process filter regular expression.";
return 1;
}
typedef std::list<ProcessInfo> WorkingSets;
WorkingSets working_sets;
const base::ProcessEntry* entry = NULL;
base::ProcessIterator process_iterator(&filter);
while (entry = process_iterator.NextProcessEntry()) {
working_sets.push_back(ProcessInfo());
ProcessInfo& info = working_sets.back();
if (info.ws.Initialize(entry->pid())) {
info.exe_file = entry->exe_file();
info.pid = entry->pid();
info.parent_pid = entry->parent_pid();
} else {
LOG(ERROR) << "Unable to capture working set information for pid: "
<< entry->pid();
working_sets.pop_back();
}
}
std::cout << "[\n";
WorkingSets::const_iterator it = working_sets.begin();
for (; it != working_sets.end(); ++it)
OutputProcessInfo(*it);
std::cout << "]\n";
return 1;
}
<|endoftext|> |
<commit_before>/* --- This file is distributed under the MIT Open Source License, as detailed
in "LICENSE.TXT" in the root of the programming_by_contract repository --- */
// needed to test programming_by_contract with NDEBUG!
#ifndef NDEBUG
# define NDEBUG 1
#endif
#include "hurchalla/programming_by_contract/programming_by_contract.h"
#include "testhelper_assert_handler.h"
#include "hurchalla/programming_by_contract/assert_handler.h"
#include "gtest/gtest.h"
#include <type_traits>
// This macro doesn't strictly test that the expression does not exit -
// If the expression exits with a value of 0 it will pass this macro
#ifndef EXPECT_NO_EXIT
#define EXPECT_NO_EXIT(EXPRESSION) do \
{ EXPECT_EXIT(EXPRESSION; exit(0), testing::ExitedWithCode(0), ""); } while(0)
#endif
// confirm the contract-asserts have zero overhead when NDEBUG is defined
static_assert(std::is_same<decltype(precondition(true)), void>::value, "");
static_assert(std::is_same<decltype(precondition2(true)), void>::value, "");
static_assert(std::is_same<decltype(precondition3(true)), void>::value, "");
static_assert(std::is_same<decltype(postcondition(true)), void>::value, "");
static_assert(std::is_same<decltype(postcondition2(true)), void>::value, "");
static_assert(std::is_same<decltype(postcondition3(true)), void>::value, "");
static_assert(std::is_same<decltype(assert_body(true)), void>::value, "");
static_assert(std::is_same<decltype(assert_body2(true)), void>::value, "");
static_assert(std::is_same<decltype(assert_body3(true)), void>::value, "");
static_assert(std::is_same<decltype(invariant(true)), void>::value, "");
static_assert(std::is_same<decltype(invariant2(true)), void>::value, "");
static_assert(std::is_same<decltype(invariant3(true)), void>::value, "");
static_assert(std::is_same<decltype(precondition(false)), void>::value, "");
static_assert(std::is_same<decltype(precondition2(false)), void>::value, "");
static_assert(std::is_same<decltype(precondition3(false)), void>::value, "");
static_assert(std::is_same<decltype(postcondition(false)), void>::value, "");
static_assert(std::is_same<decltype(postcondition2(false)), void>::value, "");
static_assert(std::is_same<decltype(postcondition3(false)), void>::value, "");
static_assert(std::is_same<decltype(assert_body(false)), void>::value, "");
static_assert(std::is_same<decltype(assert_body2(false)), void>::value, "");
static_assert(std::is_same<decltype(assert_body3(false)), void>::value, "");
static_assert(std::is_same<decltype(invariant(false)), void>::value, "");
static_assert(std::is_same<decltype(invariant2(false)), void>::value, "");
static_assert(std::is_same<decltype(invariant3(false)), void>::value, "");
namespace {
// since all the programming by contract asserts map to void when NDEBUG
// is defined, we expect they will never exit/abort when NDEBUG is defined.
TEST(PbcNdebugTest, PreconditionsHandlerLevel3) {
setTestHandlerPreconditionAssertLevel(3);
EXPECT_NO_EXIT(precondition(true));
EXPECT_NO_EXIT(precondition2(true));
EXPECT_NO_EXIT(precondition3(true));
EXPECT_NO_EXIT(precondition(false));
EXPECT_NO_EXIT(precondition2(false));
EXPECT_NO_EXIT(precondition3(false));
}
TEST(PbcNdebugTest, PreconditionsHandlerLevel0) {
setTestHandlerPreconditionAssertLevel(0);
EXPECT_NO_EXIT(precondition(true));
EXPECT_NO_EXIT(precondition2(true));
EXPECT_NO_EXIT(precondition3(true));
EXPECT_NO_EXIT(precondition(false));
EXPECT_NO_EXIT(precondition2(false));
EXPECT_NO_EXIT(precondition3(false));
}
TEST(PbcNdebugTest, GeneralAssertsHandlerLevel3) {
setTestHandlerAssertLevel(3);
EXPECT_NO_EXIT(assert_body(false));
EXPECT_NO_EXIT(assert_body2(false));
EXPECT_NO_EXIT(assert_body3(false));
EXPECT_NO_EXIT(postcondition(false));
EXPECT_NO_EXIT(postcondition2(false));
EXPECT_NO_EXIT(postcondition3(false));
EXPECT_NO_EXIT(invariant(false));
EXPECT_NO_EXIT(invariant2(false));
EXPECT_NO_EXIT(invariant3(false));
EXPECT_NO_EXIT(assert_body(true));
EXPECT_NO_EXIT(assert_body2(true));
EXPECT_NO_EXIT(assert_body3(true));
EXPECT_NO_EXIT(postcondition(true));
EXPECT_NO_EXIT(postcondition2(true));
EXPECT_NO_EXIT(postcondition3(true));
EXPECT_NO_EXIT(invariant(true));
EXPECT_NO_EXIT(invariant2(true));
EXPECT_NO_EXIT(invariant3(true));
}
TEST(PbcNdebugTest, GeneralAssertsHandlerLevel0) {
setTestHandlerAssertLevel(0);
EXPECT_NO_EXIT(assert_body(false));
EXPECT_NO_EXIT(assert_body2(false));
EXPECT_NO_EXIT(assert_body3(false));
EXPECT_NO_EXIT(postcondition(false));
EXPECT_NO_EXIT(postcondition2(false));
EXPECT_NO_EXIT(postcondition3(false));
EXPECT_NO_EXIT(invariant(false));
EXPECT_NO_EXIT(invariant2(false));
EXPECT_NO_EXIT(invariant3(false));
EXPECT_NO_EXIT(assert_body(true));
EXPECT_NO_EXIT(assert_body2(true));
EXPECT_NO_EXIT(assert_body3(true));
EXPECT_NO_EXIT(postcondition(true));
EXPECT_NO_EXIT(postcondition2(true));
EXPECT_NO_EXIT(postcondition3(true));
EXPECT_NO_EXIT(invariant(true));
EXPECT_NO_EXIT(invariant2(true));
EXPECT_NO_EXIT(invariant3(true));
}
}
<commit_msg>improve macros and formatting<commit_after>/* --- This file is distributed under the MIT Open Source License, as detailed
in "LICENSE.TXT" in the root of the programming_by_contract repository --- */
// needed to test programming_by_contract with NDEBUG!
#ifndef NDEBUG
# define NDEBUG 1
#endif
#include "hurchalla/programming_by_contract/programming_by_contract.h"
#include "testhelper_assert_handler.h"
#include "hurchalla/programming_by_contract/assert_handler.h"
#include "gtest/gtest.h"
#include <type_traits>
// This macro doesn't strictly test that the expression does not exit -
// If the expression exits with a value of 0 it will pass this macro
#ifndef PBC_EXPECT_NO_EXIT
#define PBC_EXPECT_NO_EXIT(EXPRESSION) do \
{ EXPECT_EXIT(EXPRESSION; exit(0), testing::ExitedWithCode(0), ""); \
} while(0)
#endif
// confirm the contract-asserts have zero overhead when NDEBUG is defined
static_assert(std::is_same<decltype(precondition(true)), void>::value, "");
static_assert(std::is_same<decltype(precondition2(true)), void>::value, "");
static_assert(std::is_same<decltype(precondition3(true)), void>::value, "");
static_assert(std::is_same<decltype(postcondition(true)), void>::value, "");
static_assert(std::is_same<decltype(postcondition2(true)), void>::value, "");
static_assert(std::is_same<decltype(postcondition3(true)), void>::value, "");
static_assert(std::is_same<decltype(assert_body(true)), void>::value, "");
static_assert(std::is_same<decltype(assert_body2(true)), void>::value, "");
static_assert(std::is_same<decltype(assert_body3(true)), void>::value, "");
static_assert(std::is_same<decltype(invariant(true)), void>::value, "");
static_assert(std::is_same<decltype(invariant2(true)), void>::value, "");
static_assert(std::is_same<decltype(invariant3(true)), void>::value, "");
static_assert(std::is_same<decltype(precondition(false)), void>::value, "");
static_assert(std::is_same<decltype(precondition2(false)), void>::value, "");
static_assert(std::is_same<decltype(precondition3(false)), void>::value, "");
static_assert(std::is_same<decltype(postcondition(false)), void>::value, "");
static_assert(std::is_same<decltype(postcondition2(false)), void>::value, "");
static_assert(std::is_same<decltype(postcondition3(false)), void>::value, "");
static_assert(std::is_same<decltype(assert_body(false)), void>::value, "");
static_assert(std::is_same<decltype(assert_body2(false)), void>::value, "");
static_assert(std::is_same<decltype(assert_body3(false)), void>::value, "");
static_assert(std::is_same<decltype(invariant(false)), void>::value, "");
static_assert(std::is_same<decltype(invariant2(false)), void>::value, "");
static_assert(std::is_same<decltype(invariant3(false)), void>::value, "");
namespace {
// since all the programming by contract asserts map to void when NDEBUG
// is defined, we expect they will never exit/abort when NDEBUG is defined.
TEST(PbcNdebugTest, PreconditionsHandlerLevel3) {
setTestHandlerPreconditionAssertLevel(3);
PBC_EXPECT_NO_EXIT(precondition(true));
PBC_EXPECT_NO_EXIT(precondition2(true));
PBC_EXPECT_NO_EXIT(precondition3(true));
PBC_EXPECT_NO_EXIT(precondition(false));
PBC_EXPECT_NO_EXIT(precondition2(false));
PBC_EXPECT_NO_EXIT(precondition3(false));
}
TEST(PbcNdebugTest, PreconditionsHandlerLevel0) {
setTestHandlerPreconditionAssertLevel(0);
PBC_EXPECT_NO_EXIT(precondition(true));
PBC_EXPECT_NO_EXIT(precondition2(true));
PBC_EXPECT_NO_EXIT(precondition3(true));
PBC_EXPECT_NO_EXIT(precondition(false));
PBC_EXPECT_NO_EXIT(precondition2(false));
PBC_EXPECT_NO_EXIT(precondition3(false));
}
TEST(PbcNdebugTest, GeneralAssertsHandlerLevel3) {
setTestHandlerAssertLevel(3);
PBC_EXPECT_NO_EXIT(assert_body(false));
PBC_EXPECT_NO_EXIT(assert_body2(false));
PBC_EXPECT_NO_EXIT(assert_body3(false));
PBC_EXPECT_NO_EXIT(postcondition(false));
PBC_EXPECT_NO_EXIT(postcondition2(false));
PBC_EXPECT_NO_EXIT(postcondition3(false));
PBC_EXPECT_NO_EXIT(invariant(false));
PBC_EXPECT_NO_EXIT(invariant2(false));
PBC_EXPECT_NO_EXIT(invariant3(false));
PBC_EXPECT_NO_EXIT(assert_body(true));
PBC_EXPECT_NO_EXIT(assert_body2(true));
PBC_EXPECT_NO_EXIT(assert_body3(true));
PBC_EXPECT_NO_EXIT(postcondition(true));
PBC_EXPECT_NO_EXIT(postcondition2(true));
PBC_EXPECT_NO_EXIT(postcondition3(true));
PBC_EXPECT_NO_EXIT(invariant(true));
PBC_EXPECT_NO_EXIT(invariant2(true));
PBC_EXPECT_NO_EXIT(invariant3(true));
}
TEST(PbcNdebugTest, GeneralAssertsHandlerLevel0) {
setTestHandlerAssertLevel(0);
PBC_EXPECT_NO_EXIT(assert_body(false));
PBC_EXPECT_NO_EXIT(assert_body2(false));
PBC_EXPECT_NO_EXIT(assert_body3(false));
PBC_EXPECT_NO_EXIT(postcondition(false));
PBC_EXPECT_NO_EXIT(postcondition2(false));
PBC_EXPECT_NO_EXIT(postcondition3(false));
PBC_EXPECT_NO_EXIT(invariant(false));
PBC_EXPECT_NO_EXIT(invariant2(false));
PBC_EXPECT_NO_EXIT(invariant3(false));
PBC_EXPECT_NO_EXIT(assert_body(true));
PBC_EXPECT_NO_EXIT(assert_body2(true));
PBC_EXPECT_NO_EXIT(assert_body3(true));
PBC_EXPECT_NO_EXIT(postcondition(true));
PBC_EXPECT_NO_EXIT(postcondition2(true));
PBC_EXPECT_NO_EXIT(postcondition3(true));
PBC_EXPECT_NO_EXIT(invariant(true));
PBC_EXPECT_NO_EXIT(invariant2(true));
PBC_EXPECT_NO_EXIT(invariant3(true));
}
}
<|endoftext|> |
<commit_before>/**
* \file dcs/macro.hpp
*
* \brief Provide C-preprocessor (macro) support.
*
* \author Marco Guazzone (marco.guazzone@gmail.com)
*
* <hr/>
*
* Copyright 2009 Marco Guazzone (marco.guazzone@gmail.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef DCS_MACRO_HPP
#define DCS_MACRO_HPP
namespace dcs { namespace macro { namespace detail {
// See: http://herbsutter.com/2009/10/18/mailbag-shutting-up-compiler-warnings/
template <typename T>
inline void suppress_unused_variable_warning(T const&) {}
}}} // Namespace dcs::macro::detail
/// Expands the given argument.
#define DCS_MACRO_EXPAND(x) x
/// The character '#' (hash).
#define DCS_MACRO_HASH_SYM #
/// Prefixes the given argument with the character '#' (hash).
#define DCS_MACRO_HASHIFY(x) DCS_MACRO_EXPAND(DCS_MACRO_HASH_SYM)x
/// Concatenates the two specified arguments.
#define DCS_MACRO_JOIN(x,y) x##y
/// Stringifies (quote) the given argument.
#define DCS_MACRO_QUOTE(x) #x
/// Tells if we're compiling with a C++11 compatible compiler
#if __cplusplus >= 201103L
# define DCS_MACRO_CXX11
#else
# undef DCS_MACRO_CXX11
#endif // DCS_MACRO_CXX111
/// Tells if we're compiling with a C++14 compatible compiler
#if __cplusplus >= 201300L
# define DCS_MACRO_CXX14
#else
# undef DCS_MACRO_CXX14
#endif // DCS_MACRO_CXX114
/// Suppresses the "unused variable" warning issued during compilation.
// TODO: see also boost/core/ignore_used.hpp
#define DCS_MACRO_SUPPRESS_UNUSED_VARIABLE_WARNING(x) \
::dcs::macro::detail::suppress_unused_variable_warning(x)
/// Declares a function, a variable or a type declaration x as deprecated, and
/// provides a suitable message m.
/// Usage:
/// - DCS_MACRO_DECL_DEPRECATED(extern int v, "Variable v is deprecated");
/// - DCS_MACRO_DECL_DEPRECATED(int v, "Variable v is deprecated");
/// - DCS_MACRO_DECL_DEPRECATED(int v, "Variable v is deprecated") = 0;
/// - int DCS_MACRO_DECL_DEPRECATED(v, "Variable v is deprecated") = 0, z = 1;
/// - DCS_MACRO_DECL_DEPRECATED(void f(int), "Function f is deprecated");
/// - DCS_MACRO_DECL_DEPRECATED(void f(int) { }, "Function f is deprecated")
/// - void f (DCS_MACRO_DECL_DEPRECATED(int x, "Parameter x is deprecated")) { }
/// - DCS_MACRO_DECL_DEPRECATED(typedef int I, "Type I is deprecated");
/// - enum DCS_MACRO_DECL_DEPRECATED(E, "Enum E is deprecated") { };
/// - struct DCS_MACRO_DECL_DEPRECATED(S, "Struct S is deprecated");
/// - struct DCS_MACRO_DECL_DEPRECATED(S { }, "Struct S is deprecated");
/// - template <typename T> class DCS_MACRO_DECL_DEPRECATED(C { }, "Template class C is deprecated");
/// - template <> class DCS_MACRO_DECL_DEPRECATED(C<int> { }, "Template specialization C<int> is deprecated");
#ifdef DCS_MACRO_CXX14
// See: http://josephmansfield.uk/articles/marking-deprecated-c++14.html
# define DCS_MACRO_DECL_DEPRECATED(x,m) [[deprecated(m)]] x
#else
//# if defined(_WIN32) || defined(__HP_cc)
# if defined(_MSC_VER)
// If the compiler encounters the use of a deprecated identifier,
// a C4996 warning is thrown
// See: https://msdn.microsoft.com/en-us/library/044swk7y.aspx
# define DCS_MACRO_DECL_DEPRECATED(x,m) __declspec(deprecated(m)) x
//# elif defined(__GNUC__) && defined(__linux__)
# elif defined(__GNUC__)
// See:
// - https://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
// - https://gcc.gnu.org/onlinedocs/gcc/Variable-Attributes.html
// - https://gcc.gnu.org/onlinedocs/gcc/Type-Attributes.html
# define DCS_MACRO_DECL_DEPRECATED(x,m) x __attribute__ ((deprecated(m)))
//# elif defined(__SUNPRO_C)
//# define DCS_MACRO_DECL_DEPRECATED
# else
// Don't know how to make it. Sorry!
// Add a warning comment.
# define DCS_MACRO_DECL_DEPRECATED(x,m) /*XXX: Deprecated declaration!!*/ x
# endif
#endif // DCS_MACRO_CXX14
/// Marks a function, a variable or a type declaration that should be exported from DLLs or binaries for runtime linking.
#if defined(_WIN32) || defined(__HP_cc)
# define DCS_MACRO_DECL_EXPORT __declspec(dllexport)
#elif defined(__GNUC__) && defined(__linux__)
# define DCS_MACRO_DECL_EXPORT __attribute__ ((visibility("default")))
#elif defined(__SUNPRO_C)
# define DCS_MACRO_DECL_EXPORT __global
#else
# define DCS_MACRO_DECL_EXPORT
#endif
#endif // DCS_MACRO_HPP
<commit_msg>[macro] Bug-fix: corrected macro for C++11<commit_after>/**
* \file dcs/macro.hpp
*
* \brief Provide C-preprocessor (macro) support.
*
* \author Marco Guazzone (marco.guazzone@gmail.com)
*
* <hr/>
*
* Copyright 2009 Marco Guazzone (marco.guazzone@gmail.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef DCS_MACRO_HPP
#define DCS_MACRO_HPP
namespace dcs { namespace macro { namespace detail {
// See: http://herbsutter.com/2009/10/18/mailbag-shutting-up-compiler-warnings/
template <typename T>
inline void suppress_unused_variable_warning(T const&) {}
}}} // Namespace dcs::macro::detail
/// Expands the given argument.
#define DCS_MACRO_EXPAND(x) x
/// The character '#' (hash).
#define DCS_MACRO_HASH_SYM #
/// Prefixes the given argument with the character '#' (hash).
#define DCS_MACRO_HASHIFY(x) DCS_MACRO_EXPAND(DCS_MACRO_HASH_SYM)x
/// Concatenates the two specified arguments.
#define DCS_MACRO_JOIN(x,y) x##y
/// Stringifies (quote) the given argument.
#define DCS_MACRO_QUOTE(x) #x
/// Tells if we're compiling with a C++11 compatible compiler
#if __cplusplus >= 201103L
# define DCS_MACRO_CXX11
#else
# undef DCS_MACRO_CXX11
#endif // DCS_MACRO_CXX111
/// Tells if we're compiling with a C++14 compatible compiler
#if __cplusplus >= 201402L
# define DCS_MACRO_CXX14
#else
# undef DCS_MACRO_CXX14
#endif // DCS_MACRO_CXX114
/// Suppresses the "unused variable" warning issued during compilation.
// TODO: see also boost/core/ignore_used.hpp
#define DCS_MACRO_SUPPRESS_UNUSED_VARIABLE_WARNING(x) \
::dcs::macro::detail::suppress_unused_variable_warning(x)
/// Declares a function, a variable or a type declaration x as deprecated, and
/// provides a suitable message m.
/// Usage:
/// - DCS_MACRO_DECL_DEPRECATED(extern int v, "Variable v is deprecated");
/// - DCS_MACRO_DECL_DEPRECATED(int v, "Variable v is deprecated");
/// - DCS_MACRO_DECL_DEPRECATED(int v, "Variable v is deprecated") = 0;
/// - int DCS_MACRO_DECL_DEPRECATED(v, "Variable v is deprecated") = 0, z = 1;
/// - DCS_MACRO_DECL_DEPRECATED(void f(int), "Function f is deprecated");
/// - DCS_MACRO_DECL_DEPRECATED(void f(int) { }, "Function f is deprecated")
/// - void f (DCS_MACRO_DECL_DEPRECATED(int x, "Parameter x is deprecated")) { }
/// - DCS_MACRO_DECL_DEPRECATED(typedef int I, "Type I is deprecated");
/// - enum DCS_MACRO_DECL_DEPRECATED(E, "Enum E is deprecated") { };
/// - struct DCS_MACRO_DECL_DEPRECATED(S, "Struct S is deprecated");
/// - struct DCS_MACRO_DECL_DEPRECATED(S { }, "Struct S is deprecated");
/// - template <typename T> class DCS_MACRO_DECL_DEPRECATED(C { }, "Template class C is deprecated");
/// - template <> class DCS_MACRO_DECL_DEPRECATED(C<int> { }, "Template specialization C<int> is deprecated");
#ifdef DCS_MACRO_CXX14
// See: http://josephmansfield.uk/articles/marking-deprecated-c++14.html
# define DCS_MACRO_DECL_DEPRECATED(x,m) [[deprecated(m)]] x
#else
//# if defined(_WIN32) || defined(__HP_cc)
# if defined(_MSC_VER)
// If the compiler encounters the use of a deprecated identifier,
// a C4996 warning is thrown
// See: https://msdn.microsoft.com/en-us/library/044swk7y.aspx
# define DCS_MACRO_DECL_DEPRECATED(x,m) __declspec(deprecated(m)) x
//# elif defined(__GNUC__) && defined(__linux__)
# elif defined(__GNUC__)
// See:
// - https://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
// - https://gcc.gnu.org/onlinedocs/gcc/Variable-Attributes.html
// - https://gcc.gnu.org/onlinedocs/gcc/Type-Attributes.html
# define DCS_MACRO_DECL_DEPRECATED(x,m) x __attribute__ ((deprecated(m)))
//# elif defined(__SUNPRO_C)
//# define DCS_MACRO_DECL_DEPRECATED
# else
// Don't know how to make it. Sorry!
// Add a warning comment.
# define DCS_MACRO_DECL_DEPRECATED(x,m) /*XXX: Deprecated declaration!!*/ x
# endif
#endif // DCS_MACRO_CXX14
/// Marks a function, a variable or a type declaration that should be exported from DLLs or binaries for runtime linking.
#if defined(_WIN32) || defined(__HP_cc)
# define DCS_MACRO_DECL_EXPORT __declspec(dllexport)
#elif defined(__GNUC__) && defined(__linux__)
# define DCS_MACRO_DECL_EXPORT __attribute__ ((visibility("default")))
#elif defined(__SUNPRO_C)
# define DCS_MACRO_DECL_EXPORT __global
#else
# define DCS_MACRO_DECL_EXPORT
#endif
#endif // DCS_MACRO_HPP
<|endoftext|> |
<commit_before>#include <iostream>
#include <vector>
using namespace std;
bool IsPrime(int x) {
if (x == 1) return false;
for (int i = 2; i * i <= x; ++i) {
if (x % i == 0) {
return false;
}
}
return true;
}
bool ProcessCase() {
int a, d, n;
cin >> a >> d >> n;
if (a == 0 && d == 0 && n == 0) return false;
int x = a;
int count = 0;
while (true) {
if (IsPrime(x)) {
++count;
}
if (count == n) {
cout << x << endl;
return true;
}
x += d;
}
}
int main() {
while (ProcessCase());
return 0;
}<commit_msg>Update 1141.<commit_after>#include <iostream>
#include <vector>
using namespace std;
const int MAX_N = 1000000;
vector<int> is_prime_table;
bool IsPrime(int x) {
if (x == 1) return false;
for (int i = 2; i * i <= x; ++i) {
if (x % i == 0) {
return false;
}
}
return true;
}
bool ProcessCase() {
int a, d, n;
cin >> a >> d >> n;
if (a == 0 && d == 0 && n == 0) return false;
int x = a;
int count = 0;
while (true) {
if (is_prime_table[x]) {
++count;
}
if (count == n) {
cout << x << endl;
return true;
}
x += d;
}
}
int main() {
is_prime_table.assign(MAX_N + 1, false);
for (int i = 1; i <= MAX_N; ++i) {
is_prime_table[i] = IsPrime(i);
}
while (ProcessCase());
return 0;
}<|endoftext|> |
<commit_before>/*!
* \file socket.cpp
* \author Nathan Eloe
* \brief Implementation of the quasi-singleton socket class
*/
#include "socket.h"
#include "context.h"
namespace zmqcpp
{
std::shared_ptr<zmq::context_t> Context::m_ctx = nullptr;
thread_local std::map<std::string, std::shared_ptr<zmq::socket_t>> Socket::m_conn;
std::map<std::string, std::shared_ptr<zmq::socket_t>> Socket::m_bind;
void Socket::connect(const char* endpt, const bool persist)
{
std::string ep(endpt);
if (!persist)
{
m_sock = std::make_shared<zmq::socket_t>(zmq::socket_t(Context::get(), m_type));
m_sock->connect(endpt);
}
else
{
if (m_conn.count(ep) == 0)
{
m_conn[ep] = std::make_shared<zmq::socket_t>(zmq::socket_t(Context::get(), m_type));
//m_conn[ep] = std::shared_ptr<zmq::socket_t>(new zmq::socket_t(Context::get(), m_type), [] (zmq::socket_t* p) {p -> close(); delete p;});
m_conn[ep]->connect(endpt);
}
m_sock = m_conn[ep];
}
}
void Socket::bind(const char* endpt, const bool persist)
{
std::string ep(endpt);
if (!persist)
{
m_sock = std::make_shared<zmq::socket_t>(zmq::socket_t(Context::get(), m_type));
m_sock->bind(endpt);
}
else
{
if (m_bind.count(ep) == 0)
{
m_bind[ep] = std::make_shared<zmq::socket_t>(zmq::socket_t(Context::get(), m_type));
m_bind[ep]->bind(endpt);
}
m_sock = m_bind[ep];
}
}
zmq::socket_t& Socket::raw_sock()
{
if (!m_sock)
throw no_endpt();
return *m_sock;
}
}<commit_msg>remove a bit of commented code<commit_after>/*!
* \file socket.cpp
* \author Nathan Eloe
* \brief Implementation of the quasi-singleton socket class
*/
#include "socket.h"
#include "context.h"
namespace zmqcpp
{
std::shared_ptr<zmq::context_t> Context::m_ctx = nullptr;
thread_local std::map<std::string, std::shared_ptr<zmq::socket_t>> Socket::m_conn;
std::map<std::string, std::shared_ptr<zmq::socket_t>> Socket::m_bind;
void Socket::connect(const char* endpt, const bool persist)
{
std::string ep(endpt);
if (!persist)
{
m_sock = std::make_shared<zmq::socket_t>(zmq::socket_t(Context::get(), m_type));
m_sock->connect(endpt);
}
else
{
if (m_conn.count(ep) == 0)
{
m_conn[ep] = std::make_shared<zmq::socket_t>(zmq::socket_t(Context::get(), m_type));
m_conn[ep]->connect(endpt);
}
m_sock = m_conn[ep];
}
}
void Socket::bind(const char* endpt, const bool persist)
{
std::string ep(endpt);
if (!persist)
{
m_sock = std::make_shared<zmq::socket_t>(zmq::socket_t(Context::get(), m_type));
m_sock->bind(endpt);
}
else
{
if (m_bind.count(ep) == 0)
{
m_bind[ep] = std::make_shared<zmq::socket_t>(zmq::socket_t(Context::get(), m_type));
m_bind[ep]->bind(endpt);
}
m_sock = m_bind[ep];
}
}
zmq::socket_t& Socket::raw_sock()
{
if (!m_sock)
throw no_endpt();
return *m_sock;
}
}<|endoftext|> |
<commit_before>#include "socket.h"
#include <stdio.h>
#include <string.h>
#if defined(_WIN32)
#pragma comment( lib, "wsock32.lib" )
#pragma comment( lib, "Ws2_32.lib" )
#else
#include <errno.h>
#endif
#if defined(_WIN32)
typedef int socklen_t;
#endif
#if defined(_WIN32)
#define BNS_SOCKET_ERROR() printf("Socket error: %d\n", WSAGetLastError())
#else
#define BNS_SOCKET_ERROR() printf("Socket error: %d\n", WSAGetLastError())
#endif
IPV4Addr::IPV4Addr(int _addr, short _port){
addr = _addr;
port = _port;
}
IPV4Addr::IPV4Addr(unsigned char a, unsigned char b, unsigned char c, unsigned char d, short _port){
addr = htonl((a << 24) | (b << 16) | (c << 8) | d);
port = htons(_port);
}
IPV4Addr::IPV4Addr(const char* hostName, int _port){
#if defined(_WIN32)
struct addrinfo hints = {};
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
struct addrinfo* result;
int error = getaddrinfo(hostName, NULL, &hints, &result);
if (result != nullptr) {
addr = ((sockaddr_in*)(result->ai_addr))->sin_addr.s_addr;
port = htons(_port);
freeaddrinfo(result);
}
else {
printf("\nError resolving host: '%s'\n", hostName);
}
#else
#endif
}
void IPV4Addr::WriteToString(char* buffer, int bufferSize){
int hostAddr = ntohl(addr);
short hostPort = ntohs(port);
snprintf(buffer, bufferSize, "%d.%d.%d.%d:%d", (hostAddr >> 24), (hostAddr >> 16) & 0xFF, (hostAddr >> 8) & 0xFF, hostAddr & 0xFF, hostPort);
}
sockaddr_in IPV4Addr::ToSockAddr(){
sockaddr_in ip = {};
ip.sin_addr.s_addr = addr;
ip.sin_port = port;
ip.sin_family = AF_INET;
return ip;
}
bool Socket::Create(SocketProtocol _protocol, SocketBlockingType _blockingType){
protocol = _protocol;
blockingType = _blockingType;
if (protocol == SP_UDP){
handle = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
}
else if (protocol == SP_TCP){
handle = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
}
else{
//uuuuhhhh...
}
if (handle <= 0){
}
#if defined(_WIN32)
if (_blockingType == SBT_NonBlocking){
u_long nonBlocking = 1;
if (ioctlsocket( handle, FIONBIO, &nonBlocking ) != 0){
printf( "failed to set non-blocking\n" );
return false;
}
}
#else
if (_blockingType == SBT_NonBlocking){
int nonBlocking = 1;
if (fcntl( handle, F_SETFL, O_NONBLOCK, nonBlocking) == -1){
printf( "failed to set non-blocking\n" );
return false;
}
}
#endif
return true;
}
bool Socket::Bind(int _port /*= 0*/){
sockaddr_in address;
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons((unsigned short)_port);
source.addr = htonl((127 << 24) | 1);
int retVal = bind(handle, (const sockaddr*) &address, sizeof(sockaddr_in));
if (retVal < 0 ){
printf( "failed to bind socket\n" );
return false;
}
if (_port == 0) {
sockaddr boundAddr;
socklen_t boundLen = sizeof(sockaddr);
int val = getsockname(handle, &boundAddr, &boundLen);
if (val != 0) {
#if defined(_WIN32)
printf("\nWarning: could not determine port of socket (error %d).\n", WSAGetLastError());
#else
printf("\nWarning: could not determine port of socket.\n");
#endif
source.port = 0;
}
else {
source.port = ((sockaddr_in*)(&boundAddr))->sin_port;
}
}
else {
source.port = htons(_port);
}
return true;
}
bool Socket::Connect(IPV4Addr addr){
destination = addr;
source = IPV4Addr(127, 0, 0, 1, source.port);
sockaddr_in dstAddr = destination.ToSockAddr();
int ret = connect(handle, (sockaddr*)(&dstAddr), sizeof(dstAddr));
if (ret != 0) {
#if defined(_WIN32)
int err = WSAGetLastError();
printf("connect failed (err: %d)\n", err);
#else
printf("connect failed\n");
#endif
return false;
}
else {
return true;
}
}
bool Socket::SetBlocking(SocketBlockingType bt) {
#if defined(_WIN32)
u_long iMode = (bt == SBT_NonBlocking ? 1 : 0);
int rv = ioctlsocket(handle, FIONBIO, &iMode);
return rv == 0;
#else
return false;
#endif
}
bool Socket::SendData(const void* buffer, int buffLength, int* bytesSent){
char srcAddr[256] = {};
char dstAddr[256] = {};
source.WriteToString(srcAddr, sizeof(srcAddr));
destination.WriteToString(dstAddr, sizeof(dstAddr));
printf("Sending %d bytes from '%s' to '%s'\n", buffLength, srcAddr, dstAddr);
sockaddr_in address = destination.ToSockAddr();
int sentBytes = sendto(handle, (const char*)buffer, buffLength, 0, (sockaddr*)&address, sizeof(sockaddr_in));
if (sentBytes != buffLength){
#if defined(_WIN32)
int lastErr = WSAGetLastError();
printf("failed to send packet (err: %d)\n", lastErr);
#else
printf("failed to send packet.\n");
#endif
return false;
}
*bytesSent = sentBytes;
return true;
}
bool Socket::ReceiveData(void* buffer, int buffLength, int* bytesReceived, IPV4Addr* outAddr){
sockaddr_in from = {};
socklen_t fromLen = sizeof(from);
int receivedBytes = recvfrom(handle, (char*)buffer, buffLength, 0, (sockaddr*)&from, &fromLen);
if (receivedBytes == -1 && errno != EWOULDBLOCK){
printf("Socket encountered error '%s'\n", strerror(errno));
}
IPV4Addr addr;
addr.addr = from.sin_addr.s_addr;
addr.port = from.sin_port;
*outAddr = addr;
*bytesReceived = receivedBytes;
return receivedBytes > 0;
}
bool Socket::Listen(int backlog){
int retVal = listen(handle, backlog);
if (retVal == 0){
return true;
}
else{
BNS_SOCKET_ERROR();
return false;
}
}
bool Socket::AcceptConnection(Socket* outSocket){
sockaddr_in from = {};
socklen_t fromLen = sizeof(from);
int rv = accept(handle, (sockaddr*)&from, &fromLen);
if (rv < 0){
return false;
}
else{
*outSocket = *this;
outSocket->handle = rv;
IPV4Addr addr;
addr.addr = from.sin_addr.s_addr;
addr.port = from.sin_port;
outSocket->destination = addr;
return true;
}
}
bool Socket::Destroy(){
#if defined(_WIN32)
// TODO: close for windows
closesocket(handle);
return true;
#else
close(handle);
return true;
#endif
}
bool isSocketSystemInitialised = false;
bool StartUpSocketSystem(){
#if defined(_WIN32)
WSADATA WsaData;
return WSAStartup(MAKEWORD(2,2), &WsaData) == NO_ERROR;
#else
return true;
#endif
}
bool ShutdownSocketSystem(){
return true;
}
#if defined(SOCKET_TEST_MAIN)
int main(int argc, char** argv){
if(StartUpSocketSystem()){
printf("Failed to init socket system, exiting.\n");
return -1;
}
Socket sock1;
sock1.Create(SP_UDP, SBT_NonBlocking);
sock1.Bind(12245);
Socket sock2;
sock2.Create(SP_UDP, SBT_NonBlocking);
sock2.Bind(12243);
sock1.Connect(sock2.source);
const char* dataToSend = "Hello World";
int bytesSent = 0;
sock1.SendData(dataToSend, strlen(dataToSend)+1, &bytesSent);
usleep(1000);
char packet[256];
int bytesReceived = 0;
int timeout = 0;
while (bytesReceived <= 0){
IPV4Addr addr;
sock2.ReceiveData(packet, sizeof(packet), &bytesReceived, &addr);
usleep(1000);
timeout++;
if (timeout > 10){
break;
}
}
printf("Received '%s' from socket.\n", packet);
if (strcmp(packet, dataToSend) != 0){
return -1;
}
return 0;
}
#endif
<commit_msg>Windows fixes.<commit_after>#include "socket.h"
#include <stdio.h>
#include <string.h>
#if defined(_WIN32)
#pragma comment( lib, "wsock32.lib" )
#pragma comment( lib, "Ws2_32.lib" )
#else
#include <errno.h>
#endif
#if defined(_WIN32)
typedef int socklen_t;
#endif
#if defined(_WIN32)
#define BNS_SOCKET_ERROR() printf("Socket error: %d\n", WSAGetLastError())
#else
#define BNS_SOCKET_ERROR() printf("Socket error: %d\n", WSAGetLastError())
#endif
IPV4Addr::IPV4Addr(int _addr, short _port){
addr = _addr;
port = _port;
}
IPV4Addr::IPV4Addr(unsigned char a, unsigned char b, unsigned char c, unsigned char d, short _port){
addr = htonl((a << 24) | (b << 16) | (c << 8) | d);
port = htons(_port);
}
IPV4Addr::IPV4Addr(const char* hostName, int _port){
#if defined(_WIN32)
struct addrinfo hints = {};
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
struct addrinfo* result;
int error = getaddrinfo(hostName, NULL, &hints, &result);
if (result != nullptr) {
addr = ((sockaddr_in*)(result->ai_addr))->sin_addr.s_addr;
port = htons(_port);
freeaddrinfo(result);
}
else {
printf("\nError resolving host: '%s'\n", hostName);
}
#else
#endif
}
void IPV4Addr::WriteToString(char* buffer, int bufferSize){
int hostAddr = ntohl(addr);
short hostPort = ntohs(port);
snprintf(buffer, bufferSize, "%d.%d.%d.%d:%d", (hostAddr >> 24), (hostAddr >> 16) & 0xFF, (hostAddr >> 8) & 0xFF, hostAddr & 0xFF, hostPort);
}
sockaddr_in IPV4Addr::ToSockAddr(){
sockaddr_in ip = {};
ip.sin_addr.s_addr = addr;
ip.sin_port = port;
ip.sin_family = AF_INET;
return ip;
}
bool Socket::Create(SocketProtocol _protocol, SocketBlockingType _blockingType){
protocol = _protocol;
blockingType = _blockingType;
if (protocol == SP_UDP){
handle = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
}
else if (protocol == SP_TCP){
handle = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
}
else{
//uuuuhhhh...
}
if (handle <= 0){
}
#if defined(_WIN32)
if (_blockingType == SBT_NonBlocking){
u_long nonBlocking = 1;
if (ioctlsocket( handle, FIONBIO, &nonBlocking ) != 0){
printf( "failed to set non-blocking\n" );
return false;
}
}
#else
if (_blockingType == SBT_NonBlocking){
int nonBlocking = 1;
if (fcntl( handle, F_SETFL, O_NONBLOCK, nonBlocking) == -1){
printf( "failed to set non-blocking\n" );
return false;
}
}
#endif
return true;
}
bool Socket::Bind(int _port /*= 0*/){
sockaddr_in address;
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons((unsigned short)_port);
source.addr = htonl((127 << 24) | 1);
int retVal = bind(handle, (const sockaddr*) &address, sizeof(sockaddr_in));
if (retVal < 0 ){
printf( "failed to bind socket\n" );
return false;
}
if (_port == 0) {
sockaddr boundAddr;
socklen_t boundLen = sizeof(sockaddr);
int val = getsockname(handle, &boundAddr, &boundLen);
if (val != 0) {
#if defined(_WIN32)
printf("\nWarning: could not determine port of socket (error %d).\n", WSAGetLastError());
#else
printf("\nWarning: could not determine port of socket.\n");
#endif
source.port = 0;
}
else {
source.port = ((sockaddr_in*)(&boundAddr))->sin_port;
}
}
else {
source.port = htons(_port);
}
return true;
}
bool Socket::Connect(IPV4Addr addr){
destination = addr;
source = IPV4Addr(127, 0, 0, 1, source.port);
sockaddr_in dstAddr = destination.ToSockAddr();
int ret = connect(handle, (sockaddr*)(&dstAddr), sizeof(dstAddr));
if (ret != 0) {
#if defined(_WIN32)
int err = WSAGetLastError();
printf("connect failed (err: %d)\n", err);
#else
printf("connect failed\n");
#endif
return false;
}
else {
return true;
}
}
bool Socket::SetBlocking(SocketBlockingType bt) {
#if defined(_WIN32)
u_long iMode = (bt == SBT_NonBlocking ? 1 : 0);
int rv = ioctlsocket(handle, FIONBIO, &iMode);
return rv == 0;
#else
return false;
#endif
}
bool Socket::SendData(const void* buffer, int buffLength, int* bytesSent){
char srcAddr[256] = {};
char dstAddr[256] = {};
source.WriteToString(srcAddr, sizeof(srcAddr));
destination.WriteToString(dstAddr, sizeof(dstAddr));
printf("Sending %d bytes from '%s' to '%s'\n", buffLength, srcAddr, dstAddr);
sockaddr_in address = destination.ToSockAddr();
int sentBytes = sendto(handle, (const char*)buffer, buffLength, 0, (sockaddr*)&address, sizeof(sockaddr_in));
if (sentBytes != buffLength){
#if defined(_WIN32)
int lastErr = WSAGetLastError();
printf("failed to send packet (err: %d)\n", lastErr);
#else
printf("failed to send packet.\n");
#endif
return false;
}
*bytesSent = sentBytes;
return true;
}
bool Socket::ReceiveData(void* buffer, int buffLength, int* bytesReceived, IPV4Addr* outAddr){
sockaddr_in from = {};
socklen_t fromLen = sizeof(from);
int receivedBytes = recvfrom(handle, (char*)buffer, buffLength, 0, (sockaddr*)&from, &fromLen);
if (receivedBytes == -1 && errno != 0 && errno != EWOULDBLOCK){
printf("Socket encountered error '%s'\n", strerror(errno));
}
IPV4Addr addr;
addr.addr = from.sin_addr.s_addr;
addr.port = from.sin_port;
*outAddr = addr;
*bytesReceived = receivedBytes;
return receivedBytes > 0;
}
bool Socket::Listen(int backlog){
int retVal = listen(handle, backlog);
if (retVal == 0){
return true;
}
else{
BNS_SOCKET_ERROR();
return false;
}
}
bool Socket::AcceptConnection(Socket* outSocket){
sockaddr_in from = {};
socklen_t fromLen = sizeof(from);
int rv = accept(handle, (sockaddr*)&from, &fromLen);
if (rv < 0){
return false;
}
else{
*outSocket = *this;
outSocket->handle = rv;
IPV4Addr addr;
addr.addr = from.sin_addr.s_addr;
addr.port = from.sin_port;
outSocket->destination = addr;
return true;
}
}
bool Socket::Destroy(){
#if defined(_WIN32)
// TODO: close for windows
closesocket(handle);
return true;
#else
close(handle);
return true;
#endif
}
bool isSocketSystemInitialised = false;
bool StartUpSocketSystem(){
#if defined(_WIN32)
WSADATA WsaData;
return WSAStartup(MAKEWORD(2,2), &WsaData) == NO_ERROR;
#else
return true;
#endif
}
bool ShutdownSocketSystem(){
return true;
}
#if defined(SOCKET_TEST_MAIN)
int main(int argc, char** argv){
if(StartUpSocketSystem()){
printf("Failed to init socket system, exiting.\n");
return -1;
}
Socket sock1;
sock1.Create(SP_UDP, SBT_NonBlocking);
sock1.Bind(12245);
Socket sock2;
sock2.Create(SP_UDP, SBT_NonBlocking);
sock2.Bind(12243);
sock1.Connect(sock2.source);
const char* dataToSend = "Hello World";
int bytesSent = 0;
sock1.SendData(dataToSend, strlen(dataToSend)+1, &bytesSent);
usleep(1000);
char packet[256];
int bytesReceived = 0;
int timeout = 0;
while (bytesReceived <= 0){
IPV4Addr addr;
sock2.ReceiveData(packet, sizeof(packet), &bytesReceived, &addr);
usleep(1000);
timeout++;
if (timeout > 10){
break;
}
}
printf("Received '%s' from socket.\n", packet);
if (strcmp(packet, dataToSend) != 0){
return -1;
}
return 0;
}
#endif
<|endoftext|> |
<commit_before>#include "Ephemeris.h"
#include "Elements.h"
#include "Properties.h"
#include <lucid/math/Algorithm.h>
#include <lucid/math/Constants.h>
#include <lucid/core/FileReader.h>
namespace core = ::lucid:: core;
namespace math = ::lucid:: math;
namespace orbit = ::lucid::orbit;
///
///
///
namespace { /// anonymous
inline orbit::matrix3x3_t Rx(float32_t theta)
{
float32_t c = ::cosf(theta);
float32_t s = ::sinf(theta);
return orbit::matrix3x3_t(1, 0, 0, 0, c, s, 0, -s, c);
}
inline orbit::matrix3x3_t Rz(float32_t theta)
{
float32_t c = ::cosf(theta);
float32_t s = ::sinf(theta);
return orbit::matrix3x3_t(c, s, 0, -s, c, 0, 0, 0, 1);
}
} /// anonymous
///
///
///
namespace lucid {
namespace orbit {
Ephemeris::Ephemeris()
{
/// create the 'special' entry that defines the 'center' of the system
Properties properties;
properties.description = "solar system barycenter";
_names.insert(std::make_pair("SSB", 0));
_properties.insert(std::make_pair(0, properties));
_entries.insert(std::make_pair(0, Entry()));
}
Ephemeris::~Ephemeris()
{
}
void Ephemeris::initialize(std::string const &path)
{
core::FileReader reader(path);
size_t bodyCount = 0;
reader.read(bodyCount);
for (size_t bodyIndex = 0; bodyIndex < bodyCount; ++bodyIndex)
{
Properties properties;
Entry entry;
size_t hid = 0;
reader.read(hid);
std::string target;
reader.read(target);
reader.read(entry.center);
LUCID_VALIDATE(_properties.end() != _properties.find(entry.center), "'" + target + "' specifies unknown center object");
reader.read(properties.description);
reader.read(properties.GM);
reader.read(properties.mass);
reader.read(properties.radius);
size_t elementsCount = 0;
reader.read(elementsCount);
for (size_t elementsIndex = 0; elementsIndex < elementsCount; ++elementsIndex)
{
Elements elements;
reader.read(&elements, sizeof(elements));
entry.elements.push_back(elements);
}
_names.insert(std::make_pair(target, hid));
_properties.insert(std::make_pair(hid, properties));
_entries.insert(std::make_pair(hid, entry));
}
}
size_t Ephemeris::lookup(std::string const &target) const
{
auto iter = _names.find(target);
LUCID_VALIDATE(iter != _names.end(), "unknown target '" + target + "' specified");
return iter->second;
}
void Ephemeris::lookup(Properties &properties, std::string const &target) const
{
lookup(properties, lookup(target));
}
void Ephemeris::lookup(Properties &properties, size_t target) const
{
auto iter = _properties.find(target);
LUCID_VALIDATE(iter != _properties.end(), "unknown target id specified");
properties = iter->second;
}
size_t Ephemeris::lookup(Elements &elements, std::string const &target, float32_t jdn) const
{
return lookup(elements, lookup(target), jdn);
}
size_t Ephemeris::lookup(Elements &elements, size_t target, float32_t jdn) const
{
auto iter = _entries.find(target);
LUCID_VALIDATE(iter != _entries.end(), "unknown target id specified");
Entry const &entry = iter->second;
size_t const count = entry.elements.size();
LUCID_VALIDATE(0 < count, "target does not define orbital elements");
/// find the closest entry to the given julian day.
/// for now, it is a simple linear scan through the list.
/// test {
size_t index = 0;
float32_t a = ::fabsf(entry.elements[index].JDN - jdn);
for (size_t i = 1; i < count; ++i)
{
float32_t b = ::fabsf(entry.elements[i].JDN - jdn);
if (b < a)
{
index = i;
a = b;
}
else
{
break;
}
}
/// } test
elements = entry.elements[index];
return entry.center;
}
void Ephemeris::compute(vector3_t &position, vector3_t &velocity, std::string const &target, float32_t jdn) const
{
compute(position, velocity, lookup(target), jdn);
}
void Ephemeris::compute(vector3_t &position, vector3_t &velocity, size_t target, float32_t jdn) const
{
Elements elements;
size_t cid = lookup(elements, target, jdn);
Properties centerProperties;
lookup(centerProperties, cid);
float32_t const spd = 86400.f;
float32_t const dt = spd * (jdn - elements.JDN);
float32_t const GM = centerProperties.GM;
float32_t const e = elements.EC;
float32_t const a = elements.A;
float32_t MA = elements.MA + dt * ::sqrtf(GM / ::powf(a, 3.f));
MA = ::fmodf(MA, math::constants::two_pi<float32_t>());
MA = (MA < 0.f) ? MA + math::constants::two_pi<float32_t>(): MA;
float32_t EA[2] = { MA, 0.f };
/// TBD: determine completion criteria
float32_t err = 1.f;
while (err > math::constants::tol<float32_t>())
{
EA[1] = EA[0] - (EA[0] - e * ::sinf(EA[0]) - MA) / (1.f - e * ::cosf(EA[0]));
std::swap(EA[0], EA[1]);
err = 0.f;
}
float32_t TA = 2.f * ::atan2f(::sqrtf(1.f + e) * ::sinf(0.5f * EA[0]), ::sqrtf(1.f - e) * ::cosf(0.5f * EA[0]));
float32_t r = a * (1.f - e * ::cosf(EA[0]));
position = r * vector3_t(::cosf(TA), ::sinf(TA), 0.f);
velocity = ::sqrtf(GM * a) / r * vector3_t(-::sinf(EA[0]), ::sqrt(1.f - e * e) * ::cosf(EA[0]), 0.f);
matrix3x3_t R = Rz(-elements.OM) * Rx(-elements.IN) * Rz(-elements.W);
position = R * position;
velocity = R * velocity;
}
Ephemeris &Ephemeris::instance()
{
static Ephemeris theInstance;
return theInstance;
}
} /// orbit
} /// lucid
<commit_msg>added convergence criteria for Newton-Raphson algo. running into the expected precision issues using float.<commit_after>#include "Ephemeris.h"
#include "Elements.h"
#include "Properties.h"
#include <lucid/math/Algorithm.h>
#include <lucid/math/Constants.h>
#include <lucid/core/FileReader.h>
namespace core = ::lucid:: core;
namespace math = ::lucid:: math;
namespace orbit = ::lucid::orbit;
///
///
///
namespace { /// anonymous
inline orbit::matrix3x3_t Rx(float32_t theta)
{
float32_t c = ::cosf(theta);
float32_t s = ::sinf(theta);
return orbit::matrix3x3_t(1, 0, 0, 0, c, s, 0, -s, c);
}
inline orbit::matrix3x3_t Rz(float32_t theta)
{
float32_t c = ::cosf(theta);
float32_t s = ::sinf(theta);
return orbit::matrix3x3_t(c, s, 0, -s, c, 0, 0, 0, 1);
}
} /// anonymous
///
///
///
namespace lucid {
namespace orbit {
Ephemeris::Ephemeris()
{
/// create the 'special' entry that defines the 'center' of the system
Properties properties;
properties.description = "solar system barycenter";
_names.insert(std::make_pair("SSB", 0));
_properties.insert(std::make_pair(0, properties));
_entries.insert(std::make_pair(0, Entry()));
}
Ephemeris::~Ephemeris()
{
}
void Ephemeris::initialize(std::string const &path)
{
core::FileReader reader(path);
size_t bodyCount = 0;
reader.read(bodyCount);
for (size_t bodyIndex = 0; bodyIndex < bodyCount; ++bodyIndex)
{
Properties properties;
Entry entry;
size_t hid = 0;
reader.read(hid);
std::string target;
reader.read(target);
reader.read(entry.center);
LUCID_VALIDATE(_properties.end() != _properties.find(entry.center), "'" + target + "' specifies unknown center object");
reader.read(properties.description);
reader.read(properties.GM);
reader.read(properties.mass);
reader.read(properties.radius);
size_t elementsCount = 0;
reader.read(elementsCount);
for (size_t elementsIndex = 0; elementsIndex < elementsCount; ++elementsIndex)
{
Elements elements;
reader.read(&elements, sizeof(elements));
entry.elements.push_back(elements);
}
_names.insert(std::make_pair(target, hid));
_properties.insert(std::make_pair(hid, properties));
_entries.insert(std::make_pair(hid, entry));
}
}
size_t Ephemeris::lookup(std::string const &target) const
{
auto iter = _names.find(target);
LUCID_VALIDATE(iter != _names.end(), "unknown target '" + target + "' specified");
return iter->second;
}
void Ephemeris::lookup(Properties &properties, std::string const &target) const
{
lookup(properties, lookup(target));
}
void Ephemeris::lookup(Properties &properties, size_t target) const
{
auto iter = _properties.find(target);
LUCID_VALIDATE(iter != _properties.end(), "unknown target id specified");
properties = iter->second;
}
size_t Ephemeris::lookup(Elements &elements, std::string const &target, float32_t jdn) const
{
return lookup(elements, lookup(target), jdn);
}
size_t Ephemeris::lookup(Elements &elements, size_t target, float32_t jdn) const
{
auto iter = _entries.find(target);
LUCID_VALIDATE(iter != _entries.end(), "unknown target id specified");
Entry const &entry = iter->second;
size_t const count = entry.elements.size();
LUCID_VALIDATE(0 < count, "target does not define orbital elements");
/// find the closest entry to the given julian day.
/// for now, it is a simple linear scan through the list.
/// test {
size_t index = 0;
float32_t a = ::fabsf(entry.elements[index].JDN - jdn);
for (size_t i = 1; i < count; ++i)
{
float32_t b = ::fabsf(entry.elements[i].JDN - jdn);
if (b < a)
{
index = i;
a = b;
}
else
{
break;
}
}
/// } test
elements = entry.elements[index];
return entry.center;
}
void Ephemeris::compute(vector3_t &position, vector3_t &velocity, std::string const &target, float32_t jdn) const
{
compute(position, velocity, lookup(target), jdn);
}
void Ephemeris::compute(vector3_t &position, vector3_t &velocity, size_t target, float32_t jdn) const
{
Elements elements;
size_t cid = lookup(elements, target, jdn);
Properties centerProperties;
lookup(centerProperties, cid);
float32_t const tolsq = math::constants::tol_tol<float32_t>();
float32_t const spd = 86400.f;
float32_t const dt = spd * (jdn - elements.JDN);
float32_t const GM = centerProperties.GM;
float32_t const e = elements.EC;
float32_t const a = elements.A;
float32_t MA = elements.MA + dt * ::sqrtf(GM / ::powf(a, 3.f));
MA = ::fmodf(MA, math::constants::two_pi<float32_t>());
MA = (MA < 0.f) ? MA + math::constants::two_pi<float32_t>(): MA;
float32_t EA[2] = { MA, 0.f };
float32_t err = EA[0] - EA[1];
size_t iter = 0;
while (((err * err) > tolsq) && (iter < 5))
{
EA[1] = EA[0] - (EA[0] - e * ::sinf(EA[0]) - MA) / (1.f - e * ::cosf(EA[0]));
err = EA[1] - EA[0];
std::swap(EA[0], EA[1]);
++iter;
}
float32_t TA = 2.f * ::atan2f(::sqrtf(1.f + e) * ::sinf(0.5f * EA[0]), ::sqrtf(1.f - e) * ::cosf(0.5f * EA[0]));
float32_t r = a * (1.f - e * ::cosf(EA[0]));
position = r * vector3_t(::cosf(TA), ::sinf(TA), 0.f);
velocity = ::sqrtf(GM * a) / r * vector3_t(-::sinf(EA[0]), ::sqrt(1.f - e * e) * ::cosf(EA[0]), 0.f);
matrix3x3_t R = Rz(-elements.OM) * Rx(-elements.IN) * Rz(-elements.W);
position = R * position;
velocity = R * velocity;
}
Ephemeris &Ephemeris::instance()
{
static Ephemeris theInstance;
return theInstance;
}
} /// orbit
} /// lucid
<|endoftext|> |
<commit_before>/*
** Copyright (C) 2012 Aldebaran Robotics
** See COPYING for the license
*/
#include <algorithm>
#include <sstream>
#include <boost/algorithm/string.hpp>
#include <boost/range/algorithm/find_if.hpp>
#include <qi/log.hpp>
#include <qi/numeric.hpp>
#include "messagesocket.hpp"
#include "transportsocketcache.hpp"
qiLogCategory("qimessaging.transportsocketcache");
namespace qi
{
TransportSocketCache::TransportSocketCache()
: _dying(false)
{
}
TransportSocketCache::~TransportSocketCache()
{
_dying = true;
destroy();
try
{
close();
}
catch (const std::exception& ex)
{
qiLogError() << "Exception caught during destruction: " << ex.what();
}
catch (...)
{
qiLogError() << "Unknown exception caught during destruction";
}
}
void TransportSocketCache::init()
{
_dying = false;
}
/// Container<DisconnectInfo> C
template<typename C>
static void releaseDisconnectInfoPromises(C& disconnectInfos)
{
for (auto& d: disconnectInfos)
{
d.promiseSocketRemoved.setValue(0);
}
}
void TransportSocketCache::close()
{
qiLogDebug() << "TransportSocketCache is closing";
{
ConnectionMap map;
std::list<MessageSocketPtr> pending;
{
boost::mutex::scoped_lock lock(_socketMutex);
_dying = true;
std::swap(map, _connections);
std::swap(pending, _allPendingConnections);
}
for (auto& pairMachineIdConnection: map)
{
auto& mapUrlConnection = pairMachineIdConnection.second;
for (auto& pairUrlConnection: mapUrlConnection)
{
auto& connectionAttempt = *pairUrlConnection.second;
auto endpoint = connectionAttempt.endpoint;
// Disconnect any valid socket we were holding.
if (endpoint)
{
endpoint->disconnect();
endpoint->disconnected.disconnect(connectionAttempt.disconnectionTracking);
}
else
{
connectionAttempt.state = State_Error;
connectionAttempt.promise.setError("TransportSocketCache is closing.");
}
}
}
for (auto& socket: pending)
{
socket->disconnect();
}
}
/// Release all disconnect promises to avoid deadlocks.
/// A deadlock could happen if the user calls `disconnect(socket)` and the cache is
/// destroyed before the disconnected socket signal has arrived.
auto sync = _disconnectInfos.synchronize();
releaseDisconnectInfoPromises(*sync);
}
bool isLocalHost(const std::string& host)
{
return boost::algorithm::starts_with(host, "127.") || host == "localhost";
}
static UrlVector localhost_only(const UrlVector& input)
{
UrlVector result;
result.reserve(input.size());
for (const auto& url: input)
{
if (isLocalHost(url.host()))
result.push_back(url);
}
return result;
}
Future<MessageSocketPtr> TransportSocketCache::socket(const ServiceInfo& servInfo, const std::string& url)
{
const std::string& machineId = servInfo.machineId();
ConnectionAttemptPtr couple = boost::make_shared<ConnectionAttempt>();
couple->relatedUrls = servInfo.endpoints();
bool local = machineId == os::getMachineId();
UrlVector connectionCandidates;
// If the connection is local, we're mainly interested in localhost endpoint
if (local)
connectionCandidates = localhost_only(servInfo.endpoints());
// If the connection isn't local or if the service doesn't expose local endpoints,
// try and connect to whatever is available.
if (connectionCandidates.size() == 0)
connectionCandidates = servInfo.endpoints();
couple->endpoint = MessageSocketPtr();
couple->state = State_Pending;
{
// If we already have a pending connection to one of the urls, we return the future in question
boost::mutex::scoped_lock lock(_socketMutex);
if (_dying)
return makeFutureError<MessageSocketPtr>("TransportSocketCache is closed.");
ConnectionMap::iterator machineIt = _connections.find(machineId);
if (machineIt != _connections.end())
{
// Check if any connection to the machine matches one of our urls
UrlVector& vurls = couple->relatedUrls;
for (std::map<Url, ConnectionAttemptPtr>::iterator b = machineIt->second.begin(), e = machineIt->second.end();
b != e;
b++)
{
UrlVector::iterator uIt = std::find(vurls.begin(), vurls.end(), b->first);
// We found a matching machineId and URL : return the connected endpoint.
if (uIt != vurls.end())
{
qiLogDebug() << "Found pending promise.";
return b->second->promise.future();
}
}
}
// Otherwise, we keep track of all those URLs and assign them the same promise in our map.
// They will all track the same connection.
couple->attemptCount = qi::numericConvert<int>(connectionCandidates.size());
std::map<Url, ConnectionAttemptPtr>& urlMap = _connections[machineId];
for (const auto& url: connectionCandidates)
{
if (!url.isValid())
continue; // Do not try to connect to an invalid url!
if (!local && isLocalHost(url.host()))
continue; // Do not try to connect on localhost when it is a remote!
urlMap[url] = couple;
MessageSocketPtr socket = makeMessageSocket(url.protocol());
_allPendingConnections.push_back(socket);
Future<void> sockFuture = socket->connect(url);
qiLogDebug() << "Inserted [" << machineId << "][" << url.str() << "]";
sockFuture.then(std::bind(&TransportSocketCache::onSocketParallelConnectionAttempt, this,
std::placeholders::_1, socket, url, servInfo));
}
}
return couple->promise.future();
}
FutureSync<void> TransportSocketCache::disconnect(MessageSocketPtr socket)
{
Promise<void> promiseSocketRemoved;
{
auto syncDisconnectInfos = _disconnectInfos.synchronize();
// TODO: Remove Promise<void>{} when get rid of VS2013.
syncDisconnectInfos->push_back(DisconnectInfo{socket, Promise<void>{}});
promiseSocketRemoved = syncDisconnectInfos->back().promiseSocketRemoved;
}
// We wait that the socket has been disconnected _and_ the `disconnected`
// signal has been received by the cache.
FutureBarrier<void> barrier;
barrier.addFuture(promiseSocketRemoved.future());
barrier.addFuture(socket->disconnect());
Promise<void> promise;
return barrier.future().andThen([=](const std::vector<Future<void>>& v) mutable {
const auto isInError = [](const Future<void>& f) {
return f.hasError();
};
if (std::any_of(begin(v), end(v), isInError))
{
promise.setError("disconnect error");
return;
}
promise.setValue(0);
});
}
void TransportSocketCache::insert(const std::string& machineId, const Url& url, MessageSocketPtr socket)
{
// If a connection is pending for this machine / url, terminate the pendage and set the
// service socket as this one
boost::mutex::scoped_lock lock(_socketMutex);
if (_dying)
return;
ServiceInfo info;
info.setMachineId(machineId);
qi::SignalLink disconnectionTracking = socket->disconnected.connect(
track([=](const std::string&) { onSocketDisconnected(url, info); }, this));
ConnectionMap::iterator mIt = _connections.find(machineId);
if (mIt != _connections.end())
{
std::map<Url, ConnectionAttemptPtr>::iterator uIt = mIt->second.find(url);
if (uIt != mIt->second.end())
{
auto& connectionAttempt = *uIt->second;
QI_ASSERT(!connectionAttempt.endpoint);
// If the attempt is done and the endpoint is null, it means the
// attempt failed and the promise is set as error.
// We replace it by a new one.
// If the attempt is not done we do not replace it, otherwise the future
// currently in circulation will never finish.
if (connectionAttempt.state != State_Pending)
connectionAttempt.promise = Promise<MessageSocketPtr>();
connectionAttempt.state = State_Connected;
connectionAttempt.endpoint = socket;
connectionAttempt.promise.setValue(socket);
connectionAttempt.disconnectionTracking = disconnectionTracking;
return;
}
}
ConnectionAttemptPtr couple = boost::make_shared<ConnectionAttempt>();
couple->promise = Promise<MessageSocketPtr>();
couple->endpoint = socket;
couple->state = State_Connected;
couple->relatedUrls.push_back(url);
_connections[machineId][url] = couple;
couple->promise.setValue(socket);
}
/*
* Corner case to manage (TODO):
*
* You are connecting to machineId foo, you are machineId bar. foo and bar are
* on different sub-networks with the same netmask. They sadly got the same IP
* on their subnet: 192.168.1.42. When trying to connect to foo from bar, we
* will try to connect its endpoints, basically:
* - tcp://1.2.3.4:1333 (public IP)
* - tcp://192.168.1.42:1333 (subnet public IP)
* If bar is listening on port 1333, we may connect to it instead of foo (our
* real target).
*/
void TransportSocketCache::onSocketParallelConnectionAttempt(Future<void> fut,
MessageSocketPtr socket,
Url url,
const ServiceInfo& info)
{
boost::mutex::scoped_lock lock(_socketMutex);
if (_dying)
{
qiLogDebug() << "ConnectionAttempt: TransportSocketCache is closed";
if (!fut.hasError())
{
_allPendingConnections.remove(socket);
socket->disconnect();
}
return;
}
ConnectionMap::iterator machineIt = _connections.find(info.machineId());
std::map<Url, ConnectionAttemptPtr>::iterator urlIt;
if (machineIt != _connections.end())
urlIt = machineIt->second.find(url);
if (machineIt == _connections.end() || urlIt == machineIt->second.end())
{
// The socket was disconnected at some point, and we removed it from our map:
// return early.
_allPendingConnections.remove(socket);
socket->disconnect();
return;
}
ConnectionAttemptPtr attempt = urlIt->second;
attempt->attemptCount--;
if (attempt->state != State_Pending)
{
qiLogDebug() << "Already connected: reject socket " << socket.get() << " endpoint " << url.str();
_allPendingConnections.remove(socket);
socket->disconnect();
checkClear(attempt, info.machineId());
return;
}
if (fut.hasError())
{
// Failing to connect to some of the endpoint is expected.
qiLogDebug() << "Could not connect to service #" << info.serviceId() << " through url " << url.str();
_allPendingConnections.remove(socket);
// It's a critical error if we've exhausted all available endpoints.
if (attempt->attemptCount == 0)
{
std::stringstream err;
err << "Could not connect to service #" << info.serviceId() << ": no endpoint replied.";
qiLogError() << err.str();
attempt->promise.setError(err.str());
attempt->state = State_Error;
checkClear(attempt, info.machineId());
}
return;
}
qi::SignalLink disconnectionTracking = socket->disconnected.connect(
track([=](const std::string&) { onSocketDisconnected(url, info); }, this));
attempt->state = State_Connected;
attempt->endpoint = socket;
attempt->promise.setValue(socket);
attempt->disconnectionTracking = disconnectionTracking;
qiLogDebug() << "Connected to service #" << info.serviceId() << " through url " << url.str() << " and socket "
<< socket.get();
}
void TransportSocketCache::checkClear(ConnectionAttemptPtr attempt, const std::string& machineId)
{
if ((attempt->attemptCount <= 0 && attempt->state != State_Connected) || attempt->state == State_Error)
{
ConnectionMap::iterator machineIt = _connections.find(machineId);
if (machineIt == _connections.end())
return;
for (UrlVector::const_iterator uit = attempt->relatedUrls.begin(), end = attempt->relatedUrls.end(); uit != end;
++uit)
machineIt->second.erase(*uit);
if (machineIt->second.size() == 0)
_connections.erase(machineIt);
}
}
/// Remove infos of the given socket and set the associated promise.
///
/// Container<DisconnectInfo> C
template<typename C>
static void updateDisconnectInfos(C& disconnectInfos, const MessageSocketPtr& socket)
{
// TODO: Replace `using` by `auto` in lambda when C++14 is available.
using Value = typename C::value_type;
const auto it = boost::find_if(disconnectInfos, [&](const Value& d) {
return d.socket == socket;
});
if (it == disconnectInfos.end())
{
qiLogWarning() << "Disconnected socket not found in disconnect infos.";
return;
}
auto promise = (*it).promiseSocketRemoved;
disconnectInfos.erase(it);
promise.setValue(0);
}
void TransportSocketCache::onSocketDisconnected(Url url, const ServiceInfo& info)
{
// remove from the available connections
boost::mutex::scoped_lock lock(_socketMutex);
ConnectionMap::iterator machineIt = _connections.find(info.machineId());
if (machineIt == _connections.end())
return;
qiLogDebug() << "onSocketDisconnected: about to erase socket";
auto attempt = machineIt->second[url];
attempt->state = State_Error;
checkClear(attempt, info.machineId());
auto syncDisconnectInfos = _disconnectInfos.synchronize();
updateDisconnectInfos(*syncDisconnectInfos, attempt->endpoint);
}
}
<commit_msg>Changes log level for socket disconnection error #42613<commit_after>/*
** Copyright (C) 2012 Aldebaran Robotics
** See COPYING for the license
*/
#include <algorithm>
#include <sstream>
#include <boost/algorithm/string.hpp>
#include <boost/range/algorithm/find_if.hpp>
#include <qi/log.hpp>
#include <qi/numeric.hpp>
#include "messagesocket.hpp"
#include "transportsocketcache.hpp"
qiLogCategory("qimessaging.transportsocketcache");
namespace qi
{
TransportSocketCache::TransportSocketCache()
: _dying(false)
{
}
TransportSocketCache::~TransportSocketCache()
{
_dying = true;
destroy();
try
{
close();
}
catch (const std::exception& ex)
{
qiLogError() << "Exception caught during destruction: " << ex.what();
}
catch (...)
{
qiLogError() << "Unknown exception caught during destruction";
}
}
void TransportSocketCache::init()
{
_dying = false;
}
/// Container<DisconnectInfo> C
template<typename C>
static void releaseDisconnectInfoPromises(C& disconnectInfos)
{
for (auto& d: disconnectInfos)
{
d.promiseSocketRemoved.setValue(0);
}
}
void TransportSocketCache::close()
{
qiLogDebug() << "TransportSocketCache is closing";
{
ConnectionMap map;
std::list<MessageSocketPtr> pending;
{
boost::mutex::scoped_lock lock(_socketMutex);
_dying = true;
std::swap(map, _connections);
std::swap(pending, _allPendingConnections);
}
for (auto& pairMachineIdConnection: map)
{
auto& mapUrlConnection = pairMachineIdConnection.second;
for (auto& pairUrlConnection: mapUrlConnection)
{
auto& connectionAttempt = *pairUrlConnection.second;
auto endpoint = connectionAttempt.endpoint;
// Disconnect any valid socket we were holding.
if (endpoint)
{
endpoint->disconnect();
endpoint->disconnected.disconnect(connectionAttempt.disconnectionTracking);
}
else
{
connectionAttempt.state = State_Error;
connectionAttempt.promise.setError("TransportSocketCache is closing.");
}
}
}
for (auto& socket: pending)
{
socket->disconnect();
}
}
/// Release all disconnect promises to avoid deadlocks.
/// A deadlock could happen if the user calls `disconnect(socket)` and the cache is
/// destroyed before the disconnected socket signal has arrived.
auto sync = _disconnectInfos.synchronize();
releaseDisconnectInfoPromises(*sync);
}
bool isLocalHost(const std::string& host)
{
return boost::algorithm::starts_with(host, "127.") || host == "localhost";
}
static UrlVector localhost_only(const UrlVector& input)
{
UrlVector result;
result.reserve(input.size());
for (const auto& url: input)
{
if (isLocalHost(url.host()))
result.push_back(url);
}
return result;
}
Future<MessageSocketPtr> TransportSocketCache::socket(const ServiceInfo& servInfo, const std::string& url)
{
const std::string& machineId = servInfo.machineId();
ConnectionAttemptPtr couple = boost::make_shared<ConnectionAttempt>();
couple->relatedUrls = servInfo.endpoints();
bool local = machineId == os::getMachineId();
UrlVector connectionCandidates;
// If the connection is local, we're mainly interested in localhost endpoint
if (local)
connectionCandidates = localhost_only(servInfo.endpoints());
// If the connection isn't local or if the service doesn't expose local endpoints,
// try and connect to whatever is available.
if (connectionCandidates.size() == 0)
connectionCandidates = servInfo.endpoints();
couple->endpoint = MessageSocketPtr();
couple->state = State_Pending;
{
// If we already have a pending connection to one of the urls, we return the future in question
boost::mutex::scoped_lock lock(_socketMutex);
if (_dying)
return makeFutureError<MessageSocketPtr>("TransportSocketCache is closed.");
ConnectionMap::iterator machineIt = _connections.find(machineId);
if (machineIt != _connections.end())
{
// Check if any connection to the machine matches one of our urls
UrlVector& vurls = couple->relatedUrls;
for (std::map<Url, ConnectionAttemptPtr>::iterator b = machineIt->second.begin(), e = machineIt->second.end();
b != e;
b++)
{
UrlVector::iterator uIt = std::find(vurls.begin(), vurls.end(), b->first);
// We found a matching machineId and URL : return the connected endpoint.
if (uIt != vurls.end())
{
qiLogDebug() << "Found pending promise.";
return b->second->promise.future();
}
}
}
// Otherwise, we keep track of all those URLs and assign them the same promise in our map.
// They will all track the same connection.
couple->attemptCount = qi::numericConvert<int>(connectionCandidates.size());
std::map<Url, ConnectionAttemptPtr>& urlMap = _connections[machineId];
for (const auto& url: connectionCandidates)
{
if (!url.isValid())
continue; // Do not try to connect to an invalid url!
if (!local && isLocalHost(url.host()))
continue; // Do not try to connect on localhost when it is a remote!
urlMap[url] = couple;
MessageSocketPtr socket = makeMessageSocket(url.protocol());
_allPendingConnections.push_back(socket);
Future<void> sockFuture = socket->connect(url);
qiLogDebug() << "Inserted [" << machineId << "][" << url.str() << "]";
sockFuture.then(std::bind(&TransportSocketCache::onSocketParallelConnectionAttempt, this,
std::placeholders::_1, socket, url, servInfo));
}
}
return couple->promise.future();
}
FutureSync<void> TransportSocketCache::disconnect(MessageSocketPtr socket)
{
Promise<void> promiseSocketRemoved;
{
auto syncDisconnectInfos = _disconnectInfos.synchronize();
// TODO: Remove Promise<void>{} when get rid of VS2013.
syncDisconnectInfos->push_back(DisconnectInfo{socket, Promise<void>{}});
promiseSocketRemoved = syncDisconnectInfos->back().promiseSocketRemoved;
}
// We wait that the socket has been disconnected _and_ the `disconnected`
// signal has been received by the cache.
FutureBarrier<void> barrier;
barrier.addFuture(promiseSocketRemoved.future());
barrier.addFuture(socket->disconnect());
Promise<void> promise;
return barrier.future().andThen([=](const std::vector<Future<void>>& v) mutable {
const auto isInError = [](const Future<void>& f) {
return f.hasError();
};
if (std::any_of(begin(v), end(v), isInError))
{
promise.setError("disconnect error");
return;
}
promise.setValue(0);
});
}
void TransportSocketCache::insert(const std::string& machineId, const Url& url, MessageSocketPtr socket)
{
// If a connection is pending for this machine / url, terminate the pendage and set the
// service socket as this one
boost::mutex::scoped_lock lock(_socketMutex);
if (_dying)
return;
ServiceInfo info;
info.setMachineId(machineId);
qi::SignalLink disconnectionTracking = socket->disconnected.connect(
track([=](const std::string&) { onSocketDisconnected(url, info); }, this));
ConnectionMap::iterator mIt = _connections.find(machineId);
if (mIt != _connections.end())
{
std::map<Url, ConnectionAttemptPtr>::iterator uIt = mIt->second.find(url);
if (uIt != mIt->second.end())
{
auto& connectionAttempt = *uIt->second;
QI_ASSERT(!connectionAttempt.endpoint);
// If the attempt is done and the endpoint is null, it means the
// attempt failed and the promise is set as error.
// We replace it by a new one.
// If the attempt is not done we do not replace it, otherwise the future
// currently in circulation will never finish.
if (connectionAttempt.state != State_Pending)
connectionAttempt.promise = Promise<MessageSocketPtr>();
connectionAttempt.state = State_Connected;
connectionAttempt.endpoint = socket;
connectionAttempt.promise.setValue(socket);
connectionAttempt.disconnectionTracking = disconnectionTracking;
return;
}
}
ConnectionAttemptPtr couple = boost::make_shared<ConnectionAttempt>();
couple->promise = Promise<MessageSocketPtr>();
couple->endpoint = socket;
couple->state = State_Connected;
couple->relatedUrls.push_back(url);
_connections[machineId][url] = couple;
couple->promise.setValue(socket);
}
/*
* Corner case to manage (TODO):
*
* You are connecting to machineId foo, you are machineId bar. foo and bar are
* on different sub-networks with the same netmask. They sadly got the same IP
* on their subnet: 192.168.1.42. When trying to connect to foo from bar, we
* will try to connect its endpoints, basically:
* - tcp://1.2.3.4:1333 (public IP)
* - tcp://192.168.1.42:1333 (subnet public IP)
* If bar is listening on port 1333, we may connect to it instead of foo (our
* real target).
*/
void TransportSocketCache::onSocketParallelConnectionAttempt(Future<void> fut,
MessageSocketPtr socket,
Url url,
const ServiceInfo& info)
{
boost::mutex::scoped_lock lock(_socketMutex);
if (_dying)
{
qiLogDebug() << "ConnectionAttempt: TransportSocketCache is closed";
if (!fut.hasError())
{
_allPendingConnections.remove(socket);
socket->disconnect();
}
return;
}
ConnectionMap::iterator machineIt = _connections.find(info.machineId());
std::map<Url, ConnectionAttemptPtr>::iterator urlIt;
if (machineIt != _connections.end())
urlIt = machineIt->second.find(url);
if (machineIt == _connections.end() || urlIt == machineIt->second.end())
{
// The socket was disconnected at some point, and we removed it from our map:
// return early.
_allPendingConnections.remove(socket);
socket->disconnect();
return;
}
ConnectionAttemptPtr attempt = urlIt->second;
attempt->attemptCount--;
if (attempt->state != State_Pending)
{
qiLogDebug() << "Already connected: reject socket " << socket.get() << " endpoint " << url.str();
_allPendingConnections.remove(socket);
socket->disconnect();
checkClear(attempt, info.machineId());
return;
}
if (fut.hasError())
{
// Failing to connect to some of the endpoint is expected.
qiLogDebug() << "Could not connect to service #" << info.serviceId() << " through url " << url.str();
_allPendingConnections.remove(socket);
// It's a critical error if we've exhausted all available endpoints.
if (attempt->attemptCount == 0)
{
std::stringstream err;
err << "Could not connect to service #" << info.serviceId() << ": no endpoint replied.";
qiLogError() << err.str();
attempt->promise.setError(err.str());
attempt->state = State_Error;
checkClear(attempt, info.machineId());
}
return;
}
qi::SignalLink disconnectionTracking = socket->disconnected.connect(
track([=](const std::string&) { onSocketDisconnected(url, info); }, this));
attempt->state = State_Connected;
attempt->endpoint = socket;
attempt->promise.setValue(socket);
attempt->disconnectionTracking = disconnectionTracking;
qiLogDebug() << "Connected to service #" << info.serviceId() << " through url " << url.str() << " and socket "
<< socket.get();
}
void TransportSocketCache::checkClear(ConnectionAttemptPtr attempt, const std::string& machineId)
{
if ((attempt->attemptCount <= 0 && attempt->state != State_Connected) || attempt->state == State_Error)
{
ConnectionMap::iterator machineIt = _connections.find(machineId);
if (machineIt == _connections.end())
return;
for (UrlVector::const_iterator uit = attempt->relatedUrls.begin(), end = attempt->relatedUrls.end(); uit != end;
++uit)
machineIt->second.erase(*uit);
if (machineIt->second.size() == 0)
_connections.erase(machineIt);
}
}
/// Remove infos of the given socket and set the associated promise.
///
/// Container<DisconnectInfo> C
template<typename C>
static void updateDisconnectInfos(C& disconnectInfos, const MessageSocketPtr& socket)
{
// TODO: Replace `using` by `auto` in lambda when C++14 is available.
using Value = typename C::value_type;
const auto it = boost::find_if(disconnectInfos, [&](const Value& d) {
return d.socket == socket;
});
if (it == disconnectInfos.end())
{
// We should not fall into this if statement, but due to the racy nature of
// the disconnection, it does indeed occur. Fixing this would be
// a significant rearchitecture, and we choose for now to lower the log
// level because there does not seem to be any other side effect besides the
// warning.
qiLogVerbose() << "Disconnected socket not found in disconnect infos.";
return;
}
auto promise = (*it).promiseSocketRemoved;
disconnectInfos.erase(it);
promise.setValue(0);
}
void TransportSocketCache::onSocketDisconnected(Url url, const ServiceInfo& info)
{
// remove from the available connections
boost::mutex::scoped_lock lock(_socketMutex);
ConnectionMap::iterator machineIt = _connections.find(info.machineId());
if (machineIt == _connections.end())
return;
qiLogDebug() << "onSocketDisconnected: about to erase socket";
auto attempt = machineIt->second[url];
attempt->state = State_Error;
checkClear(attempt, info.machineId());
auto syncDisconnectInfos = _disconnectInfos.synchronize();
updateDisconnectInfos(*syncDisconnectInfos, attempt->endpoint);
}
}
<|endoftext|> |
<commit_before>/*
** Copyright (C) 2012 Aldebaran Robotics
** See COPYING for the license
*/
#include <sstream>
#include <boost/algorithm/string.hpp>
#include <qi/log.hpp>
#include "transportsocket.hpp"
#include "transportsocketcache.hpp"
qiLogCategory("qimessaging.transportsocketcache");
namespace qi
{
TransportSocketCache::TransportSocketCache()
: _dying(false)
{
}
TransportSocketCache::~TransportSocketCache()
{
_dying = true;
destroy();
close();
}
void TransportSocketCache::init()
{
_dying = false;
}
void TransportSocketCache::close()
{
qiLogDebug() << "TransportSocketCache is closing";
ConnectionMap map;
std::list<TransportSocketPtr> pending;
{
boost::mutex::scoped_lock lock(_socketMutex);
_dying = true;
std::swap(map, _connections);
std::swap(pending, _allPendingConnections);
}
for (ConnectionMap::iterator mIt = map.begin(), mEnd = map.end(); mIt != mEnd; ++mIt)
{
for (std::map<Url, ConnectionAttemptPtr>::iterator uIt = mIt->second.begin(), uEnd = mIt->second.end();
uIt != uEnd;
++uIt)
{
TransportSocketPtr endpoint = uIt->second->endpoint;
// Disconnect any valid socket we were holding.
if (endpoint)
{
endpoint->disconnect();
}
else
{
uIt->second->state = State_Error;
uIt->second->promise.setError("TransportSocketCache is closing.");
}
}
}
for (std::list<TransportSocketPtr>::iterator it = pending.begin(), end = pending.end(); it != end; ++it)
(*it)->disconnect();
}
static UrlVector localhost_only(const UrlVector& input)
{
UrlVector result;
result.reserve(input.size());
for (UrlVector::const_iterator it = input.begin(), end = input.end(); it != end; ++it)
{
const std::string& host = it->host();
if (boost::algorithm::starts_with(host, "127.") || host == "localhost")
result.push_back(*it);
}
return result;
}
Future<TransportSocketPtr> TransportSocketCache::socket(const ServiceInfo& servInfo, const std::string& protocol)
{
const std::string& machineId = servInfo.machineId();
ConnectionAttemptPtr couple = boost::make_shared<ConnectionAttempt>();
couple->relatedUrls = servInfo.endpoints();
bool local = machineId == os::getMachineId();
UrlVector connectionCandidates;
// If the connection is local, we're mainly interested in localhost endpoint
if (local)
connectionCandidates = localhost_only(servInfo.endpoints());
// If the connection isn't local or if the service doesn't expose local endpoints,
// try and connect to whatever is available.
if (connectionCandidates.size() == 0)
connectionCandidates = servInfo.endpoints();
couple->endpoint = TransportSocketPtr();
couple->state = State_Pending;
{
// If we already have a pending connection to one of the urls, we return the future in question
boost::mutex::scoped_lock lock(_socketMutex);
if (_dying)
return makeFutureError<TransportSocketPtr>("TransportSocketCache is closed.");
ConnectionMap::iterator machineIt = _connections.find(machineId);
if (machineIt != _connections.end())
{
// Check if any connection to the machine matches one of our urls
UrlVector& vurls = couple->relatedUrls;
for (std::map<Url, ConnectionAttemptPtr>::iterator b = machineIt->second.begin(), e = machineIt->second.end();
b != e;
b++)
{
UrlVector::iterator uIt = std::find(vurls.begin(), vurls.end(), b->first);
// We found a matching machineId and URL : return the connected endpoint.
if (uIt != vurls.end())
return b->second->promise.future();
}
}
// Otherwise, we keep track of all those URLs and assign them the same promise in our map.
// They will all track the same connection.
couple->attemptCount = connectionCandidates.size();
std::map<Url, ConnectionAttemptPtr>& urlMap = _connections[machineId];
for (UrlVector::iterator it = connectionCandidates.begin(), end = connectionCandidates.end(); it != end; ++it)
{
urlMap[*it] = couple;
TransportSocketPtr socket = makeTransportSocket(it->protocol());
_allPendingConnections.push_back(socket);
Future<void> sockFuture = socket->connect(*it);
qiLogDebug() << "Inserted [" << machineId << "][" << it->str() << "]";
sockFuture.connect(&TransportSocketCache::onSocketParallelConnectionAttempt, this, _1, socket, *it, servInfo);
}
}
return couple->promise.future();
}
void TransportSocketCache::insert(const std::string& machineId, const Url& url, TransportSocketPtr socket)
{
// If a connection is pending for this machine / url, terminate the pendage and set the
// service socket as this one
boost::mutex::scoped_lock lock(_socketMutex);
if (_dying)
return;
ServiceInfo info;
info.setMachineId(machineId);
socket->disconnected.connect(&TransportSocketCache::onSocketDisconnected, this, socket, url, _1, info)
.setCallType(MetaCallType_Direct);
ConnectionMap::iterator mIt = _connections.find(machineId);
if (mIt != _connections.end())
{
std::map<Url, ConnectionAttemptPtr>::iterator uIt = mIt->second.find(url);
if (uIt != mIt->second.end())
{
QI_ASSERT(!uIt->second->endpoint);
// If the attempt is done and the endpoint is null, it means the
// attempt failed and the promise is set as error.
// We replace it by a new one.
// If the attempt is not done we do not replace it, otherwise the future
// currently in circulation will never finish.
if (uIt->second->state != State_Pending)
uIt->second->promise = Promise<TransportSocketPtr>();
uIt->second->state = State_Connected;
uIt->second->endpoint = socket;
uIt->second->promise.setValue(socket);
return;
}
}
ConnectionAttemptPtr couple = boost::make_shared<ConnectionAttempt>();
couple->promise = Promise<TransportSocketPtr>();
couple->endpoint = socket;
couple->state = State_Connected;
couple->relatedUrls.push_back(url);
_connections[machineId][url] = couple;
couple->promise.setValue(socket);
}
/*
* Corner case to manage (TODO):
*
* You are connecting to machineId foo, you are machineId bar. foo and bar are
* on different sub-networks with the same netmask. They sadly got the same IP
* on their subnet: 192.168.1.42. When trying to connect to foo from bar, we
* will try to connect its endpoints, basically:
* - tcp://1.2.3.4:1333 (public IP)
* - tcp://192.168.1.42:1333 (subnet public IP)
* If bar is listening on port 1333, we may connect to it instead of foo (our
* real target).
*/
void TransportSocketCache::onSocketParallelConnectionAttempt(Future<void> fut,
TransportSocketPtr socket,
Url url,
const ServiceInfo& info)
{
boost::mutex::scoped_lock lock(_socketMutex);
if (_dying)
{
qiLogDebug() << "ConnectionAttempt: TransportSocketCache is closed";
if (!fut.hasError())
{
_allPendingConnections.remove(socket);
socket->disconnect();
}
return;
}
ConnectionMap::iterator machineIt = _connections.find(info.machineId());
std::map<Url, ConnectionAttemptPtr>::iterator urlIt;
if (machineIt != _connections.end())
urlIt = machineIt->second.find(url);
if (machineIt == _connections.end() || urlIt == machineIt->second.end())
{
// The socket was disconnected at some point, and we removed it from our map:
// return early.
_allPendingConnections.remove(socket);
socket->disconnect();
return;
}
ConnectionAttemptPtr attempt = urlIt->second;
attempt->attemptCount--;
if (attempt->state != State_Pending)
{
qiLogDebug() << "Already connected: reject socket " << socket.get() << " endpoint " << url.str();
_allPendingConnections.remove(socket);
socket->disconnect();
checkClear(attempt, info.machineId());
return;
}
if (fut.hasError())
{
// Failing to connect to some of the endpoint is expected.
qiLogDebug() << "Could not connect to service #" << info.serviceId() << " through url " << url.str();
_allPendingConnections.remove(socket);
// It's a critical error if we've exhausted all available endpoints.
if (attempt->attemptCount == 0)
{
std::stringstream err;
err << "Could not connect to service #" << info.serviceId() << ": no endpoint answered.";
qiLogError() << err.str();
attempt->promise.setError(err.str());
attempt->state = State_Error;
checkClear(attempt, info.machineId());
}
return;
}
socket->disconnected.connect(&TransportSocketCache::onSocketDisconnected, this, socket, url, _1, info)
.setCallType(MetaCallType_Direct);
attempt->state = State_Connected;
attempt->endpoint = socket;
attempt->promise.setValue(socket);
qiLogDebug() << "Connected to service #" << info.serviceId() << " through url " << url.str() << " and socket "
<< socket.get();
}
void TransportSocketCache::checkClear(ConnectionAttemptPtr attempt, const std::string& machineId)
{
if ((attempt->attemptCount <= 0 && attempt->state != State_Connected) || attempt->state == State_Error)
{
ConnectionMap::iterator machineIt = _connections.find(machineId);
if (machineIt == _connections.end())
return;
for (UrlVector::const_iterator uit = attempt->relatedUrls.begin(), end = attempt->relatedUrls.end(); uit != end;
++uit)
machineIt->second.erase(*uit);
if (machineIt->second.size() == 0)
_connections.erase(machineIt);
}
}
void TransportSocketCache::onSocketDisconnected(TransportSocketPtr socket,
Url url,
const std::string& reason,
const ServiceInfo& info)
{
// remove from the available connections
boost::mutex::scoped_lock lock(_socketMutex);
ConnectionMap::iterator machineIt = _connections.find(info.machineId());
if (machineIt == _connections.end())
return;
machineIt->second[url]->state = State_Error;
checkClear(machineIt->second[url], info.machineId());
}
}
<commit_msg>Transport Socket Cache: fix error message<commit_after>/*
** Copyright (C) 2012 Aldebaran Robotics
** See COPYING for the license
*/
#include <sstream>
#include <boost/algorithm/string.hpp>
#include <qi/log.hpp>
#include "transportsocket.hpp"
#include "transportsocketcache.hpp"
qiLogCategory("qimessaging.transportsocketcache");
namespace qi
{
TransportSocketCache::TransportSocketCache()
: _dying(false)
{
}
TransportSocketCache::~TransportSocketCache()
{
_dying = true;
destroy();
close();
}
void TransportSocketCache::init()
{
_dying = false;
}
void TransportSocketCache::close()
{
qiLogDebug() << "TransportSocketCache is closing";
ConnectionMap map;
std::list<TransportSocketPtr> pending;
{
boost::mutex::scoped_lock lock(_socketMutex);
_dying = true;
std::swap(map, _connections);
std::swap(pending, _allPendingConnections);
}
for (ConnectionMap::iterator mIt = map.begin(), mEnd = map.end(); mIt != mEnd; ++mIt)
{
for (std::map<Url, ConnectionAttemptPtr>::iterator uIt = mIt->second.begin(), uEnd = mIt->second.end();
uIt != uEnd;
++uIt)
{
TransportSocketPtr endpoint = uIt->second->endpoint;
// Disconnect any valid socket we were holding.
if (endpoint)
{
endpoint->disconnect();
}
else
{
uIt->second->state = State_Error;
uIt->second->promise.setError("TransportSocketCache is closing.");
}
}
}
for (std::list<TransportSocketPtr>::iterator it = pending.begin(), end = pending.end(); it != end; ++it)
(*it)->disconnect();
}
static UrlVector localhost_only(const UrlVector& input)
{
UrlVector result;
result.reserve(input.size());
for (UrlVector::const_iterator it = input.begin(), end = input.end(); it != end; ++it)
{
const std::string& host = it->host();
if (boost::algorithm::starts_with(host, "127.") || host == "localhost")
result.push_back(*it);
}
return result;
}
Future<TransportSocketPtr> TransportSocketCache::socket(const ServiceInfo& servInfo, const std::string& protocol)
{
const std::string& machineId = servInfo.machineId();
ConnectionAttemptPtr couple = boost::make_shared<ConnectionAttempt>();
couple->relatedUrls = servInfo.endpoints();
bool local = machineId == os::getMachineId();
UrlVector connectionCandidates;
// If the connection is local, we're mainly interested in localhost endpoint
if (local)
connectionCandidates = localhost_only(servInfo.endpoints());
// If the connection isn't local or if the service doesn't expose local endpoints,
// try and connect to whatever is available.
if (connectionCandidates.size() == 0)
connectionCandidates = servInfo.endpoints();
couple->endpoint = TransportSocketPtr();
couple->state = State_Pending;
{
// If we already have a pending connection to one of the urls, we return the future in question
boost::mutex::scoped_lock lock(_socketMutex);
if (_dying)
return makeFutureError<TransportSocketPtr>("TransportSocketCache is closed.");
ConnectionMap::iterator machineIt = _connections.find(machineId);
if (machineIt != _connections.end())
{
// Check if any connection to the machine matches one of our urls
UrlVector& vurls = couple->relatedUrls;
for (std::map<Url, ConnectionAttemptPtr>::iterator b = machineIt->second.begin(), e = machineIt->second.end();
b != e;
b++)
{
UrlVector::iterator uIt = std::find(vurls.begin(), vurls.end(), b->first);
// We found a matching machineId and URL : return the connected endpoint.
if (uIt != vurls.end())
return b->second->promise.future();
}
}
// Otherwise, we keep track of all those URLs and assign them the same promise in our map.
// They will all track the same connection.
couple->attemptCount = connectionCandidates.size();
std::map<Url, ConnectionAttemptPtr>& urlMap = _connections[machineId];
for (UrlVector::iterator it = connectionCandidates.begin(), end = connectionCandidates.end(); it != end; ++it)
{
urlMap[*it] = couple;
TransportSocketPtr socket = makeTransportSocket(it->protocol());
_allPendingConnections.push_back(socket);
Future<void> sockFuture = socket->connect(*it);
qiLogDebug() << "Inserted [" << machineId << "][" << it->str() << "]";
sockFuture.connect(&TransportSocketCache::onSocketParallelConnectionAttempt, this, _1, socket, *it, servInfo);
}
}
return couple->promise.future();
}
void TransportSocketCache::insert(const std::string& machineId, const Url& url, TransportSocketPtr socket)
{
// If a connection is pending for this machine / url, terminate the pendage and set the
// service socket as this one
boost::mutex::scoped_lock lock(_socketMutex);
if (_dying)
return;
ServiceInfo info;
info.setMachineId(machineId);
socket->disconnected.connect(&TransportSocketCache::onSocketDisconnected, this, socket, url, _1, info)
.setCallType(MetaCallType_Direct);
ConnectionMap::iterator mIt = _connections.find(machineId);
if (mIt != _connections.end())
{
std::map<Url, ConnectionAttemptPtr>::iterator uIt = mIt->second.find(url);
if (uIt != mIt->second.end())
{
QI_ASSERT(!uIt->second->endpoint);
// If the attempt is done and the endpoint is null, it means the
// attempt failed and the promise is set as error.
// We replace it by a new one.
// If the attempt is not done we do not replace it, otherwise the future
// currently in circulation will never finish.
if (uIt->second->state != State_Pending)
uIt->second->promise = Promise<TransportSocketPtr>();
uIt->second->state = State_Connected;
uIt->second->endpoint = socket;
uIt->second->promise.setValue(socket);
return;
}
}
ConnectionAttemptPtr couple = boost::make_shared<ConnectionAttempt>();
couple->promise = Promise<TransportSocketPtr>();
couple->endpoint = socket;
couple->state = State_Connected;
couple->relatedUrls.push_back(url);
_connections[machineId][url] = couple;
couple->promise.setValue(socket);
}
/*
* Corner case to manage (TODO):
*
* You are connecting to machineId foo, you are machineId bar. foo and bar are
* on different sub-networks with the same netmask. They sadly got the same IP
* on their subnet: 192.168.1.42. When trying to connect to foo from bar, we
* will try to connect its endpoints, basically:
* - tcp://1.2.3.4:1333 (public IP)
* - tcp://192.168.1.42:1333 (subnet public IP)
* If bar is listening on port 1333, we may connect to it instead of foo (our
* real target).
*/
void TransportSocketCache::onSocketParallelConnectionAttempt(Future<void> fut,
TransportSocketPtr socket,
Url url,
const ServiceInfo& info)
{
boost::mutex::scoped_lock lock(_socketMutex);
if (_dying)
{
qiLogDebug() << "ConnectionAttempt: TransportSocketCache is closed";
if (!fut.hasError())
{
_allPendingConnections.remove(socket);
socket->disconnect();
}
return;
}
ConnectionMap::iterator machineIt = _connections.find(info.machineId());
std::map<Url, ConnectionAttemptPtr>::iterator urlIt;
if (machineIt != _connections.end())
urlIt = machineIt->second.find(url);
if (machineIt == _connections.end() || urlIt == machineIt->second.end())
{
// The socket was disconnected at some point, and we removed it from our map:
// return early.
_allPendingConnections.remove(socket);
socket->disconnect();
return;
}
ConnectionAttemptPtr attempt = urlIt->second;
attempt->attemptCount--;
if (attempt->state != State_Pending)
{
qiLogDebug() << "Already connected: reject socket " << socket.get() << " endpoint " << url.str();
_allPendingConnections.remove(socket);
socket->disconnect();
checkClear(attempt, info.machineId());
return;
}
if (fut.hasError())
{
// Failing to connect to some of the endpoint is expected.
qiLogDebug() << "Could not connect to service #" << info.serviceId() << " through url " << url.str();
_allPendingConnections.remove(socket);
// It's a critical error if we've exhausted all available endpoints.
if (attempt->attemptCount == 0)
{
std::stringstream err;
err << "Could not connect to service #" << info.serviceId() << ": no endpoint replied.";
qiLogError() << err.str();
attempt->promise.setError(err.str());
attempt->state = State_Error;
checkClear(attempt, info.machineId());
}
return;
}
socket->disconnected.connect(&TransportSocketCache::onSocketDisconnected, this, socket, url, _1, info)
.setCallType(MetaCallType_Direct);
attempt->state = State_Connected;
attempt->endpoint = socket;
attempt->promise.setValue(socket);
qiLogDebug() << "Connected to service #" << info.serviceId() << " through url " << url.str() << " and socket "
<< socket.get();
}
void TransportSocketCache::checkClear(ConnectionAttemptPtr attempt, const std::string& machineId)
{
if ((attempt->attemptCount <= 0 && attempt->state != State_Connected) || attempt->state == State_Error)
{
ConnectionMap::iterator machineIt = _connections.find(machineId);
if (machineIt == _connections.end())
return;
for (UrlVector::const_iterator uit = attempt->relatedUrls.begin(), end = attempt->relatedUrls.end(); uit != end;
++uit)
machineIt->second.erase(*uit);
if (machineIt->second.size() == 0)
_connections.erase(machineIt);
}
}
void TransportSocketCache::onSocketDisconnected(TransportSocketPtr socket,
Url url,
const std::string& reason,
const ServiceInfo& info)
{
// remove from the available connections
boost::mutex::scoped_lock lock(_socketMutex);
ConnectionMap::iterator machineIt = _connections.find(info.machineId());
if (machineIt == _connections.end())
return;
machineIt->second[url]->state = State_Error;
checkClear(machineIt->second[url], info.machineId());
}
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Visualization Library
Module: BArray.hh
Language: C++
Date: $Date$
Version: $Revision$
This file is part of the Visualization Library. No part of this file or its
contents may be copied, reproduced or altered in any way without the express
written consent of the authors.
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994
=========================================================================*/
//
// Dynamic, self adjusting bit array
//
#ifndef __vlBitArray_h
#define __vlBitArray_h
#include "Object.hh"
class vlBitArray : public vlObject
{
public:
vlBitArray():Array(NULL),Size(0),MaxId(-1),Extend(1000) {};
void Initialize();
int Allocate(const int sz, const int ext);
vlBitArray(const int sz, const int ext);
vlBitArray(const vlBitArray& ia);
~vlBitArray();
int GetValue(const int id) {return (this->Array[id/8]&(0x80 >> (id%8)));};
char *GetPtr(const int id) {return this->Array + id/8;};
vlBitArray &SetValue(const int id, const int i)
{
if (i) this->Array[id/8] != (0x80 >> id%8);
else this->Array[id/8] &= (~(0x80 >> id%8));
if ( id > this->MaxId ) this->MaxId = id;
}
vlBitArray &InsertValue(const int id, const int i)
{
if ( id >= this->Size ) this->Resize(id);
if (i) this->Array[id/8] != (0x80 >> id%8);
else this->Array[id/8] &= (~(0x80 >> id%8));
if ( id > this->MaxId ) this->MaxId = id;
return *this;
}
int InsertNextValue(const int i)
{this->InsertValue (++this->MaxId,i); return this->MaxId;};
vlBitArray &operator=(const vlBitArray& ia);
vlBitArray &operator+=(const vlBitArray& ia);
void operator+=(const char i) {this->InsertNextValue(i);};
// operator[] can be used on both left and right side of expression;
// Note: if used on lh side, user's responsibility to do range checking
// Note: bit arrays don't handle [] very well
// char& operator[](const int i)
// {if (i > this->MaxId) this->MaxId = i;
// return (this->Array[i/8]&(0x80 >> (id%8)));};
void Squeeze() {this->Resize (this->MaxId+1);};
int GetSize() {return this->Size;};
int GetMaxId() {return this->MaxId;};
char *GetArray() {return this->Array;};
void Reset() {this->MaxId = -1;};
virtual char *GetClassName() {return "vlBitArray";};
void PrintSelf(ostream& os, vlIndent indent);
private:
unsigned char *Array; // pointer to data
int Size; // allocated size of data
int MaxId; // maximum index inserted thus iar
int Extend; // grow array by this point
char *Resize(const int sz); // function to resize data
};
#endif
<commit_msg>fixed bug in the Set methods<commit_after>/*=========================================================================
Program: Visualization Library
Module: BArray.hh
Language: C++
Date: $Date$
Version: $Revision$
This file is part of the Visualization Library. No part of this file or its
contents may be copied, reproduced or altered in any way without the express
written consent of the authors.
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994
=========================================================================*/
//
// Dynamic, self adjusting bit array
//
#ifndef __vlBitArray_h
#define __vlBitArray_h
#include "Object.hh"
class vlBitArray : public vlObject
{
public:
vlBitArray():Array(NULL),Size(0),MaxId(-1),Extend(1000) {};
void Initialize();
int Allocate(const int sz, const int ext);
vlBitArray(const int sz, const int ext);
vlBitArray(const vlBitArray& ia);
~vlBitArray();
int GetValue(const int id) {return (this->Array[id/8]&(0x80 >> (id%8)));};
char *GetPtr(const int id) {return this->Array + id/8;};
vlBitArray &SetValue(const int id, const int i)
{
if (i) this->Array[id/8] |= (0x80 >> id%8);
else this->Array[id/8] &= (~(0x80 >> id%8));
if ( id > this->MaxId ) this->MaxId = id;
}
vlBitArray &InsertValue(const int id, const int i)
{
if ( id >= this->Size ) this->Resize(id);
if (i) this->Array[id/8] |= (0x80 >> id%8);
else this->Array[id/8] &= (~(0x80 >> id%8));
if ( id > this->MaxId ) this->MaxId = id;
return *this;
}
int InsertNextValue(const int i)
{this->InsertValue (++this->MaxId,i); return this->MaxId;};
vlBitArray &operator=(const vlBitArray& ia);
vlBitArray &operator+=(const vlBitArray& ia);
void operator+=(const char i) {this->InsertNextValue(i);};
// operator[] can be used on both left and right side of expression;
// Note: if used on lh side, user's responsibility to do range checking
// Note: bit arrays don't handle [] very well
// char& operator[](const int i)
// {if (i > this->MaxId) this->MaxId = i;
// return (this->Array[i/8]&(0x80 >> (id%8)));};
void Squeeze() {this->Resize (this->MaxId+1);};
int GetSize() {return this->Size;};
int GetMaxId() {return this->MaxId;};
char *GetArray() {return this->Array;};
void Reset() {this->MaxId = -1;};
virtual char *GetClassName() {return "vlBitArray";};
void PrintSelf(ostream& os, vlIndent indent);
private:
unsigned char *Array; // pointer to data
int Size; // allocated size of data
int MaxId; // maximum index inserted thus iar
int Extend; // grow array by this point
char *Resize(const int sz); // function to resize data
};
#endif
<|endoftext|> |
<commit_before>//======================================================================
//-----------------------------------------------------------------------
/**
* @file iutest_ostream_formatter_tests.cpp
* @brief QuietResultPrinter test
*
* @author t.shirayanagi
* @par copyright
* Copyright (C) 2014, Takazumi Shirayanagi\n
* This software is released under the new BSD License,
* see LICENSE
*/
//-----------------------------------------------------------------------
//======================================================================
//======================================================================
// include
#include "../include/iutest.hpp"
#include "iutest_logger_tests.hpp"
#include <iomanip>
TestLogger logger;
IUTEST(Test, Hex)
{
IUTEST_ASSERT_EQ(1024, 1025);
}
IUTEST(Test, Float)
{
IUTEST_ASSERT_EQ(0.33f, 1.0f/3.0f);
}
#ifdef UNICODE
int wmain(int argc, wchar_t* argv[])
#else
int main(int argc, char* argv[])
#endif
{
IUTEST_INIT(&argc, argv);
#if defined(OUTPUTXML)
// 実行対象テストがないので xml 出力しない
::iutest::IUTEST_FLAG(output) = NULL;
#endif
::iutest::detail::iuConsole::SetLogger(&logger);
::iutest::IUTEST_FLAG(color) = "no";
#if IUTEST_HAS_STRINGSTREAM || IUTEST_HAS_STRSTREAM
::iutest::IUTEST_FLAG(ostream_formatter) << ::std::hex << ::std::setw(8) << ::std::setfill('0') << std::setprecision(5);
#endif
{
if( IUTEST_RUN_ALL_TESTS() == 0 ) return 1;
#if IUTEST_HAS_STRINGSTREAM || IUTEST_HAS_STRSTREAM
#if IUTEST_HAS_ASSERTION_RETURN
IUTEST_ASSERT_STRIN(" Actual: 00000401", logger.c_str()) << ::iutest::AssertionReturn<int>(1);
IUTEST_ASSERT_STRIN("Which is: 00000400", logger.c_str()) << ::iutest::AssertionReturn<int>(1);
IUTEST_ASSERT_STRIN(" Actual: 00.33333", logger.c_str()) << ::iutest::AssertionReturn<int>(1);
IUTEST_ASSERT_STRIN("Which is: 00000.33", logger.c_str()) << ::iutest::AssertionReturn<int>(1);
#endif
#endif
}
printf("*** Successful ***\n");
return 0;
}
<commit_msg>update r685<commit_after>//======================================================================
//-----------------------------------------------------------------------
/**
* @file iutest_ostream_formatter_tests.cpp
* @brief QuietResultPrinter test
*
* @author t.shirayanagi
* @par copyright
* Copyright (C) 2014, Takazumi Shirayanagi\n
* This software is released under the new BSD License,
* see LICENSE
*/
//-----------------------------------------------------------------------
//======================================================================
//======================================================================
// include
#include "../include/iutest.hpp"
#include "iutest_logger_tests.hpp"
#include <iomanip>
TestLogger logger;
IUTEST(Test, Hex)
{
IUTEST_ASSERT_EQ(1024, 1025);
}
IUTEST(Test, Float)
{
IUTEST_ASSERT_EQ(0.33f, 1.0f/3.0f);
}
#ifdef UNICODE
int wmain(int argc, wchar_t* argv[])
#else
int main(int argc, char* argv[])
#endif
{
IUTEST_INIT(&argc, argv);
#if defined(OUTPUTXML)
// 実行対象テストがないので xml 出力しない
::iutest::IUTEST_FLAG(output) = NULL;
#endif
::iutest::detail::iuConsole::SetLogger(&logger);
::iutest::IUTEST_FLAG(color) = "no";
#if IUTEST_HAS_STRINGSTREAM || IUTEST_HAS_STRSTREAM
::iutest::IUTEST_FLAG(ostream_formatter) << ::std::hex << ::std::setw(8) << ::std::setfill('0');
::iutest::IUTEST_FLAG(ostream_formatter) << ::std::setprecision(5);
#endif
{
if( IUTEST_RUN_ALL_TESTS() == 0 ) return 1;
#if IUTEST_HAS_STRINGSTREAM || IUTEST_HAS_STRSTREAM
#if IUTEST_HAS_ASSERTION_RETURN
IUTEST_ASSERT_STRIN(" Actual: 00000401", logger.c_str()) << ::iutest::AssertionReturn<int>(1);
IUTEST_ASSERT_STRIN("Which is: 00000400", logger.c_str()) << ::iutest::AssertionReturn<int>(1);
IUTEST_ASSERT_STRIN(" Actual: 00.33333", logger.c_str()) << ::iutest::AssertionReturn<int>(1);
IUTEST_ASSERT_STRIN("Which is: 00000.33", logger.c_str()) << ::iutest::AssertionReturn<int>(1);
#endif
#endif
}
printf("*** Successful ***\n");
return 0;
}
<|endoftext|> |
<commit_before><commit_msg>added function collison<commit_after>mains
aflkjsd
askljdf
skldfjk
<|endoftext|> |
<commit_before>// Test that out-of-scope local variables are ignored by LSan.
// RUN: LSAN_BASE="detect_leaks=1:report_objects=1:use_registers=0:use_stacks=1"
// RUN: %clangxx_lsan %s -o %t
// RUN: LSAN_OPTIONS=$LSAN_BASE not %run %t 2>&1 | FileCheck %s
// RUN: LSAN_OPTIONS=$LSAN_BASE":exitcode=0" %run %t 2>&1 | FileCheck --check-prefix=CHECK-sanity %s
//
// x86 passes parameters through stack that may lead to false negatives
// UNSPPORTED: x86
#include <stdio.h>
#include <stdlib.h>
#include "sanitizer_common/print_address.h"
void **pp;
// Put pointer far enough on the stack that LSan has space to run in without
// overwriting it.
// Hopefully the argument p will be passed on a register, saving us from false
// negatives.
__attribute__((noinline))
void *PutPointerOnStaleStack(void *p) {
void *locals[2048];
locals[0] = p;
pp = &locals[0];
print_address("Test alloc: ", 1, locals[0]);
return 0;
}
int main() {
PutPointerOnStaleStack(malloc(1337));
return 0;
}
// This must run after LSan, to ensure LSan didn't overwrite the pointer before
// it had a chance to see it. If LSan is invoked with atexit(), this works.
// Otherwise, we need a different method.
__attribute__((destructor))
__attribute__((no_sanitize_address))
void ConfirmPointerHasSurvived() {
print_address("Value after LSan: ", 1, *pp);
}
// CHECK: Test alloc: [[ADDR:0x[0-9,a-f]+]]
// CHECK-sanity: Test alloc: [[ADDR:0x[0-9,a-f]+]]
// CHECK: LeakSanitizer: detected memory leaks
// CHECK: [[ADDR]] (1337 bytes)
// CHECK: SUMMARY: {{(Leak|Address)}}Sanitizer:
// CHECK-sanity: Value after LSan: [[ADDR]]
<commit_msg>[lsan] Fix typo in stale_stack_leak.cc testcase<commit_after>// Test that out-of-scope local variables are ignored by LSan.
// RUN: LSAN_BASE="detect_leaks=1:report_objects=1:use_registers=0:use_stacks=1"
// RUN: %clangxx_lsan %s -o %t
// RUN: LSAN_OPTIONS=$LSAN_BASE not %run %t 2>&1 | FileCheck %s
// RUN: LSAN_OPTIONS=$LSAN_BASE":exitcode=0" %run %t 2>&1 | FileCheck --check-prefix=CHECK-sanity %s
//
// x86 passes parameters through stack that may lead to false negatives
// UNSUPPORTED: x86
#include <stdio.h>
#include <stdlib.h>
#include "sanitizer_common/print_address.h"
void **pp;
// Put pointer far enough on the stack that LSan has space to run in without
// overwriting it.
// Hopefully the argument p will be passed on a register, saving us from false
// negatives.
__attribute__((noinline))
void *PutPointerOnStaleStack(void *p) {
void *locals[2048];
locals[0] = p;
pp = &locals[0];
print_address("Test alloc: ", 1, locals[0]);
return 0;
}
int main() {
PutPointerOnStaleStack(malloc(1337));
return 0;
}
// This must run after LSan, to ensure LSan didn't overwrite the pointer before
// it had a chance to see it. If LSan is invoked with atexit(), this works.
// Otherwise, we need a different method.
__attribute__((destructor))
__attribute__((no_sanitize_address))
void ConfirmPointerHasSurvived() {
print_address("Value after LSan: ", 1, *pp);
}
// CHECK: Test alloc: [[ADDR:0x[0-9,a-f]+]]
// CHECK-sanity: Test alloc: [[ADDR:0x[0-9,a-f]+]]
// CHECK: LeakSanitizer: detected memory leaks
// CHECK: [[ADDR]] (1337 bytes)
// CHECK: SUMMARY: {{(Leak|Address)}}Sanitizer:
// CHECK-sanity: Value after LSan: [[ADDR]]
<|endoftext|> |
<commit_before>// This file is part of UDPipe <http://github.com/ufal/udpipe/>.
//
// Copyright 2015 Institute of Formal and Applied Linguistics, Faculty of
// Mathematics and Physics, Charles University in Prague, Czech Republic.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
#include <algorithm>
#include "common.h"
#include "model_morphodita_parsito.h"
#include "utils/parse_int.h"
namespace ufal {
namespace udpipe {
tokenizer* model_morphodita_parsito::new_tokenizer(const string& /*options*/) const {
return new tokenizer_morphodita(this);
}
bool model_morphodita_parsito::tag(sentence& s, const string& /*options*/, string& error) const {
error.clear();
tagger_cache* c = tagger_caches.pop();
if (!c) c = new tagger_cache();
c->forms.clear();
for (size_t i = 1; i < s.words.size(); i++)
c->forms.emplace_back(s.words[i].form.c_str(), s.words[i].form.size());
tagger->tag(c->forms, c->lemmas);
for (size_t i = 0; i < c->lemmas.size(); i++) {
// Lemma
s.words[i + 1].lemma.assign(c->lemmas[i].lemma);
// UPOSTag
size_t start = 0, end = min(c->lemmas[i].tag.find('|'), c->lemmas[i].tag.size());
s.words[i+1].upostag.assign(c->lemmas[i].tag, start, end - start);
// XPOSTag
start = min(end + 1, c->lemmas[i].tag.size());
end = min(c->lemmas[i].tag.find('|', start), c->lemmas[i].tag.size());
s.words[i+1].xpostag.assign(c->lemmas[i].tag, start, end - start);
// Features
start = min(end + 1, c->lemmas[i].tag.size());
s.words[i+1].feats.assign(c->lemmas[i].tag, start, c->lemmas[i].tag.size() - start);
}
tagger_caches.push(c);
return true;
}
bool model_morphodita_parsito::parse(sentence& s, const string& options, string& error) const {
error.clear();
parser_cache* c = parser_caches.pop();
if (!c) c = new parser_cache();
int beam_search = 1;
if (!named_values::parse(options, c->options, error))
return false;
if (c->options.count("beam_search"))
if (!parse_int(c->options["beam_search"], "beam_search", beam_search, error))
return false;
c->tree.clear();
for (size_t i = 1; i < s.words.size(); i++) {
c->tree.add_node(s.words[i].form);
c->tree.nodes.back().lemma.assign(s.words[i].lemma);
c->tree.nodes.back().upostag.assign(s.words[i].upostag);
c->tree.nodes.back().xpostag.assign(s.words[i].xpostag);
c->tree.nodes.back().feats.assign(s.words[i].feats);
c->tree.nodes.back().deps.assign(s.words[i].deps);
c->tree.nodes.back().misc.assign(s.words[i].misc);
}
parser->parse(c->tree, beam_search);
for (size_t i = 1; i < s.words.size(); i++)
s.set_head(i, c->tree.nodes[i].head, c->tree.nodes[i].deprel);
parser_caches.push(c);
return true;
}
model* model_morphodita_parsito::load(istream& is) {
char version;
if (!is.get(version)) return nullptr;
unique_ptr<model_morphodita_parsito> m(new model_morphodita_parsito());
if (!m) return nullptr;
m->tagger.reset(morphodita::tagger::load(is));
if (!m->tagger) return nullptr;
m->parser.reset(parsito::parser::load(is));
if (!m->parser) return nullptr;
return m.release();
}
model_morphodita_parsito::tokenizer_morphodita::tokenizer_morphodita(const model_morphodita_parsito* m)
: tokenizer(m->tagger->new_tokenizer()) {}
bool model_morphodita_parsito::tokenizer_morphodita::read_block(istream& is, string& block) const {
block.clear();
string line;
while (getline(is, line)) {
block.append(line).push_back('\n');
if (line.empty()) break;
}
return !block.empty();
}
void model_morphodita_parsito::tokenizer_morphodita::set_text(string_piece text, bool make_copy) {
tokenizer->set_text(text, make_copy);
}
bool model_morphodita_parsito::tokenizer_morphodita::next_sentence(sentence& s, string& error) {
s.clear();
error.clear();
if (tokenizer->next_sentence(&forms, nullptr)) {
for (size_t i = 0; i < forms.size(); i++) {
s.add_word(string(forms[i].str, forms[i].len));
if (i+1 < forms.size() && forms[i+1].str == forms[i].str + forms[i].len)
s.words.back().misc.assign("SpaceAfter=No");
}
return true;
}
return false;
}
} // namespace udpipe
} // namespace ufal
<commit_msg>Make beam search of size 5 default.<commit_after>// This file is part of UDPipe <http://github.com/ufal/udpipe/>.
//
// Copyright 2015 Institute of Formal and Applied Linguistics, Faculty of
// Mathematics and Physics, Charles University in Prague, Czech Republic.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
#include <algorithm>
#include "common.h"
#include "model_morphodita_parsito.h"
#include "utils/parse_int.h"
namespace ufal {
namespace udpipe {
tokenizer* model_morphodita_parsito::new_tokenizer(const string& /*options*/) const {
return new tokenizer_morphodita(this);
}
bool model_morphodita_parsito::tag(sentence& s, const string& /*options*/, string& error) const {
error.clear();
tagger_cache* c = tagger_caches.pop();
if (!c) c = new tagger_cache();
c->forms.clear();
for (size_t i = 1; i < s.words.size(); i++)
c->forms.emplace_back(s.words[i].form.c_str(), s.words[i].form.size());
tagger->tag(c->forms, c->lemmas);
for (size_t i = 0; i < c->lemmas.size(); i++) {
// Lemma
s.words[i + 1].lemma.assign(c->lemmas[i].lemma);
// UPOSTag
size_t start = 0, end = min(c->lemmas[i].tag.find('|'), c->lemmas[i].tag.size());
s.words[i+1].upostag.assign(c->lemmas[i].tag, start, end - start);
// XPOSTag
start = min(end + 1, c->lemmas[i].tag.size());
end = min(c->lemmas[i].tag.find('|', start), c->lemmas[i].tag.size());
s.words[i+1].xpostag.assign(c->lemmas[i].tag, start, end - start);
// Features
start = min(end + 1, c->lemmas[i].tag.size());
s.words[i+1].feats.assign(c->lemmas[i].tag, start, c->lemmas[i].tag.size() - start);
}
tagger_caches.push(c);
return true;
}
bool model_morphodita_parsito::parse(sentence& s, const string& options, string& error) const {
error.clear();
parser_cache* c = parser_caches.pop();
if (!c) c = new parser_cache();
int beam_search = 5;
if (!named_values::parse(options, c->options, error))
return false;
if (c->options.count("beam_search"))
if (!parse_int(c->options["beam_search"], "beam_search", beam_search, error))
return false;
c->tree.clear();
for (size_t i = 1; i < s.words.size(); i++) {
c->tree.add_node(s.words[i].form);
c->tree.nodes.back().lemma.assign(s.words[i].lemma);
c->tree.nodes.back().upostag.assign(s.words[i].upostag);
c->tree.nodes.back().xpostag.assign(s.words[i].xpostag);
c->tree.nodes.back().feats.assign(s.words[i].feats);
c->tree.nodes.back().deps.assign(s.words[i].deps);
c->tree.nodes.back().misc.assign(s.words[i].misc);
}
parser->parse(c->tree, beam_search);
for (size_t i = 1; i < s.words.size(); i++)
s.set_head(i, c->tree.nodes[i].head, c->tree.nodes[i].deprel);
parser_caches.push(c);
return true;
}
model* model_morphodita_parsito::load(istream& is) {
char version;
if (!is.get(version)) return nullptr;
unique_ptr<model_morphodita_parsito> m(new model_morphodita_parsito());
if (!m) return nullptr;
m->tagger.reset(morphodita::tagger::load(is));
if (!m->tagger) return nullptr;
m->parser.reset(parsito::parser::load(is));
if (!m->parser) return nullptr;
return m.release();
}
model_morphodita_parsito::tokenizer_morphodita::tokenizer_morphodita(const model_morphodita_parsito* m)
: tokenizer(m->tagger->new_tokenizer()) {}
bool model_morphodita_parsito::tokenizer_morphodita::read_block(istream& is, string& block) const {
block.clear();
string line;
while (getline(is, line)) {
block.append(line).push_back('\n');
if (line.empty()) break;
}
return !block.empty();
}
void model_morphodita_parsito::tokenizer_morphodita::set_text(string_piece text, bool make_copy) {
tokenizer->set_text(text, make_copy);
}
bool model_morphodita_parsito::tokenizer_morphodita::next_sentence(sentence& s, string& error) {
s.clear();
error.clear();
if (tokenizer->next_sentence(&forms, nullptr)) {
for (size_t i = 0; i < forms.size(); i++) {
s.add_word(string(forms[i].str, forms[i].len));
if (i+1 < forms.size() && forms[i+1].str == forms[i].str + forms[i].len)
s.words.back().misc.assign("SpaceAfter=No");
}
return true;
}
return false;
}
} // namespace udpipe
} // namespace ufal
<|endoftext|> |
<commit_before>/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Module: FGSwitch.cpp
Author: Jon S. Berndt
Date started: 4/2000
------------- Copyright (C) 2000 -------------
This program is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the Free Software
Foundation; either version 2 of the License, or (at your option) any later
version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
details.
You should have received a copy of the GNU Lesser General Public License along with
this program; if not, write to the Free Software Foundation, Inc., 59 Temple
Place - Suite 330, Boston, MA 02111-1307, USA.
Further information about the GNU Lesser General Public License can also be found on
the world wide web at http://www.gnu.org.
FUNCTIONAL DESCRIPTION
--------------------------------------------------------------------------------
HISTORY
--------------------------------------------------------------------------------
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
COMMENTS, REFERENCES, and NOTES
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
The switch component is defined as follows (see the API documentation for more
information):
@code
<switch name="switch1">
<default value="{property|value}"/>
<test logic="{AND|OR}" value="{property|value}">
{property} {conditional} {property|value}
<test logic="{AND|OR}">
{property} {conditional} {property|value}
...
</test>
...
</test>
<test logic="{AND|OR}" value="{property|value}">
{property} {conditional} {property|value}
...
</test>
...
</switch>
@endcode
Also, see the header file (FGSwitch.h) for further details.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
INCLUDES
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
#include "FGSwitch.h"
#include <iostream>
using namespace std;
namespace JSBSim {
static const char *IdSrc = "$Id: FGSwitch.cpp,v 1.25 2012/12/02 12:59:19 bcoconni Exp $";
static const char *IdHdr = ID_SWITCH;
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
CLASS IMPLEMENTATION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
FGSwitch::FGSwitch(FGFCS* fcs, Element* element) : FGFCSComponent(fcs, element)
{
string value;
struct test *current_test;
Element *test_element;
FGFCSComponent::bind(); // Bind() this component here in case it is used
// in its own definition for a sample-and-hold
int num = element->GetNumElements("test");
if (element->FindElement("default")) num++;
tests.reserve(num);
test_element = element->FindElement("default");
if (test_element) {
current_test = new struct test;
current_test->condition = 0;
value = test_element->GetAttributeValue("value");
current_test->setTestValue(value, Name, PropertyManager);
current_test->Default = true;
tests.push_back(current_test);
}
test_element = element->FindElement("test");
while (test_element) {
current_test = new struct test;
current_test->condition = new FGCondition(test_element, PropertyManager);
value = test_element->GetAttributeValue("value");
current_test->setTestValue(value, Name, PropertyManager);
tests.push_back(current_test);
test_element = element->FindNextElement("test");
}
Debug(0);
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
FGSwitch::~FGSwitch()
{
for (unsigned int i=0; i<tests.size(); i++) {
delete tests[i]->condition;
delete tests[i]->OutputProp;
delete tests[i];
}
Debug(1);
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
bool FGSwitch::Run(void )
{
bool pass = false;
double default_output=0.0;
for (unsigned int i=0; i<tests.size(); i++) {
if (tests[i]->Default) {
default_output = tests[i]->GetValue();
} else {
pass = tests[i]->condition->Evaluate();
}
if (pass) {
Output = tests[i]->GetValue();
break;
}
}
if (!pass) Output = default_output;
if (delay != 0) Delay();
Clip();
if (IsOutput) SetOutput();
return true;
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
// The bitmasked value choices are as follows:
// unset: In this case (the default) JSBSim would only print
// out the normally expected messages, essentially echoing
// the config files as they are read. If the environment
// variable is not set, debug_lvl is set to 1 internally
// 0: This requests JSBSim not to output any messages
// whatsoever.
// 1: This value explicity requests the normal JSBSim
// startup messages
// 2: This value asks for a message to be printed out when
// a class is instantiated
// 4: When this value is set, a message is displayed when a
// FGModel object executes its Run() method
// 8: When this value is set, various runtime state variables
// are printed out periodically
// 16: When set various parameters are sanity checked and
// a message is printed out when they go out of bounds
void FGSwitch::Debug(int from)
{
string comp, scratch;
string indent = " ";
//bool first = false;
if (debug_lvl <= 0) return;
if (debug_lvl & 1) { // Standard console startup message output
if (from == 0) { // Constructor
for (unsigned int i=0; i<tests.size(); i++) {
if (tests[i]->Default) {
if (tests[i]->OutputProp == 0) {
cout << " Switch default value is: " << tests[i]->OutputVal;
} else {
cout << " Switch default value is: " << tests[i]->OutputProp->GetName();
}
} else {
if (tests[i]->OutputProp == 0) {
cout << " Switch takes test " << i << " value (" << tests[i]->OutputVal << ")" << endl;
} else {
cout << " Switch takes test " << i << " value (" << tests[i]->OutputProp->GetName() << ")" << endl;
}
tests[i]->condition->PrintCondition(" ");
}
cout << endl;
}
if (IsOutput) {
for (unsigned int i=0; i<OutputNodes.size(); i++)
cout << " OUTPUT: " << OutputNodes[i]->getName() << endl;
}
}
}
if (debug_lvl & 2 ) { // Instantiation/Destruction notification
if (from == 0) cout << "Instantiated: FGSwitch" << endl;
if (from == 1) cout << "Destroyed: FGSwitch" << endl;
}
if (debug_lvl & 4 ) { // Run() method entry print for FGModel-derived objects
}
if (debug_lvl & 8 ) { // Runtime state variables
}
if (debug_lvl & 16) { // Sanity checking
}
if (debug_lvl & 64) {
if (from == 0) { // Constructor
cout << IdSrc << endl;
cout << IdHdr << endl;
}
}
}
} //namespace JSBSim
<commit_msg>Added the delay code to the switch<commit_after>/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Module: FGSwitch.cpp
Author: Jon S. Berndt
Date started: 4/2000
------------- Copyright (C) 2000 -------------
This program is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the Free Software
Foundation; either version 2 of the License, or (at your option) any later
version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
details.
You should have received a copy of the GNU Lesser General Public License along with
this program; if not, write to the Free Software Foundation, Inc., 59 Temple
Place - Suite 330, Boston, MA 02111-1307, USA.
Further information about the GNU Lesser General Public License can also be found on
the world wide web at http://www.gnu.org.
FUNCTIONAL DESCRIPTION
--------------------------------------------------------------------------------
HISTORY
--------------------------------------------------------------------------------
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
COMMENTS, REFERENCES, and NOTES
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
The switch component is defined as follows (see the API documentation for more
information):
@code
<switch name="switch1">
<default value="{property|value}"/>
<test logic="{AND|OR}" value="{property|value}">
{property} {conditional} {property|value}
<test logic="{AND|OR}">
{property} {conditional} {property|value}
...
</test>
...
</test>
<test logic="{AND|OR}" value="{property|value}">
{property} {conditional} {property|value}
...
</test>
...
</switch>
@endcode
Also, see the header file (FGSwitch.h) for further details.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
INCLUDES
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
#include "FGSwitch.h"
#include <iostream>
using namespace std;
namespace JSBSim {
static const char *IdSrc = "$Id: FGSwitch.cpp,v 1.26 2013/11/17 05:11:03 jberndt Exp $";
static const char *IdHdr = ID_SWITCH;
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
CLASS IMPLEMENTATION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
FGSwitch::FGSwitch(FGFCS* fcs, Element* element) : FGFCSComponent(fcs, element)
{
string value;
struct test *current_test;
Element *test_element;
FGFCSComponent::bind(); // Bind() this component here in case it is used
// in its own definition for a sample-and-hold
int num = element->GetNumElements("test");
if (element->FindElement("default")) num++;
tests.reserve(num);
test_element = element->FindElement("default");
if (test_element) {
current_test = new struct test;
current_test->condition = 0;
value = test_element->GetAttributeValue("value");
current_test->setTestValue(value, Name, PropertyManager);
current_test->Default = true;
if (delay > 0 && is_number(value)) { // If there is a delay, initialize the
for (int i=0; i<delay-1; i++) { // delay buffer to the default value
output_array[i] = atof(value.c_str()); // for the switch if that value is a number.
}
}
tests.push_back(current_test);
}
test_element = element->FindElement("test");
while (test_element) {
current_test = new struct test;
current_test->condition = new FGCondition(test_element, PropertyManager);
value = test_element->GetAttributeValue("value");
current_test->setTestValue(value, Name, PropertyManager);
tests.push_back(current_test);
test_element = element->FindNextElement("test");
}
Debug(0);
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
FGSwitch::~FGSwitch()
{
for (unsigned int i=0; i<tests.size(); i++) {
delete tests[i]->condition;
delete tests[i]->OutputProp;
delete tests[i];
}
Debug(1);
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
bool FGSwitch::Run(void )
{
bool pass = false;
double default_output=0.0;
for (unsigned int i=0; i<tests.size(); i++) {
if (tests[i]->Default) {
default_output = tests[i]->GetValue();
} else {
pass = tests[i]->condition->Evaluate();
}
if (pass) {
Output = tests[i]->GetValue();
break;
}
}
if (!pass) Output = default_output;
if (delay != 0) Delay();
Clip();
if (IsOutput) SetOutput();
return true;
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
// The bitmasked value choices are as follows:
// unset: In this case (the default) JSBSim would only print
// out the normally expected messages, essentially echoing
// the config files as they are read. If the environment
// variable is not set, debug_lvl is set to 1 internally
// 0: This requests JSBSim not to output any messages
// whatsoever.
// 1: This value explicity requests the normal JSBSim
// startup messages
// 2: This value asks for a message to be printed out when
// a class is instantiated
// 4: When this value is set, a message is displayed when a
// FGModel object executes its Run() method
// 8: When this value is set, various runtime state variables
// are printed out periodically
// 16: When set various parameters are sanity checked and
// a message is printed out when they go out of bounds
void FGSwitch::Debug(int from)
{
string comp, scratch;
string indent = " ";
//bool first = false;
if (debug_lvl <= 0) return;
if (debug_lvl & 1) { // Standard console startup message output
if (from == 0) { // Constructor
for (unsigned int i=0; i<tests.size(); i++) {
if (tests[i]->Default) {
if (tests[i]->OutputProp == 0) {
cout << " Switch default value is: " << tests[i]->OutputVal;
} else {
cout << " Switch default value is: " << tests[i]->OutputProp->GetName();
}
} else {
if (tests[i]->OutputProp == 0) {
cout << " Switch takes test " << i << " value (" << tests[i]->OutputVal << ")" << endl;
} else {
cout << " Switch takes test " << i << " value (" << tests[i]->OutputProp->GetName() << ")" << endl;
}
tests[i]->condition->PrintCondition(" ");
}
cout << endl;
}
if (IsOutput) {
for (unsigned int i=0; i<OutputNodes.size(); i++)
cout << " OUTPUT: " << OutputNodes[i]->getName() << endl;
}
}
}
if (debug_lvl & 2 ) { // Instantiation/Destruction notification
if (from == 0) cout << "Instantiated: FGSwitch" << endl;
if (from == 1) cout << "Destroyed: FGSwitch" << endl;
}
if (debug_lvl & 4 ) { // Run() method entry print for FGModel-derived objects
}
if (debug_lvl & 8 ) { // Runtime state variables
}
if (debug_lvl & 16) { // Sanity checking
}
if (debug_lvl & 64) {
if (from == 0) { // Constructor
cout << IdSrc << endl;
cout << IdHdr << endl;
}
}
}
} //namespace JSBSim
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Visualization Library
Module: Object.hh
Language: C++
Date: $Date$
Version: $Revision$
This file is part of the Visualization Library. No part of this file or its
contents may be copied, reproduced or altered in any way without the express
written consent of the authors.
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994
=========================================================================*/
//
// Common abstract class for Visualization Library. Maintains debug
// flag, reference counting, modified time, and other common
// functions/parameters.
//
#ifndef __vlObject_hh
#define __vlObject_hh
#include <iostream.h>
#include "TimeSt.hh"
#include "SetGet.hh"
#include "Indent.hh"
#include "PrintLst.hh"
//
// Common #defines / parameters
//
//
// Class definition
//
class vlObject
{
public:
vlObject();
virtual ~vlObject();
void Register(void* p);
void UnRegister(void* p);
int GetRefCount() {return this->RefCount;};
void DebugOn();
void DebugOff();
virtual unsigned long int GetMTime() {return this->MTime.GetMTime();};
int GetDebug();
void Modified() {MTime.Modified();};
virtual char *GetClassName() {return "vlObject";};
void Print(ostream& os);
virtual void PrintHeader(ostream& os, vlIndent indent);
virtual void PrintSelf(ostream& os, vlIndent indent);
int ShouldIPrint(char *a) { return this->PrintList.ShouldIPrint(a);};
virtual void PrintTrailer(ostream& os, vlIndent indent);
void PrintWatchOn() {this->PrintList.ActiveOn();};
void PrintWatchOff() {this->PrintList.ActiveOff();};
protected:
int Debug; // Enable debug messages
vlTimeStamp MTime; // Keep track of modification time
private:
int RefCount; // Number of uses of this object by other objects
vlPrintList PrintList;
friend ostream& operator<<(ostream& os, vlObject& o) {o.Print(os);return os;}
};
#endif
<commit_msg>Made the ostream friend function not inline<commit_after>/*=========================================================================
Program: Visualization Library
Module: Object.hh
Language: C++
Date: $Date$
Version: $Revision$
This file is part of the Visualization Library. No part of this file or its
contents may be copied, reproduced or altered in any way without the express
written consent of the authors.
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994
=========================================================================*/
//
// Common abstract class for Visualization Library. Maintains debug
// flag, reference counting, modified time, and other common
// functions/parameters.
//
#ifndef __vlObject_hh
#define __vlObject_hh
#include <iostream.h>
#include "TimeSt.hh"
#include "SetGet.hh"
#include "Indent.hh"
#include "PrintLst.hh"
//
// Common #defines / parameters
//
//
// Class definition
//
class vlObject
{
public:
vlObject();
virtual ~vlObject();
void Register(void* p);
void UnRegister(void* p);
int GetRefCount() {return this->RefCount;};
void DebugOn();
void DebugOff();
virtual unsigned long int GetMTime() {return this->MTime.GetMTime();};
int GetDebug();
void Modified() {MTime.Modified();};
virtual char *GetClassName() {return "vlObject";};
void Print(ostream& os);
virtual void PrintHeader(ostream& os, vlIndent indent);
virtual void PrintSelf(ostream& os, vlIndent indent);
int ShouldIPrint(char *a) { return this->PrintList.ShouldIPrint(a);};
virtual void PrintTrailer(ostream& os, vlIndent indent);
void PrintWatchOn() {this->PrintList.ActiveOn();};
void PrintWatchOff() {this->PrintList.ActiveOff();};
protected:
int Debug; // Enable debug messages
vlTimeStamp MTime; // Keep track of modification time
private:
int RefCount; // Number of uses of this object by other objects
vlPrintList PrintList;
friend ostream& operator<<(ostream& os, vlObject& o);
};
#endif
<|endoftext|> |
<commit_before><commit_msg>imgproc: use target type for calculations<commit_after><|endoftext|> |
<commit_before>#pragma once
#include "../widget.hpp"
#include "../container.hpp"
#include "../base/oriented_widget.hpp"
namespace morda{
/**
* @brief Scrollable list widget.
* This is a base class for vertical and horizontal lists.
*/
class list_widget :
// NOTE: order of virtual public and private declarations here matters for clang due to some bug,
// see http://stackoverflow.com/questions/42427145/clang-cannot-cast-to-private-base-while-there-is-a-public-virtual-inheritance
virtual public widget,
private container,
protected oriented_widget
{
// index of the first item added to container as child
size_t added_index = size_t(-1);
size_t pos_index = 0; // index of the first visible item
real pos_offset = real(0); // offset in pixels of the first visible item
size_t num_tail_items = 0; // Zero means that number of tail items has to be recomputed
size_t first_tail_item_index = 0;
real first_tail_item_offset = real(0);
protected:
list_widget(std::shared_ptr<morda::context> c, const puu::forest& desc, bool vertical);
public:
list_widget(const list_widget&) = delete;
list_widget& operator=(const list_widget&) = delete;
/**
* @brief list items provider.
* User should subclass this class to provide items to the list.
*/
class provider : virtual public utki::shared{
friend class list_widget;
list_widget* parent_list = nullptr;
protected:
provider(){}
public:
/**
* @brief Get parent list widget.
* @return list widget which owns the provider, in case the provider is set to some list widget.
* @return nullptr in case the provider is not set to any list widget.
*/
list_widget* get_list()noexcept{
return this->parent_list;
}
/**
* @brief Get total number of items in the list.
* @return Number of items in the list.
*/
virtual size_t count()const noexcept = 0;
/**
* @brief Get widget for item.
* @param index - index of item to get widget for.
* @return widget for the requested item.
*/
virtual std::shared_ptr<widget> get_widget(size_t index) = 0;
/**
* @brief Recycle widget of item.
* @param index - index of item to recycle widget of.
* @param w - widget to recycle.
*/
virtual void recycle(size_t index, std::shared_ptr<widget> w){}
void notify_data_set_change();
};
void set_provider(std::shared_ptr<provider> item_provider = nullptr);
void lay_out()override;
morda::vector2 measure(const morda::vector2& quotum) const override;
/**
* @brief Set scroll position as factor from [0:1].
* @param factor - factor of the scroll position to set.
*/
void set_scroll_factor(real factor);
/**
* @brief Get scroll factor.
* @return Current scroll position as factor from [0:1].
*/
real get_scroll_factor()const noexcept;
/**
* @brief Scroll the list by given number of pixels.
* @param delta - number of pixels to scroll, can be positive or negative.
*/
void scroll_by(real delta);
/**
* @brief Data set changed signal.
* Emitted when list widget contents have actually been updated due to change in provider's model data set.
*/
std::function<void(list_widget&)> data_set_change_handler;
private:
std::shared_ptr<provider> item_provider;
void update_children_list();
// returns true if it was the last visible widget
bool arrange_widget(
std::shared_ptr<widget>& w,
real& pos,
bool add,
size_t index,
widget_list::const_iterator& insertBefore
);
void update_tail_items_info();
void handle_data_set_changed();
};
/**
* @brief Horizontal list widget.
* Panorama list widget.
* From GUI script it can be instantiated as "pan_list".
*/
class pan_list : public list_widget{
public:
pan_list(std::shared_ptr<morda::context> c, const puu::forest& desc) :
widget(std::move(c), desc),
list_widget(this->context, desc, false)
{}
pan_list(const pan_list&) = delete;
pan_list& operator=(const pan_list&) = delete;
};
/**
* @brief Vertical list widget.
* From GUI script it can be instantiated as "list".
*/
class list : public list_widget{
public:
list(std::shared_ptr<morda::context> c, const puu::forest& desc) :
widget(std::move(c), desc),
list_widget(this->context, desc, true)
{}
list(const list&) = delete;
list& operator=(const list&) = delete;
};
}
<commit_msg>add list::get_pos_index()/get_pos_offset()<commit_after>#pragma once
#include "../widget.hpp"
#include "../container.hpp"
#include "../base/oriented_widget.hpp"
namespace morda{
/**
* @brief Scrollable list widget.
* This is a base class for vertical and horizontal lists.
*/
class list_widget :
// NOTE: order of virtual public and private declarations here matters for clang due to some bug,
// see http://stackoverflow.com/questions/42427145/clang-cannot-cast-to-private-base-while-there-is-a-public-virtual-inheritance
virtual public widget,
private container,
protected oriented_widget
{
// index of the first item added to container as child
size_t added_index = size_t(-1);
size_t pos_index = 0; // index of the first visible item
// offset in pixels of the first visible item.
// the value is positive, tough the item is biased towards negative coordinate values.
real pos_offset = real(0);
size_t num_tail_items = 0; // Zero means that number of tail items has to be recomputed
size_t first_tail_item_index = 0;
real first_tail_item_offset = real(0);
protected:
list_widget(std::shared_ptr<morda::context> c, const puu::forest& desc, bool vertical);
public:
list_widget(const list_widget&) = delete;
list_widget& operator=(const list_widget&) = delete;
/**
* @brief list items provider.
* User should subclass this class to provide items to the list.
*/
class provider : virtual public utki::shared{
friend class list_widget;
list_widget* parent_list = nullptr;
protected:
provider(){}
public:
/**
* @brief Get parent list widget.
* @return list widget which owns the provider, in case the provider is set to some list widget.
* @return nullptr in case the provider is not set to any list widget.
*/
list_widget* get_list()noexcept{
return this->parent_list;
}
/**
* @brief Get total number of items in the list.
* @return Number of items in the list.
*/
virtual size_t count()const noexcept = 0;
/**
* @brief Get widget for item.
* @param index - index of item to get widget for.
* @return widget for the requested item.
*/
virtual std::shared_ptr<widget> get_widget(size_t index) = 0;
/**
* @brief Recycle widget of item.
* @param index - index of item to recycle widget of.
* @param w - widget to recycle.
*/
virtual void recycle(size_t index, std::shared_ptr<widget> w){}
void notify_data_set_change();
};
void set_provider(std::shared_ptr<provider> item_provider = nullptr);
void lay_out()override;
morda::vector2 measure(const morda::vector2& quotum) const override;
/**
* @brief Set scroll position as factor from [0:1].
* @param factor - factor of the scroll position to set.
*/
void set_scroll_factor(real factor);
/**
* @brief Get scroll factor.
* @return Current scroll position as factor from [0:1].
*/
real get_scroll_factor()const noexcept;
/**
* @brief Get index of the first visible item.
* @return index of the first visible item.
*/
size_t get_pos_index()const noexcept{
return this->pos_index;
}
/**
* @brief Get offset of the first visible item.
* The value is positive, though the item coordinate is <= 0.
* @return offset in pixels of the first visible item.
*/
real get_pos_offset()const noexcept{
return this->pos_offset;
}
/**
* @brief Scroll the list by given number of pixels.
* @param delta - number of pixels to scroll, can be positive or negative.
*/
void scroll_by(real delta);
/**
* @brief Data set changed signal.
* Emitted when list widget contents have actually been updated due to change in provider's model data set.
*/
std::function<void(list_widget&)> data_set_change_handler;
private:
std::shared_ptr<provider> item_provider;
void update_children_list();
// returns true if it was the last visible widget
bool arrange_widget(
std::shared_ptr<widget>& w,
real& pos,
bool add,
size_t index,
widget_list::const_iterator& insertBefore
);
void update_tail_items_info();
void handle_data_set_changed();
};
/**
* @brief Horizontal list widget.
* Panorama list widget.
* From GUI script it can be instantiated as "pan_list".
*/
class pan_list : public list_widget{
public:
pan_list(std::shared_ptr<morda::context> c, const puu::forest& desc) :
widget(std::move(c), desc),
list_widget(this->context, desc, false)
{}
pan_list(const pan_list&) = delete;
pan_list& operator=(const pan_list&) = delete;
};
/**
* @brief Vertical list widget.
* From GUI script it can be instantiated as "list".
*/
class list : public list_widget{
public:
list(std::shared_ptr<morda::context> c, const puu::forest& desc) :
widget(std::move(c), desc),
list_widget(this->context, desc, true)
{}
list(const list&) = delete;
list& operator=(const list&) = delete;
};
}
<|endoftext|> |
<commit_before>#include <stdio.h>
#include "gtest/gtest.h"
#include "gmock/gmock.h"
#include "os/os.h"
#include "nmranet/GlobalEventHandler.hxx"
#include "nmranet/NMRAnetEventRegistry.hxx"
using testing::Eq;
using testing::Field;
using testing::InSequence;
using testing::Invoke;
using testing::InvokeWithoutArgs;
using testing::StrictMock;
using testing::WithArg;
using testing::_;
static ThreadExecutor global_executor("ex_thread", 0, 1024);
extern void DecodeRange(EventReport* r);
class DecodeRangeTest : public testing::Test {
protected:
void ExpectDecode(uint64_t complex, uint64_t exp_event, uint64_t exp_mask) {
EventReport r;
r.event = complex;
DecodeRange(&r);
EXPECT_EQ(exp_event, r.event);
EXPECT_EQ(exp_mask, r.mask);
}
uint64_t eventid_;
uint64_t mask_;
};
TEST_F(DecodeRangeTest, TrivPositive) { ExpectDecode(0b1100, 0b1100, 0b0011); }
TEST_F(DecodeRangeTest, TrivNegative) {
ExpectDecode(0b110011, 0b110000, 0b0011);
}
TEST_F(DecodeRangeTest, SimplePositive) {
ExpectDecode(0b1010101110000, 0b1010101110000, 0b1111);
}
TEST_F(DecodeRangeTest, SimpleNegative) {
ExpectDecode(0b101010111000011111, 0b101010111000000000, 0b11111);
}
TEST_F(DecodeRangeTest, LongPositive) {
ExpectDecode(0xfffffffffffffff0ULL, 0xfffffffffffffff0ULL, 0xf);
}
TEST_F(DecodeRangeTest, LongNegative) {
ExpectDecode(0xffffffffffffff0fULL, 0xffffffffffffff00ULL, 0xf);
}
class MockEventHandler : public NMRAnetEventHandler {
public:
#define DEFPROXYFN(FN) \
MOCK_METHOD2(FN, void(EventReport* event, Notifiable* done))
DEFPROXYFN(HandleEventReport);
DEFPROXYFN(HandleConsumerIdentified);
DEFPROXYFN(HandleConsumerRangeIdentified);
DEFPROXYFN(HandleProducerIdentified);
DEFPROXYFN(HandleProducerRangeIdentified);
DEFPROXYFN(HandleIdentifyGlobal);
DEFPROXYFN(HandleIdentifyConsumer);
DEFPROXYFN(HandleIdentifyProducer);
#undef DEFPROXYFN
};
static void InvokeNotification(Notifiable* done) { done->Notify(); }
static const uint64_t kExitEventId = 0x0808080804040404ULL;
static const uint64_t kTestEventId = 0x0102030405060708ULL;
static const int kEventReportMti = 0x5b4;
static const int kProducerIdentifiedResvdMti = 0x546;
class EventHandlerTests : public ::testing::Test {
protected:
EventHandlerTests() : flow_(&global_executor, 10) {
for (auto* h : {&h1_, &h2_, &h3_, &h4_}) {
EXPECT_CALL(*h, HandleProducerIdentified(
Field(&EventReport::event, kExitEventId), _))
.WillRepeatedly(
DoAll(WithArg<1>(Invoke(&InvokeNotification)),
InvokeWithoutArgs(
this, &EventHandlerTests::InvokeExitNotification)));
}
}
void InvokeExitNotification() { exit_notify_.Notify(); }
void WaitForCompleted() {
GlobalEventMessage* m = flow_.AllocateMessage();
m = flow_.AllocateMessage();
m->mti = kProducerIdentifiedResvdMti;
m->event = kExitEventId;
m->dst_node = 0;
m->src_node = {0, 0};
flow_.PostEvent(m);
exit_notify_.WaitForNotification();
while (!flow_.executor()->empty()) usleep(100);
}
StrictMock<MockEventHandler> h1_;
StrictMock<MockEventHandler> h2_;
StrictMock<MockEventHandler> h3_;
StrictMock<MockEventHandler> h4_;
GlobalEventFlow flow_;
SyncNotifiable exit_notify_;
};
TEST_F(EventHandlerTests, SimpleRunTest) {
NMRAnetEventRegistry::instance()->RegisterHandler(&h1_, 0, 0);
NMRAnetEventRegistry::instance()->RegisterHandler(&h2_, 0, 0);
EXPECT_CALL(h1_, HandleEventReport(_, _))
.WillOnce(WithArg<1>(Invoke(&InvokeNotification)));
EXPECT_CALL(h2_, HandleEventReport(_, _))
.WillOnce(WithArg<1>(Invoke(&InvokeNotification)));
GlobalEventMessage* m = flow_.AllocateMessage();
m->mti = kEventReportMti;
m->event = kTestEventId;
m->dst_node = 0;
m->src_node = {0, 0};
flow_.PostEvent(m);
WaitForCompleted();
}
TEST_F(EventHandlerTests, SimpleRunTest2) {
NMRAnetEventRegistry::instance()->RegisterHandler(&h1_, 0, 0);
NMRAnetEventRegistry::instance()->RegisterHandler(&h2_, 0, 0);
EXPECT_CALL(h1_, HandleEventReport(_, _))
.WillOnce(WithArg<1>(Invoke(&InvokeNotification)));
EXPECT_CALL(h2_, HandleEventReport(_, _))
.WillOnce(WithArg<1>(Invoke(&InvokeNotification)));
GlobalEventMessage* m = flow_.AllocateMessage();
m->mti = kEventReportMti;
m->event = 0x0102030405060708ULL;
m->dst_node = 0;
m->src_node = {0, 0};
flow_.PostEvent(m);
WaitForCompleted();
}
TEST_F(EventHandlerTests, Run100EventsTest) {
NMRAnetEventRegistry::instance()->RegisterHandler(&h1_, 0, 0);
NMRAnetEventRegistry::instance()->RegisterHandler(&h2_, 0, 0);
EXPECT_CALL(h1_, HandleEventReport(_, _)).Times(100).WillRepeatedly(
WithArg<1>(Invoke(&InvokeNotification)));
EXPECT_CALL(h2_, HandleEventReport(_, _)).Times(100).WillRepeatedly(
WithArg<1>(Invoke(&InvokeNotification)));
for (int i = 0; i < 100; i++) {
GlobalEventMessage* m = flow_.AllocateMessage();
m->mti = kEventReportMti;
m->event = 0x0102030405060708ULL;
m->dst_node = 0;
m->src_node = {0, 0};
flow_.PostEvent(m);
}
WaitForCompleted();
}
TEST_F(EventHandlerTests, EventsOrderTest) {
NMRAnetEventRegistry::instance()->RegisterHandler(&h1_, 0, 0);
{
InSequence s;
EXPECT_CALL(
h1_, HandleEventReport(Field(&EventReport::event, kTestEventId + 0), _))
.WillOnce(WithArg<1>(Invoke(&InvokeNotification)));
EXPECT_CALL(
h1_, HandleEventReport(Field(&EventReport::event, kTestEventId + 1), _))
.WillOnce(WithArg<1>(Invoke(&InvokeNotification)));
EXPECT_CALL(
h1_, HandleEventReport(Field(&EventReport::event, kTestEventId + 2), _))
.WillOnce(WithArg<1>(Invoke(&InvokeNotification)));
}
event_handler_mutex.Lock();
for (int i = 0; i < 3; i++) {
GlobalEventMessage* m = flow_.AllocateMessage();
m->mti = kEventReportMti;
m->event = kTestEventId + i;
m->dst_node = 0;
m->src_node = {0, 0};
flow_.PostEvent(m);
}
event_handler_mutex.Unlock();
WaitForCompleted();
}
int appl_main(int argc, char* argv[]) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
<commit_msg>Makes use of the new test_main.hxx in the global event handler test.<commit_after>#include "utils/test_main.hxx"
#include "nmranet/GlobalEventHandler.hxx"
#include "nmranet/NMRAnetEventRegistry.hxx"
using testing::Eq;
using testing::Field;
using testing::InSequence;
using testing::Invoke;
using testing::InvokeWithoutArgs;
using testing::StrictMock;
using testing::WithArg;
using testing::_;
static ThreadExecutor global_executor("ex_thread", 0, 1024);
extern void DecodeRange(EventReport* r);
class DecodeRangeTest : public testing::Test {
protected:
void ExpectDecode(uint64_t complex, uint64_t exp_event, uint64_t exp_mask) {
EventReport r;
r.event = complex;
DecodeRange(&r);
EXPECT_EQ(exp_event, r.event);
EXPECT_EQ(exp_mask, r.mask);
}
uint64_t eventid_;
uint64_t mask_;
};
TEST_F(DecodeRangeTest, TrivPositive) { ExpectDecode(0b1100, 0b1100, 0b0011); }
TEST_F(DecodeRangeTest, TrivNegative) {
ExpectDecode(0b110011, 0b110000, 0b0011);
}
TEST_F(DecodeRangeTest, SimplePositive) {
ExpectDecode(0b1010101110000, 0b1010101110000, 0b1111);
}
TEST_F(DecodeRangeTest, SimpleNegative) {
ExpectDecode(0b101010111000011111, 0b101010111000000000, 0b11111);
}
TEST_F(DecodeRangeTest, LongPositive) {
ExpectDecode(0xfffffffffffffff0ULL, 0xfffffffffffffff0ULL, 0xf);
}
TEST_F(DecodeRangeTest, LongNegative) {
ExpectDecode(0xffffffffffffff0fULL, 0xffffffffffffff00ULL, 0xf);
}
class MockEventHandler : public NMRAnetEventHandler {
public:
#define DEFPROXYFN(FN) \
MOCK_METHOD2(FN, void(EventReport* event, Notifiable* done))
DEFPROXYFN(HandleEventReport);
DEFPROXYFN(HandleConsumerIdentified);
DEFPROXYFN(HandleConsumerRangeIdentified);
DEFPROXYFN(HandleProducerIdentified);
DEFPROXYFN(HandleProducerRangeIdentified);
DEFPROXYFN(HandleIdentifyGlobal);
DEFPROXYFN(HandleIdentifyConsumer);
DEFPROXYFN(HandleIdentifyProducer);
#undef DEFPROXYFN
};
static void InvokeNotification(Notifiable* done) { done->Notify(); }
static const uint64_t kExitEventId = 0x0808080804040404ULL;
static const uint64_t kTestEventId = 0x0102030405060708ULL;
static const int kEventReportMti = 0x5b4;
static const int kProducerIdentifiedResvdMti = 0x546;
class EventHandlerTests : public ::testing::Test {
protected:
EventHandlerTests() : flow_(&global_executor, 10) {
for (auto* h : {&h1_, &h2_, &h3_, &h4_}) {
EXPECT_CALL(*h, HandleProducerIdentified(
Field(&EventReport::event, kExitEventId), _))
.WillRepeatedly(
DoAll(WithArg<1>(Invoke(&InvokeNotification)),
InvokeWithoutArgs(
this, &EventHandlerTests::InvokeExitNotification)));
}
}
void InvokeExitNotification() { exit_notify_.Notify(); }
void WaitForCompleted() {
GlobalEventMessage* m = flow_.AllocateMessage();
m = flow_.AllocateMessage();
m->mti = kProducerIdentifiedResvdMti;
m->event = kExitEventId;
m->dst_node = 0;
m->src_node = {0, 0};
flow_.PostEvent(m);
exit_notify_.WaitForNotification();
while (!flow_.executor()->empty()) usleep(100);
}
StrictMock<MockEventHandler> h1_;
StrictMock<MockEventHandler> h2_;
StrictMock<MockEventHandler> h3_;
StrictMock<MockEventHandler> h4_;
GlobalEventFlow flow_;
SyncNotifiable exit_notify_;
};
TEST_F(EventHandlerTests, SimpleRunTest) {
NMRAnetEventRegistry::instance()->RegisterHandler(&h1_, 0, 0);
NMRAnetEventRegistry::instance()->RegisterHandler(&h2_, 0, 0);
EXPECT_CALL(h1_, HandleEventReport(_, _))
.WillOnce(WithArg<1>(Invoke(&InvokeNotification)));
EXPECT_CALL(h2_, HandleEventReport(_, _))
.WillOnce(WithArg<1>(Invoke(&InvokeNotification)));
GlobalEventMessage* m = flow_.AllocateMessage();
m->mti = kEventReportMti;
m->event = kTestEventId;
m->dst_node = 0;
m->src_node = {0, 0};
flow_.PostEvent(m);
WaitForCompleted();
}
TEST_F(EventHandlerTests, SimpleRunTest2) {
NMRAnetEventRegistry::instance()->RegisterHandler(&h1_, 0, 0);
NMRAnetEventRegistry::instance()->RegisterHandler(&h2_, 0, 0);
EXPECT_CALL(h1_, HandleEventReport(_, _))
.WillOnce(WithArg<1>(Invoke(&InvokeNotification)));
EXPECT_CALL(h2_, HandleEventReport(_, _))
.WillOnce(WithArg<1>(Invoke(&InvokeNotification)));
GlobalEventMessage* m = flow_.AllocateMessage();
m->mti = kEventReportMti;
m->event = 0x0102030405060708ULL;
m->dst_node = 0;
m->src_node = {0, 0};
flow_.PostEvent(m);
WaitForCompleted();
}
TEST_F(EventHandlerTests, Run100EventsTest) {
NMRAnetEventRegistry::instance()->RegisterHandler(&h1_, 0, 0);
NMRAnetEventRegistry::instance()->RegisterHandler(&h2_, 0, 0);
EXPECT_CALL(h1_, HandleEventReport(_, _)).Times(100).WillRepeatedly(
WithArg<1>(Invoke(&InvokeNotification)));
EXPECT_CALL(h2_, HandleEventReport(_, _)).Times(100).WillRepeatedly(
WithArg<1>(Invoke(&InvokeNotification)));
for (int i = 0; i < 100; i++) {
GlobalEventMessage* m = flow_.AllocateMessage();
m->mti = kEventReportMti;
m->event = 0x0102030405060708ULL;
m->dst_node = 0;
m->src_node = {0, 0};
flow_.PostEvent(m);
}
WaitForCompleted();
}
TEST_F(EventHandlerTests, EventsOrderTest) {
NMRAnetEventRegistry::instance()->RegisterHandler(&h1_, 0, 0);
{
InSequence s;
EXPECT_CALL(
h1_, HandleEventReport(Field(&EventReport::event, kTestEventId + 0), _))
.WillOnce(WithArg<1>(Invoke(&InvokeNotification)));
EXPECT_CALL(
h1_, HandleEventReport(Field(&EventReport::event, kTestEventId + 1), _))
.WillOnce(WithArg<1>(Invoke(&InvokeNotification)));
EXPECT_CALL(
h1_, HandleEventReport(Field(&EventReport::event, kTestEventId + 2), _))
.WillOnce(WithArg<1>(Invoke(&InvokeNotification)));
}
event_handler_mutex.Lock();
for (int i = 0; i < 3; i++) {
GlobalEventMessage* m = flow_.AllocateMessage();
m->mti = kEventReportMti;
m->event = kTestEventId + i;
m->dst_node = 0;
m->src_node = {0, 0};
flow_.PostEvent(m);
}
event_handler_mutex.Unlock();
WaitForCompleted();
}
<|endoftext|> |
<commit_before>/*Copyright (c) 2011, Edgar Solomonik, all rights reserved.*/
#ifndef __CTF_HPP__
#define __CTF_HPP__
#include "mpi.h"
#include <stdio.h>
#include <stdint.h>
#include <vector>
#include <map>
#include <set>
#include <deque>
#include <complex>
#include <assert.h>
#define CTF_VERSION 131
#include "../src/interface/tensor.h"
#include "../src/interface/idx_tensor.h"
#include "../src/interface/timer.h"
#include "../src/interface/back_comp.h"
#endif
<commit_msg>increment version to 1.32<commit_after>/*Copyright (c) 2011, Edgar Solomonik, all rights reserved.*/
#ifndef __CTF_HPP__
#define __CTF_HPP__
#include "mpi.h"
#include <stdio.h>
#include <stdint.h>
#include <vector>
#include <map>
#include <set>
#include <deque>
#include <complex>
#include <assert.h>
#define CTF_VERSION 132
#include "../src/interface/tensor.h"
#include "../src/interface/idx_tensor.h"
#include "../src/interface/timer.h"
#include "../src/interface/back_comp.h"
#endif
<|endoftext|> |
<commit_before><commit_msg>Start: [skip ci] replace QTextStream and its manipulators with stringstream to avoid deprecation warnings with Qt 5.15<commit_after><|endoftext|> |
<commit_before>#pragma once
#include <vector>
#include <tuple>
#include <utility>
namespace helene
{
namespace soa_detail
{
template <class MemberPointerType>
struct deduce_member_pointer;
template <class MemberType, class ObjectType>
struct deduce_member_pointer<MemberType ObjectType::*>
{
typedef MemberType member_type;
typedef ObjectType object_type;
};
template <class MemberPointerType>
using member_type_t =
typename deduce_member_pointer<MemberPointerType>::member_type;
template <class MemberPointerType>
using object_type_t =
typename deduce_member_pointer<MemberPointerType>::object_type;
}
template <class PointerType, PointerType PointerValue>
struct member_reference
{
static constexpr PointerType pointer_value = PointerValue;
};
template <class T, class... MemberRefs>
class element_proxy;
template <class T, class... PointerTypes, PointerTypes... PointerValues>
class element_proxy<T, member_reference<PointerTypes, PointerValues>...>
{
typedef std::tuple<soa_detail::member_type_t<PointerTypes>*...> tuple_type;
template <std::size_t S, class FirstRef, class... RestRefs>
struct assignment_helper
{
static void
assign(std::tuple<soa_detail::member_type_t<PointerTypes>*...>& tpl,
const T& value)
{
*std::get<S>(tpl) = value.*FirstRef::pointer_value;
assignment_helper<S + 1, RestRefs...>::assign(tpl, value);
}
};
template <std::size_t S, class LastRef>
struct assignment_helper<S, LastRef>
{
static void
assign(std::tuple<soa_detail::member_type_t<PointerTypes>*...>& tpl,
const T& value)
{
*std::get<S>(tpl) = value.*LastRef::pointer_value;
}
};
template <std::size_t S, class FirstRef, class... RestRefs>
struct make_helper
{
static void
apply(T& v, const tuple_type& tpl)
{
v.*FirstRef::pointer_value = *std::get<S>(tpl);
make_helper<S + 1, RestRefs...>::apply(v, tpl);
}
};
template <std::size_t S, class LastRef>
struct make_helper<S, LastRef>
{
static void
apply(T& v, const tuple_type& tpl)
{
v.*LastRef::pointer_value = *std::get<S>(tpl);
}
};
public:
element_proxy(soa_detail::member_type_t<PointerTypes>&... args)
: pointers_(&args...)
{
}
operator T() const
{
T out{};
make_helper<0, member_reference<PointerTypes, PointerValues>...>::apply(
out, pointers_);
return out;
}
element_proxy&
operator=(const T& value)
{
assignment_helper<0, member_reference<PointerTypes, PointerValues>...>::
assign(pointers_, value);
return *this;
}
private:
tuple_type pointers_;
};
// helper to access respective parents that are multiply inherited
template <class FirstParent, class... RestParents>
struct parent_helper
{
template <class SoaType>
static std::size_t
size(const SoaType& s)
{
return s.FirstParent::members_.size();
}
template <class SoaType>
static void
push_back(SoaType& s, const typename SoaType::value_type& value)
{
s.FirstParent::members_.push_back(value.*FirstParent::pointer_value);
parent_helper<RestParents...>::push_back(s, value);
}
template <class SoaType, class FirstElem, class... RestElems>
static void
push_back_members(SoaType& s, FirstElem&& f_elm, RestElems&&... rest)
{
s.FirstParent::members_.push_back(std::forward<FirstElem>(f_elm));
parent_helper<RestParents...>::push_back_members(
s, std::forward<RestElems>(rest)...);
}
};
template <class LastParent>
struct parent_helper<LastParent>
{
template <class SoaType>
static std::size_t
size(const SoaType& s)
{
return s.LastParent::members_.size();
}
template <class SoaType>
static void
push_back(SoaType& s, const typename SoaType::value_type& value)
{
s.LastParent::members_.push_back(value.*LastParent::pointer_value);
}
template <class SoaType, class LastElem>
static void
push_back_members(SoaType& s, LastElem&& elem)
{
s.LastParent::members_.push_back(std::forward<LastElem>(elem));
}
};
template <class MemberPointerType, MemberPointerType MemberPointerValue>
class member_container
{
public:
typedef soa_detail::member_type_t<MemberPointerType> member_type;
typedef soa_detail::object_type_t<MemberPointerType> object_type;
static constexpr MemberPointerType pointer_value = MemberPointerValue;
public:
member_container() = default;
std::vector<member_type> members_;
};
template <class T, class... MemberContainer>
class soa;
template <class T, class... MemberPtrTypes, MemberPtrTypes... MemberPtrValues>
class soa<T, member_container<MemberPtrTypes, MemberPtrValues>...>
: public member_container<MemberPtrTypes, MemberPtrValues>...
{
public:
typedef T value_type;
typedef element_proxy<T,
member_reference<MemberPtrTypes, MemberPtrValues>...>
proxy_value_type;
public:
soa() : member_container<MemberPtrTypes, MemberPtrValues>()...
{
}
std::size_t
size() const
{
return parent_helper<
member_container<MemberPtrTypes, MemberPtrValues>...>::size(*this);
}
void
push_back(const T& value)
{
parent_helper<member_container<MemberPtrTypes, MemberPtrValues>...>::
push_back(*this, value);
}
template <class... Elems>
void
push_back_members(Elems&&... elems)
{
parent_helper<member_container<MemberPtrTypes, MemberPtrValues>...>::
push_back_members(*this, std::forward<Elems>(elems)...);
}
proxy_value_type operator[](std::size_t n)
{
return proxy_value_type(
member_container<MemberPtrTypes, MemberPtrValues>::members_[n]...);
}
const proxy_value_type operator[](std::size_t n) const
{
return proxy_value_type(
member_container<MemberPtrTypes, MemberPtrValues>::members_[n]...);
}
template <class MemberPtrType, MemberPtrType MemberPtrValue>
soa_detail::member_type_t<MemberPtrType>*
data()
{
return member_container<MemberPtrType, MemberPtrValue>::members_.data();
}
template <class MemberPtrType, MemberPtrType MemberPtrValue>
const soa_detail::member_type_t<MemberPtrType>*
data() const
{
return member_container<MemberPtrType, MemberPtrValue>::members_.data();
}
};
}
<commit_msg>Add member function reserve. modified: include/soa.hpp<commit_after>#pragma once
#include <vector>
#include <tuple>
#include <utility>
namespace helene
{
namespace soa_detail
{
template <class MemberPointerType>
struct deduce_member_pointer;
template <class MemberType, class ObjectType>
struct deduce_member_pointer<MemberType ObjectType::*>
{
typedef MemberType member_type;
typedef ObjectType object_type;
};
template <class MemberPointerType>
using member_type_t =
typename deduce_member_pointer<MemberPointerType>::member_type;
template <class MemberPointerType>
using object_type_t =
typename deduce_member_pointer<MemberPointerType>::object_type;
}
template <class PointerType, PointerType PointerValue>
struct member_reference
{
static constexpr PointerType pointer_value = PointerValue;
};
template <class T, class... MemberRefs>
class element_proxy;
template <class T, class... PointerTypes, PointerTypes... PointerValues>
class element_proxy<T, member_reference<PointerTypes, PointerValues>...>
{
typedef std::tuple<soa_detail::member_type_t<PointerTypes>*...> tuple_type;
template <std::size_t S, class FirstRef, class... RestRefs>
struct assignment_helper
{
static void
assign(std::tuple<soa_detail::member_type_t<PointerTypes>*...>& tpl,
const T& value)
{
*std::get<S>(tpl) = value.*FirstRef::pointer_value;
assignment_helper<S + 1, RestRefs...>::assign(tpl, value);
}
};
template <std::size_t S, class LastRef>
struct assignment_helper<S, LastRef>
{
static void
assign(std::tuple<soa_detail::member_type_t<PointerTypes>*...>& tpl,
const T& value)
{
*std::get<S>(tpl) = value.*LastRef::pointer_value;
}
};
template <std::size_t S, class FirstRef, class... RestRefs>
struct make_helper
{
static void
apply(T& v, const tuple_type& tpl)
{
v.*FirstRef::pointer_value = *std::get<S>(tpl);
make_helper<S + 1, RestRefs...>::apply(v, tpl);
}
};
template <std::size_t S, class LastRef>
struct make_helper<S, LastRef>
{
static void
apply(T& v, const tuple_type& tpl)
{
v.*LastRef::pointer_value = *std::get<S>(tpl);
}
};
public:
element_proxy(soa_detail::member_type_t<PointerTypes>&... args)
: pointers_(&args...)
{
}
operator T() const
{
T out{};
make_helper<0, member_reference<PointerTypes, PointerValues>...>::apply(
out, pointers_);
return out;
}
element_proxy&
operator=(const T& value)
{
assignment_helper<0, member_reference<PointerTypes, PointerValues>...>::
assign(pointers_, value);
return *this;
}
private:
tuple_type pointers_;
};
// helper to access respective parents that are multiply inherited
template <class FirstParent, class... RestParents>
struct parent_helper
{
template <class SoaType>
static std::size_t
size(const SoaType& s)
{
return s.FirstParent::members_.size();
}
template <class SoaType>
static void
push_back(SoaType& s, const typename SoaType::value_type& value)
{
s.FirstParent::members_.push_back(value.*FirstParent::pointer_value);
parent_helper<RestParents...>::push_back(s, value);
}
template <class SoaType, class FirstElem, class... RestElems>
static void
push_back_members(SoaType& s, FirstElem&& f_elm, RestElems&&... rest)
{
s.FirstParent::members_.push_back(std::forward<FirstElem>(f_elm));
parent_helper<RestParents...>::push_back_members(
s, std::forward<RestElems>(rest)...);
}
template <class SoaType>
static void
reserve(SoaType& s, std::size_t n)
{
s.FirstParent::members_.reserve(n);
parent_helper<RestParents...>::reserve(s, n);
}
};
template <class LastParent>
struct parent_helper<LastParent>
{
template <class SoaType>
static std::size_t
size(const SoaType& s)
{
return s.LastParent::members_.size();
}
template <class SoaType>
static void
push_back(SoaType& s, const typename SoaType::value_type& value)
{
s.LastParent::members_.push_back(value.*LastParent::pointer_value);
}
template <class SoaType, class LastElem>
static void
push_back_members(SoaType& s, LastElem&& elem)
{
s.LastParent::members_.push_back(std::forward<LastElem>(elem));
}
template <class SoaType>
static void
reserve(SoaType& s, std::size_t n)
{
s.LastParent::members_.reserve(n);
}
};
template <class MemberPointerType, MemberPointerType MemberPointerValue>
class member_container
{
public:
typedef soa_detail::member_type_t<MemberPointerType> member_type;
typedef soa_detail::object_type_t<MemberPointerType> object_type;
static constexpr MemberPointerType pointer_value = MemberPointerValue;
public:
member_container() = default;
std::vector<member_type> members_;
};
template <class T, class... MemberContainer>
class soa;
template <class T, class... MemberPtrTypes, MemberPtrTypes... MemberPtrValues>
class soa<T, member_container<MemberPtrTypes, MemberPtrValues>...>
: public member_container<MemberPtrTypes, MemberPtrValues>...
{
public:
typedef T value_type;
typedef element_proxy<T,
member_reference<MemberPtrTypes, MemberPtrValues>...>
proxy_value_type;
public:
soa() : member_container<MemberPtrTypes, MemberPtrValues>()...
{
}
std::size_t
size() const
{
return parent_helper<
member_container<MemberPtrTypes, MemberPtrValues>...>::size(*this);
}
void
push_back(const T& value)
{
parent_helper<member_container<MemberPtrTypes, MemberPtrValues>...>::
push_back(*this, value);
}
template <class... Elems>
void
push_back_members(Elems&&... elems)
{
parent_helper<member_container<MemberPtrTypes, MemberPtrValues>...>::
push_back_members(*this, std::forward<Elems>(elems)...);
}
proxy_value_type operator[](std::size_t n)
{
return proxy_value_type(
member_container<MemberPtrTypes, MemberPtrValues>::members_[n]...);
}
const proxy_value_type operator[](std::size_t n) const
{
return proxy_value_type(
member_container<MemberPtrTypes, MemberPtrValues>::members_[n]...);
}
template <class MemberPtrType, MemberPtrType MemberPtrValue>
soa_detail::member_type_t<MemberPtrType>*
data()
{
return member_container<MemberPtrType, MemberPtrValue>::members_.data();
}
template <class MemberPtrType, MemberPtrType MemberPtrValue>
const soa_detail::member_type_t<MemberPtrType>*
data() const
{
return member_container<MemberPtrType, MemberPtrValue>::members_.data();
}
void
reserve(std::size_t n)
{
parent_helper<member_container<MemberPtrTypes,
MemberPtrValues>...>::reserve(*this, n);
}
};
}
<|endoftext|> |
<commit_before>#include "tangram.h"
#include "platform.h"
#include "gl.h"
#include <cmath>
// Forward declaration
void init_main_window();
// Input handling
// ==============
const double double_tap_time = 0.5; // seconds
const double scroll_multiplier = 0.05; // scaling for zoom
const double single_tap_time = 0.25; //seconds (to avoid a long press being considered as a tap)
bool was_panning = false;
double last_mouse_up = -double_tap_time; // First click should never trigger a double tap
double last_mouse_down = 0.0f;
double last_x_down = 0.0;
double last_y_down = 0.0;
void mouse_button_callback(GLFWwindow* window, int button, int action, int mods) {
if (button != GLFW_MOUSE_BUTTON_1) {
return; // This event is for a mouse button that we don't care about
}
if (was_panning) {
was_panning = false;
return; // Clicks with movement don't count as taps
}
double x, y;
glfwGetCursorPos(window, &x, &y);
double time = glfwGetTime();
if (action == GLFW_PRESS) {
Tangram::handlePanGesture(0.0f, 0.0f, 0.0f, 0.0f);
last_x_down = x;
last_y_down = y;
last_mouse_down = glfwGetTime();
return;
}
if (time - last_mouse_up < double_tap_time) {
Tangram::handleDoubleTapGesture(x, y);
} else if ( (time - last_mouse_down) < single_tap_time) {
Tangram::handleTapGesture(x, y);
}
last_mouse_up = time;
}
void cursor_pos_callback(GLFWwindow* window, double x, double y) {
int action = glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_1);
if (action == GLFW_PRESS) {
if (was_panning) {
Tangram::handlePanGesture(last_x_down, last_y_down, x, y);
}
was_panning = true;
last_x_down = x;
last_y_down = y;
}
}
void scroll_callback(GLFWwindow* window, double scrollx, double scrolly) {
double x, y;
glfwGetCursorPos(window, &x, &y);
bool rotating = glfwGetKey(window, GLFW_KEY_LEFT_ALT) == GLFW_PRESS || glfwGetKey(window, GLFW_KEY_RIGHT_ALT) == GLFW_PRESS;
bool shoving = glfwGetKey(window, GLFW_KEY_LEFT_CONTROL) == GLFW_PRESS || glfwGetKey(window, GLFW_KEY_RIGHT_CONTROL) == GLFW_PRESS;
if (shoving) {
Tangram::handleShoveGesture(scroll_multiplier * scrolly);
} else if (rotating) {
Tangram::handleRotateGesture(x, y, scroll_multiplier * scrolly);
} else {
Tangram::handlePinchGesture(x, y, 1.0 + scroll_multiplier * scrolly, 0.f);
}
}
void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods) {
if (action == GLFW_PRESS) {
switch (key) {
case GLFW_KEY_1:
Tangram::toggleDebugFlag(Tangram::DebugFlags::freeze_tiles);
break;
case GLFW_KEY_2:
Tangram::toggleDebugFlag(Tangram::DebugFlags::proxy_colors);
break;
case GLFW_KEY_3:
Tangram::toggleDebugFlag(Tangram::DebugFlags::tile_bounds);
break;
case GLFW_KEY_4:
Tangram::toggleDebugFlag(Tangram::DebugFlags::tile_infos);
break;
case GLFW_KEY_5:
Tangram::toggleDebugFlag(Tangram::DebugFlags::labels);
break;
case GLFW_KEY_BACKSPACE:
init_main_window(); // Simulate GL context loss
break;
default:
break;
}
}
}
// Window handling
// ===============
GLFWwindow* main_window = nullptr;
int width = 800;
int height = 600;
void window_size_callback(GLFWwindow* window, int width, int height) {
Tangram::resize(width, height);
}
void init_main_window() {
// Setup tangram
Tangram::initialize("scene.yaml");
// Destroy old window
if (main_window != nullptr) {
glfwDestroyWindow(main_window);
}
// Create a windowed mode window and its OpenGL context
glfwWindowHint(GLFW_SAMPLES, 2);
main_window = glfwCreateWindow(width, height, "Tangram ES", NULL, NULL);
if (!main_window) {
glfwTerminate();
}
// Make the main_window's context current
glfwMakeContextCurrent(main_window);
// Set input callbacks
glfwSetWindowSizeCallback(main_window, window_size_callback);
glfwSetMouseButtonCallback(main_window, mouse_button_callback);
glfwSetCursorPosCallback(main_window, cursor_pos_callback);
glfwSetScrollCallback(main_window, scroll_callback);
glfwSetKeyCallback(main_window, key_callback);
// Setup graphics
Tangram::setupGL();
Tangram::resize(width, height);
// Work-around for a bug in GLFW on retina displays
int fbWidth = 0, fbHeight = 0;
glfwGetFramebufferSize(main_window, &fbWidth, &fbHeight);
glViewport(0, 0, fbWidth, fbHeight);
}
// Main program
// ============
int main(void) {
// Initialize the windowing library
if (!glfwInit()) {
return -1;
}
init_main_window();
// Initialize networking
NSurlInit();
double lastTime = glfwGetTime();
// Loop until the user closes the window
while (!glfwWindowShouldClose(main_window)) {
double currentTime = glfwGetTime();
double delta = currentTime - lastTime;
lastTime = currentTime;
// Render
Tangram::update(delta);
Tangram::render();
// Swap front and back buffers
glfwSwapBuffers(main_window);
// Poll for and process events
if (isContinuousRendering()) {
glfwPollEvents();
} else {
glfwWaitEvents();
}
}
glfwTerminate();
return 0;
}
<commit_msg>Dynamic data rendering in OS X demo<commit_after>#include "tangram.h"
#include "platform.h"
#include "gl.h"
#include <cmath>
// Forward declaration
void init_main_window();
// Input handling
// ==============
const double double_tap_time = 0.5; // seconds
const double scroll_multiplier = 0.05; // scaling for zoom
const double single_tap_time = 0.25; //seconds (to avoid a long press being considered as a tap)
bool was_panning = false;
double last_mouse_up = -double_tap_time; // First click should never trigger a double tap
double last_mouse_down = 0.0f;
double last_x_down = 0.0;
double last_y_down = 0.0;
int data_source_id = -1;
void mouse_button_callback(GLFWwindow* window, int button, int action, int mods) {
if (button != GLFW_MOUSE_BUTTON_1) {
return; // This event is for a mouse button that we don't care about
}
if (was_panning) {
was_panning = false;
return; // Clicks with movement don't count as taps
}
double x, y;
glfwGetCursorPos(window, &x, &y);
double time = glfwGetTime();
if (action == GLFW_PRESS) {
Tangram::handlePanGesture(0.0f, 0.0f, 0.0f, 0.0f);
last_x_down = x;
last_y_down = y;
last_mouse_down = glfwGetTime();
return;
}
if (time - last_mouse_up < double_tap_time) {
Tangram::clearSourceData(data_source_id);
// Tangram::handleDoubleTapGesture(x, y);
} else if ( (time - last_mouse_down) < single_tap_time) {
double point[2] = { x, y };
Tangram::screenToWorldCoordinates(point[0], point[1]);
Tangram::addSourcePoint(data_source_id, point);
// Tangram::handleTapGesture(x, y);
}
last_mouse_up = time;
}
void cursor_pos_callback(GLFWwindow* window, double x, double y) {
int action = glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_1);
if (action == GLFW_PRESS) {
if (was_panning) {
Tangram::handlePanGesture(last_x_down, last_y_down, x, y);
}
was_panning = true;
last_x_down = x;
last_y_down = y;
}
}
void scroll_callback(GLFWwindow* window, double scrollx, double scrolly) {
double x, y;
glfwGetCursorPos(window, &x, &y);
bool rotating = glfwGetKey(window, GLFW_KEY_LEFT_ALT) == GLFW_PRESS || glfwGetKey(window, GLFW_KEY_RIGHT_ALT) == GLFW_PRESS;
bool shoving = glfwGetKey(window, GLFW_KEY_LEFT_CONTROL) == GLFW_PRESS || glfwGetKey(window, GLFW_KEY_RIGHT_CONTROL) == GLFW_PRESS;
if (shoving) {
Tangram::handleShoveGesture(scroll_multiplier * scrolly);
} else if (rotating) {
Tangram::handleRotateGesture(x, y, scroll_multiplier * scrolly);
} else {
Tangram::handlePinchGesture(x, y, 1.0 + scroll_multiplier * scrolly, 0.f);
}
}
void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods) {
if (action == GLFW_PRESS) {
switch (key) {
case GLFW_KEY_1:
Tangram::toggleDebugFlag(Tangram::DebugFlags::freeze_tiles);
break;
case GLFW_KEY_2:
Tangram::toggleDebugFlag(Tangram::DebugFlags::proxy_colors);
break;
case GLFW_KEY_3:
Tangram::toggleDebugFlag(Tangram::DebugFlags::tile_bounds);
break;
case GLFW_KEY_4:
Tangram::toggleDebugFlag(Tangram::DebugFlags::tile_infos);
break;
case GLFW_KEY_5:
Tangram::toggleDebugFlag(Tangram::DebugFlags::labels);
break;
case GLFW_KEY_BACKSPACE:
init_main_window(); // Simulate GL context loss
break;
default:
break;
}
}
}
// Window handling
// ===============
GLFWwindow* main_window = nullptr;
int width = 800;
int height = 600;
void window_size_callback(GLFWwindow* window, int width, int height) {
Tangram::resize(width, height);
}
void init_main_window() {
// Setup tangram
Tangram::initialize("scene.yaml");
// Destroy old window
if (main_window != nullptr) {
glfwDestroyWindow(main_window);
}
// Create a windowed mode window and its OpenGL context
glfwWindowHint(GLFW_SAMPLES, 2);
main_window = glfwCreateWindow(width, height, "Tangram ES", NULL, NULL);
if (!main_window) {
glfwTerminate();
}
// Make the main_window's context current
glfwMakeContextCurrent(main_window);
// Set input callbacks
glfwSetWindowSizeCallback(main_window, window_size_callback);
glfwSetMouseButtonCallback(main_window, mouse_button_callback);
glfwSetCursorPosCallback(main_window, cursor_pos_callback);
glfwSetScrollCallback(main_window, scroll_callback);
glfwSetKeyCallback(main_window, key_callback);
// Setup graphics
Tangram::setupGL();
Tangram::resize(width, height);
// Work-around for a bug in GLFW on retina displays
int fbWidth = 0, fbHeight = 0;
glfwGetFramebufferSize(main_window, &fbWidth, &fbHeight);
glViewport(0, 0, fbWidth, fbHeight);
data_source_id = Tangram::addDataSource("touch");
}
// Main program
// ============
int main(void) {
// Initialize the windowing library
if (!glfwInit()) {
return -1;
}
init_main_window();
// Initialize networking
NSurlInit();
double lastTime = glfwGetTime();
// Loop until the user closes the window
while (!glfwWindowShouldClose(main_window)) {
double currentTime = glfwGetTime();
double delta = currentTime - lastTime;
lastTime = currentTime;
// Render
Tangram::update(delta);
Tangram::render();
// Swap front and back buffers
glfwSwapBuffers(main_window);
// Poll for and process events
if (isContinuousRendering()) {
glfwPollEvents();
} else {
glfwWaitEvents();
}
}
glfwTerminate();
return 0;
}
<|endoftext|> |
<commit_before>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "QmitkPropertyTreeItem.h"
#include "QmitkPropertyTreeModel.h"
#include <mitkProperties.h>
#include <mitkColorProperty.h>
#include <mitkEnumerationProperty.h>
#include <mitkStringProperty.h>
#include <mitkRenderingManager.h>
#include <QColor>
QmitkPropertyTreeModel::QmitkPropertyTreeModel(QObject *parent)
: QAbstractItemModel(parent),
m_Properties(NULL),
m_RootItem(NULL)
{
CreateRootItem();
}
void QmitkPropertyTreeModel::SetProperties(mitk::PropertyList *properties)
{
if (properties == m_Properties)
return;
beginResetModel();
if (m_RootItem != NULL)
{
delete m_RootItem;
m_RootItem = NULL;
m_Properties = NULL;
}
CreateRootItem();
if (properties != NULL && !properties->IsEmpty())
{
m_Properties = properties;
std::map<std::string, mitk::BaseProperty::Pointer>::const_iterator end = properties->GetMap()->end();
for (std::map<std::string, mitk::BaseProperty::Pointer>::const_iterator iter = properties->GetMap()->begin(); iter != end; ++iter)
{
QList<QVariant> data;
data << iter->first.c_str() << QVariant::fromValue<void *>((reinterpret_cast<void *>(iter->second.GetPointer())));
m_RootItem->AppendChild(new QmitkPropertyTreeItem(data));
}
}
endResetModel();
}
void QmitkPropertyTreeModel::CreateRootItem()
{
if (m_RootItem == NULL)
{
QList<QVariant> rootData;
rootData << "Property" << "Value";
m_RootItem = new QmitkPropertyTreeItem(rootData);
}
}
QmitkPropertyTreeModel::~QmitkPropertyTreeModel()
{
delete m_RootItem;
}
int QmitkPropertyTreeModel::columnCount(const QModelIndex &parent) const
{
if (parent.isValid())
return static_cast<QmitkPropertyTreeItem *>(parent.internalPointer())->GetColumnCount();
else
return m_RootItem->GetColumnCount();
}
QVariant QmitkPropertyTreeModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid())
return QVariant();
if (index.column() == 0 && role == Qt::DisplayRole)
return static_cast<QmitkPropertyTreeItem *>(index.internalPointer())->GetData(index.column());
if (index.column() == 1 && static_cast<QmitkPropertyTreeItem *>(index.internalPointer())->GetData(index.column()).isValid())
{
mitk::BaseProperty *property = reinterpret_cast<mitk::BaseProperty *>(static_cast<QmitkPropertyTreeItem *>(index.internalPointer())->GetData(index.column()).value<void *>());
if (mitk::ColorProperty *colorProperty = dynamic_cast<mitk::ColorProperty *>(property))
{
if (role == Qt::DisplayRole || role == Qt::EditRole)
{
mitk::Color mitkColor = colorProperty->GetColor();
QColor qtColor(static_cast<int>(mitkColor.GetRed() * 255), static_cast<int>(mitkColor.GetGreen() * 255), static_cast<int>(mitkColor.GetBlue() * 255));
return QVariant::fromValue<QColor>(qtColor);
}
}
else if (mitk::BoolProperty *boolProperty = dynamic_cast<mitk::BoolProperty *>(property))
{
if (role == Qt::CheckStateRole)
return boolProperty->GetValue() ? Qt::Checked : Qt::Unchecked;
}
else if (mitk::StringProperty *stringProperty = dynamic_cast<mitk::StringProperty *>(property))
{
if (role == Qt::DisplayRole || role == Qt::EditRole)
return QString(stringProperty->GetValue());
}
else if (mitk::IntProperty *intProperty = dynamic_cast<mitk::IntProperty *>(property))
{
if (role == Qt::DisplayRole || role == Qt::EditRole)
return intProperty->GetValue();
}
else if (mitk::FloatProperty *floatProperty = dynamic_cast<mitk::FloatProperty *>(property))
{
if (role == Qt::DisplayRole || role == Qt::EditRole)
return floatProperty->GetValue();
}
else if (mitk::DoubleProperty *doubleProperty = dynamic_cast<mitk::DoubleProperty *>(property))
{
if (role == Qt::DisplayRole || role == Qt::EditRole)
return doubleProperty->GetValue();
}
else if (mitk::EnumerationProperty *enumProperty = dynamic_cast<mitk::EnumerationProperty *>(property))
{
if (role == Qt::DisplayRole)
{
return QString::fromStdString(enumProperty->GetValueAsString());
}
else if (role == Qt::EditRole)
{
QStringList values;
for (mitk::EnumerationProperty::EnumConstIterator iter = enumProperty->Begin(); iter != enumProperty->End(); ++iter)
values << QString::fromStdString(iter->second);
return QVariant(values);
}
}
else
{
if (role == Qt::DisplayRole)
return QString::fromStdString(property->GetValueAsString());
}
}
return QVariant();
}
Qt::ItemFlags QmitkPropertyTreeModel::flags(const QModelIndex &index) const
{
Qt::ItemFlags flags = QAbstractItemModel::flags(index);
if (index.column() == 1)
{
if (index.data(Qt::EditRole).isValid())
flags |= Qt::ItemIsEditable;
if (index.data(Qt::CheckStateRole).isValid())
flags |= Qt::ItemIsUserCheckable;
}
return flags;
}
QVariant QmitkPropertyTreeModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if (orientation == Qt::Horizontal && role == Qt::DisplayRole)
return m_RootItem->GetData(section);
return QVariant();
}
QModelIndex QmitkPropertyTreeModel::index(int row, int column, const QModelIndex &parent) const
{
if (!hasIndex(row, column, parent))
return QModelIndex();
QmitkPropertyTreeItem *parentItem = parent.isValid() ? static_cast<QmitkPropertyTreeItem *>(parent.internalPointer()) : m_RootItem;
QmitkPropertyTreeItem *childItem = parentItem->GetChild(row);
if (childItem != NULL)
return createIndex(row, column, childItem);
else
return QModelIndex();
}
QModelIndex QmitkPropertyTreeModel::parent(const QModelIndex &child) const
{
if (!child.isValid())
return QModelIndex();
QmitkPropertyTreeItem *parentItem = static_cast<QmitkPropertyTreeItem *>(child.internalPointer())->GetParent();
if (parentItem == m_RootItem)
return QModelIndex();
return createIndex(parentItem->GetRow(), 0, parentItem);
}
int QmitkPropertyTreeModel::rowCount(const QModelIndex &parent) const
{
if (parent.column() > 0)
return 0;
QmitkPropertyTreeItem *parentItem = parent.isValid() ? static_cast<QmitkPropertyTreeItem *>(parent.internalPointer()) : m_RootItem;
return parentItem->GetChildCount();
}
bool QmitkPropertyTreeModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
if (index.isValid() && (role == Qt::EditRole || role == Qt::CheckStateRole))
{
if (index.column() == 1)
{
mitk::BaseProperty *property = reinterpret_cast<mitk::BaseProperty *>(static_cast<QmitkPropertyTreeItem *>(index.internalPointer())->GetData(index.column()).value<void *>());
if (mitk::ColorProperty *colorProperty = dynamic_cast<mitk::ColorProperty *>(property))
{
QColor qtColor = value.value<QColor>();
if (!qtColor.isValid())
return false;
mitk::Color mitkColor = colorProperty->GetColor();
mitkColor.SetRed(qtColor.red() / 255.0);
mitkColor.SetGreen(qtColor.green() / 255.0);
mitkColor.SetBlue(qtColor.blue() / 255.0);
colorProperty->SetColor(mitkColor);
m_Properties->InvokeEvent(itk::ModifiedEvent());
m_Properties->Modified();
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
}
else if (mitk::BoolProperty *boolProperty = dynamic_cast<mitk::BoolProperty *>(property))
{
boolProperty->SetValue(value.toInt() == Qt::Checked ? true : false);
m_Properties->InvokeEvent(itk::ModifiedEvent());
m_Properties->Modified();
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
}
else if (mitk::StringProperty *stringProperty = dynamic_cast<mitk::StringProperty *>(property))
{
stringProperty->SetValue(value.toString().toStdString());
m_Properties->InvokeEvent(itk::ModifiedEvent());
m_Properties->Modified();
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
}
else if (mitk::IntProperty *intProperty = dynamic_cast<mitk::IntProperty *>(property))
{
int intValue = value.toInt();
if (intValue != intProperty->GetValue())
{
intProperty->SetValue(intValue);
m_Properties->InvokeEvent(itk::ModifiedEvent());
m_Properties->Modified();
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
}
}
else if (mitk::FloatProperty *floatProperty = dynamic_cast<mitk::FloatProperty *>(property))
{
int floatValue = value.toFloat();
if (floatValue != floatProperty->GetValue())
{
floatProperty->SetValue(floatValue);
m_Properties->InvokeEvent(itk::ModifiedEvent());
m_Properties->Modified();
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
}
}
else if (mitk::EnumerationProperty *enumProperty = dynamic_cast<mitk::EnumerationProperty *>(property))
{
std::string activatedItem = value.toString().toStdString();
if (activatedItem != enumProperty->GetValueAsString())
{
enumProperty->SetValue(activatedItem);
m_Properties->InvokeEvent(itk::ModifiedEvent());
m_Properties->Modified();
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
}
}
}
emit dataChanged(index, index);
return true;
}
return false;
}
<commit_msg>Fixed accidental type conversion and enhanced float comparison.<commit_after>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "QmitkPropertyTreeItem.h"
#include "QmitkPropertyTreeModel.h"
#include <mitkProperties.h>
#include <mitkColorProperty.h>
#include <mitkEnumerationProperty.h>
#include <mitkStringProperty.h>
#include <mitkRenderingManager.h>
#include <QColor>
QmitkPropertyTreeModel::QmitkPropertyTreeModel(QObject *parent)
: QAbstractItemModel(parent),
m_Properties(NULL),
m_RootItem(NULL)
{
CreateRootItem();
}
void QmitkPropertyTreeModel::SetProperties(mitk::PropertyList *properties)
{
if (properties == m_Properties)
return;
beginResetModel();
if (m_RootItem != NULL)
{
delete m_RootItem;
m_RootItem = NULL;
m_Properties = NULL;
}
CreateRootItem();
if (properties != NULL && !properties->IsEmpty())
{
m_Properties = properties;
std::map<std::string, mitk::BaseProperty::Pointer>::const_iterator end = properties->GetMap()->end();
for (std::map<std::string, mitk::BaseProperty::Pointer>::const_iterator iter = properties->GetMap()->begin(); iter != end; ++iter)
{
QList<QVariant> data;
data << iter->first.c_str() << QVariant::fromValue<void *>((reinterpret_cast<void *>(iter->second.GetPointer())));
m_RootItem->AppendChild(new QmitkPropertyTreeItem(data));
}
}
endResetModel();
}
void QmitkPropertyTreeModel::CreateRootItem()
{
if (m_RootItem == NULL)
{
QList<QVariant> rootData;
rootData << "Property" << "Value";
m_RootItem = new QmitkPropertyTreeItem(rootData);
}
}
QmitkPropertyTreeModel::~QmitkPropertyTreeModel()
{
delete m_RootItem;
}
int QmitkPropertyTreeModel::columnCount(const QModelIndex &parent) const
{
if (parent.isValid())
return static_cast<QmitkPropertyTreeItem *>(parent.internalPointer())->GetColumnCount();
else
return m_RootItem->GetColumnCount();
}
QVariant QmitkPropertyTreeModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid())
return QVariant();
if (index.column() == 0 && role == Qt::DisplayRole)
return static_cast<QmitkPropertyTreeItem *>(index.internalPointer())->GetData(index.column());
if (index.column() == 1 && static_cast<QmitkPropertyTreeItem *>(index.internalPointer())->GetData(index.column()).isValid())
{
mitk::BaseProperty *property = reinterpret_cast<mitk::BaseProperty *>(static_cast<QmitkPropertyTreeItem *>(index.internalPointer())->GetData(index.column()).value<void *>());
if (mitk::ColorProperty *colorProperty = dynamic_cast<mitk::ColorProperty *>(property))
{
if (role == Qt::DisplayRole || role == Qt::EditRole)
{
mitk::Color mitkColor = colorProperty->GetColor();
QColor qtColor(static_cast<int>(mitkColor.GetRed() * 255), static_cast<int>(mitkColor.GetGreen() * 255), static_cast<int>(mitkColor.GetBlue() * 255));
return QVariant::fromValue<QColor>(qtColor);
}
}
else if (mitk::BoolProperty *boolProperty = dynamic_cast<mitk::BoolProperty *>(property))
{
if (role == Qt::CheckStateRole)
return boolProperty->GetValue() ? Qt::Checked : Qt::Unchecked;
}
else if (mitk::StringProperty *stringProperty = dynamic_cast<mitk::StringProperty *>(property))
{
if (role == Qt::DisplayRole || role == Qt::EditRole)
return QString(stringProperty->GetValue());
}
else if (mitk::IntProperty *intProperty = dynamic_cast<mitk::IntProperty *>(property))
{
if (role == Qt::DisplayRole || role == Qt::EditRole)
return intProperty->GetValue();
}
else if (mitk::FloatProperty *floatProperty = dynamic_cast<mitk::FloatProperty *>(property))
{
if (role == Qt::DisplayRole || role == Qt::EditRole)
return floatProperty->GetValue();
}
else if (mitk::DoubleProperty *doubleProperty = dynamic_cast<mitk::DoubleProperty *>(property))
{
if (role == Qt::DisplayRole || role == Qt::EditRole)
return doubleProperty->GetValue();
}
else if (mitk::EnumerationProperty *enumProperty = dynamic_cast<mitk::EnumerationProperty *>(property))
{
if (role == Qt::DisplayRole)
{
return QString::fromStdString(enumProperty->GetValueAsString());
}
else if (role == Qt::EditRole)
{
QStringList values;
for (mitk::EnumerationProperty::EnumConstIterator iter = enumProperty->Begin(); iter != enumProperty->End(); ++iter)
values << QString::fromStdString(iter->second);
return QVariant(values);
}
}
else
{
if (role == Qt::DisplayRole)
return QString::fromStdString(property->GetValueAsString());
}
}
return QVariant();
}
Qt::ItemFlags QmitkPropertyTreeModel::flags(const QModelIndex &index) const
{
Qt::ItemFlags flags = QAbstractItemModel::flags(index);
if (index.column() == 1)
{
if (index.data(Qt::EditRole).isValid())
flags |= Qt::ItemIsEditable;
if (index.data(Qt::CheckStateRole).isValid())
flags |= Qt::ItemIsUserCheckable;
}
return flags;
}
QVariant QmitkPropertyTreeModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if (orientation == Qt::Horizontal && role == Qt::DisplayRole)
return m_RootItem->GetData(section);
return QVariant();
}
QModelIndex QmitkPropertyTreeModel::index(int row, int column, const QModelIndex &parent) const
{
if (!hasIndex(row, column, parent))
return QModelIndex();
QmitkPropertyTreeItem *parentItem = parent.isValid() ? static_cast<QmitkPropertyTreeItem *>(parent.internalPointer()) : m_RootItem;
QmitkPropertyTreeItem *childItem = parentItem->GetChild(row);
if (childItem != NULL)
return createIndex(row, column, childItem);
else
return QModelIndex();
}
QModelIndex QmitkPropertyTreeModel::parent(const QModelIndex &child) const
{
if (!child.isValid())
return QModelIndex();
QmitkPropertyTreeItem *parentItem = static_cast<QmitkPropertyTreeItem *>(child.internalPointer())->GetParent();
if (parentItem == m_RootItem)
return QModelIndex();
return createIndex(parentItem->GetRow(), 0, parentItem);
}
int QmitkPropertyTreeModel::rowCount(const QModelIndex &parent) const
{
if (parent.column() > 0)
return 0;
QmitkPropertyTreeItem *parentItem = parent.isValid() ? static_cast<QmitkPropertyTreeItem *>(parent.internalPointer()) : m_RootItem;
return parentItem->GetChildCount();
}
bool QmitkPropertyTreeModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
if (index.isValid() && (role == Qt::EditRole || role == Qt::CheckStateRole))
{
if (index.column() == 1)
{
mitk::BaseProperty *property = reinterpret_cast<mitk::BaseProperty *>(static_cast<QmitkPropertyTreeItem *>(index.internalPointer())->GetData(index.column()).value<void *>());
if (mitk::ColorProperty *colorProperty = dynamic_cast<mitk::ColorProperty *>(property))
{
QColor qtColor = value.value<QColor>();
if (!qtColor.isValid())
return false;
mitk::Color mitkColor = colorProperty->GetColor();
mitkColor.SetRed(qtColor.red() / 255.0);
mitkColor.SetGreen(qtColor.green() / 255.0);
mitkColor.SetBlue(qtColor.blue() / 255.0);
colorProperty->SetColor(mitkColor);
m_Properties->InvokeEvent(itk::ModifiedEvent());
m_Properties->Modified();
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
}
else if (mitk::BoolProperty *boolProperty = dynamic_cast<mitk::BoolProperty *>(property))
{
boolProperty->SetValue(value.toInt() == Qt::Checked ? true : false);
m_Properties->InvokeEvent(itk::ModifiedEvent());
m_Properties->Modified();
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
}
else if (mitk::StringProperty *stringProperty = dynamic_cast<mitk::StringProperty *>(property))
{
stringProperty->SetValue(value.toString().toStdString());
m_Properties->InvokeEvent(itk::ModifiedEvent());
m_Properties->Modified();
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
}
else if (mitk::IntProperty *intProperty = dynamic_cast<mitk::IntProperty *>(property))
{
int intValue = value.toInt();
if (intValue != intProperty->GetValue())
{
intProperty->SetValue(intValue);
m_Properties->InvokeEvent(itk::ModifiedEvent());
m_Properties->Modified();
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
}
}
else if (mitk::FloatProperty *floatProperty = dynamic_cast<mitk::FloatProperty *>(property))
{
float floatValue = value.toFloat();
if (abs(floatValue - floatProperty->GetValue()) >= mitk::eps)
{
floatProperty->SetValue(floatValue);
m_Properties->InvokeEvent(itk::ModifiedEvent());
m_Properties->Modified();
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
}
}
else if (mitk::EnumerationProperty *enumProperty = dynamic_cast<mitk::EnumerationProperty *>(property))
{
std::string activatedItem = value.toString().toStdString();
if (activatedItem != enumProperty->GetValueAsString())
{
enumProperty->SetValue(activatedItem);
m_Properties->InvokeEvent(itk::ModifiedEvent());
m_Properties->Modified();
mitk::RenderingManager::GetInstance()->RequestUpdateAll();
}
}
}
emit dataChanged(index, index);
return true;
}
return false;
}
<|endoftext|> |
<commit_before>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2013 Torus Knot Software Ltd
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/
#include "OgreStableHeaders.h"
#include "OgreGLES2StateCacheManagerImp.h"
#include "OgreGLES2RenderSystem.h"
#include "OgreLogManager.h"
#include "OgreRoot.h"
namespace Ogre {
GLES2StateCacheManagerImp::GLES2StateCacheManagerImp(void)
{
clearCache();
}
void GLES2StateCacheManagerImp::initializeCache()
{
OGRE_CHECK_GL_ERROR(glBlendEquation(GL_FUNC_ADD));
OGRE_CHECK_GL_ERROR(glBlendFunc(GL_ONE, GL_ZERO));
OGRE_CHECK_GL_ERROR(glCullFace(mCullFace));
OGRE_CHECK_GL_ERROR(glDepthFunc(mDepthFunc));
OGRE_CHECK_GL_ERROR(glDepthMask(mDepthMask));
OGRE_CHECK_GL_ERROR(glStencilMask(mStencilMask));
OGRE_CHECK_GL_ERROR(glClearDepthf(mClearDepth));
OGRE_CHECK_GL_ERROR(glBindTexture(GL_TEXTURE_2D, 0));
OGRE_CHECK_GL_ERROR(glBindBuffer(GL_ARRAY_BUFFER, 0));
OGRE_CHECK_GL_ERROR(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0));
OGRE_CHECK_GL_ERROR(glBindFramebuffer(GL_FRAMEBUFFER, 0));
OGRE_CHECK_GL_ERROR(glBindRenderbuffer(GL_RENDERBUFFER, 0));
OGRE_CHECK_GL_ERROR(glActiveTexture(GL_TEXTURE0));
OGRE_CHECK_GL_ERROR(glClearColor(mClearColour[0], mClearColour[1], mClearColour[2], mClearColour[3]));
OGRE_CHECK_GL_ERROR(glColorMask(mColourMask[0], mColourMask[1], mColourMask[2], mColourMask[3]));
}
void GLES2StateCacheManagerImp::clearCache()
{
mDepthMask = GL_TRUE;
mPolygonMode = GL_FILL;
mBlendEquation = GL_FUNC_ADD;
mCullFace = GL_BACK;
mDepthFunc = GL_LESS;
mStencilMask = 0xFFFFFFFF;
mActiveTextureUnit = 0;
mDiscardBuffers = 0;
mClearDepth = 1.0f;
mLastBoundTexID = 0;
// Initialize our cache variables and also the GL so that the
// stored values match the GL state
mBlendFuncSource = GL_ONE;
mBlendFuncDest = GL_ZERO;
mClearColour.resize(4);
mClearColour[0] = mClearColour[1] = mClearColour[2] = mClearColour[3] = 0.0f;
mColourMask.resize(4);
mColourMask[0] = mColourMask[1] = mColourMask[2] = mColourMask[3] = GL_TRUE;
mEnableVector.reserve(25);
mEnableVector.clear();
mActiveBufferMap.clear();
mTexUnitsMap.clear();
mEnableVector.reserve(64);
mEnabledVertexAttribs.clear();
}
GLES2StateCacheManagerImp::~GLES2StateCacheManagerImp(void)
{
mColourMask.clear();
mClearColour.clear();
mActiveBufferMap.clear();
mEnableVector.clear();
mTexUnitsMap.clear();
}
void GLES2StateCacheManagerImp::bindGLBuffer(GLenum target, GLuint buffer, GLenum attach, bool force)
{
bool update = false;
BindBufferMap::iterator i = mActiveBufferMap.find(target);
if (i == mActiveBufferMap.end())
{
// Haven't cached this state yet. Insert it into the map
mActiveBufferMap.insert(BindBufferMap::value_type(target, buffer));
update = true;
}
else if((*i).second != buffer || force) // Update the cached value if needed
{
(*i).second = buffer;
update = true;
}
// Update GL
if(update)
{
if(target == GL_FRAMEBUFFER)
{
OGRE_CHECK_GL_ERROR(glBindFramebuffer(target, buffer));
}
else if(target == GL_RENDERBUFFER)
{
OGRE_CHECK_GL_ERROR(glBindRenderbuffer(target, buffer));
}
else
{
OGRE_CHECK_GL_ERROR(glBindBuffer(target, buffer));
}
}
}
void GLES2StateCacheManagerImp::deleteGLBuffer(GLenum target, GLuint buffer, GLenum attach, bool force)
{
// Buffer name 0 is reserved and we should never try to delete it
if(buffer == 0)
return;
BindBufferMap::iterator i = mActiveBufferMap.find(target);
if (i != mActiveBufferMap.end() && ((*i).second == buffer || force))
{
if(target == GL_FRAMEBUFFER)
{
OGRE_CHECK_GL_ERROR(glDeleteFramebuffers(1, &buffer));
}
else if(target == GL_RENDERBUFFER)
{
OGRE_CHECK_GL_ERROR(glDeleteRenderbuffers(1, &buffer));
}
else
{
OGRE_CHECK_GL_ERROR(glDeleteBuffers(1, &buffer));
}
// Currently bound buffer is being deleted, update the cached value to 0,
// which it likely the buffer that will be bound by the driver.
// An update will be forced next time we try to bind on this target.
(*i).second = 0;
}
}
void GLES2StateCacheManagerImp::invalidateStateForTexture(GLuint texture)
{
TexUnitsMap::iterator it = mTexUnitsMap.find(texture);
mTexUnitsMap.erase(it);
}
// TODO: Store as high/low bits of a GLuint, use vector instead of map for TexParameteriMap
void GLES2StateCacheManagerImp::setTexParameteri(GLenum target, GLenum pname, GLint param)
{
// Check if we have a map entry for this texture id. If not, create a blank one and insert it.
TexUnitsMap::iterator it = mTexUnitsMap.find(mLastBoundTexID);
if (it == mTexUnitsMap.end())
{
TextureUnitParams unit;
mTexUnitsMap[mLastBoundTexID] = unit;
// Update the iterator
it = mTexUnitsMap.find(mLastBoundTexID);
}
// Get a local copy of the parameter map and search for this parameter
TexParameteriMap &myMap = (*it).second.mTexParameteriMap;
TexParameteriMap::iterator i = myMap.find(pname);
if (i == myMap.end())
{
// Haven't cached this state yet. Insert it into the map
myMap.insert(TexParameteriMap::value_type(pname, param));
// Update GL
OGRE_CHECK_GL_ERROR(glTexParameteri(target, pname, param));
}
else
{
// Update the cached value if needed
if((*i).second != param)
{
(*i).second = param;
// Update GL
OGRE_CHECK_GL_ERROR(glTexParameteri(target, pname, param));
}
}
}
void GLES2StateCacheManagerImp::setTexParameterf(GLenum target, GLenum pname, GLfloat param)
{
// Check if we have a map entry for this texture id. If not, create a blank one and insert it.
TexUnitsMap::iterator it = mTexUnitsMap.find(mLastBoundTexID);
if (it == mTexUnitsMap.end())
{
TextureUnitParams unit;
mTexUnitsMap[mLastBoundTexID] = unit;
// Update the iterator
it = mTexUnitsMap.find(mLastBoundTexID);
}
// Get a local copy of the parameter map and search for this parameter
TexParameterfMap &myMap = (*it).second.mTexParameterfMap;
TexParameterfMap::iterator i = myMap.find(pname);
if (i == myMap.end())
{
// Haven't cached this state yet. Insert it into the map
myMap.insert(TexParameterfMap::value_type(pname, param));
// Update GL
OGRE_CHECK_GL_ERROR(glTexParameterf(target, pname, param));
}
else
{
// Update the cached value if needed
if((*i).second != param)
{
(*i).second = param;
// Update GL
OGRE_CHECK_GL_ERROR(glTexParameterf(target, pname, param));
}
}
}
void GLES2StateCacheManagerImp::getTexParameterfv(GLenum target, GLenum pname, GLfloat *params)
{
// Check if we have a map entry for this texture id.
TexUnitsMap::iterator it = mTexUnitsMap.find(mLastBoundTexID);
// Get a local copy of the parameter map and search for this parameter
TexParameterfMap::iterator i = (*it).second.mTexParameterfMap.find(pname);
params = &(*i).second;
}
void GLES2StateCacheManagerImp::bindGLTexture(GLenum target, GLuint texture)
{
mLastBoundTexID = texture;
// Update GL
OGRE_CHECK_GL_ERROR(glBindTexture(target, texture));
}
bool GLES2StateCacheManagerImp::activateGLTextureUnit(size_t unit)
{
if (mActiveTextureUnit != unit)
{
if (unit < dynamic_cast<GLES2RenderSystem*>(Root::getSingleton().getRenderSystem())->getCapabilities()->getNumTextureUnits())
{
OGRE_CHECK_GL_ERROR(glActiveTexture(GL_TEXTURE0 + unit));
mActiveTextureUnit = unit;
return true;
}
else if (!unit)
{
// always ok to use the first unit
return true;
}
else
{
return false;
}
}
else
{
return true;
}
}
// TODO: Store as high/low bits of a GLuint
void GLES2StateCacheManagerImp::setBlendFunc(GLenum source, GLenum dest)
{
if(mBlendFuncSource != source || mBlendFuncDest != dest)
{
mBlendFuncSource = source;
mBlendFuncDest = dest;
OGRE_CHECK_GL_ERROR(glBlendFunc(source, dest));
}
}
void GLES2StateCacheManagerImp::setBlendEquation(GLenum eq)
{
if(mBlendEquation != eq)
{
mBlendEquation = eq;
OGRE_CHECK_GL_ERROR(glBlendEquation(eq));
}
}
void GLES2StateCacheManagerImp::setDepthMask(GLboolean mask)
{
if(mDepthMask != mask)
{
mDepthMask = mask;
OGRE_CHECK_GL_ERROR(glDepthMask(mask));
}
}
void GLES2StateCacheManagerImp::setDepthFunc(GLenum func)
{
if(mDepthFunc != func)
{
mDepthFunc = func;
OGRE_CHECK_GL_ERROR(glDepthFunc(func));
}
}
void GLES2StateCacheManagerImp::setClearDepth(GLclampf depth)
{
if(mClearDepth != depth)
{
mClearDepth = depth;
OGRE_CHECK_GL_ERROR(glClearDepthf(depth));
}
}
void GLES2StateCacheManagerImp::setClearColour(GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha)
{
if((mClearColour[0] != red) ||
(mClearColour[1] != green) ||
(mClearColour[2] != blue) ||
(mClearColour[3] != alpha))
{
mClearColour[0] = red;
mClearColour[1] = green;
mClearColour[2] = blue;
mClearColour[3] = alpha;
OGRE_CHECK_GL_ERROR(glClearColor(mClearColour[0], mClearColour[1], mClearColour[2], mClearColour[3]));
}
}
void GLES2StateCacheManagerImp::setColourMask(GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha)
{
if((mColourMask[0] != red) ||
(mColourMask[1] != green) ||
(mColourMask[2] != blue) ||
(mColourMask[3] != alpha))
{
mColourMask[0] = red;
mColourMask[1] = green;
mColourMask[2] = blue;
mColourMask[3] = alpha;
OGRE_CHECK_GL_ERROR(glColorMask(mColourMask[0], mColourMask[1], mColourMask[2], mColourMask[3]));
}
}
void GLES2StateCacheManagerImp::setStencilMask(GLuint mask)
{
if(mStencilMask != mask)
{
mStencilMask = mask;
OGRE_CHECK_GL_ERROR(glStencilMask(mask));
}
}
void GLES2StateCacheManagerImp::setEnabled(GLenum flag)
{
bool found = std::find(mEnableVector.begin(), mEnableVector.end(), flag) != mEnableVector.end();
if(!found)
{
mEnableVector.push_back(flag);
OGRE_CHECK_GL_ERROR(glEnable(flag));
}
}
void GLES2StateCacheManagerImp::setDisabled(GLenum flag)
{
vector<GLenum>::iterator iter = std::find(mEnableVector.begin(), mEnableVector.end(), flag);
if(iter != mEnableVector.end())
{
mEnableVector.erase(iter);
OGRE_CHECK_GL_ERROR(glDisable(flag));
}
}
void GLES2StateCacheManagerImp::setVertexAttribEnabled(GLuint attrib)
{
bool found = std::find(mEnabledVertexAttribs.begin(), mEnabledVertexAttribs.end(), attrib) != mEnabledVertexAttribs.end();
if(!found)
{
mEnabledVertexAttribs.push_back(attrib);
OGRE_CHECK_GL_ERROR(glEnableVertexAttribArray(attrib));
}
}
void GLES2StateCacheManagerImp::setVertexAttribDisabled(GLuint attrib)
{
vector<GLuint>::iterator iter = std::find(mEnabledVertexAttribs.begin(), mEnabledVertexAttribs.end(), attrib);
if(iter != mEnabledVertexAttribs.end())
{
mEnabledVertexAttribs.erase(iter);
OGRE_CHECK_GL_ERROR(glDisableVertexAttribArray(attrib));
}
}
void GLES2StateCacheManagerImp::setCullFace(GLenum face)
{
if(mCullFace != face)
{
mCullFace = face;
OGRE_CHECK_GL_ERROR(glCullFace(face));
}
}
}
<commit_msg>[OGRE-300] Apply GL state cache crash fix to GLES2 state cache.<commit_after>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2013 Torus Knot Software Ltd
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/
#include "OgreStableHeaders.h"
#include "OgreGLES2StateCacheManagerImp.h"
#include "OgreGLES2RenderSystem.h"
#include "OgreLogManager.h"
#include "OgreRoot.h"
namespace Ogre {
GLES2StateCacheManagerImp::GLES2StateCacheManagerImp(void)
{
clearCache();
}
void GLES2StateCacheManagerImp::initializeCache()
{
OGRE_CHECK_GL_ERROR(glBlendEquation(GL_FUNC_ADD));
OGRE_CHECK_GL_ERROR(glBlendFunc(GL_ONE, GL_ZERO));
OGRE_CHECK_GL_ERROR(glCullFace(mCullFace));
OGRE_CHECK_GL_ERROR(glDepthFunc(mDepthFunc));
OGRE_CHECK_GL_ERROR(glDepthMask(mDepthMask));
OGRE_CHECK_GL_ERROR(glStencilMask(mStencilMask));
OGRE_CHECK_GL_ERROR(glClearDepthf(mClearDepth));
OGRE_CHECK_GL_ERROR(glBindTexture(GL_TEXTURE_2D, 0));
OGRE_CHECK_GL_ERROR(glBindBuffer(GL_ARRAY_BUFFER, 0));
OGRE_CHECK_GL_ERROR(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0));
OGRE_CHECK_GL_ERROR(glBindFramebuffer(GL_FRAMEBUFFER, 0));
OGRE_CHECK_GL_ERROR(glBindRenderbuffer(GL_RENDERBUFFER, 0));
OGRE_CHECK_GL_ERROR(glActiveTexture(GL_TEXTURE0));
OGRE_CHECK_GL_ERROR(glClearColor(mClearColour[0], mClearColour[1], mClearColour[2], mClearColour[3]));
OGRE_CHECK_GL_ERROR(glColorMask(mColourMask[0], mColourMask[1], mColourMask[2], mColourMask[3]));
}
void GLES2StateCacheManagerImp::clearCache()
{
mDepthMask = GL_TRUE;
mPolygonMode = GL_FILL;
mBlendEquation = GL_FUNC_ADD;
mCullFace = GL_BACK;
mDepthFunc = GL_LESS;
mStencilMask = 0xFFFFFFFF;
mActiveTextureUnit = 0;
mDiscardBuffers = 0;
mClearDepth = 1.0f;
mLastBoundTexID = 0;
// Initialize our cache variables and also the GL so that the
// stored values match the GL state
mBlendFuncSource = GL_ONE;
mBlendFuncDest = GL_ZERO;
mClearColour.resize(4);
mClearColour[0] = mClearColour[1] = mClearColour[2] = mClearColour[3] = 0.0f;
mColourMask.resize(4);
mColourMask[0] = mColourMask[1] = mColourMask[2] = mColourMask[3] = GL_TRUE;
mEnableVector.reserve(25);
mEnableVector.clear();
mActiveBufferMap.clear();
mTexUnitsMap.clear();
mEnableVector.reserve(64);
mEnabledVertexAttribs.clear();
}
GLES2StateCacheManagerImp::~GLES2StateCacheManagerImp(void)
{
mColourMask.clear();
mClearColour.clear();
mActiveBufferMap.clear();
mEnableVector.clear();
mTexUnitsMap.clear();
}
void GLES2StateCacheManagerImp::bindGLBuffer(GLenum target, GLuint buffer, GLenum attach, bool force)
{
bool update = false;
BindBufferMap::iterator i = mActiveBufferMap.find(target);
if (i == mActiveBufferMap.end())
{
// Haven't cached this state yet. Insert it into the map
mActiveBufferMap.insert(BindBufferMap::value_type(target, buffer));
update = true;
}
else if((*i).second != buffer || force) // Update the cached value if needed
{
(*i).second = buffer;
update = true;
}
// Update GL
if(update)
{
if(target == GL_FRAMEBUFFER)
{
OGRE_CHECK_GL_ERROR(glBindFramebuffer(target, buffer));
}
else if(target == GL_RENDERBUFFER)
{
OGRE_CHECK_GL_ERROR(glBindRenderbuffer(target, buffer));
}
else
{
OGRE_CHECK_GL_ERROR(glBindBuffer(target, buffer));
}
}
}
void GLES2StateCacheManagerImp::deleteGLBuffer(GLenum target, GLuint buffer, GLenum attach, bool force)
{
// Buffer name 0 is reserved and we should never try to delete it
if(buffer == 0)
return;
BindBufferMap::iterator i = mActiveBufferMap.find(target);
if (i != mActiveBufferMap.end() && ((*i).second == buffer || force))
{
if(target == GL_FRAMEBUFFER)
{
OGRE_CHECK_GL_ERROR(glDeleteFramebuffers(1, &buffer));
}
else if(target == GL_RENDERBUFFER)
{
OGRE_CHECK_GL_ERROR(glDeleteRenderbuffers(1, &buffer));
}
else
{
OGRE_CHECK_GL_ERROR(glDeleteBuffers(1, &buffer));
}
// Currently bound buffer is being deleted, update the cached value to 0,
// which it likely the buffer that will be bound by the driver.
// An update will be forced next time we try to bind on this target.
(*i).second = 0;
}
}
void GLES2StateCacheManagerImp::invalidateStateForTexture(GLuint texture)
{
mTexUnitsMap.erase(texture);
}
// TODO: Store as high/low bits of a GLuint, use vector instead of map for TexParameteriMap
void GLES2StateCacheManagerImp::setTexParameteri(GLenum target, GLenum pname, GLint param)
{
// Check if we have a map entry for this texture id. If not, create a blank one and insert it.
TexUnitsMap::iterator it = mTexUnitsMap.find(mLastBoundTexID);
if (it == mTexUnitsMap.end())
{
TextureUnitParams unit;
mTexUnitsMap[mLastBoundTexID] = unit;
// Update the iterator
it = mTexUnitsMap.find(mLastBoundTexID);
}
// Get a local copy of the parameter map and search for this parameter
TexParameteriMap &myMap = (*it).second.mTexParameteriMap;
TexParameteriMap::iterator i = myMap.find(pname);
if (i == myMap.end())
{
// Haven't cached this state yet. Insert it into the map
myMap.insert(TexParameteriMap::value_type(pname, param));
// Update GL
OGRE_CHECK_GL_ERROR(glTexParameteri(target, pname, param));
}
else
{
// Update the cached value if needed
if((*i).second != param)
{
(*i).second = param;
// Update GL
OGRE_CHECK_GL_ERROR(glTexParameteri(target, pname, param));
}
}
}
void GLES2StateCacheManagerImp::setTexParameterf(GLenum target, GLenum pname, GLfloat param)
{
// Check if we have a map entry for this texture id. If not, create a blank one and insert it.
TexUnitsMap::iterator it = mTexUnitsMap.find(mLastBoundTexID);
if (it == mTexUnitsMap.end())
{
TextureUnitParams unit;
mTexUnitsMap[mLastBoundTexID] = unit;
// Update the iterator
it = mTexUnitsMap.find(mLastBoundTexID);
}
// Get a local copy of the parameter map and search for this parameter
TexParameterfMap &myMap = (*it).second.mTexParameterfMap;
TexParameterfMap::iterator i = myMap.find(pname);
if (i == myMap.end())
{
// Haven't cached this state yet. Insert it into the map
myMap.insert(TexParameterfMap::value_type(pname, param));
// Update GL
OGRE_CHECK_GL_ERROR(glTexParameterf(target, pname, param));
}
else
{
// Update the cached value if needed
if((*i).second != param)
{
(*i).second = param;
// Update GL
OGRE_CHECK_GL_ERROR(glTexParameterf(target, pname, param));
}
}
}
void GLES2StateCacheManagerImp::getTexParameterfv(GLenum target, GLenum pname, GLfloat *params)
{
// Check if we have a map entry for this texture id.
TexUnitsMap::iterator it = mTexUnitsMap.find(mLastBoundTexID);
// Get a local copy of the parameter map and search for this parameter
TexParameterfMap::iterator i = (*it).second.mTexParameterfMap.find(pname);
params = &(*i).second;
}
void GLES2StateCacheManagerImp::bindGLTexture(GLenum target, GLuint texture)
{
mLastBoundTexID = texture;
// Update GL
OGRE_CHECK_GL_ERROR(glBindTexture(target, texture));
}
bool GLES2StateCacheManagerImp::activateGLTextureUnit(size_t unit)
{
if (mActiveTextureUnit != unit)
{
if (unit < dynamic_cast<GLES2RenderSystem*>(Root::getSingleton().getRenderSystem())->getCapabilities()->getNumTextureUnits())
{
OGRE_CHECK_GL_ERROR(glActiveTexture(GL_TEXTURE0 + unit));
mActiveTextureUnit = unit;
return true;
}
else if (!unit)
{
// always ok to use the first unit
return true;
}
else
{
return false;
}
}
else
{
return true;
}
}
// TODO: Store as high/low bits of a GLuint
void GLES2StateCacheManagerImp::setBlendFunc(GLenum source, GLenum dest)
{
if(mBlendFuncSource != source || mBlendFuncDest != dest)
{
mBlendFuncSource = source;
mBlendFuncDest = dest;
OGRE_CHECK_GL_ERROR(glBlendFunc(source, dest));
}
}
void GLES2StateCacheManagerImp::setBlendEquation(GLenum eq)
{
if(mBlendEquation != eq)
{
mBlendEquation = eq;
OGRE_CHECK_GL_ERROR(glBlendEquation(eq));
}
}
void GLES2StateCacheManagerImp::setDepthMask(GLboolean mask)
{
if(mDepthMask != mask)
{
mDepthMask = mask;
OGRE_CHECK_GL_ERROR(glDepthMask(mask));
}
}
void GLES2StateCacheManagerImp::setDepthFunc(GLenum func)
{
if(mDepthFunc != func)
{
mDepthFunc = func;
OGRE_CHECK_GL_ERROR(glDepthFunc(func));
}
}
void GLES2StateCacheManagerImp::setClearDepth(GLclampf depth)
{
if(mClearDepth != depth)
{
mClearDepth = depth;
OGRE_CHECK_GL_ERROR(glClearDepthf(depth));
}
}
void GLES2StateCacheManagerImp::setClearColour(GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha)
{
if((mClearColour[0] != red) ||
(mClearColour[1] != green) ||
(mClearColour[2] != blue) ||
(mClearColour[3] != alpha))
{
mClearColour[0] = red;
mClearColour[1] = green;
mClearColour[2] = blue;
mClearColour[3] = alpha;
OGRE_CHECK_GL_ERROR(glClearColor(mClearColour[0], mClearColour[1], mClearColour[2], mClearColour[3]));
}
}
void GLES2StateCacheManagerImp::setColourMask(GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha)
{
if((mColourMask[0] != red) ||
(mColourMask[1] != green) ||
(mColourMask[2] != blue) ||
(mColourMask[3] != alpha))
{
mColourMask[0] = red;
mColourMask[1] = green;
mColourMask[2] = blue;
mColourMask[3] = alpha;
OGRE_CHECK_GL_ERROR(glColorMask(mColourMask[0], mColourMask[1], mColourMask[2], mColourMask[3]));
}
}
void GLES2StateCacheManagerImp::setStencilMask(GLuint mask)
{
if(mStencilMask != mask)
{
mStencilMask = mask;
OGRE_CHECK_GL_ERROR(glStencilMask(mask));
}
}
void GLES2StateCacheManagerImp::setEnabled(GLenum flag)
{
bool found = std::find(mEnableVector.begin(), mEnableVector.end(), flag) != mEnableVector.end();
if(!found)
{
mEnableVector.push_back(flag);
OGRE_CHECK_GL_ERROR(glEnable(flag));
}
}
void GLES2StateCacheManagerImp::setDisabled(GLenum flag)
{
vector<GLenum>::iterator iter = std::find(mEnableVector.begin(), mEnableVector.end(), flag);
if(iter != mEnableVector.end())
{
mEnableVector.erase(iter);
OGRE_CHECK_GL_ERROR(glDisable(flag));
}
}
void GLES2StateCacheManagerImp::setVertexAttribEnabled(GLuint attrib)
{
bool found = std::find(mEnabledVertexAttribs.begin(), mEnabledVertexAttribs.end(), attrib) != mEnabledVertexAttribs.end();
if(!found)
{
mEnabledVertexAttribs.push_back(attrib);
OGRE_CHECK_GL_ERROR(glEnableVertexAttribArray(attrib));
}
}
void GLES2StateCacheManagerImp::setVertexAttribDisabled(GLuint attrib)
{
vector<GLuint>::iterator iter = std::find(mEnabledVertexAttribs.begin(), mEnabledVertexAttribs.end(), attrib);
if(iter != mEnabledVertexAttribs.end())
{
mEnabledVertexAttribs.erase(iter);
OGRE_CHECK_GL_ERROR(glDisableVertexAttribArray(attrib));
}
}
void GLES2StateCacheManagerImp::setCullFace(GLenum face)
{
if(mCullFace != face)
{
mCullFace = face;
OGRE_CHECK_GL_ERROR(glCullFace(face));
}
}
}
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.