text
stringlengths
54
60.6k
<commit_before>/** * Copyright (c) 2011-2015 libbitcoin developers (see AUTHORS) * Copyright (c) 2016-2017 metaverse core developers (see MVS-AUTHORS) * * This file is part of metaverse-explorer. * * metaverse-explorer is free software: you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License with * additional permissions to the one published by the Free Software * Foundation, either version 3 of the License, or (at your option) * any later version. For more information see LICENSE. * * 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <metaverse/explorer/commands/offline_commands_impl.hpp> #include <metaverse/explorer/extensions/exception.hpp> namespace libbitcoin { namespace explorer { namespace commands { //seed data_chunk get_seed(uint16_t bit_length) { // These are soft requirements for security and rationality. // We use bit vs. byte length input as the more familiar convention. if (bit_length < minimum_seed_size * byte_bits || bit_length % byte_bits != 0) { // chenhao exception throw seed_size_exception{MVSCLI_SEED_BIT_LENGTH_UNSUPPORTED}; } return new_seed(bit_length); } //mnemonic-new bw::word_list get_mnemonic_new(const bw::dictionary_list& language, const data_chunk& entropy) { const auto entropy_size = entropy.size(); if ((entropy_size % bw::mnemonic_seed_multiple) != 0) { // chenhao exception throw seed_length_exception{MVSCLI_EC_MNEMONIC_NEW_INVALID_ENTROPY}; } // If 'any' default to first ('en'), otherwise the one specified. const auto dictionary = language.front(); return bw::create_mnemonic(entropy, *dictionary); } //mnemonic-to-seed data_chunk get_mnemonic_to_seed(const bw::dictionary_list& language, const bw::word_list& words, std::string passphrase) { const auto word_count = words.size(); if ((word_count % bw::mnemonic_word_multiple) != 0) { // chenhao exception throw mnemonicwords_amount_exception{MVSCLI_EC_MNEMONIC_TO_SEED_LENGTH_INVALID_SENTENCE}; } const auto valid = bw::validate_mnemonic(words, language); if (!valid && language.size() == 1) { // This is fatal because a dictionary was specified explicitly. // chenhao exception throw mnemonicwords_content_exception{MVSCLI_EC_MNEMONIC_TO_SEED_INVALID_IN_LANGUAGE}; } // chenhao exception if (!valid && language.size() > 1) throw mnemonicwords_content_exception{MVSCLI_EC_MNEMONIC_TO_SEED_INVALID_IN_LANGUAGES}; #ifdef WITH_ICU // Any word set divisible by 3 works regardless of language validation. const auto seed = bw::decode_mnemonic(words, passphrase); #else if (!passphrase.empty()) { // chenhao exception throw mnemonicwords_content_exception{MVSCLI_EC_MNEMONIC_TO_SEED_PASSPHRASE_UNSUPPORTED}; } // The passphrase requires ICU normalization. const auto seed = bw::decode_mnemonic(words); #endif const data_chunk& dc_seed = bc::config::base16(seed); return dc_seed; } //hd-new bw::hd_private get_hd_new(const data_chunk& seed, uint32_t version) { if (seed.size() < minimum_seed_size) { // chenhao exception throw hd_length_exception{MVSCLI_HD_NEW_SHORT_SEED}; } // We require the private version, but public is unused here. const auto prefixes = bc::wallet::hd_private::to_prefixes(version, 0); const bc::wallet::hd_private private_key(seed, prefixes); if (!private_key) { // chenhao exception throw hd_key_exception{MVSCLI_HD_NEW_INVALID_KEY}; } return private_key; } } //namespace commands } //namespace explorer } //namespace libbitcoin <commit_msg>fix get_hd_new issue: return dc_seed&<commit_after>/** * Copyright (c) 2011-2015 libbitcoin developers (see AUTHORS) * Copyright (c) 2016-2017 metaverse core developers (see MVS-AUTHORS) * * This file is part of metaverse-explorer. * * metaverse-explorer is free software: you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License with * additional permissions to the one published by the Free Software * Foundation, either version 3 of the License, or (at your option) * any later version. For more information see LICENSE. * * 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <metaverse/explorer/commands/offline_commands_impl.hpp> #include <metaverse/explorer/extensions/exception.hpp> namespace libbitcoin { namespace explorer { namespace commands { //seed data_chunk get_seed(uint16_t bit_length) { // These are soft requirements for security and rationality. // We use bit vs. byte length input as the more familiar convention. if (bit_length < minimum_seed_size * byte_bits || bit_length % byte_bits != 0) { // chenhao exception throw seed_size_exception{MVSCLI_SEED_BIT_LENGTH_UNSUPPORTED}; } return new_seed(bit_length); } //mnemonic-new bw::word_list get_mnemonic_new(const bw::dictionary_list& language, const data_chunk& entropy) { const auto entropy_size = entropy.size(); if ((entropy_size % bw::mnemonic_seed_multiple) != 0) { // chenhao exception throw seed_length_exception{MVSCLI_EC_MNEMONIC_NEW_INVALID_ENTROPY}; } // If 'any' default to first ('en'), otherwise the one specified. const auto dictionary = language.front(); return bw::create_mnemonic(entropy, *dictionary); } //mnemonic-to-seed data_chunk get_mnemonic_to_seed(const bw::dictionary_list& language, const bw::word_list& words, std::string passphrase) { const auto word_count = words.size(); if ((word_count % bw::mnemonic_word_multiple) != 0) { // chenhao exception throw mnemonicwords_amount_exception{MVSCLI_EC_MNEMONIC_TO_SEED_LENGTH_INVALID_SENTENCE}; } const auto valid = bw::validate_mnemonic(words, language); if (!valid && language.size() == 1) { // This is fatal because a dictionary was specified explicitly. // chenhao exception throw mnemonicwords_content_exception{MVSCLI_EC_MNEMONIC_TO_SEED_INVALID_IN_LANGUAGE}; } // chenhao exception if (!valid && language.size() > 1) throw mnemonicwords_content_exception{MVSCLI_EC_MNEMONIC_TO_SEED_INVALID_IN_LANGUAGES}; #ifdef WITH_ICU // Any word set divisible by 3 works regardless of language validation. const auto seed = bw::decode_mnemonic(words, passphrase); #else if (!passphrase.empty()) { // chenhao exception throw mnemonicwords_content_exception{MVSCLI_EC_MNEMONIC_TO_SEED_PASSPHRASE_UNSUPPORTED}; } // The passphrase requires ICU normalization. const auto seed = bw::decode_mnemonic(words); #endif return bc::config::base16(seed); } //hd-new bw::hd_private get_hd_new(const data_chunk& seed, uint32_t version) { if (seed.size() < minimum_seed_size) { // chenhao exception throw hd_length_exception{MVSCLI_HD_NEW_SHORT_SEED}; } // We require the private version, but public is unused here. const auto prefixes = bc::wallet::hd_private::to_prefixes(version, 0); const bc::wallet::hd_private private_key(seed, prefixes); if (!private_key) { // chenhao exception throw hd_key_exception{MVSCLI_HD_NEW_INVALID_KEY}; } return private_key; } } //namespace commands } //namespace explorer } //namespace libbitcoin <|endoftext|>
<commit_before>/*************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (directui@nokia.com) ** ** This file is part of mhome. ** ** If you have questions regarding the use of this file, please contact ** Nokia at directui@nokia.com. ** ** 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 ** and appearing in the file LICENSE.LGPL included in the packaging ** of this file. ** ****************************************************************************/ #include "applicationpackagemonitor.h" #include "launcherdatastore.h" #include <QDir> #include <QDBusConnection> #include <mdesktopentry.h> #include <mfiledatastore.h> #include <msubdatastore.h> static const QString PACKAGE_MANAGER_DBUS_SERVICE="com.nokia.package_manager"; static const QString PACKAGE_MANAGER_DBUS_PATH="/com/nokia/package_manager"; static const QString PACKAGE_MANAGER_DBUS_INTERFACE="com.nokia.package_manager"; static const QString OPERATION_INSTALL = "Install"; static const QString OPERATION_UNINSTALL = "Uninstall"; static const QString OPERATION_REFRESH = "Refresh"; static const QString OPERATION_UPGRADE = "Upgrade"; static const QString DESKTOPENTRY_PREFIX = "DesktopEntries"; static const QString PACKAGE_PREFIX = "Packages/"; static const QString INSTALLER_EXTRA = "installer-extra/"; static const QString CONFIG_PATH = "/.config/meegotouchhome"; static const QString PACKAGE_STATE_INSTALLED = "installed"; static const QString PACKAGE_STATE_INSTALLABLE = "installable"; static const QString PACKAGE_STATE_BROKEN = "broken"; static const QString PACKAGE_STATE_UPDATEABLE = "updateable"; static const QString PACKAGE_STATE_INSTALLING ="installing"; static const QString PACKAGE_STATE_DOWNLOADING ="downloading"; static const QString DESKTOP_ENTRY_KEY_PACKAGE_STATE = "PackageState"; static const QString DESKTOP_ENTRY_KEY_PACKAGE_NAME = "Package"; static const QString DESKTOP_ENTRY_GROUP_MEEGO = "X-MeeGo"; class ApplicationPackageMonitor::ExtraDirWatcher : public LauncherDataStore { public: ExtraDirWatcher(MDataStore *dataStore, const QString &directoryPath); ~ExtraDirWatcher(); protected: virtual bool isDesktopEntryValid(const MDesktopEntry &entry, const QStringList &acceptedTypes); }; ApplicationPackageMonitor::ApplicationPackageMonitor() : con(QDBusConnection::systemBus()) { con.connect(QString(),PACKAGE_MANAGER_DBUS_PATH, PACKAGE_MANAGER_DBUS_INTERFACE, "download_progress", this, SLOT(packageDownloadProgress(const QString&, const QString&, const QString&, int, int))); con.connect(QString(),PACKAGE_MANAGER_DBUS_PATH, PACKAGE_MANAGER_DBUS_INTERFACE, "operation_started", this, SLOT(packageOperationStarted(const QString&, const QString&, const QString&))); con.connect(QString(),PACKAGE_MANAGER_DBUS_PATH, PACKAGE_MANAGER_DBUS_INTERFACE, "operation_progress", this, SLOT(packageOperationProgress(const QString&, const QString &, const QString&, int))); con.connect(QString(),PACKAGE_MANAGER_DBUS_PATH, PACKAGE_MANAGER_DBUS_INTERFACE, "operation_complete", this, SLOT(packageOperationComplete(const QString&, const QString&, const QString&, const QString&, bool))); QString configPath = QDir::homePath() + CONFIG_PATH; if (!QDir::root().exists(configPath)) { QDir::root().mkpath(configPath); } QString dataStoreFileName = configPath + "/applicationpackage.data"; dataStore = new MFileDataStore(dataStoreFileName); // ExtraDirWatcher takes ownership of dataStore extraDirWatcher = QSharedPointer<ExtraDirWatcher>(new ExtraDirWatcher(dataStore, APPLICATIONS_DIRECTORY+INSTALLER_EXTRA)); connect(extraDirWatcher.data(), SIGNAL(desktopEntryAdded(QString)), this, SLOT(updatePackageState(QString)), Qt::UniqueConnection); connect(extraDirWatcher.data(), SIGNAL(desktopEntryChanged(QString)), this, SLOT(updatePackageState(QString)), Qt::UniqueConnection); connect(extraDirWatcher.data(), SIGNAL(desktopEntryRemoved(QString)), this, SLOT(packageRemoved(QString)), Qt::UniqueConnection); } ApplicationPackageMonitor::~ApplicationPackageMonitor() { } void ApplicationPackageMonitor::packageRemoved(const QString &desktopEntryPath) { QString packageKey; foreach(const QString &pkgKey, dataStore->allKeys()) { if(pkgKey.contains(PACKAGE_PREFIX)) { if(dataStore->value(pkgKey).toString() == desktopEntryPath) { packageKey = pkgKey; break; } } } dataStore->remove(DESKTOPENTRY_PREFIX+desktopEntryPath); dataStore->remove(packageKey); activePackages.remove(packageKey.remove(PACKAGE_PREFIX)); emit installExtraEntryRemoved(desktopEntryPath); } void ApplicationPackageMonitor::updatePackageStates() { QStringList keyList(dataStore->allKeys()); foreach (QString key, keyList) { if (key.contains(PACKAGE_PREFIX)) { QString desktopEntryPath = dataStore->value(key).toString(); QString state = dataStore->value(DESKTOPENTRY_PREFIX + desktopEntryPath).toString(); if (state == PACKAGE_STATE_BROKEN) { // emit operation error for a broken package emit operationError(desktopEntryPath, QString()); } else if(state == PACKAGE_STATE_DOWNLOADING) { emit downloadProgress(desktopEntryPath, 0, 0); } else if(state == PACKAGE_STATE_INSTALLING) { emit installProgress(desktopEntryPath, 0); } } } } ApplicationPackageMonitor::PackageProperties &ApplicationPackageMonitor::activePackageProperties(const QString packageName) { if (!activePackages.contains(packageName)) { // Set the desktopEntryName if already known activePackages[packageName].desktopEntryName = desktopEntryName(packageName); } return activePackages[packageName]; } void ApplicationPackageMonitor::packageDownloadProgress(const QString &operation, const QString &packageName, const QString &packageVersion, int already, int total) { Q_UNUSED(operation) Q_UNUSED(packageVersion) PackageProperties &properties = activePackageProperties(packageName); if (isValidOperation(properties, operation)) { emit downloadProgress(properties.desktopEntryName, already, total); } storePackageState(packageName, PACKAGE_STATE_DOWNLOADING); } void ApplicationPackageMonitor::packageOperationStarted(const QString &operation, const QString &packageName, const QString &version) { Q_UNUSED(operation) Q_UNUSED(packageName) Q_UNUSED(version) } void ApplicationPackageMonitor::packageOperationProgress(const QString &operation, const QString &packageName, const QString &packageVersion, int percentage) { Q_UNUSED(packageVersion) PackageProperties &properties = activePackageProperties(packageName); if (isValidOperation(properties, operation)) { properties.installing = true; emit installProgress(properties.desktopEntryName, percentage); storePackageState(packageName, PACKAGE_STATE_INSTALLING); } } void ApplicationPackageMonitor::packageOperationComplete(const QString &operation, const QString &packageName, const QString &packageVersion, const QString &error, bool need_reboot) { Q_UNUSED(packageVersion) Q_UNUSED(need_reboot) PackageProperties &properties = activePackageProperties(packageName); if (!isValidOperation(properties, operation)) { return; } if (!error.isEmpty()) { if (properties.installing) { emit operationError(properties.desktopEntryName, error); storePackageState(packageName, PACKAGE_STATE_BROKEN); } else { // Downloading MDesktopEntry entry(properties.desktopEntryName); QString packageState = entry.value(DESKTOP_ENTRY_GROUP_MEEGO, DESKTOP_ENTRY_KEY_PACKAGE_STATE); if (packageState == PACKAGE_STATE_INSTALLED || packageState == PACKAGE_STATE_UPDATEABLE) { // Application is previously installed. Downloading update failed but application still usable. emit operationSuccess(properties.desktopEntryName.replace(INSTALLER_EXTRA, QString())); storePackageState(packageName, packageState); } else { emit operationError(properties.desktopEntryName, error); storePackageState(packageName, PACKAGE_STATE_BROKEN); } } } else { emit operationSuccess(properties.desktopEntryName.replace(INSTALLER_EXTRA, QString())); storePackageState(packageName, PACKAGE_STATE_INSTALLED); } activePackages.remove(packageName); } void ApplicationPackageMonitor::storePackageState(const QString& packageName, const QString& state) { QString path = dataStore->value(PACKAGE_PREFIX + packageName).toString(); extraDirWatcher->updateDataForDesktopEntry(path, state); } bool ApplicationPackageMonitor::isValidOperation(const PackageProperties &properties, const QString &operation) { if ((operation.compare(OPERATION_INSTALL, Qt::CaseInsensitive) == 0 || operation.compare(OPERATION_UPGRADE, Qt::CaseInsensitive) == 0 ) && !properties.desktopEntryName.isEmpty() ) { return true; } else { return false; } } void ApplicationPackageMonitor::updatePackageState(const QString &desktopEntryPath) { MDesktopEntry entry(desktopEntryPath); QString packageName = entry.value(DESKTOP_ENTRY_GROUP_MEEGO, DESKTOP_ENTRY_KEY_PACKAGE_NAME); QString packageState = entry.value(DESKTOP_ENTRY_GROUP_MEEGO, DESKTOP_ENTRY_KEY_PACKAGE_STATE); if (!packageName.isEmpty()) { QString pkgKey = PACKAGE_PREFIX+packageName; if (packageState == PACKAGE_STATE_BROKEN) { // emit operation error for a broken package emit operationError(desktopEntryPath, QString()); } dataStore->createValue(pkgKey, desktopEntryPath); if (activePackages.contains(packageName)) { // Package is being installed, add the desktop entry path directly activePackages[packageName].desktopEntryName = desktopEntryPath; } } extraDirWatcher->updateDataForDesktopEntry(desktopEntryPath, packageState); } QString ApplicationPackageMonitor::desktopEntryName(const QString &packageName) { QString pkgKey = PACKAGE_PREFIX+packageName; if (!dataStore->contains(pkgKey)) { // Package not installed return QString(); } if (!QFile::exists(dataStore->value(pkgKey).toString())) { // The extra desktop file doesn't exist anymore, the package has been uninstalled dataStore->remove(pkgKey); return QString(); } return dataStore->value(pkgKey).toString(); } ApplicationPackageMonitor::ExtraDirWatcher::ExtraDirWatcher(MDataStore *dataStore, const QString &directoryPath) : LauncherDataStore(dataStore, directoryPath) { } ApplicationPackageMonitor::ExtraDirWatcher::~ExtraDirWatcher() { } bool ApplicationPackageMonitor::ExtraDirWatcher::isDesktopEntryValid(const MDesktopEntry &entry, const QStringList &acceptedTypes) { Q_UNUSED(acceptedTypes); return entry.contains(DESKTOP_ENTRY_GROUP_MEEGO, DESKTOP_ENTRY_KEY_PACKAGE_NAME) && entry.contains(DESKTOP_ENTRY_GROUP_MEEGO, DESKTOP_ENTRY_KEY_PACKAGE_STATE); } <commit_msg>Also check PackageHadError field in installer-extra Desktop Entry supplements.<commit_after>/*************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (directui@nokia.com) ** ** This file is part of mhome. ** ** If you have questions regarding the use of this file, please contact ** Nokia at directui@nokia.com. ** ** 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 ** and appearing in the file LICENSE.LGPL included in the packaging ** of this file. ** ****************************************************************************/ #include "applicationpackagemonitor.h" #include "launcherdatastore.h" #include <QDir> #include <QDBusConnection> #include <mdesktopentry.h> #include <mfiledatastore.h> #include <msubdatastore.h> static const QString PACKAGE_MANAGER_DBUS_SERVICE="com.nokia.package_manager"; static const QString PACKAGE_MANAGER_DBUS_PATH="/com/nokia/package_manager"; static const QString PACKAGE_MANAGER_DBUS_INTERFACE="com.nokia.package_manager"; static const QString OPERATION_INSTALL = "Install"; static const QString OPERATION_UNINSTALL = "Uninstall"; static const QString OPERATION_REFRESH = "Refresh"; static const QString OPERATION_UPGRADE = "Upgrade"; static const QString DESKTOPENTRY_PREFIX = "DesktopEntries"; static const QString PACKAGE_PREFIX = "Packages/"; static const QString INSTALLER_EXTRA = "installer-extra/"; static const QString CONFIG_PATH = "/.config/meegotouchhome"; static const QString PACKAGE_STATE_INSTALLED = "installed"; static const QString PACKAGE_STATE_INSTALLABLE = "installable"; static const QString PACKAGE_STATE_BROKEN = "broken"; static const QString PACKAGE_STATE_UPDATEABLE = "updateable"; static const QString PACKAGE_STATE_INSTALLING ="installing"; static const QString PACKAGE_STATE_DOWNLOADING ="downloading"; static const QString DESKTOP_ENTRY_KEY_PACKAGE_STATE = "PackageState"; static const QString DESKTOP_ENTRY_KEY_PACKAGE_HAD_ERROR = "PackageHadError"; static const QString DESKTOP_ENTRY_KEY_PACKAGE_NAME = "Package"; static const QString DESKTOP_ENTRY_GROUP_MEEGO = "X-MeeGo"; class ApplicationPackageMonitor::ExtraDirWatcher : public LauncherDataStore { public: ExtraDirWatcher(MDataStore *dataStore, const QString &directoryPath); ~ExtraDirWatcher(); protected: virtual bool isDesktopEntryValid(const MDesktopEntry &entry, const QStringList &acceptedTypes); }; ApplicationPackageMonitor::ApplicationPackageMonitor() : con(QDBusConnection::systemBus()) { con.connect(QString(),PACKAGE_MANAGER_DBUS_PATH, PACKAGE_MANAGER_DBUS_INTERFACE, "download_progress", this, SLOT(packageDownloadProgress(const QString&, const QString&, const QString&, int, int))); con.connect(QString(),PACKAGE_MANAGER_DBUS_PATH, PACKAGE_MANAGER_DBUS_INTERFACE, "operation_started", this, SLOT(packageOperationStarted(const QString&, const QString&, const QString&))); con.connect(QString(),PACKAGE_MANAGER_DBUS_PATH, PACKAGE_MANAGER_DBUS_INTERFACE, "operation_progress", this, SLOT(packageOperationProgress(const QString&, const QString &, const QString&, int))); con.connect(QString(),PACKAGE_MANAGER_DBUS_PATH, PACKAGE_MANAGER_DBUS_INTERFACE, "operation_complete", this, SLOT(packageOperationComplete(const QString&, const QString&, const QString&, const QString&, bool))); QString configPath = QDir::homePath() + CONFIG_PATH; if (!QDir::root().exists(configPath)) { QDir::root().mkpath(configPath); } QString dataStoreFileName = configPath + "/applicationpackage.data"; dataStore = new MFileDataStore(dataStoreFileName); // ExtraDirWatcher takes ownership of dataStore extraDirWatcher = QSharedPointer<ExtraDirWatcher>(new ExtraDirWatcher(dataStore, APPLICATIONS_DIRECTORY+INSTALLER_EXTRA)); connect(extraDirWatcher.data(), SIGNAL(desktopEntryAdded(QString)), this, SLOT(updatePackageState(QString)), Qt::UniqueConnection); connect(extraDirWatcher.data(), SIGNAL(desktopEntryChanged(QString)), this, SLOT(updatePackageState(QString)), Qt::UniqueConnection); connect(extraDirWatcher.data(), SIGNAL(desktopEntryRemoved(QString)), this, SLOT(packageRemoved(QString)), Qt::UniqueConnection); } ApplicationPackageMonitor::~ApplicationPackageMonitor() { } void ApplicationPackageMonitor::packageRemoved(const QString &desktopEntryPath) { QString packageKey; foreach(const QString &pkgKey, dataStore->allKeys()) { if(pkgKey.contains(PACKAGE_PREFIX)) { if(dataStore->value(pkgKey).toString() == desktopEntryPath) { packageKey = pkgKey; break; } } } dataStore->remove(DESKTOPENTRY_PREFIX+desktopEntryPath); dataStore->remove(packageKey); activePackages.remove(packageKey.remove(PACKAGE_PREFIX)); emit installExtraEntryRemoved(desktopEntryPath); } void ApplicationPackageMonitor::updatePackageStates() { QStringList keyList(dataStore->allKeys()); foreach (QString key, keyList) { if (key.contains(PACKAGE_PREFIX)) { QString desktopEntryPath = dataStore->value(key).toString(); QString state = dataStore->value(DESKTOPENTRY_PREFIX + desktopEntryPath).toString(); if (state == PACKAGE_STATE_BROKEN) { // emit operation error for a broken package emit operationError(desktopEntryPath, QString()); } else if(state == PACKAGE_STATE_DOWNLOADING) { emit downloadProgress(desktopEntryPath, 0, 0); } else if(state == PACKAGE_STATE_INSTALLING) { emit installProgress(desktopEntryPath, 0); } } } } ApplicationPackageMonitor::PackageProperties &ApplicationPackageMonitor::activePackageProperties(const QString packageName) { if (!activePackages.contains(packageName)) { // Set the desktopEntryName if already known activePackages[packageName].desktopEntryName = desktopEntryName(packageName); } return activePackages[packageName]; } void ApplicationPackageMonitor::packageDownloadProgress(const QString &operation, const QString &packageName, const QString &packageVersion, int already, int total) { Q_UNUSED(operation) Q_UNUSED(packageVersion) PackageProperties &properties = activePackageProperties(packageName); if (isValidOperation(properties, operation)) { emit downloadProgress(properties.desktopEntryName, already, total); } storePackageState(packageName, PACKAGE_STATE_DOWNLOADING); } void ApplicationPackageMonitor::packageOperationStarted(const QString &operation, const QString &packageName, const QString &version) { Q_UNUSED(operation) Q_UNUSED(packageName) Q_UNUSED(version) } void ApplicationPackageMonitor::packageOperationProgress(const QString &operation, const QString &packageName, const QString &packageVersion, int percentage) { Q_UNUSED(packageVersion) PackageProperties &properties = activePackageProperties(packageName); if (isValidOperation(properties, operation)) { properties.installing = true; emit installProgress(properties.desktopEntryName, percentage); storePackageState(packageName, PACKAGE_STATE_INSTALLING); } } void ApplicationPackageMonitor::packageOperationComplete(const QString &operation, const QString &packageName, const QString &packageVersion, const QString &error, bool need_reboot) { Q_UNUSED(packageVersion) Q_UNUSED(need_reboot) PackageProperties &properties = activePackageProperties(packageName); if (!isValidOperation(properties, operation)) { return; } if (!error.isEmpty()) { if (properties.installing) { emit operationError(properties.desktopEntryName, error); storePackageState(packageName, PACKAGE_STATE_BROKEN); } else { // Downloading MDesktopEntry entry(properties.desktopEntryName); QString packageState = entry.value(DESKTOP_ENTRY_GROUP_MEEGO, DESKTOP_ENTRY_KEY_PACKAGE_STATE); if (packageState == PACKAGE_STATE_INSTALLED || packageState == PACKAGE_STATE_UPDATEABLE) { // Application is previously installed. Downloading update failed but application still usable. emit operationSuccess(properties.desktopEntryName.replace(INSTALLER_EXTRA, QString())); storePackageState(packageName, packageState); } else { emit operationError(properties.desktopEntryName, error); storePackageState(packageName, PACKAGE_STATE_BROKEN); } } } else { emit operationSuccess(properties.desktopEntryName.replace(INSTALLER_EXTRA, QString())); storePackageState(packageName, PACKAGE_STATE_INSTALLED); } activePackages.remove(packageName); } void ApplicationPackageMonitor::storePackageState(const QString& packageName, const QString& state) { QString path = dataStore->value(PACKAGE_PREFIX + packageName).toString(); extraDirWatcher->updateDataForDesktopEntry(path, state); } bool ApplicationPackageMonitor::isValidOperation(const PackageProperties &properties, const QString &operation) { if ((operation.compare(OPERATION_INSTALL, Qt::CaseInsensitive) == 0 || operation.compare(OPERATION_UPGRADE, Qt::CaseInsensitive) == 0 ) && !properties.desktopEntryName.isEmpty() ) { return true; } else { return false; } } void ApplicationPackageMonitor::updatePackageState(const QString &desktopEntryPath) { MDesktopEntry entry(desktopEntryPath); QString packageName = entry.value(DESKTOP_ENTRY_GROUP_MEEGO, DESKTOP_ENTRY_KEY_PACKAGE_NAME); QString packageState = entry.value(DESKTOP_ENTRY_GROUP_MEEGO, DESKTOP_ENTRY_KEY_PACKAGE_STATE); bool packageHadError = entry.value(DESKTOP_ENTRY_GROUP_MEEGO, DESKTOP_ENTRY_KEY_PACKAGE_HAD_ERROR) == "true"; if (packageHadError) packageState = PACKAGE_STATE_BROKEN; if (!packageName.isEmpty()) { QString pkgKey = PACKAGE_PREFIX+packageName; if (packageState == PACKAGE_STATE_BROKEN) { // emit operation error for a broken package emit operationError(desktopEntryPath, QString()); } dataStore->createValue(pkgKey, desktopEntryPath); if (activePackages.contains(packageName)) { // Package is being installed, add the desktop entry path directly activePackages[packageName].desktopEntryName = desktopEntryPath; } } extraDirWatcher->updateDataForDesktopEntry(desktopEntryPath, packageState); } QString ApplicationPackageMonitor::desktopEntryName(const QString &packageName) { QString pkgKey = PACKAGE_PREFIX+packageName; if (!dataStore->contains(pkgKey)) { // Package not installed return QString(); } if (!QFile::exists(dataStore->value(pkgKey).toString())) { // The extra desktop file doesn't exist anymore, the package has been uninstalled dataStore->remove(pkgKey); return QString(); } return dataStore->value(pkgKey).toString(); } ApplicationPackageMonitor::ExtraDirWatcher::ExtraDirWatcher(MDataStore *dataStore, const QString &directoryPath) : LauncherDataStore(dataStore, directoryPath) { } ApplicationPackageMonitor::ExtraDirWatcher::~ExtraDirWatcher() { } bool ApplicationPackageMonitor::ExtraDirWatcher::isDesktopEntryValid(const MDesktopEntry &entry, const QStringList &acceptedTypes) { Q_UNUSED(acceptedTypes); return entry.contains(DESKTOP_ENTRY_GROUP_MEEGO, DESKTOP_ENTRY_KEY_PACKAGE_NAME) && entry.contains(DESKTOP_ENTRY_GROUP_MEEGO, DESKTOP_ENTRY_KEY_PACKAGE_STATE); } <|endoftext|>
<commit_before>/* RawSpeed - RAW file decoder. Copyright (C) 2017 Axel Waggershauser 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 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 "decompressors/LJpegDecompressor.h" #include "common/Common.h" // for uint32, unroll_loop, ushort16 #include "common/Point.h" // for iPoint2D #include "common/RawImage.h" // for RawImage, RawImageData #include "decoders/RawDecoderException.h" // for ThrowRDE #include "io/BitPumpJPEG.h" // for BitPumpJPEG #include <algorithm> // for min, copy_n using std::copy_n; using std::min; namespace rawspeed { LJpegDecompressor::LJpegDecompressor(const ByteStream& bs, const RawImage& img) : AbstractLJpegDecompressor(bs, img) { if (mRaw->getDataType() != TYPE_USHORT16) ThrowRDE("Unexpected data type (%u)", mRaw->getDataType()); if (!((mRaw->getCpp() == 1 && mRaw->getBpp() == 2) || (mRaw->getCpp() == 3 && mRaw->getBpp() == 6))) ThrowRDE("Unexpected component count (%u)", mRaw->getCpp()); if (mRaw->dim.x == 0 || mRaw->dim.y == 0) ThrowRDE("Image has zero size"); #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION // Yeah, sure, here it would be just dumb to leave this for production :) if (mRaw->dim.x > 7424 || mRaw->dim.y > 5552) { ThrowRDE("Unexpected image dimensions found: (%u; %u)", mRaw->dim.x, mRaw->dim.y); } #endif } void LJpegDecompressor::decode(uint32 offsetX, uint32 offsetY, bool fixDng16Bug_) { if (static_cast<int>(offsetX) >= mRaw->dim.x) ThrowRDE("X offset outside of image"); if (static_cast<int>(offsetY) >= mRaw->dim.y) ThrowRDE("Y offset outside of image"); offX = offsetX; offY = offsetY; fixDng16Bug = fixDng16Bug_; AbstractLJpegDecompressor::decode(); } void LJpegDecompressor::decodeScan() { if (predictorMode != 1) ThrowRDE("Unsupported predictor mode: %u", predictorMode); for (uint32 i = 0; i < frame.cps; i++) if (frame.compInfo[i].superH != 1 || frame.compInfo[i].superV != 1) ThrowRDE("Unsupported subsampling"); if((mRaw->getCpp() * (mRaw->dim.x - offX)) < frame.cps) ThrowRDE("Got less pixels than the components per sample"); switch (frame.cps) { case 2: decodeN<2>(); break; case 3: decodeN<3>(); break; case 4: decodeN<4>(); break; default: ThrowRDE("Unsupported number of components: %u", frame.cps); } } // N_COMP == number of components (2, 3 or 4) template <int N_COMP> void LJpegDecompressor::decodeN() { assert(mRaw->getCpp() > 0); assert(N_COMP > 0); assert(N_COMP >= mRaw->getCpp()); assert((N_COMP / mRaw->getCpp()) > 0); assert(mRaw->dim.x >= N_COMP); assert((mRaw->getCpp() * (mRaw->dim.x - offX)) >= N_COMP); auto ht = getHuffmanTables<N_COMP>(); auto pred = getInitialPredictors<N_COMP>(); auto predNext = pred.data(); BitPumpJPEG bitStream(input); for (unsigned y = 0; y < frame.h; ++y) { auto destY = offY + y; // A recoded DNG might be split up into tiles of self contained LJpeg // blobs. The tiles at the bottom and the right may extend beyond the // dimension of the raw image buffer. The excessive content has to be // ignored. For y, we can simply stop decoding when we reached the border. if (destY >= static_cast<unsigned>(mRaw->dim.y)) break; auto dest = reinterpret_cast<ushort16*>(mRaw->getDataUncropped(offX, destY)); copy_n(predNext, N_COMP, pred.data()); // the predictor for the next line is the start of this line predNext = dest; unsigned width = min(frame.w, (mRaw->dim.x - offX) / (N_COMP / mRaw->getCpp())); // For x, we first process all pixels within the image buffer ... for (unsigned x = 0; x < width; ++x) { unroll_loop<N_COMP>([&](int i) { *dest++ = pred[i] += ht[i]->decodeNext(bitStream); }); } // ... and discard the rest. for (unsigned x = width; x < frame.w; ++x) { unroll_loop<N_COMP>([&](int i) { ht[i]->decodeNext(bitStream); }); } } } } // namespace rawspeed <commit_msg>LJpegDecompressor::decodeN(): fix curr. slice width clipping.<commit_after>/* RawSpeed - RAW file decoder. Copyright (C) 2017 Axel Waggershauser 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 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 "decompressors/LJpegDecompressor.h" #include "common/Common.h" // for uint32, unroll_loop, ushort16 #include "common/Point.h" // for iPoint2D #include "common/RawImage.h" // for RawImage, RawImageData #include "decoders/RawDecoderException.h" // for ThrowRDE #include "io/BitPumpJPEG.h" // for BitPumpJPEG #include <algorithm> // for min, copy_n using std::copy_n; namespace rawspeed { LJpegDecompressor::LJpegDecompressor(const ByteStream& bs, const RawImage& img) : AbstractLJpegDecompressor(bs, img) { if (mRaw->getDataType() != TYPE_USHORT16) ThrowRDE("Unexpected data type (%u)", mRaw->getDataType()); if (!((mRaw->getCpp() == 1 && mRaw->getBpp() == 2) || (mRaw->getCpp() == 3 && mRaw->getBpp() == 6))) ThrowRDE("Unexpected component count (%u)", mRaw->getCpp()); if (mRaw->dim.x == 0 || mRaw->dim.y == 0) ThrowRDE("Image has zero size"); #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION // Yeah, sure, here it would be just dumb to leave this for production :) if (mRaw->dim.x > 7424 || mRaw->dim.y > 5552) { ThrowRDE("Unexpected image dimensions found: (%u; %u)", mRaw->dim.x, mRaw->dim.y); } #endif } void LJpegDecompressor::decode(uint32 offsetX, uint32 offsetY, bool fixDng16Bug_) { if (static_cast<int>(offsetX) >= mRaw->dim.x) ThrowRDE("X offset outside of image"); if (static_cast<int>(offsetY) >= mRaw->dim.y) ThrowRDE("Y offset outside of image"); offX = offsetX; offY = offsetY; fixDng16Bug = fixDng16Bug_; AbstractLJpegDecompressor::decode(); } void LJpegDecompressor::decodeScan() { if (predictorMode != 1) ThrowRDE("Unsupported predictor mode: %u", predictorMode); for (uint32 i = 0; i < frame.cps; i++) if (frame.compInfo[i].superH != 1 || frame.compInfo[i].superV != 1) ThrowRDE("Unsupported subsampling"); if((mRaw->getCpp() * (mRaw->dim.x - offX)) < frame.cps) ThrowRDE("Got less pixels than the components per sample"); switch (frame.cps) { case 2: decodeN<2>(); break; case 3: decodeN<3>(); break; case 4: decodeN<4>(); break; default: ThrowRDE("Unsupported number of components: %u", frame.cps); } } // N_COMP == number of components (2, 3 or 4) template <int N_COMP> void LJpegDecompressor::decodeN() { assert(mRaw->getCpp() > 0); assert(N_COMP > 0); assert(N_COMP >= mRaw->getCpp()); assert((N_COMP / mRaw->getCpp()) > 0); assert(mRaw->dim.x >= N_COMP); assert((mRaw->getCpp() * (mRaw->dim.x - offX)) >= N_COMP); auto ht = getHuffmanTables<N_COMP>(); auto pred = getInitialPredictors<N_COMP>(); auto predNext = pred.data(); BitPumpJPEG bitStream(input); for (unsigned y = 0; y < frame.h; ++y) { auto destY = offY + y; // A recoded DNG might be split up into tiles of self contained LJpeg // blobs. The tiles at the bottom and the right may extend beyond the // dimension of the raw image buffer. The excessive content has to be // ignored. For y, we can simply stop decoding when we reached the border. if (destY >= static_cast<unsigned>(mRaw->dim.y)) break; auto dest = reinterpret_cast<ushort16*>(mRaw->getDataUncropped(offX, destY)); copy_n(predNext, N_COMP, pred.data()); // the predictor for the next line is the start of this line predNext = dest; unsigned width = std::min(frame.w, (mRaw->getCpp() * (mRaw->dim.x - offX)) / N_COMP); // For x, we first process all pixels within the image buffer ... for (unsigned x = 0; x < width; ++x) { unroll_loop<N_COMP>([&](int i) { *dest++ = pred[i] += ht[i]->decodeNext(bitStream); }); } // ... and discard the rest. for (unsigned x = width; x < frame.w; ++x) { unroll_loop<N_COMP>([&](int i) { ht[i]->decodeNext(bitStream); }); } } } } // namespace rawspeed <|endoftext|>
<commit_before>/* RawSpeed - RAW file decoder. Copyright (C) 2009-2014 Klaus Post 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 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 "decompressors/NikonDecompressor.h" #include "common/Common.h" // for uint32, ushort16, clampBits #include "common/Point.h" // for iPoint2D #include "common/RawImage.h" // for RawImage, RawImageData, RawI... #include "decoders/RawDecoderException.h" // for ThrowRDE #include "decompressors/HuffmanTable.h" // for HuffmanTable #include "io/BitPumpMSB.h" // for BitPumpMSB, BitStream<>::fil... #include "io/Buffer.h" // for Buffer #include "io/ByteStream.h" // for ByteStream #include <cstdio> // for size_t, NULL #include <vector> // for vector, allocator namespace rawspeed { const uchar8 NikonDecompressor::nikon_tree[][2][16] = { {/* 12-bit lossy */ {0, 1, 5, 1, 1, 1, 1, 1, 1, 2, 0, 0, 0, 0, 0, 0}, {5, 4, 3, 6, 2, 7, 1, 0, 8, 9, 11, 10, 12}}, {/* 12-bit lossy after split */ {0, 1, 5, 1, 1, 1, 1, 1, 1, 2, 0, 0, 0, 0, 0, 0}, {0x39, 0x5a, 0x38, 0x27, 0x16, 5, 4, 3, 2, 1, 0, 11, 12, 12}}, {/* 12-bit lossless */ {0, 1, 4, 2, 3, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {5, 4, 6, 3, 7, 2, 8, 1, 9, 0, 10, 11, 12}}, {/* 14-bit lossy */ {0, 1, 4, 3, 1, 1, 1, 1, 1, 2, 0, 0, 0, 0, 0, 0}, {5, 6, 4, 7, 8, 3, 9, 2, 1, 0, 10, 11, 12, 13, 14}}, {/* 14-bit lossy after split */ {0, 1, 5, 1, 1, 1, 1, 1, 1, 1, 2, 0, 0, 0, 0, 0}, {8, 0x5c, 0x4b, 0x3a, 0x29, 7, 6, 5, 4, 3, 2, 1, 0, 13, 14}}, {/* 14-bit lossless */ {0, 1, 4, 2, 2, 3, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0}, {7, 6, 8, 5, 9, 4, 10, 3, 11, 12, 2, 0, 1, 13, 14}}, }; std::vector<ushort16> NikonDecompressor::createCurve(ByteStream* metadata, uint32 bitsPS, uint32 v0, uint32 v1, uint32* split) { // 'curve' will hold a peace wise linearly interpolated function. // there are 'csize' segements, each is 'step' values long. // the very last value is not part of the used table but necessary // to linearly interpolate the last segment, therefor the '+1/-1' // size adjustments of 'curve'. std::vector<ushort16> curve((1 << bitsPS & 0x7fff) + 1); assert(curve.size() > 1); for (size_t i = 0; i < curve.size(); i++) curve[i] = i; uint32 step = 0; uint32 csize = metadata->getU16(); if (csize > 1) step = curve.size() / (csize - 1); if (v0 == 68 && v1 == 32 && step > 0) { for (size_t i = 0; i < csize; i++) curve[i * step] = metadata->getU16(); for (size_t i = 0; i < curve.size() - 1; i++) { curve[i] = (curve[i - i % step] * (step - i % step) + curve[i - i % step + step] * (i % step)) / step; } metadata->setPosition(562); *split = metadata->getU16(); } else if (v0 != 70) { if (csize == 0 || csize > 0x4001) ThrowRDE("Don't know how to compute curve! csize = %u", csize); curve.resize(csize + 1UL); assert(curve.size() > 1); for (uint32 i = 0; i < csize; i++) { curve[i] = metadata->getU16(); } } // and drop the last value curve.resize(curve.size() - 1); assert(!curve.empty()); return curve; } HuffmanTable NikonDecompressor::createHuffmanTable(uint32 huffSelect) { HuffmanTable ht; uint32 count = ht.setNCodesPerLength(Buffer(nikon_tree[huffSelect][0], 16)); ht.setCodeValues(Buffer(nikon_tree[huffSelect][1], count)); ht.setup(true, false); return ht; } void NikonDecompressor::decompress(RawImage* mRaw, ByteStream&& data, ByteStream metadata, const iPoint2D& size, uint32 bitsPS, bool uncorrectedRawValues) { assert(bitsPS > 0); uint32 v0 = metadata.getByte(); uint32 v1 = metadata.getByte(); uint32 huffSelect = 0; uint32 split = 0; int pUp1[2]; int pUp2[2]; writeLog(DEBUG_PRIO_EXTRA, "Nef version v0:%u, v1:%u", v0, v1); if (v0 == 73 || v1 == 88) metadata.skipBytes(2110); if (v0 == 70) huffSelect = 2; if (bitsPS == 14) huffSelect += 3; pUp1[0] = metadata.getU16(); pUp1[1] = metadata.getU16(); pUp2[0] = metadata.getU16(); pUp2[1] = metadata.getU16(); HuffmanTable ht = createHuffmanTable(huffSelect); auto curve = createCurve(&metadata, bitsPS, v0, v1, &split); RawImageCurveGuard curveHandler(mRaw, curve, uncorrectedRawValues); BitPumpMSB bits(data); uchar8* draw = mRaw->get()->getData(); uint32 pitch = mRaw->get()->pitch; int pLeft1 = 0; int pLeft2 = 0; uint32 random = bits.peekBits(24); //allow gcc to devirtualize the calls below auto* rawdata = reinterpret_cast<RawImageDataU16*>(mRaw->get()); assert(size.x % 2 == 0); assert(size.x >= 2); for (uint32 y = 0; y < static_cast<unsigned>(size.y); y++) { if (split && y == split) { ht = createHuffmanTable(huffSelect + 1); } auto* dest = reinterpret_cast<ushort16*>(&draw[y * pitch]); // Adjust destination pUp1[y&1] += ht.decodeNext(bits); pUp2[y&1] += ht.decodeNext(bits); pLeft1 = pUp1[y&1]; pLeft2 = pUp2[y&1]; rawdata->setWithLookUp(clampBits(pLeft1, 15), reinterpret_cast<uchar8*>(dest + 0), &random); rawdata->setWithLookUp(clampBits(pLeft2, 15), reinterpret_cast<uchar8*>(dest + 1), &random); dest += 2; for (uint32 x = 2; x < static_cast<uint32>(size.x); x += 2) { pLeft1 += ht.decodeNext(bits); pLeft2 += ht.decodeNext(bits); rawdata->setWithLookUp(clampBits(pLeft1, 15), reinterpret_cast<uchar8*>(dest + 0), &random); rawdata->setWithLookUp(clampBits(pLeft2, 15), reinterpret_cast<uchar8*>(dest + 1), &random); dest += 2; } } } } // namespace rawspeed <commit_msg>NikonDecompressor::createCurve(): make sure curve size is valid<commit_after>/* RawSpeed - RAW file decoder. Copyright (C) 2009-2014 Klaus Post 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 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 "decompressors/NikonDecompressor.h" #include "common/Common.h" // for uint32, ushort16, clampBits #include "common/Point.h" // for iPoint2D #include "common/RawImage.h" // for RawImage, RawImageData, RawI... #include "decoders/RawDecoderException.h" // for ThrowRDE #include "decompressors/HuffmanTable.h" // for HuffmanTable #include "io/BitPumpMSB.h" // for BitPumpMSB, BitStream<>::fil... #include "io/Buffer.h" // for Buffer #include "io/ByteStream.h" // for ByteStream #include <cstdio> // for size_t, NULL #include <vector> // for vector, allocator namespace rawspeed { const uchar8 NikonDecompressor::nikon_tree[][2][16] = { {/* 12-bit lossy */ {0, 1, 5, 1, 1, 1, 1, 1, 1, 2, 0, 0, 0, 0, 0, 0}, {5, 4, 3, 6, 2, 7, 1, 0, 8, 9, 11, 10, 12}}, {/* 12-bit lossy after split */ {0, 1, 5, 1, 1, 1, 1, 1, 1, 2, 0, 0, 0, 0, 0, 0}, {0x39, 0x5a, 0x38, 0x27, 0x16, 5, 4, 3, 2, 1, 0, 11, 12, 12}}, {/* 12-bit lossless */ {0, 1, 4, 2, 3, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {5, 4, 6, 3, 7, 2, 8, 1, 9, 0, 10, 11, 12}}, {/* 14-bit lossy */ {0, 1, 4, 3, 1, 1, 1, 1, 1, 2, 0, 0, 0, 0, 0, 0}, {5, 6, 4, 7, 8, 3, 9, 2, 1, 0, 10, 11, 12, 13, 14}}, {/* 14-bit lossy after split */ {0, 1, 5, 1, 1, 1, 1, 1, 1, 1, 2, 0, 0, 0, 0, 0}, {8, 0x5c, 0x4b, 0x3a, 0x29, 7, 6, 5, 4, 3, 2, 1, 0, 13, 14}}, {/* 14-bit lossless */ {0, 1, 4, 2, 2, 3, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0}, {7, 6, 8, 5, 9, 4, 10, 3, 11, 12, 2, 0, 1, 13, 14}}, }; std::vector<ushort16> NikonDecompressor::createCurve(ByteStream* metadata, uint32 bitsPS, uint32 v0, uint32 v1, uint32* split) { // 'curve' will hold a peace wise linearly interpolated function. // there are 'csize' segements, each is 'step' values long. // the very last value is not part of the used table but necessary // to linearly interpolate the last segment, therefor the '+1/-1' // size adjustments of 'curve'. std::vector<ushort16> curve((1 << bitsPS & 0x7fff) + 1); assert(curve.size() > 1); for (size_t i = 0; i < curve.size(); i++) curve[i] = i; uint32 step = 0; uint32 csize = metadata->getU16(); if (csize > 1) step = curve.size() / (csize - 1); if (v0 == 68 && v1 == 32 && step > 0) { if ((csize - 1) * step != curve.size() - 1) ThrowRDE("Bad curve segment count (%u)", csize); for (size_t i = 0; i < csize; i++) curve[i * step] = metadata->getU16(); for (size_t i = 0; i < curve.size() - 1; i++) { const uint32 b_scale = i % step; const uint32 a_pos = i - b_scale; const uint32 b_pos = a_pos + step; assert(a_pos >= 0); assert(a_pos < curve.size()); assert(b_pos > 0); assert(b_pos < curve.size()); assert(a_pos != b_pos); const uint32 a_scale = step - b_scale; curve[i] = (a_scale * curve[a_pos] + b_scale * curve[b_pos]) / step; } metadata->setPosition(562); *split = metadata->getU16(); } else if (v0 != 70) { if (csize == 0 || csize > 0x4001) ThrowRDE("Don't know how to compute curve! csize = %u", csize); curve.resize(csize + 1UL); assert(curve.size() > 1); for (uint32 i = 0; i < csize; i++) { curve[i] = metadata->getU16(); } } // and drop the last value curve.resize(curve.size() - 1); assert(!curve.empty()); return curve; } HuffmanTable NikonDecompressor::createHuffmanTable(uint32 huffSelect) { HuffmanTable ht; uint32 count = ht.setNCodesPerLength(Buffer(nikon_tree[huffSelect][0], 16)); ht.setCodeValues(Buffer(nikon_tree[huffSelect][1], count)); ht.setup(true, false); return ht; } void NikonDecompressor::decompress(RawImage* mRaw, ByteStream&& data, ByteStream metadata, const iPoint2D& size, uint32 bitsPS, bool uncorrectedRawValues) { assert(bitsPS > 0); uint32 v0 = metadata.getByte(); uint32 v1 = metadata.getByte(); uint32 huffSelect = 0; uint32 split = 0; int pUp1[2]; int pUp2[2]; writeLog(DEBUG_PRIO_EXTRA, "Nef version v0:%u, v1:%u", v0, v1); if (v0 == 73 || v1 == 88) metadata.skipBytes(2110); if (v0 == 70) huffSelect = 2; if (bitsPS == 14) huffSelect += 3; pUp1[0] = metadata.getU16(); pUp1[1] = metadata.getU16(); pUp2[0] = metadata.getU16(); pUp2[1] = metadata.getU16(); HuffmanTable ht = createHuffmanTable(huffSelect); auto curve = createCurve(&metadata, bitsPS, v0, v1, &split); RawImageCurveGuard curveHandler(mRaw, curve, uncorrectedRawValues); BitPumpMSB bits(data); uchar8* draw = mRaw->get()->getData(); uint32 pitch = mRaw->get()->pitch; int pLeft1 = 0; int pLeft2 = 0; uint32 random = bits.peekBits(24); //allow gcc to devirtualize the calls below auto* rawdata = reinterpret_cast<RawImageDataU16*>(mRaw->get()); assert(size.x % 2 == 0); assert(size.x >= 2); for (uint32 y = 0; y < static_cast<unsigned>(size.y); y++) { if (split && y == split) { ht = createHuffmanTable(huffSelect + 1); } auto* dest = reinterpret_cast<ushort16*>(&draw[y * pitch]); // Adjust destination pUp1[y&1] += ht.decodeNext(bits); pUp2[y&1] += ht.decodeNext(bits); pLeft1 = pUp1[y&1]; pLeft2 = pUp2[y&1]; rawdata->setWithLookUp(clampBits(pLeft1, 15), reinterpret_cast<uchar8*>(dest + 0), &random); rawdata->setWithLookUp(clampBits(pLeft2, 15), reinterpret_cast<uchar8*>(dest + 1), &random); dest += 2; for (uint32 x = 2; x < static_cast<uint32>(size.x); x += 2) { pLeft1 += ht.decodeNext(bits); pLeft2 += ht.decodeNext(bits); rawdata->setWithLookUp(clampBits(pLeft1, 15), reinterpret_cast<uchar8*>(dest + 0), &random); rawdata->setWithLookUp(clampBits(pLeft2, 15), reinterpret_cast<uchar8*>(dest + 1), &random); dest += 2; } } } } // namespace rawspeed <|endoftext|>
<commit_before>/// \file /// \ingroup tutorial_tdataframe /// \notebook -nodraw /// This tutorial shows how to create a dataset from scratch with TDataFrame /// \macro_code /// /// \date June 2017 /// \author Danilo Piparo void tdf008_createDataSetFromScratch() { // We create an empty data frame of 100 entries ROOT::Experimental::TDataFrame tdf(100); // We now fill it with random numbers gRandom.SetSeed(1); auto tdf_1 = tdf.Define("rnd", [&rnd]() { return gRandom->Gaus(); }); // And we write out the dataset on disk tdf_1.Snapshot("randomNumbers", "tdf008_createDataSetFromScratch.root"); } <commit_msg>[TDF] Fix tdf008_createDataSetFromScratch<commit_after>/// \file /// \ingroup tutorial_tdataframe /// \notebook -nodraw /// This tutorial shows how to create a dataset from scratch with TDataFrame /// \macro_code /// /// \date June 2017 /// \author Danilo Piparo void tdf008_createDataSetFromScratch() { // We create an empty data frame of 100 entries ROOT::Experimental::TDataFrame tdf(100); // We now fill it with random numbers gRandom->SetSeed(1); auto tdf_1 = tdf.Define("rnd", []() { return gRandom->Gaus(); }); // And we write out the dataset on disk tdf_1.Snapshot("randomNumbers", "tdf008_createDataSetFromScratch.root"); } <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * 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/. * * This file incorporates work covered by the following license notice: * * 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 . */ #include <iostream> #include <string.h> #include <ooxml/resourceids.hxx> #include "OOXMLFastTokenHandler.hxx" #if defined __clang__ #if __has_warning("-Wdeprecated-register") #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wdeprecated-register" #endif #endif #include "gperffasttoken.hxx" #if defined __clang__ #if __has_warning("-Wdeprecated-register") #pragma GCC diagnostic pop #endif #endif namespace writerfilter { namespace ooxml { using namespace ::std; OOXMLFastTokenHandler::OOXMLFastTokenHandler (css::uno::Reference< css::uno::XComponentContext > const & context) : m_xContext(context) {} // ::com::sun::star::xml::sax::XFastTokenHandler: ::sal_Int32 SAL_CALL OOXMLFastTokenHandler::getToken(const OUString & Identifier) throw (css::uno::RuntimeException) { ::sal_Int32 nResult = OOXML_FAST_TOKENS_END; struct tokenmap::token * pToken = tokenmap::Perfect_Hash::in_word_set (OUStringToOString(Identifier, RTL_TEXTENCODING_ASCII_US).getStr(), Identifier.getLength()); if (pToken != NULL) nResult = pToken->nToken; #ifdef DEBUG_TOKEN clog << "getToken: " << OUStringToOString(Identifier, RTL_TEXTENCODING_ASCII_US).getStr() << ", " << nResult << endl; #endif return nResult; } OUString SAL_CALL OOXMLFastTokenHandler::getIdentifier(::sal_Int32 Token) throw (css::uno::RuntimeException) { OUString sResult; #if 0 //FIXME this is broken: tokenmap::wordlist is not indexed by Token! if ( Token >= 0 || Token < OOXML_FAST_TOKENS_END ) { static OUString aTokens[OOXML_FAST_TOKENS_END]; if (aTokens[Token].getLength() == 0) aTokens[Token] = OUString::createFromAscii (tokenmap::wordlist[Token].name); } #else (void) Token; #endif return sResult; } css::uno::Sequence< ::sal_Int8 > SAL_CALL OOXMLFastTokenHandler::getUTF8Identifier(::sal_Int32 Token) throw (css::uno::RuntimeException) { #if 0 if ( Token < 0 || Token >= OOXML_FAST_TOKENS_END ) #endif return css::uno::Sequence< ::sal_Int8 >(); #if 0 //FIXME this is broken: tokenmap::wordlist is not indexed by Token! return css::uno::Sequence< ::sal_Int8 >(reinterpret_cast< const sal_Int8 *>(tokenmap::wordlist[Token].name), strlen(tokenmap::wordlist[Token].name)); #else (void) Token; #endif } ::sal_Int32 SAL_CALL OOXMLFastTokenHandler::getTokenDirect( const char *pStr, sal_Int32 nLength ) const { struct tokenmap::token * pToken = tokenmap::Perfect_Hash::in_word_set( pStr, nLength ); sal_Int32 nResult = pToken != NULL ? pToken->nToken : OOXML_FAST_TOKENS_END; #ifdef DEBUG_TOKEN clog << "getTokenFromUTF8: " << string(pStr, nLength) << ", " << nResult << (pToken == NULL ? ", failed" : "") << endl; #endif return nResult; } ::sal_Int32 SAL_CALL OOXMLFastTokenHandler::getTokenFromUTF8 (const css::uno::Sequence< ::sal_Int8 > & Identifier) throw (css::uno::RuntimeException) { return getTokenDirect(reinterpret_cast<const char *> (Identifier.getConstArray()), Identifier.getLength()); } }} /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>SAL_CALL mismatch<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * 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/. * * This file incorporates work covered by the following license notice: * * 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 . */ #include <iostream> #include <string.h> #include <ooxml/resourceids.hxx> #include "OOXMLFastTokenHandler.hxx" #if defined __clang__ #if __has_warning("-Wdeprecated-register") #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wdeprecated-register" #endif #endif #include "gperffasttoken.hxx" #if defined __clang__ #if __has_warning("-Wdeprecated-register") #pragma GCC diagnostic pop #endif #endif namespace writerfilter { namespace ooxml { using namespace ::std; OOXMLFastTokenHandler::OOXMLFastTokenHandler (css::uno::Reference< css::uno::XComponentContext > const & context) : m_xContext(context) {} // ::com::sun::star::xml::sax::XFastTokenHandler: ::sal_Int32 SAL_CALL OOXMLFastTokenHandler::getToken(const OUString & Identifier) throw (css::uno::RuntimeException) { ::sal_Int32 nResult = OOXML_FAST_TOKENS_END; struct tokenmap::token * pToken = tokenmap::Perfect_Hash::in_word_set (OUStringToOString(Identifier, RTL_TEXTENCODING_ASCII_US).getStr(), Identifier.getLength()); if (pToken != NULL) nResult = pToken->nToken; #ifdef DEBUG_TOKEN clog << "getToken: " << OUStringToOString(Identifier, RTL_TEXTENCODING_ASCII_US).getStr() << ", " << nResult << endl; #endif return nResult; } OUString SAL_CALL OOXMLFastTokenHandler::getIdentifier(::sal_Int32 Token) throw (css::uno::RuntimeException) { OUString sResult; #if 0 //FIXME this is broken: tokenmap::wordlist is not indexed by Token! if ( Token >= 0 || Token < OOXML_FAST_TOKENS_END ) { static OUString aTokens[OOXML_FAST_TOKENS_END]; if (aTokens[Token].getLength() == 0) aTokens[Token] = OUString::createFromAscii (tokenmap::wordlist[Token].name); } #else (void) Token; #endif return sResult; } css::uno::Sequence< ::sal_Int8 > SAL_CALL OOXMLFastTokenHandler::getUTF8Identifier(::sal_Int32 Token) throw (css::uno::RuntimeException) { #if 0 if ( Token < 0 || Token >= OOXML_FAST_TOKENS_END ) #endif return css::uno::Sequence< ::sal_Int8 >(); #if 0 //FIXME this is broken: tokenmap::wordlist is not indexed by Token! return css::uno::Sequence< ::sal_Int8 >(reinterpret_cast< const sal_Int8 *>(tokenmap::wordlist[Token].name), strlen(tokenmap::wordlist[Token].name)); #else (void) Token; #endif } ::sal_Int32 OOXMLFastTokenHandler::getTokenDirect( const char *pStr, sal_Int32 nLength ) const { struct tokenmap::token * pToken = tokenmap::Perfect_Hash::in_word_set( pStr, nLength ); sal_Int32 nResult = pToken != NULL ? pToken->nToken : OOXML_FAST_TOKENS_END; #ifdef DEBUG_TOKEN clog << "getTokenFromUTF8: " << string(pStr, nLength) << ", " << nResult << (pToken == NULL ? ", failed" : "") << endl; #endif return nResult; } ::sal_Int32 SAL_CALL OOXMLFastTokenHandler::getTokenFromUTF8 (const css::uno::Sequence< ::sal_Int8 > & Identifier) throw (css::uno::RuntimeException) { return getTokenDirect(reinterpret_cast<const char *> (Identifier.getConstArray()), Identifier.getLength()); } }} /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>#include "particle_system.h" #include "core/blob.h" #include "core/crc32.h" #include "core/math_utils.h" #include "core/resource_manager.h" #include "core/resource_manager_base.h" #include "renderer/material.h" #include "universe/universe.h" namespace Lumix { static ParticleEmitter::ModuleBase* createModule(uint32_t type, ParticleEmitter& emitter) { if (type == ParticleEmitter::LinearMovementModule::s_type) { return LUMIX_NEW(emitter.getAllocator(), ParticleEmitter::LinearMovementModule)(emitter); } if (type == ParticleEmitter::AlphaModule::s_type) { return LUMIX_NEW(emitter.getAllocator(), ParticleEmitter::AlphaModule)(emitter); } if (type == ParticleEmitter::RandomRotationModule::s_type) { return LUMIX_NEW(emitter.getAllocator(), ParticleEmitter::RandomRotationModule)(emitter); } return nullptr; } ParticleEmitter::ModuleBase::ModuleBase(ParticleEmitter& emitter) : m_emitter(emitter) { } ParticleEmitter::LinearMovementModule::LinearMovementModule(ParticleEmitter& emitter) : ModuleBase(emitter) { } void ParticleEmitter::LinearMovementModule::spawnParticle(int index) { m_emitter.m_velocity[index].x = m_x.getRandom(); m_emitter.m_velocity[index].y = m_y.getRandom(); m_emitter.m_velocity[index].z = m_z.getRandom(); } void ParticleEmitter::LinearMovementModule::serialize(OutputBlob& blob) { blob.write(m_x); blob.write(m_y); blob.write(m_z); } void ParticleEmitter::LinearMovementModule::deserialize(InputBlob& blob) { blob.read(m_x); blob.read(m_y); blob.read(m_z); } const uint32_t ParticleEmitter::LinearMovementModule::s_type = Lumix::crc32("linear_movement"); ParticleEmitter::AlphaModule::AlphaModule(ParticleEmitter& emitter) : ModuleBase(emitter) { } void ParticleEmitter::AlphaModule::update(float time_delta) { if (m_emitter.m_alpha.empty()) return; float* alpha = &m_emitter.m_alpha[0]; for (int i = 0, c = m_emitter.m_alpha.size(); i < c; ++i) { alpha[i] = Math::minValue(m_emitter.m_life[i], 1.0f); } } const uint32_t ParticleEmitter::AlphaModule::s_type = Lumix::crc32("alpha"); ParticleEmitter::RandomRotationModule::RandomRotationModule(ParticleEmitter& emitter) : ModuleBase(emitter) { } void ParticleEmitter::RandomRotationModule::spawnParticle(int index) { m_emitter.m_rotation[index] = Math::degreesToRadians(float(rand() % 360)); } const uint32_t ParticleEmitter::RandomRotationModule::s_type = Lumix::crc32("random_rotation"); Interval::Interval() : from(0) , to(0) { } void Interval::check() { from = Math::maxValue(from, 0.0f); to = Math::maxValue(from, to); } float Interval::getRandom() const { return from + rand() * ((to - from) / RAND_MAX); } ParticleEmitter::ParticleEmitter(Entity entity, Universe& universe, IAllocator& allocator) : m_next_spawn_time(0) , m_allocator(allocator) , m_life(allocator) , m_modules(allocator) , m_position(allocator) , m_velocity(allocator) , m_rotation(allocator) , m_rotational_speed(allocator) , m_alpha(allocator) , m_universe(universe) , m_entity(entity) , m_size(allocator) , m_material(nullptr) { m_spawn_period.from = 1; m_spawn_period.to = 2; m_initial_life.from = 1; m_initial_life.to = 2; m_initial_size.from = 1; m_initial_size.to = 1; } ParticleEmitter::~ParticleEmitter() { setMaterial(nullptr); for (auto* module : m_modules) { LUMIX_DELETE(m_allocator, module); } } void ParticleEmitter::setMaterial(Material* material) { if (m_material) { auto* manager = m_material->getResourceManager().get(ResourceManager::MATERIAL); manager->unload(*m_material); } m_material = material; } void ParticleEmitter::spawnParticle() { m_position.push(m_universe.getPosition(m_entity)); m_rotation.push(0); m_rotational_speed.push(0); m_life.push(m_initial_life.getRandom()); m_alpha.push(1); m_velocity.push(Vec3(0, 0, 0)); m_size.push(m_initial_size.getRandom()); for (auto* module : m_modules) { module->spawnParticle(m_life.size() - 1); } } void ParticleEmitter::addModule(ModuleBase* module) { m_modules.push(module); TODO("todo check whether anything else is necessary to do here"); } void ParticleEmitter::destroyParticle(int index) { for (auto* module : m_modules) { module->destoryParticle(index); } m_life.eraseFast(index); m_position.eraseFast(index); m_velocity.eraseFast(index); m_rotation.eraseFast(index); m_rotational_speed.eraseFast(index); m_alpha.eraseFast(index); m_size.eraseFast(index); } void ParticleEmitter::updateLives(float time_delta) { for (int i = 0, c = m_life.size(); i < c; ++i) { float life = m_life[i]; life -= time_delta; m_life[i] = life; if (life < 0) { destroyParticle(i); --i; --c; } } } void ParticleEmitter::serialize(OutputBlob& blob) { blob.write(m_spawn_period); blob.write(m_initial_life); blob.write(m_initial_size); blob.write(m_entity); blob.writeString(m_material ? m_material->getPath().c_str() : ""); blob.write(m_modules.size()); for (auto* module : m_modules) { blob.write(module->getType()); module->serialize(blob); } } void ParticleEmitter::deserialize(InputBlob& blob, ResourceManager& manager) { blob.read(m_spawn_period); blob.read(m_initial_life); blob.read(m_initial_size); blob.read(m_entity); char path[MAX_PATH_LENGTH]; blob.readString(path, lengthOf(path)); auto material_manager = manager.get(ResourceManager::MATERIAL); auto material = static_cast<Material*>(material_manager->load(Lumix::Path(path))); setMaterial(material); int size; blob.read(size); for (auto* module : m_modules) { LUMIX_DELETE(m_allocator, module); } m_modules.clear(); for (int i = 0; i < size; ++i) { uint32_t type; blob.read(type); auto* module = createModule(type, *this); m_modules.push(module); module->deserialize(blob); } } void ParticleEmitter::updatePositions(float time_delta) { for (int i = 0, c = m_position.size(); i < c; ++i) { m_position[i] += m_velocity[i] * time_delta; } } void ParticleEmitter::updateRotations(float time_delta) { for (int i = 0, c = m_rotation.size(); i < c; ++i) { m_rotation[i] += m_rotational_speed[i] * time_delta; } } void ParticleEmitter::update(float time_delta) { spawnParticles(time_delta); updateLives(time_delta); updatePositions(time_delta); updateRotations(time_delta); for (auto* module : m_modules) { module->update(time_delta); } } void ParticleEmitter::spawnParticles(float time_delta) { m_next_spawn_time -= time_delta; while (m_next_spawn_time < 0) { m_next_spawn_time += m_spawn_period.getRandom(); spawnParticle(); } } struct InitialVelocityModule : public ParticleEmitter::ModuleBase { Interval m_x; Interval m_y; Interval m_z; InitialVelocityModule(ParticleEmitter& emitter) : ModuleBase(emitter) { m_z.from = -1; m_z.to = 1; m_x.from = m_x.to = m_x.to = m_y.from = m_y.to = 0; } void spawnParticle(int index) override { Vec3 v; v.x = m_x.getRandom(); v.y = m_y.getRandom(); v.z = m_z.getRandom(); m_emitter.m_velocity[index] = v; } }; } // namespace Lumix<commit_msg>todo removed<commit_after>#include "particle_system.h" #include "core/blob.h" #include "core/crc32.h" #include "core/math_utils.h" #include "core/resource_manager.h" #include "core/resource_manager_base.h" #include "renderer/material.h" #include "universe/universe.h" namespace Lumix { static ParticleEmitter::ModuleBase* createModule(uint32_t type, ParticleEmitter& emitter) { if (type == ParticleEmitter::LinearMovementModule::s_type) { return LUMIX_NEW(emitter.getAllocator(), ParticleEmitter::LinearMovementModule)(emitter); } if (type == ParticleEmitter::AlphaModule::s_type) { return LUMIX_NEW(emitter.getAllocator(), ParticleEmitter::AlphaModule)(emitter); } if (type == ParticleEmitter::RandomRotationModule::s_type) { return LUMIX_NEW(emitter.getAllocator(), ParticleEmitter::RandomRotationModule)(emitter); } return nullptr; } ParticleEmitter::ModuleBase::ModuleBase(ParticleEmitter& emitter) : m_emitter(emitter) { } ParticleEmitter::LinearMovementModule::LinearMovementModule(ParticleEmitter& emitter) : ModuleBase(emitter) { } void ParticleEmitter::LinearMovementModule::spawnParticle(int index) { m_emitter.m_velocity[index].x = m_x.getRandom(); m_emitter.m_velocity[index].y = m_y.getRandom(); m_emitter.m_velocity[index].z = m_z.getRandom(); } void ParticleEmitter::LinearMovementModule::serialize(OutputBlob& blob) { blob.write(m_x); blob.write(m_y); blob.write(m_z); } void ParticleEmitter::LinearMovementModule::deserialize(InputBlob& blob) { blob.read(m_x); blob.read(m_y); blob.read(m_z); } const uint32_t ParticleEmitter::LinearMovementModule::s_type = Lumix::crc32("linear_movement"); ParticleEmitter::AlphaModule::AlphaModule(ParticleEmitter& emitter) : ModuleBase(emitter) { } void ParticleEmitter::AlphaModule::update(float time_delta) { if (m_emitter.m_alpha.empty()) return; float* alpha = &m_emitter.m_alpha[0]; for (int i = 0, c = m_emitter.m_alpha.size(); i < c; ++i) { alpha[i] = Math::minValue(m_emitter.m_life[i], 1.0f); } } const uint32_t ParticleEmitter::AlphaModule::s_type = Lumix::crc32("alpha"); ParticleEmitter::RandomRotationModule::RandomRotationModule(ParticleEmitter& emitter) : ModuleBase(emitter) { } void ParticleEmitter::RandomRotationModule::spawnParticle(int index) { m_emitter.m_rotation[index] = Math::degreesToRadians(float(rand() % 360)); } const uint32_t ParticleEmitter::RandomRotationModule::s_type = Lumix::crc32("random_rotation"); Interval::Interval() : from(0) , to(0) { } void Interval::check() { from = Math::maxValue(from, 0.0f); to = Math::maxValue(from, to); } float Interval::getRandom() const { return from + rand() * ((to - from) / RAND_MAX); } ParticleEmitter::ParticleEmitter(Entity entity, Universe& universe, IAllocator& allocator) : m_next_spawn_time(0) , m_allocator(allocator) , m_life(allocator) , m_modules(allocator) , m_position(allocator) , m_velocity(allocator) , m_rotation(allocator) , m_rotational_speed(allocator) , m_alpha(allocator) , m_universe(universe) , m_entity(entity) , m_size(allocator) , m_material(nullptr) { m_spawn_period.from = 1; m_spawn_period.to = 2; m_initial_life.from = 1; m_initial_life.to = 2; m_initial_size.from = 1; m_initial_size.to = 1; } ParticleEmitter::~ParticleEmitter() { setMaterial(nullptr); for (auto* module : m_modules) { LUMIX_DELETE(m_allocator, module); } } void ParticleEmitter::setMaterial(Material* material) { if (m_material) { auto* manager = m_material->getResourceManager().get(ResourceManager::MATERIAL); manager->unload(*m_material); } m_material = material; } void ParticleEmitter::spawnParticle() { m_position.push(m_universe.getPosition(m_entity)); m_rotation.push(0); m_rotational_speed.push(0); m_life.push(m_initial_life.getRandom()); m_alpha.push(1); m_velocity.push(Vec3(0, 0, 0)); m_size.push(m_initial_size.getRandom()); for (auto* module : m_modules) { module->spawnParticle(m_life.size() - 1); } } void ParticleEmitter::addModule(ModuleBase* module) { m_modules.push(module); } void ParticleEmitter::destroyParticle(int index) { for (auto* module : m_modules) { module->destoryParticle(index); } m_life.eraseFast(index); m_position.eraseFast(index); m_velocity.eraseFast(index); m_rotation.eraseFast(index); m_rotational_speed.eraseFast(index); m_alpha.eraseFast(index); m_size.eraseFast(index); } void ParticleEmitter::updateLives(float time_delta) { for (int i = 0, c = m_life.size(); i < c; ++i) { float life = m_life[i]; life -= time_delta; m_life[i] = life; if (life < 0) { destroyParticle(i); --i; --c; } } } void ParticleEmitter::serialize(OutputBlob& blob) { blob.write(m_spawn_period); blob.write(m_initial_life); blob.write(m_initial_size); blob.write(m_entity); blob.writeString(m_material ? m_material->getPath().c_str() : ""); blob.write(m_modules.size()); for (auto* module : m_modules) { blob.write(module->getType()); module->serialize(blob); } } void ParticleEmitter::deserialize(InputBlob& blob, ResourceManager& manager) { blob.read(m_spawn_period); blob.read(m_initial_life); blob.read(m_initial_size); blob.read(m_entity); char path[MAX_PATH_LENGTH]; blob.readString(path, lengthOf(path)); auto material_manager = manager.get(ResourceManager::MATERIAL); auto material = static_cast<Material*>(material_manager->load(Lumix::Path(path))); setMaterial(material); int size; blob.read(size); for (auto* module : m_modules) { LUMIX_DELETE(m_allocator, module); } m_modules.clear(); for (int i = 0; i < size; ++i) { uint32_t type; blob.read(type); auto* module = createModule(type, *this); m_modules.push(module); module->deserialize(blob); } } void ParticleEmitter::updatePositions(float time_delta) { for (int i = 0, c = m_position.size(); i < c; ++i) { m_position[i] += m_velocity[i] * time_delta; } } void ParticleEmitter::updateRotations(float time_delta) { for (int i = 0, c = m_rotation.size(); i < c; ++i) { m_rotation[i] += m_rotational_speed[i] * time_delta; } } void ParticleEmitter::update(float time_delta) { spawnParticles(time_delta); updateLives(time_delta); updatePositions(time_delta); updateRotations(time_delta); for (auto* module : m_modules) { module->update(time_delta); } } void ParticleEmitter::spawnParticles(float time_delta) { m_next_spawn_time -= time_delta; while (m_next_spawn_time < 0) { m_next_spawn_time += m_spawn_period.getRandom(); spawnParticle(); } } struct InitialVelocityModule : public ParticleEmitter::ModuleBase { Interval m_x; Interval m_y; Interval m_z; InitialVelocityModule(ParticleEmitter& emitter) : ModuleBase(emitter) { m_z.from = -1; m_z.to = 1; m_x.from = m_x.to = m_x.to = m_y.from = m_y.to = 0; } void spawnParticle(int index) override { Vec3 v; v.x = m_x.getRandom(); v.y = m_y.getRandom(); v.z = m_z.getRandom(); m_emitter.m_velocity[index] = v; } }; } // namespace Lumix<|endoftext|>
<commit_before>// Edge.cpp // Copyright (c) 2009, Dan Heeks // This program is released under the BSD license. See the file COPYING for details. #include "stdafx.h" #include "Edge.h" #include "Face.h" #include "Vertex.h" #include "Solid.h" #include "../interface/Tool.h" #include "HeeksConfig.h" #include "Gripper.h" #include "../interface/PropertyLength.h" CEdge::CEdge(const TopoDS_Edge &edge):m_topods_edge(edge), m_midpoint_calculated(false), m_temp_attr(0), m_vertex0(NULL), m_vertex1(NULL){ GetCurveParams2(&m_start_u, &m_end_u, &m_isClosed, &m_isPeriodic); Evaluate(m_start_u, &m_start_x, &m_start_tangent_x); double t[3]; Evaluate(m_end_u, &m_end_x, t); m_orientation = Orientation(); } CEdge::~CEdge(){ } void CEdge::glCommands(bool select, bool marked, bool no_color){ if(!no_color){ wxGetApp().glColorEnsuringContrast(HeeksColor(0, 0, 0)); } if(Owner() && Owner()->Owner() && Owner()->Owner()->GetType() == SolidType) { // triangulate a face on the edge first TopTools_IndexedDataMapOfShapeListOfShape lface; TopExp::MapShapesAndAncestors(((CShape*)(Owner()->Owner()))->Shape(),TopAbs_EDGE,TopAbs_FACE,lface); const TopTools_ListOfShape& lfac = lface.FindFromKey(m_topods_edge); Standard_Integer nelem= lfac.Extent(); if(nelem == 2){ TopTools_ListIteratorOfListOfShape It; It.Initialize(lfac); TopoDS_Face Face1 = TopoDS::Face(It.Value()); TopLoc_Location fL; Handle_Poly_Triangulation facing = BRep_Tool::Triangulation(Face1,fL); if(!facing.IsNull()) { // Get polygon Handle_Poly_PolygonOnTriangulation polygon = BRep_Tool::PolygonOnTriangulation(m_topods_edge, facing, fL); gp_Trsf tr = fL; double m[16]; extract_transposed(tr, m); glPushMatrix(); glMultMatrixd(m); if (!polygon.IsNull()) { glBegin(GL_LINE_STRIP); const TColStd_Array1OfInteger& Nodes = polygon->Nodes(); const TColgp_Array1OfPnt& FNodes = facing->Nodes(); int nnn = polygon->NbNodes(); for (int nn = 1; nn <= nnn; nn++) { gp_Pnt v = FNodes(Nodes(nn)); glVertex3d(v.X(), v.Y(), v.Z()); } glEnd(); } glPopMatrix(); } } } else { bool glwidth_done = false; GLfloat save_depth_range[2]; if(Owner() == NULL || Owner()->Owner() == NULL || Owner()->Owner()->GetType() != WireType) { BRepTools::Clean(m_topods_edge); double pixels_per_mm = wxGetApp().GetPixelScale(); BRepMesh::Mesh(m_topods_edge, 1/pixels_per_mm); if(marked){ glGetFloatv(GL_DEPTH_RANGE, save_depth_range); glDepthRange(0, 0); glLineWidth(2); glwidth_done = true; } } TopLoc_Location L; Handle(Poly_Polygon3D) Polyg = BRep_Tool::Polygon3D(m_topods_edge, L); if (!Polyg.IsNull()) { const TColgp_Array1OfPnt& Points = Polyg->Nodes(); Standard_Integer po; glBegin(GL_LINE_STRIP); for (po = Points.Lower(); po <= Points.Upper(); po++) { gp_Pnt p = (Points.Value(po)).Transformed(L); glVertex3d(p.X(), p.Y(), p.Z()); } glEnd(); } if(glwidth_done) { glLineWidth(1); glDepthRange(save_depth_range[0], save_depth_range[1]); } } } void CEdge::GetBox(CBox &box){ } void CEdge::GetGripperPositions(std::list<GripData> *list, bool just_for_endof){ if(just_for_endof) { list->push_back(GripData(GripperTypeTranslate,m_start_x,m_start_y,m_start_z,NULL)); list->push_back(GripData(GripperTypeTranslate,m_end_x,m_end_y,m_end_z,NULL)); } else { // add a gripper in the middle, just to show the edge is selected if(!m_midpoint_calculated) { BRepAdaptor_Curve curve(m_topods_edge); double us = curve.FirstParameter(); double ue = curve.LastParameter(); double umiddle = (us+ue)/2; Evaluate(umiddle, m_midpoint, NULL); } list->push_back(GripData(GripperTypeTranslate,m_midpoint[0],m_midpoint[1],m_midpoint[2],NULL)); } } class BlendTool:public Tool { public: CEdge* m_edge; BlendTool(CEdge* edge):m_edge(edge){} const wxChar* GetTitle(){return _("Blend");} wxString BitmapPath(){return _T("edgeblend");} const wxChar* GetToolTip(){return _T("Blend edge");} void Run(){ double rad = 2.0; HeeksConfig config; config.Read(_T("EdgeBlendRadius"), &rad); if(wxGetApp().InputDouble(_("Enter Blend Radius"), _("Radius"), rad)) { m_edge->Blend(rad); config.Write(_T("EdgeBlendRadius"), rad); } } }; static BlendTool blend_tool(NULL); void CEdge::GetTools(std::list<Tool*>* t_list, const wxPoint* p){ if(Owner() && Owner()->Owner() && Owner()->Owner()->GetType() == SolidType) blend_tool.m_edge = this; t_list->push_back(&blend_tool); } void CEdge::Blend(double radius){ try{ if(Owner() && Owner()->Owner() && CShape::IsTypeAShape(Owner()->Owner()->GetType())){ BRepFilletAPI_MakeFillet fillet(((CShape*)(Owner()->Owner()))->Shape()); fillet.Add(radius, m_topods_edge); TopoDS_Shape new_shape = fillet.Shape(); wxGetApp().StartHistory(); wxGetApp().AddUndoably(new CSolid(*((TopoDS_Solid*)(&new_shape)), _("Solid with edge blend"), *(Owner()->Owner()->GetColor())), NULL, NULL); wxGetApp().DeleteUndoably(Owner()->Owner()); wxGetApp().EndHistory(); } } catch(wxChar *message) { wxMessageBox(wxString(_("A fatal error happened during Blend")) + _T(" -\n") + wxString(message)); } catch(...) { wxMessageBox(_("A fatal error happened during Blend")); } } void CEdge::GetProperties(std::list<Property *> *list) { list->push_back(new PropertyLength(_("length"), Length(), NULL)); HeeksObj::GetProperties(list); } void CEdge::WriteXML(TiXmlNode *root) { CShape::m_solids_found = true; } CFace* CEdge::GetFirstFace() { if (m_faces.size()==0) return NULL; m_faceIt = m_faces.begin(); return *m_faceIt; } CFace* CEdge::GetNextFace() { if (m_faces.size()==0 || m_faceIt==m_faces.end()) return NULL; m_faceIt++; if (m_faceIt==m_faces.end()) return NULL; return *m_faceIt; } int CEdge::GetCurveType() { // enum GeomAbs_CurveType // 0 - GeomAbs_Line // 1 - GeomAbs_Circle // 2 - GeomAbs_Ellipse // 3 - GeomAbs_Hyperbola // 4 - GeomAbs_Parabola // 5 - GeomAbs_BezierCurve // 6 - GeomAbs_BSplineCurve // 7 - GeomAbs_OtherCurve BRepAdaptor_Curve curve(m_topods_edge); GeomAbs_CurveType curve_type = curve.GetType(); return curve_type; } void CEdge::GetCurveParams(double* start, double* end, double* uStart, double* uEnd, int* Reversed) { BRepAdaptor_Curve curve(m_topods_edge); double us = curve.FirstParameter(); double ue = curve.LastParameter(); if(uStart)*uStart = us; if(uEnd)*uEnd = ue; if(start)extract(curve.Value(us), start); if(end)extract(curve.Value(ue), end); if(Reversed)*Reversed = Orientation() ? 0:1; } void CEdge::GetCurveParams2(double *uStart, double *uEnd, int *isClosed, int *isPeriodic) { BRepAdaptor_Curve curve(m_topods_edge); *uStart = curve.FirstParameter(); *uEnd = curve.LastParameter(); if(isClosed)*isClosed = curve.IsClosed(); if(isPeriodic)*isPeriodic = curve.IsPeriodic(); } bool CEdge::InFaceSense(CFace* face) { std::list<CFace*>::iterator FIt = m_faces.begin(); std::list<bool>::iterator FSIt = m_face_senses.begin(); for(;FIt != m_faces.end(); FIt++, FSIt++) { CFace* f = *FIt; bool sense = *FSIt; if(f == face) { bool eo = Orientation(); return (sense == eo); } } return false; // shouldn't get here } void CEdge::Evaluate(double u, double *p, double *tangent) { BRepAdaptor_Curve curve(m_topods_edge); gp_Pnt P; gp_Vec V; curve.D1(u, P, V); extract(P, p); if(tangent)extract(V, tangent); } bool CEdge::GetLineParams(double *d6) { BRepAdaptor_Curve curve(m_topods_edge); if(curve.GetType() != GeomAbs_Line)return false; gp_Lin line = curve.Line(); const gp_Pnt& pos = line.Location(); const gp_Dir& dir = line.Direction(); d6[0] = pos.X(); d6[1] = pos.Y(); d6[2] = pos.Z(); d6[3] = dir.X(); d6[4] = dir.Y(); d6[5] = dir.Z(); return true; } bool CEdge::GetCircleParams(double *d7) { //center.x, center.y, center.z, axis.x, axis.y, axis.z, radius BRepAdaptor_Curve curve(m_topods_edge); if(curve.GetType() != GeomAbs_Circle)return false; gp_Circ c = curve.Circle(); const gp_Pnt& pos = c.Location(); const gp_Dir& dir = c.Axis().Direction(); d7[0] = pos.X(); d7[1] = pos.Y(); d7[2] = pos.Z(); d7[3] = dir.X(); d7[4] = dir.Y(); d7[5] = dir.Z(); d7[6] = c.Radius(); return true; } bool CEdge::Orientation() { TopAbs_Orientation o = m_topods_edge.Orientation(); return (o == TopAbs_FORWARD); } double CEdge::Length() { BRepAdaptor_Curve c(m_topods_edge); double len = GCPnts_AbscissaPoint::Length( c ); return len; } double CEdge::Length2(double uStart, double uEnd) { BRepAdaptor_Curve c(m_topods_edge); double len = GCPnts_AbscissaPoint::Length( c, uStart, uEnd ); return len; } void CEdge::FindVertices() { CShape* body = GetParentBody(); if(body) { int i = 0; for (TopExp_Explorer expVertex(m_topods_edge, TopAbs_VERTEX); expVertex.More() && i<2; expVertex.Next(), i++) { const TopoDS_Shape &V = expVertex.Current(); for(HeeksObj* object = body->m_vertices->GetFirstChild(); object; object = body->m_vertices->GetNextChild()) { CVertex* v = (CVertex*)object; if(v->Vertex().IsSame(V)) { if(i == 0)m_vertex0 = v; else m_vertex1 = v; break; } } } } } CVertex* CEdge::GetVertex0() { if(m_vertex0 == NULL)FindVertices(); return m_vertex0; } CVertex* CEdge::GetVertex1() { if(m_vertex1 == NULL)FindVertices(); return m_vertex1; } CShape* CEdge::GetParentBody() { if(Owner() == NULL)return NULL; if(Owner()->Owner() == NULL)return NULL; if(Owner()->Owner()->GetType() != SolidType)return NULL; return (CShape*)(Owner()->Owner()); } <commit_msg>fixed a compile warning<commit_after>// Edge.cpp // Copyright (c) 2009, Dan Heeks // This program is released under the BSD license. See the file COPYING for details. #include "stdafx.h" #include "Edge.h" #include "Face.h" #include "Vertex.h" #include "Solid.h" #include "../interface/Tool.h" #include "HeeksConfig.h" #include "Gripper.h" #include "../interface/PropertyLength.h" CEdge::CEdge(const TopoDS_Edge &edge):m_topods_edge(edge), m_vertex0(NULL), m_vertex1(NULL), m_midpoint_calculated(false), m_temp_attr(0){ GetCurveParams2(&m_start_u, &m_end_u, &m_isClosed, &m_isPeriodic); Evaluate(m_start_u, &m_start_x, &m_start_tangent_x); double t[3]; Evaluate(m_end_u, &m_end_x, t); m_orientation = Orientation(); } CEdge::~CEdge(){ } void CEdge::glCommands(bool select, bool marked, bool no_color){ if(!no_color){ wxGetApp().glColorEnsuringContrast(HeeksColor(0, 0, 0)); } if(Owner() && Owner()->Owner() && Owner()->Owner()->GetType() == SolidType) { // triangulate a face on the edge first TopTools_IndexedDataMapOfShapeListOfShape lface; TopExp::MapShapesAndAncestors(((CShape*)(Owner()->Owner()))->Shape(),TopAbs_EDGE,TopAbs_FACE,lface); const TopTools_ListOfShape& lfac = lface.FindFromKey(m_topods_edge); Standard_Integer nelem= lfac.Extent(); if(nelem == 2){ TopTools_ListIteratorOfListOfShape It; It.Initialize(lfac); TopoDS_Face Face1 = TopoDS::Face(It.Value()); TopLoc_Location fL; Handle_Poly_Triangulation facing = BRep_Tool::Triangulation(Face1,fL); if(!facing.IsNull()) { // Get polygon Handle_Poly_PolygonOnTriangulation polygon = BRep_Tool::PolygonOnTriangulation(m_topods_edge, facing, fL); gp_Trsf tr = fL; double m[16]; extract_transposed(tr, m); glPushMatrix(); glMultMatrixd(m); if (!polygon.IsNull()) { glBegin(GL_LINE_STRIP); const TColStd_Array1OfInteger& Nodes = polygon->Nodes(); const TColgp_Array1OfPnt& FNodes = facing->Nodes(); int nnn = polygon->NbNodes(); for (int nn = 1; nn <= nnn; nn++) { gp_Pnt v = FNodes(Nodes(nn)); glVertex3d(v.X(), v.Y(), v.Z()); } glEnd(); } glPopMatrix(); } } } else { bool glwidth_done = false; GLfloat save_depth_range[2]; if(Owner() == NULL || Owner()->Owner() == NULL || Owner()->Owner()->GetType() != WireType) { BRepTools::Clean(m_topods_edge); double pixels_per_mm = wxGetApp().GetPixelScale(); BRepMesh::Mesh(m_topods_edge, 1/pixels_per_mm); if(marked){ glGetFloatv(GL_DEPTH_RANGE, save_depth_range); glDepthRange(0, 0); glLineWidth(2); glwidth_done = true; } } TopLoc_Location L; Handle(Poly_Polygon3D) Polyg = BRep_Tool::Polygon3D(m_topods_edge, L); if (!Polyg.IsNull()) { const TColgp_Array1OfPnt& Points = Polyg->Nodes(); Standard_Integer po; glBegin(GL_LINE_STRIP); for (po = Points.Lower(); po <= Points.Upper(); po++) { gp_Pnt p = (Points.Value(po)).Transformed(L); glVertex3d(p.X(), p.Y(), p.Z()); } glEnd(); } if(glwidth_done) { glLineWidth(1); glDepthRange(save_depth_range[0], save_depth_range[1]); } } } void CEdge::GetBox(CBox &box){ } void CEdge::GetGripperPositions(std::list<GripData> *list, bool just_for_endof){ if(just_for_endof) { list->push_back(GripData(GripperTypeTranslate,m_start_x,m_start_y,m_start_z,NULL)); list->push_back(GripData(GripperTypeTranslate,m_end_x,m_end_y,m_end_z,NULL)); } else { // add a gripper in the middle, just to show the edge is selected if(!m_midpoint_calculated) { BRepAdaptor_Curve curve(m_topods_edge); double us = curve.FirstParameter(); double ue = curve.LastParameter(); double umiddle = (us+ue)/2; Evaluate(umiddle, m_midpoint, NULL); } list->push_back(GripData(GripperTypeTranslate,m_midpoint[0],m_midpoint[1],m_midpoint[2],NULL)); } } class BlendTool:public Tool { public: CEdge* m_edge; BlendTool(CEdge* edge):m_edge(edge){} const wxChar* GetTitle(){return _("Blend");} wxString BitmapPath(){return _T("edgeblend");} const wxChar* GetToolTip(){return _T("Blend edge");} void Run(){ double rad = 2.0; HeeksConfig config; config.Read(_T("EdgeBlendRadius"), &rad); if(wxGetApp().InputDouble(_("Enter Blend Radius"), _("Radius"), rad)) { m_edge->Blend(rad); config.Write(_T("EdgeBlendRadius"), rad); } } }; static BlendTool blend_tool(NULL); void CEdge::GetTools(std::list<Tool*>* t_list, const wxPoint* p){ if(Owner() && Owner()->Owner() && Owner()->Owner()->GetType() == SolidType) blend_tool.m_edge = this; t_list->push_back(&blend_tool); } void CEdge::Blend(double radius){ try{ if(Owner() && Owner()->Owner() && CShape::IsTypeAShape(Owner()->Owner()->GetType())){ BRepFilletAPI_MakeFillet fillet(((CShape*)(Owner()->Owner()))->Shape()); fillet.Add(radius, m_topods_edge); TopoDS_Shape new_shape = fillet.Shape(); wxGetApp().StartHistory(); wxGetApp().AddUndoably(new CSolid(*((TopoDS_Solid*)(&new_shape)), _("Solid with edge blend"), *(Owner()->Owner()->GetColor())), NULL, NULL); wxGetApp().DeleteUndoably(Owner()->Owner()); wxGetApp().EndHistory(); } } catch(wxChar *message) { wxMessageBox(wxString(_("A fatal error happened during Blend")) + _T(" -\n") + wxString(message)); } catch(...) { wxMessageBox(_("A fatal error happened during Blend")); } } void CEdge::GetProperties(std::list<Property *> *list) { list->push_back(new PropertyLength(_("length"), Length(), NULL)); HeeksObj::GetProperties(list); } void CEdge::WriteXML(TiXmlNode *root) { CShape::m_solids_found = true; } CFace* CEdge::GetFirstFace() { if (m_faces.size()==0) return NULL; m_faceIt = m_faces.begin(); return *m_faceIt; } CFace* CEdge::GetNextFace() { if (m_faces.size()==0 || m_faceIt==m_faces.end()) return NULL; m_faceIt++; if (m_faceIt==m_faces.end()) return NULL; return *m_faceIt; } int CEdge::GetCurveType() { // enum GeomAbs_CurveType // 0 - GeomAbs_Line // 1 - GeomAbs_Circle // 2 - GeomAbs_Ellipse // 3 - GeomAbs_Hyperbola // 4 - GeomAbs_Parabola // 5 - GeomAbs_BezierCurve // 6 - GeomAbs_BSplineCurve // 7 - GeomAbs_OtherCurve BRepAdaptor_Curve curve(m_topods_edge); GeomAbs_CurveType curve_type = curve.GetType(); return curve_type; } void CEdge::GetCurveParams(double* start, double* end, double* uStart, double* uEnd, int* Reversed) { BRepAdaptor_Curve curve(m_topods_edge); double us = curve.FirstParameter(); double ue = curve.LastParameter(); if(uStart)*uStart = us; if(uEnd)*uEnd = ue; if(start)extract(curve.Value(us), start); if(end)extract(curve.Value(ue), end); if(Reversed)*Reversed = Orientation() ? 0:1; } void CEdge::GetCurveParams2(double *uStart, double *uEnd, int *isClosed, int *isPeriodic) { BRepAdaptor_Curve curve(m_topods_edge); *uStart = curve.FirstParameter(); *uEnd = curve.LastParameter(); if(isClosed)*isClosed = curve.IsClosed(); if(isPeriodic)*isPeriodic = curve.IsPeriodic(); } bool CEdge::InFaceSense(CFace* face) { std::list<CFace*>::iterator FIt = m_faces.begin(); std::list<bool>::iterator FSIt = m_face_senses.begin(); for(;FIt != m_faces.end(); FIt++, FSIt++) { CFace* f = *FIt; bool sense = *FSIt; if(f == face) { bool eo = Orientation(); return (sense == eo); } } return false; // shouldn't get here } void CEdge::Evaluate(double u, double *p, double *tangent) { BRepAdaptor_Curve curve(m_topods_edge); gp_Pnt P; gp_Vec V; curve.D1(u, P, V); extract(P, p); if(tangent)extract(V, tangent); } bool CEdge::GetLineParams(double *d6) { BRepAdaptor_Curve curve(m_topods_edge); if(curve.GetType() != GeomAbs_Line)return false; gp_Lin line = curve.Line(); const gp_Pnt& pos = line.Location(); const gp_Dir& dir = line.Direction(); d6[0] = pos.X(); d6[1] = pos.Y(); d6[2] = pos.Z(); d6[3] = dir.X(); d6[4] = dir.Y(); d6[5] = dir.Z(); return true; } bool CEdge::GetCircleParams(double *d7) { //center.x, center.y, center.z, axis.x, axis.y, axis.z, radius BRepAdaptor_Curve curve(m_topods_edge); if(curve.GetType() != GeomAbs_Circle)return false; gp_Circ c = curve.Circle(); const gp_Pnt& pos = c.Location(); const gp_Dir& dir = c.Axis().Direction(); d7[0] = pos.X(); d7[1] = pos.Y(); d7[2] = pos.Z(); d7[3] = dir.X(); d7[4] = dir.Y(); d7[5] = dir.Z(); d7[6] = c.Radius(); return true; } bool CEdge::Orientation() { TopAbs_Orientation o = m_topods_edge.Orientation(); return (o == TopAbs_FORWARD); } double CEdge::Length() { BRepAdaptor_Curve c(m_topods_edge); double len = GCPnts_AbscissaPoint::Length( c ); return len; } double CEdge::Length2(double uStart, double uEnd) { BRepAdaptor_Curve c(m_topods_edge); double len = GCPnts_AbscissaPoint::Length( c, uStart, uEnd ); return len; } void CEdge::FindVertices() { CShape* body = GetParentBody(); if(body) { int i = 0; for (TopExp_Explorer expVertex(m_topods_edge, TopAbs_VERTEX); expVertex.More() && i<2; expVertex.Next(), i++) { const TopoDS_Shape &V = expVertex.Current(); for(HeeksObj* object = body->m_vertices->GetFirstChild(); object; object = body->m_vertices->GetNextChild()) { CVertex* v = (CVertex*)object; if(v->Vertex().IsSame(V)) { if(i == 0)m_vertex0 = v; else m_vertex1 = v; break; } } } } } CVertex* CEdge::GetVertex0() { if(m_vertex0 == NULL)FindVertices(); return m_vertex0; } CVertex* CEdge::GetVertex1() { if(m_vertex1 == NULL)FindVertices(); return m_vertex1; } CShape* CEdge::GetParentBody() { if(Owner() == NULL)return NULL; if(Owner()->Owner() == NULL)return NULL; if(Owner()->Owner()->GetType() != SolidType)return NULL; return (CShape*)(Owner()->Owner()); } <|endoftext|>
<commit_before>/// /// @file l1d_cache_size.cpp /// @brief Get the L1 cache size in kilobytes on Windows /// and most Unix-like operating systems. /// /// Copyright (C) 2015 Kim Walisch, <kim.walisch@gmail.com> /// /// This file is distributed under the BSD License. /// #include <cstdlib> #if defined(_WIN32) || defined(_WIN64) #include <windows.h> typedef BOOL (WINAPI *LPFN_GLPI)(PSYSTEM_LOGICAL_PROCESSOR_INFORMATION, PDWORD); /// Get the CPU's L1 data cache size (per core) in kilobytes. /// Successfully tested on Windows x64. /// @return L1 data cache size in kilobytes or -1 if an error occurred. /// int get_l1d_cache_size() { LPFN_GLPI glpi = (LPFN_GLPI) GetProcAddress(GetModuleHandle(TEXT("kernel32")), "GetLogicalProcessorInformation"); // GetLogicalProcessorInformation not supported if (glpi == NULL) return -1; DWORD buffer_bytes = 0; int cache_size = 0; glpi(0, &buffer_bytes); std::size_t size = buffer_bytes / sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION); SYSTEM_LOGICAL_PROCESSOR_INFORMATION* buffer = new SYSTEM_LOGICAL_PROCESSOR_INFORMATION[size]; glpi(buffer, &buffer_bytes); for (std::size_t i = 0; i < size; i++) { if (buffer[i].Relationship == RelationCache && buffer[i].Cache.Level == 1) { cache_size = (int) buffer[i].Cache.Size; break; } } delete buffer; return cache_size / 1024; } #else /// Get the CPU's L1 data cache size (per core) in kilobytes. /// Successfully tested on Linux and Mac OS X. /// @return L1 data cache size in kilobytes or -1 if an error occurred. /// int get_l1d_cache_size() { // Posix shell script for UNIX like OSes // Returns log2 of L1_DCACHE_SIZE in kilobytes // https://github.com/kimwalisch/primesieve/blob/master/configure.ac const char* shell_script = "command -v getconf >/dev/null 2>/dev/null; " "if [ $? -eq 0 ]; " "then " " L1_DCACHE_BYTES=$(getconf LEVEL1_DCACHE_SIZE 2>/dev/null); " "fi; " "if test \"x$L1_DCACHE_BYTES\" = \"x\" || test \"$L1_DCACHE_BYTES\" = \"0\"; " "then " " L1_DCACHE_BYTES=$(cat /sys/devices/system/cpu/cpu0/cache/index0/size 2>/dev/null); " " if test \"x$L1_DCACHE_BYTES\" != \"x\"; " " then " " is_kilobytes=$(echo $L1_DCACHE_BYTES | grep K); " " if test \"x$is_kilobytes\" != \"x\"; " " then " " L1_DCACHE_BYTES=$(expr $(echo $L1_DCACHE_BYTES | sed -e s'/K$//') '*' 1024); " " fi; " " is_megabytes=$(echo $L1_DCACHE_BYTES | grep M); " " if test \"x$is_megabytes\" != \"x\"; " " then " " L1_DCACHE_BYTES=$(expr $(echo $L1_DCACHE_BYTES | sed -e s'/M$//') '*' 1024 '*' 1024); " " fi; " " else " " command -v sysctl >/dev/null 2>/dev/null; " " if [ $? -eq 0 ]; " " then " " L1_DCACHE_BYTES=$(sysctl hw.l1dcachesize 2>/dev/null | sed -e 's/^.* //'); " " fi; " " fi; " "fi; " "if test \"x$L1_DCACHE_BYTES\" != \"x\"; " "then " " if [ $L1_DCACHE_BYTES -ge 1024 2>/dev/null ]; " " then " " L1_DCACHE_SIZE=$(expr $L1_DCACHE_BYTES '/' 1024); " " fi; " "fi; " "if test \"x$L1_DCACHE_SIZE\" = \"x\"; " "then " " exit 1; " "fi; " "LOG2_L1_DCACHE_SIZE=0; " "while [ $L1_DCACHE_SIZE -ge 2 ]; " "do " " L1_DCACHE_SIZE=$(expr $L1_DCACHE_SIZE '/' 2); " " LOG2_L1_DCACHE_SIZE=$(expr $LOG2_L1_DCACHE_SIZE '+' 1); " "done; " "exit $LOG2_L1_DCACHE_SIZE; "; int exit_code = std::system(shell_script); exit_code = WEXITSTATUS(exit_code); // check if shell script executed without any errors if (exit_code <= 1) return -1; int l1d_cache_size = 1 << exit_code; return l1d_cache_size; } #endif <commit_msg>Refactoring<commit_after>/// /// @file l1d_cache_size.cpp /// @brief Get the L1 cache size in kilobytes on Windows /// and most Unix-like operating systems. /// /// Copyright (C) 2015 Kim Walisch, <kim.walisch@gmail.com> /// /// This file is distributed under the BSD License. /// #include <cstdlib> #if defined(_WIN32) || defined(_WIN64) #include <windows.h> typedef BOOL (WINAPI *LPFN_GLPI)(PSYSTEM_LOGICAL_PROCESSOR_INFORMATION, PDWORD); /// Get the CPU's L1 data cache size (per core) in kilobytes. /// Successfully tested on Windows x64. /// @return L1 data cache size in kilobytes or -1 if an error occurred. /// int get_l1d_cache_size() { LPFN_GLPI glpi = (LPFN_GLPI) GetProcAddress(GetModuleHandle(TEXT("kernel32")), "GetLogicalProcessorInformation"); // GetLogicalProcessorInformation not supported if (glpi == NULL) return -1; DWORD buffer_bytes = 0; int cache_size = 0; glpi(0, &buffer_bytes); std::size_t size = buffer_bytes / sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION); SYSTEM_LOGICAL_PROCESSOR_INFORMATION* buffer = new SYSTEM_LOGICAL_PROCESSOR_INFORMATION[size]; glpi(buffer, &buffer_bytes); for (std::size_t i = 0; i < size; i++) { if (buffer[i].Relationship == RelationCache && buffer[i].Cache.Level == 1) { cache_size = (int) buffer[i].Cache.Size; break; } } delete buffer; return cache_size / 1024; } #else /// Get the CPU's L1 data cache size (per core) in kilobytes. /// Successfully tested on Linux and Mac OS X. /// @return L1 data cache size in kilobytes or -1 if an error occurred. /// int get_l1d_cache_size() { // Posix shell script for UNIX like OSes // Returns log2 of L1_DCACHE_SIZE in kilobytes // https://github.com/kimwalisch/primesieve/blob/master/configure.ac const char* shell_script = "command -v getconf >/dev/null 2>/dev/null; " "if [ $? -eq 0 ]; " "then " " L1_DCACHE_BYTES=$(getconf LEVEL1_DCACHE_SIZE 2>/dev/null); " "fi; " "if test \"x$L1_DCACHE_BYTES\" = \"x\" || test \"$L1_DCACHE_BYTES\" = \"0\"; " "then " " L1_DCACHE_BYTES=$(cat /sys/devices/system/cpu/cpu0/cache/index0/size 2>/dev/null); " " if test \"x$L1_DCACHE_BYTES\" != \"x\"; " " then " " is_kilobytes=$(echo $L1_DCACHE_BYTES | grep K); " " if test \"x$is_kilobytes\" != \"x\"; " " then " " L1_DCACHE_BYTES=$(expr $(echo $L1_DCACHE_BYTES | sed -e s'/K$//') '*' 1024); " " fi; " " is_megabytes=$(echo $L1_DCACHE_BYTES | grep M); " " if test \"x$is_megabytes\" != \"x\"; " " then " " L1_DCACHE_BYTES=$(expr $(echo $L1_DCACHE_BYTES | sed -e s'/M$//') '*' 1024 '*' 1024); " " fi; " " else " " command -v sysctl >/dev/null 2>/dev/null; " " if [ $? -eq 0 ]; " " then " " L1_DCACHE_BYTES=$(sysctl hw.l1dcachesize 2>/dev/null | sed -e 's/^.* //'); " " fi; " " fi; " "fi; " "if test \"x$L1_DCACHE_BYTES\" != \"x\"; " "then " " if [ $L1_DCACHE_BYTES -ge 1024 2>/dev/null ]; " " then " " L1_DCACHE_SIZE=$(expr $L1_DCACHE_BYTES '/' 1024); " " fi; " "fi; " "if test \"x$L1_DCACHE_SIZE\" = \"x\"; " "then " " exit 1; " "fi; " "LOG2_L1_DCACHE_SIZE=0; " "while [ $L1_DCACHE_SIZE -ge 2 ]; " "do " " L1_DCACHE_SIZE=$(expr $L1_DCACHE_SIZE '/' 2); " " LOG2_L1_DCACHE_SIZE=$(expr $LOG2_L1_DCACHE_SIZE '+' 1); " "done; " "exit $LOG2_L1_DCACHE_SIZE; "; int exit_code = std::system(shell_script); exit_code = WEXITSTATUS(exit_code); // check if shell script executed without any errors if (exit_code <= 1) return -1; int l1d_cache_size = 1 << exit_code; return l1d_cache_size; } #endif <|endoftext|>
<commit_before><commit_msg>[routing] Updated comments in route.cpp<commit_after><|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. ==============================================================================*/ // See docs in ../ops/math_ops.cc. #include "tensorflow/core/kernels/sequence_ops.h" #include <cmath> #include "tensorflow/core/framework/op_kernel.h" #include "tensorflow/core/framework/op_requires.h" #include "tensorflow/core/framework/register_types.h" #include "tensorflow/core/framework/tensor.h" #include "tensorflow/core/framework/tensor_shape.h" #include "tensorflow/core/framework/types.h" namespace tensorflow { using CPUDevice = Eigen::ThreadPoolDevice; using GPUDevice = Eigen::GpuDevice; namespace functor { template <typename T> struct RangeFunctor<CPUDevice, T> { void operator()(OpKernelContext* context, int64_t size, T start, T delta, typename TTypes<T>::Flat output) const { (void)context; for (int64_t i = 0; i < size; ++i) { output(i) = start + static_cast<T>(i) * delta; } } }; } // namespace functor template <typename Device, typename T> class RangeOp : public OpKernel { public: explicit RangeOp(OpKernelConstruction* context) : OpKernel(context) {} void Compute(OpKernelContext* context) override { const Tensor& start_in = context->input(0); const Tensor& limit_in = context->input(1); const Tensor& delta_in = context->input(2); // TODO(rmlarsen): Disallow legacy use of length-1 vectors as scalars. OP_REQUIRES(context, TensorShapeUtils::IsScalar(start_in.shape()) || (TensorShapeUtils::IsVector(start_in.shape()) && start_in.shape().dim_size(0) == 1), errors::InvalidArgument("start must be a scalar, not shape ", start_in.shape().DebugString())); OP_REQUIRES(context, TensorShapeUtils::IsScalar(limit_in.shape()) || (TensorShapeUtils::IsVector(limit_in.shape()) && limit_in.shape().dim_size(0) == 1), errors::InvalidArgument("limit must be a scalar, not shape ", limit_in.shape().DebugString())); OP_REQUIRES(context, TensorShapeUtils::IsScalar(delta_in.shape()) || (TensorShapeUtils::IsVector(delta_in.shape()) && delta_in.shape().dim_size(0) == 1), errors::InvalidArgument("delta must be a scalar, not shape ", delta_in.shape().DebugString())); const T start = start_in.scalar<T>()(); const T limit = limit_in.scalar<T>()(); const T delta = delta_in.scalar<T>()(); OP_REQUIRES(context, delta != 0, errors::InvalidArgument("Requires delta != 0: ", delta)); if (delta > 0) { OP_REQUIRES( context, start <= limit, errors::InvalidArgument( "Requires start <= limit when delta > 0: ", start, "/", limit)); } else { OP_REQUIRES( context, start >= limit, errors::InvalidArgument( "Requires start >= limit when delta < 0: ", start, "/", limit)); } int64_t size; if (std::is_integral<T>::value) { size = Eigen::divup(Eigen::numext::abs(limit - start), Eigen::numext::abs(delta)); } else { auto size_auto = Eigen::numext::ceil(Eigen::numext::abs((limit - start) / delta)); OP_REQUIRES( context, size_auto <= std::numeric_limits<int64_t>::max(), errors::InvalidArgument("Requires ((limit - start) / delta) <= ", std::numeric_limits<int64_t>::max())); size = static_cast<int64_t>(size_auto); } TensorShape shape; OP_REQUIRES_OK(context, shape.AddDimWithStatus(size)); Tensor* out = nullptr; OP_REQUIRES_OK(context, context->allocate_output(0, shape, &out)); if (size == 0) return; auto flat = out->flat<T>(); functor::RangeFunctor<Device, T>()(context, size, start, delta, flat); } }; #define REGISTER_KERNEL(DEV, DEV_TYPE, TYPE) \ REGISTER_KERNEL_BUILDER(Name("Range") \ .Device(DEV) \ .HostMemory("start") \ .HostMemory("limit") \ .HostMemory("delta") \ .TypeConstraint<TYPE>("Tidx"), \ RangeOp<DEV_TYPE, TYPE>); #define REGISTER_CPU_KERNEL(T) REGISTER_KERNEL(DEVICE_CPU, CPUDevice, T) #define REGISTER_GPU_KERNEL(T) REGISTER_KERNEL(DEVICE_GPU, GPUDevice, T) TF_CALL_float(REGISTER_CPU_KERNEL); TF_CALL_double(REGISTER_CPU_KERNEL); TF_CALL_int32(REGISTER_CPU_KERNEL); TF_CALL_int64(REGISTER_CPU_KERNEL); #if GOOGLE_CUDA || TENSORFLOW_USE_ROCM TF_CALL_float(REGISTER_GPU_KERNEL); TF_CALL_double(REGISTER_GPU_KERNEL); TF_CALL_int64(REGISTER_GPU_KERNEL); #endif // GOOGLE_CUDA || TENSORFLOW_USE_ROCM // Special case to execute int32 on the host with host output. REGISTER_KERNEL_BUILDER(Name("Range") .Device(DEVICE_DEFAULT) .HostMemory("start") .HostMemory("limit") .HostMemory("delta") .HostMemory("output") .TypeConstraint<int32_t>("Tidx"), RangeOp<CPUDevice, int32_t>); #undef REGISTER_KERNEL #undef REGISTER_CPU_KERNEL #undef REGISTER_GPU_KERNEL template <typename T, typename Tnum> class LinSpaceOp : public OpKernel { public: explicit LinSpaceOp(OpKernelConstruction* context) : OpKernel(context) {} void Compute(OpKernelContext* context) override { const Tensor& start_in = context->input(0); const Tensor& stop_in = context->input(1); const Tensor& num_in = context->input(2); OP_REQUIRES(context, TensorShapeUtils::IsScalar(start_in.shape()), errors::InvalidArgument("start must be a scalar, not shape ", start_in.shape().DebugString())); OP_REQUIRES(context, TensorShapeUtils::IsScalar(stop_in.shape()), errors::InvalidArgument("stop must be a scalar, not shape ", stop_in.shape().DebugString())); OP_REQUIRES(context, TensorShapeUtils::IsScalar(num_in.shape()), errors::InvalidArgument("num must be a scalar, not shape ", num_in.shape().DebugString())); const T start = start_in.scalar<T>()(); const T stop = stop_in.scalar<T>()(); const Tnum num = num_in.scalar<Tnum>()(); OP_REQUIRES(context, num > 0, errors::InvalidArgument("Requires num > 0: ", num)); Tensor* out = nullptr; OP_REQUIRES_OK(context, context->allocate_output(0, TensorShape({num}), &out)); auto flat = out->flat<T>(); flat(0) = start; if (num > 1) { const T step = (stop - start) / (num - 1); for (Tnum i = 1; i < num - 1; ++i) flat(i) = start + step * i; // Ensure final value == stop; float arithmetic won't guarantee this. flat(num - 1) = stop; } } }; #define REGISTER_KERNEL(DEV, T, Tidx) \ REGISTER_KERNEL_BUILDER(Name("LinSpace") \ .Device(DEV) \ .TypeConstraint<T>("T") \ .TypeConstraint<Tidx>("Tidx") \ .HostMemory("start") \ .HostMemory("stop") \ .HostMemory("num") \ .HostMemory("output"), \ LinSpaceOp<T, Tidx>); #define REGISTER_KERNEL_ALL_NUMS(dev, T) \ REGISTER_KERNEL(dev, T, int32); \ REGISTER_KERNEL(dev, T, int64_t) #define REGISTER_CPU_KERNEL(T) REGISTER_KERNEL_ALL_NUMS(DEVICE_CPU, T) TF_CALL_float(REGISTER_CPU_KERNEL); TF_CALL_double(REGISTER_CPU_KERNEL); #define REGISTER_DEFAULT_KERNEL(T) REGISTER_KERNEL_ALL_NUMS(DEVICE_DEFAULT, T) TF_CALL_float(REGISTER_DEFAULT_KERNEL); TF_CALL_double(REGISTER_DEFAULT_KERNEL); #undef REGISTER_DEFAULT_KERNEL #undef REGISTER_CPU_KERNEL #undef REGISTER_KERNEL_ALL_NUMS #undef REGISTER_KERNEL } // namespace tensorflow <commit_msg>Rollback of PR #58259 PR #58259: Range kenrel: align CPU and GPU impl<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. ==============================================================================*/ // See docs in ../ops/math_ops.cc. #include "tensorflow/core/kernels/sequence_ops.h" #include <cmath> #include "tensorflow/core/framework/op_kernel.h" #include "tensorflow/core/framework/op_requires.h" #include "tensorflow/core/framework/register_types.h" #include "tensorflow/core/framework/tensor.h" #include "tensorflow/core/framework/tensor_shape.h" #include "tensorflow/core/framework/types.h" namespace tensorflow { using CPUDevice = Eigen::ThreadPoolDevice; using GPUDevice = Eigen::GpuDevice; namespace functor { template <typename T> struct RangeFunctor<CPUDevice, T> { void operator()(OpKernelContext* context, int64_t size, T start, T delta, typename TTypes<T>::Flat output) const { (void)context; T val = start; for (int64_t i = 0; i < size; ++i) { output(i) = T(val); val += delta; } } }; } // namespace functor template <typename Device, typename T> class RangeOp : public OpKernel { public: explicit RangeOp(OpKernelConstruction* context) : OpKernel(context) {} void Compute(OpKernelContext* context) override { const Tensor& start_in = context->input(0); const Tensor& limit_in = context->input(1); const Tensor& delta_in = context->input(2); // TODO(rmlarsen): Disallow legacy use of length-1 vectors as scalars. OP_REQUIRES(context, TensorShapeUtils::IsScalar(start_in.shape()) || (TensorShapeUtils::IsVector(start_in.shape()) && start_in.shape().dim_size(0) == 1), errors::InvalidArgument("start must be a scalar, not shape ", start_in.shape().DebugString())); OP_REQUIRES(context, TensorShapeUtils::IsScalar(limit_in.shape()) || (TensorShapeUtils::IsVector(limit_in.shape()) && limit_in.shape().dim_size(0) == 1), errors::InvalidArgument("limit must be a scalar, not shape ", limit_in.shape().DebugString())); OP_REQUIRES(context, TensorShapeUtils::IsScalar(delta_in.shape()) || (TensorShapeUtils::IsVector(delta_in.shape()) && delta_in.shape().dim_size(0) == 1), errors::InvalidArgument("delta must be a scalar, not shape ", delta_in.shape().DebugString())); const T start = start_in.scalar<T>()(); const T limit = limit_in.scalar<T>()(); const T delta = delta_in.scalar<T>()(); OP_REQUIRES(context, delta != 0, errors::InvalidArgument("Requires delta != 0: ", delta)); if (delta > 0) { OP_REQUIRES( context, start <= limit, errors::InvalidArgument( "Requires start <= limit when delta > 0: ", start, "/", limit)); } else { OP_REQUIRES( context, start >= limit, errors::InvalidArgument( "Requires start >= limit when delta < 0: ", start, "/", limit)); } int64_t size; if (std::is_integral<T>::value) { size = Eigen::divup(Eigen::numext::abs(limit - start), Eigen::numext::abs(delta)); } else { auto size_auto = Eigen::numext::ceil(Eigen::numext::abs((limit - start) / delta)); OP_REQUIRES( context, size_auto <= std::numeric_limits<int64_t>::max(), errors::InvalidArgument("Requires ((limit - start) / delta) <= ", std::numeric_limits<int64_t>::max())); size = static_cast<int64_t>(size_auto); } TensorShape shape; OP_REQUIRES_OK(context, shape.AddDimWithStatus(size)); Tensor* out = nullptr; OP_REQUIRES_OK(context, context->allocate_output(0, shape, &out)); if (size == 0) return; auto flat = out->flat<T>(); functor::RangeFunctor<Device, T>()(context, size, start, delta, flat); } }; #define REGISTER_KERNEL(DEV, DEV_TYPE, TYPE) \ REGISTER_KERNEL_BUILDER(Name("Range") \ .Device(DEV) \ .HostMemory("start") \ .HostMemory("limit") \ .HostMemory("delta") \ .TypeConstraint<TYPE>("Tidx"), \ RangeOp<DEV_TYPE, TYPE>); #define REGISTER_CPU_KERNEL(T) REGISTER_KERNEL(DEVICE_CPU, CPUDevice, T) #define REGISTER_GPU_KERNEL(T) REGISTER_KERNEL(DEVICE_GPU, GPUDevice, T) TF_CALL_float(REGISTER_CPU_KERNEL); TF_CALL_double(REGISTER_CPU_KERNEL); TF_CALL_int32(REGISTER_CPU_KERNEL); TF_CALL_int64(REGISTER_CPU_KERNEL); #if GOOGLE_CUDA || TENSORFLOW_USE_ROCM TF_CALL_float(REGISTER_GPU_KERNEL); TF_CALL_double(REGISTER_GPU_KERNEL); TF_CALL_int64(REGISTER_GPU_KERNEL); #endif // GOOGLE_CUDA || TENSORFLOW_USE_ROCM // Special case to execute int32 on the host with host output. REGISTER_KERNEL_BUILDER(Name("Range") .Device(DEVICE_DEFAULT) .HostMemory("start") .HostMemory("limit") .HostMemory("delta") .HostMemory("output") .TypeConstraint<int32_t>("Tidx"), RangeOp<CPUDevice, int32_t>); #undef REGISTER_KERNEL #undef REGISTER_CPU_KERNEL #undef REGISTER_GPU_KERNEL template <typename T, typename Tnum> class LinSpaceOp : public OpKernel { public: explicit LinSpaceOp(OpKernelConstruction* context) : OpKernel(context) {} void Compute(OpKernelContext* context) override { const Tensor& start_in = context->input(0); const Tensor& stop_in = context->input(1); const Tensor& num_in = context->input(2); OP_REQUIRES(context, TensorShapeUtils::IsScalar(start_in.shape()), errors::InvalidArgument("start must be a scalar, not shape ", start_in.shape().DebugString())); OP_REQUIRES(context, TensorShapeUtils::IsScalar(stop_in.shape()), errors::InvalidArgument("stop must be a scalar, not shape ", stop_in.shape().DebugString())); OP_REQUIRES(context, TensorShapeUtils::IsScalar(num_in.shape()), errors::InvalidArgument("num must be a scalar, not shape ", num_in.shape().DebugString())); const T start = start_in.scalar<T>()(); const T stop = stop_in.scalar<T>()(); const Tnum num = num_in.scalar<Tnum>()(); OP_REQUIRES(context, num > 0, errors::InvalidArgument("Requires num > 0: ", num)); Tensor* out = nullptr; OP_REQUIRES_OK(context, context->allocate_output(0, TensorShape({num}), &out)); auto flat = out->flat<T>(); flat(0) = start; if (num > 1) { const T step = (stop - start) / (num - 1); for (Tnum i = 1; i < num - 1; ++i) flat(i) = start + step * i; // Ensure final value == stop; float arithmetic won't guarantee this. flat(num - 1) = stop; } } }; #define REGISTER_KERNEL(DEV, T, Tidx) \ REGISTER_KERNEL_BUILDER(Name("LinSpace") \ .Device(DEV) \ .TypeConstraint<T>("T") \ .TypeConstraint<Tidx>("Tidx") \ .HostMemory("start") \ .HostMemory("stop") \ .HostMemory("num") \ .HostMemory("output"), \ LinSpaceOp<T, Tidx>); #define REGISTER_KERNEL_ALL_NUMS(dev, T) \ REGISTER_KERNEL(dev, T, int32); \ REGISTER_KERNEL(dev, T, int64_t) #define REGISTER_CPU_KERNEL(T) REGISTER_KERNEL_ALL_NUMS(DEVICE_CPU, T) TF_CALL_float(REGISTER_CPU_KERNEL); TF_CALL_double(REGISTER_CPU_KERNEL); #define REGISTER_DEFAULT_KERNEL(T) REGISTER_KERNEL_ALL_NUMS(DEVICE_DEFAULT, T) TF_CALL_float(REGISTER_DEFAULT_KERNEL); TF_CALL_double(REGISTER_DEFAULT_KERNEL); #undef REGISTER_DEFAULT_KERNEL #undef REGISTER_CPU_KERNEL #undef REGISTER_KERNEL_ALL_NUMS #undef REGISTER_KERNEL } // namespace tensorflow <|endoftext|>
<commit_before>#include "acmacs-base/stream.hh" #include "acmacs-base/enumerate.hh" #include "aa-at-pos-draw.hh" #include "tree.hh" #include "tree-iterate.hh" // ---------------------------------------------------------------------- void AAAtPosDraw::prepare() { if (mSettings.width > 0) { if (!mSettings.positions.empty()) { positions_.resize(mSettings.positions.size()); std::transform(mSettings.positions.begin(), mSettings.positions.end(), positions_.begin(), [](size_t pos_based_1) { return pos_based_1 - 1; }); collect_aa_per_pos(); } else if (mSettings.most_diverse_positions > 0) { find_most_diverse_positions(); } if (!positions_.empty()) { for (auto pos : positions_) { const auto& aa_freq = aa_per_pos_[pos]; std::vector<char> aas(aa_freq.size()); std::transform(aa_freq.begin(), aa_freq.end(), aas.begin(), [](const auto& entry) { return entry.first; }); std::sort(aas.begin(), aas.end(), [&](char aa1, char aa2) { return aa_freq.find(aa1)->second > aa_freq.find(aa2)->second; }); // most frequent aa first std::cout << pos << ' ' << aas << ' ' << aa_freq << '\n'; for (size_t no = 1; no < aas.size(); ++no) // no color for the most frequent aa colors_[pos].emplace(aas[no], Color::distinct(no)); } } } } // AAAtPosDraw::prepare // ---------------------------------------------------------------------- void AAAtPosDraw::collect_aa_per_pos() { auto update = [this](size_t pos, char aa) { if (aa != 'X') ++this->aa_per_pos_[pos][aa]; }; auto collect = [&, this](const Node& node) { const auto sequence = node.data.amino_acids(); if (this->positions_.empty()) { for (auto [pos, aa] : acmacs::enumerate(sequence)) update(pos, aa); } else { for (auto pos : this->positions_) { if (pos < sequence.size()) update(pos, sequence[pos]); } } }; tree::iterate_leaf(mTree, collect); } // AAAtPosDraw::collect_aa_per_pos // ---------------------------------------------------------------------- void AAAtPosDraw::find_most_diverse_positions() { collect_aa_per_pos(); } // AAAtPosDraw::find_most_diverse_positions // ---------------------------------------------------------------------- void AAAtPosDraw::draw() { if (!positions_.empty()) { const auto surface_width = mSurface.viewport().size.width; const auto section_width = surface_width / positions_.size(); const auto line_length = section_width * mSettings.line_length; auto draw_dash = [&, this](const Node& aNode) { const auto aas = aNode.data.amino_acids(); for (size_t section_no = 0; section_no < positions_.size(); ++section_no) { if (const auto pos = this->positions_[section_no]; pos < aas.size()) { const auto aa = aas[pos]; if (const auto found = this->colors_[pos].find(aa); found != colors_[pos].end()) { const auto base_x = section_width * section_no + (section_width - line_length) / 2; const std::string aa_s(1, aa); const auto aa_width = mSurface.text_size(aa_s, Pixels{this->mSettings.line_width}).width * 2; mSurface.text({base_x, aNode.draw.vertical_pos + this->mSettings.line_width / 2}, aa_s, 0 /* found->second */, Pixels{this->mSettings.line_width}); mSurface.line({base_x + aa_width, aNode.draw.vertical_pos}, {base_x + line_length - aa_width, aNode.draw.vertical_pos}, found->second, Pixels{this->mSettings.line_width}, acmacs::surface::LineCap::Round); } } } }; tree::iterate_leaf(mTree, draw_dash); // const auto pos_text_height = mSurface.text_size("8", Pixels{}).height; for (size_t section_no = 0; section_no < positions_.size(); ++section_no) { const auto pos = positions_[section_no]; mSurface.text({section_width * section_no + section_width / 4, mSurface.viewport().size.height + 10}, std::to_string(pos + 1), 0, Pixels{line_length}, acmacs::TextStyle{}, Rotation{M_PI_2}); } } } // AAAtPosDraw::draw // ---------------------------------------------------------------------- // ---------------------------------------------------------------------- /// Local Variables: /// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer)) /// End: <commit_msg>section to show AA at few positions<commit_after>#include "acmacs-base/stream.hh" #include "acmacs-base/enumerate.hh" #include "aa-at-pos-draw.hh" #include "tree.hh" #include "tree-iterate.hh" // ---------------------------------------------------------------------- void AAAtPosDraw::prepare() { if (mSettings.width > 0) { if (!mSettings.positions.empty()) { positions_.resize(mSettings.positions.size()); std::transform(mSettings.positions.begin(), mSettings.positions.end(), positions_.begin(), [](size_t pos_based_1) { return pos_based_1 - 1; }); collect_aa_per_pos(); } else if (mSettings.most_diverse_positions > 0) { find_most_diverse_positions(); } if (!positions_.empty()) { for (auto pos : positions_) { const auto& aa_freq = aa_per_pos_[pos]; std::vector<char> aas(aa_freq.size()); std::transform(aa_freq.begin(), aa_freq.end(), aas.begin(), [](const auto& entry) { return entry.first; }); std::sort(aas.begin(), aas.end(), [&](char aa1, char aa2) { return aa_freq.find(aa1)->second > aa_freq.find(aa2)->second; }); // most frequent aa first std::cout << pos << ' ' << aas << ' ' << aa_freq << '\n'; for (size_t no = 1; no < aas.size(); ++no) // no color for the most frequent aa colors_[pos].emplace(aas[no], Color::distinct(no)); } } } } // AAAtPosDraw::prepare // ---------------------------------------------------------------------- void AAAtPosDraw::collect_aa_per_pos() { auto update = [this](size_t pos, char aa) { if (aa != 'X') ++this->aa_per_pos_[pos][aa]; }; auto collect = [&, this](const Node& node) { const auto sequence = node.data.amino_acids(); if (this->positions_.empty()) { for (auto [pos, aa] : acmacs::enumerate(sequence)) update(pos, aa); } else { for (auto pos : this->positions_) { if (pos < sequence.size()) update(pos, sequence[pos]); } } }; tree::iterate_leaf(mTree, collect); } // AAAtPosDraw::collect_aa_per_pos // ---------------------------------------------------------------------- void AAAtPosDraw::find_most_diverse_positions() { collect_aa_per_pos(); // https://en.wikipedia.org/wiki/Diversity_index using all_pos_t = std::pair<size_t, ssize_t>; // position, shannon_index std::vector<all_pos_t> all_pos(aa_per_pos_.size()); std::transform(aa_per_pos_.begin(), aa_per_pos_.end(), all_pos.begin(), [](const auto& src) -> all_pos_t { const auto sum = std::accumulate(src.second.begin(), src.second.end(), 0UL, [](auto accum, const auto& entry) { return accum + entry.second; }); const auto shannon_index = -std::accumulate(src.second.begin(), src.second.end(), 0.0, [sum = double(sum)](auto accum, const auto& entry) { const double p = entry.second / sum; return accum + p * std::log(p); }); return {src.first, std::lround(shannon_index * 100)}; }); // sort all_pos by shannon_index, more diverse first std::sort(std::begin(all_pos), std::end(all_pos), [](const auto& p1, const auto& p2) { return p1.second > p2.second; }); positions_.resize(std::min(static_cast<size_t>(mSettings.most_diverse_positions), all_pos.size())); std::transform(all_pos.begin(), all_pos.begin() + static_cast<ssize_t>(positions_.size()), positions_.begin(), [](const all_pos_t& entry) { return entry.first; }); } // AAAtPosDraw::find_most_diverse_positions // ---------------------------------------------------------------------- void AAAtPosDraw::draw() { if (!positions_.empty()) { const auto surface_width = mSurface.viewport().size.width; const auto section_width = surface_width / positions_.size(); const auto line_length = section_width * mSettings.line_length; auto draw_dash = [&, this](const Node& aNode) { const auto aas = aNode.data.amino_acids(); for (size_t section_no = 0; section_no < positions_.size(); ++section_no) { if (const auto pos = this->positions_[section_no]; pos < aas.size()) { const auto aa = aas[pos]; if (const auto found = this->colors_[pos].find(aa); found != colors_[pos].end()) { const auto base_x = section_width * section_no + (section_width - line_length) / 2; const std::string aa_s(1, aa); const auto aa_width = mSurface.text_size(aa_s, Pixels{this->mSettings.line_width}).width * 2; mSurface.text({base_x, aNode.draw.vertical_pos + this->mSettings.line_width / 2}, aa_s, 0 /* found->second */, Pixels{this->mSettings.line_width}); mSurface.line({base_x + aa_width, aNode.draw.vertical_pos}, {base_x + line_length - aa_width, aNode.draw.vertical_pos}, found->second, Pixels{this->mSettings.line_width}, acmacs::surface::LineCap::Round); } } } }; tree::iterate_leaf(mTree, draw_dash); // const auto pos_text_height = mSurface.text_size("8", Pixels{}).height; for (size_t section_no = 0; section_no < positions_.size(); ++section_no) { const auto pos = positions_[section_no]; mSurface.text({section_width * section_no + section_width / 4, mSurface.viewport().size.height + 10}, std::to_string(pos + 1), 0, Pixels{line_length}, acmacs::TextStyle{}, Rotation{M_PI_2}); } } } // AAAtPosDraw::draw // ---------------------------------------------------------------------- // ---------------------------------------------------------------------- /// Local Variables: /// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer)) /// End: <|endoftext|>
<commit_before>#include <csapex/msg/io.h> #include <csapex/model/node.h> #include <csapex/model/node_modifier.h> #include <csapex/model/variadic_io.h> #include <csapex/param/parameter_factory.h> #include <csapex/utility/register_apex_plugin.h> #include <csapex/msg/generic_vector_message.hpp> #include <csapex_ml/features_message.h> using namespace csapex::connection_types; namespace csapex { class JoinFeatures : public Node, public VariadicInputs { public: virtual void setup(csapex::NodeModifier& node_modifier) override { VariadicInputs::setupVariadic(node_modifier); output_features_ = node_modifier.addOutput<GenericVectorMessage, FeaturesMessage>("Features"); } virtual void setupParameters(Parameterizable &parameters) override { VariadicInputs::setupVariadicParameters(parameters); } virtual void process() override { std::shared_ptr<std::vector<FeaturesMessage>> output_features(new std::vector<FeaturesMessage>); int vectorSize = -1; for (const InputPtr& input : variadic_inputs_) { int inputSize; if (msg::isMessage<FeaturesMessage>(input.get())) inputSize = 1; else { auto msg = msg::getMessage<GenericVectorMessage, FeaturesMessage>(input.get()); inputSize = msg->size(); } if (vectorSize == -1) vectorSize = inputSize; else apex_assert(inputSize == vectorSize); } std::vector<std::vector<FeaturesMessage>> input_features; input_features.resize(vectorSize); for (const InputPtr& input : variadic_inputs_) { if(msg::isMessage<FeaturesMessage>(input.get())) { FeaturesMessage::ConstPtr feature = msg::getMessage<FeaturesMessage>(input.get()); input_features[0].push_back(*feature); } else { std::shared_ptr<std::vector<FeaturesMessage> const> features = msg::getMessage<GenericVectorMessage, FeaturesMessage>(input.get()); for (std::size_t i = 0; i < features->size(); ++i) input_features[i].push_back((*features)[i]); } } for (auto& input_set : input_features) { FeaturesMessage feature; feature.classification = 0; feature.confidence = 0; for (auto& part : input_set) feature.value.insert(feature.value.end(), part.value.begin(), part.value.end()); output_features->emplace_back(std::move(feature)); } msg::publish<GenericVectorMessage, FeaturesMessage>(output_features_, output_features); } Input* createVariadicInput(TokenDataConstPtr type, const std::string& label, bool /*optional*/) override { return VariadicInputs::createVariadicInput(multi_type::make<GenericVectorMessage, FeaturesMessage>(), label.empty() ? "Features" : label, getVariadicInputCount() == 0 ? false : true); } private: Output* output_features_; }; } CSAPEX_REGISTER_CLASS(csapex::JoinFeatures, csapex::Node) <commit_msg>ml: JoinFeatures - fix class assignment<commit_after>#include <csapex/msg/io.h> #include <csapex/model/node.h> #include <csapex/model/node_modifier.h> #include <csapex/model/variadic_io.h> #include <csapex/param/parameter_factory.h> #include <csapex/utility/register_apex_plugin.h> #include <csapex/msg/generic_vector_message.hpp> #include <csapex_ml/features_message.h> using namespace csapex::connection_types; namespace csapex { class JoinFeatures : public Node, public VariadicInputs { public: virtual void setup(csapex::NodeModifier& node_modifier) override { VariadicInputs::setupVariadic(node_modifier); output_features_ = node_modifier.addOutput<GenericVectorMessage, FeaturesMessage>("Features"); } virtual void setupParameters(Parameterizable &parameters) override { VariadicInputs::setupVariadicParameters(parameters); } virtual void process() override { std::shared_ptr<std::vector<FeaturesMessage>> output_features(new std::vector<FeaturesMessage>); int vectorSize = -1; for (const InputPtr& input : variadic_inputs_) { int inputSize; if (msg::isMessage<FeaturesMessage>(input.get())) inputSize = 1; else { auto msg = msg::getMessage<GenericVectorMessage, FeaturesMessage>(input.get()); inputSize = msg->size(); } if (vectorSize == -1) vectorSize = inputSize; else apex_assert(inputSize == vectorSize); } std::vector<std::vector<FeaturesMessage>> input_features; input_features.resize(vectorSize); for (const InputPtr& input : variadic_inputs_) { if(msg::isMessage<FeaturesMessage>(input.get())) { FeaturesMessage::ConstPtr feature = msg::getMessage<FeaturesMessage>(input.get()); input_features[0].push_back(*feature); } else { std::shared_ptr<std::vector<FeaturesMessage> const> features = msg::getMessage<GenericVectorMessage, FeaturesMessage>(input.get()); for (std::size_t i = 0; i < features->size(); ++i) input_features[i].push_back((*features)[i]); } } for (auto& input_set : input_features) { int ref_class = !input_set.empty() ? input_set[0].classification : 0; FeaturesMessage feature; feature.classification = ref_class; feature.confidence = 0; for (auto& part : input_set) { if (feature.classification != ref_class) throw std::runtime_error("Feature classification mismatch"); feature.value.insert(feature.value.end(), part.value.begin(), part.value.end()); } output_features->emplace_back(std::move(feature)); } msg::publish<GenericVectorMessage, FeaturesMessage>(output_features_, output_features); } Input* createVariadicInput(TokenDataConstPtr type, const std::string& label, bool /*optional*/) override { return VariadicInputs::createVariadicInput(multi_type::make<GenericVectorMessage, FeaturesMessage>(), label.empty() ? "Features" : label, getVariadicInputCount() == 0 ? false : true); } private: Output* output_features_; }; } CSAPEX_REGISTER_CLASS(csapex::JoinFeatures, csapex::Node) <|endoftext|>
<commit_before>// $Id: RegularData3D_test.C,v 1.1 2000/12/05 12:20:58 amoll Exp $ #include <BALL/CONCEPT/classTest.h> #include <BALL/DATATYPE/regularData3D.h> START_TEST(RegularData3D, "$Id: RegularData3D_test.C,v 1.1 2000/12/05 12:20:58 amoll Exp $") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// using namespace BALL; using namespace std; String filename; using BALL::RegularData3D; RegularData3D<float>* grid; CHECK(RegularData3D<T>()) grid = new RegularData3D<float>(); TEST_NOT_EQUAL(grid, 0) RESULT CHECK(~RegularData3D<T>()) delete grid; RESULT CHECK(RegularData3D<T>(float, float, float, float, float, float, Size, Size, Size)) grid = new RegularData3D<float>(0.0, 0.0, 0.0, 10.0, 10.0, 10.0, 11, 11, 11); TEST_NOT_EQUAL(grid, 0) TEST_EQUAL(grid->getSize(), 1331) delete grid; RESULT using BALL::Vector3; Vector3 lower(0.0, 0.0, 0.0); Vector3 upper(10.0, 10.0, 10.0); CHECK(RegularData3D<T>(const Vector3& lower, const Vector3& upper, float spacing)) grid = new RegularData3D<float>(lower, upper, 1.0); TEST_NOT_EQUAL(grid, 0) TEST_EQUAL(grid->getSize(), 1331) delete grid; RESULT CHECK(RegularData3D<T>(const Vector3& lower, const Vector3& upper, Size, Size, Size)) grid = new RegularData3D<float>(lower, upper, 11, 11, 11); TEST_NOT_EQUAL(grid, 0) RESULT CHECK(getSize()) TEST_EQUAL(grid->getSize(), 1331) RESULT RegularData3D<float> g(0.0, 0.0, 0.0, 10.0, 10.0, 10.0, 11, 11, 11); CHECK(set(const RegularData3D<T>& grid)) RegularData3D<float> g1; g1.set(g); TEST_EQUAL(g1.getSize(), 1331) RESULT CHECK(operator = (const RegularData3D<T>& grid)) RegularData3D<float> g1; g1 = g; TEST_EQUAL(g1.getSize(), 1331) RESULT CHECK(dump()) String filename; NEW_TMP_FILE(filename) std::ofstream outfile(filename.c_str(), File::OUT); // fill g with zero! for (Position k = 0; k < g.getSize(); k++) { g[k] = 0.0; } g.dump(outfile); outfile.close(); TEST_FILE(filename.c_str(), "data/RegularData3D_test.txt", true) RESULT CHECK(isValid()) TEST_EQUAL(g.isValid(), true) RESULT CHECK(getMaxX()) TEST_REAL_EQUAL(grid->getMaxX(), 10.0) RESULT CHECK(getMaxY()) TEST_REAL_EQUAL(grid->getMaxY(), 10.0) RESULT CHECK(getMaxZ()) TEST_REAL_EQUAL(grid->getMaxZ(), 10.0) RESULT CHECK(getMinX()) TEST_REAL_EQUAL(grid->getMinX(), 0.0) RESULT CHECK(getMinY()) TEST_REAL_EQUAL(grid->getMinY(), 0.0) RESULT CHECK(getMinZ()) TEST_REAL_EQUAL(grid->getMinZ(), 0.0) RESULT CHECK(getMaxXIndex()) TEST_EQUAL(grid->getMaxXIndex(), 10) RESULT CHECK(getMaxYIndex()) TEST_EQUAL(grid->getMaxYIndex(), 10) RESULT CHECK(getMaxZIndex()) TEST_EQUAL(grid->getMaxZIndex(), 10) RESULT CHECK(getXSpacing()) TEST_REAL_EQUAL(grid->getXSpacing(), 1.0) RESULT CHECK(getYSpacing()) TEST_REAL_EQUAL(grid->getYSpacing(), 1.0) RESULT CHECK(getZSpacing()) TEST_REAL_EQUAL(grid->getZSpacing(), 1.0) RESULT BALL::RegularData3D<float>::GridIndex index; CHECK(getIndex(const Vector3& vector)) lower.set(3.49, 3.51, 3.0); index = grid->getIndex(lower); TEST_EQUAL(index.x, 3) TEST_EQUAL(index.y, 4) TEST_EQUAL(index.z, 3) RESULT CHECK(getIndex(float, float, float)) index = grid->getIndex(3.49, 3.51, 3.0); TEST_EQUAL(index.x, 3) TEST_EQUAL(index.y, 4) TEST_EQUAL(index.z, 3) RESULT CHECK(getData(Position)) *(grid->getData(0, 0, 0)) = 5.4321; lower = grid->getOrigin(); TEST_REAL_EQUAL(*(grid->getData(0)), 5.4321); TEST_REAL_EQUAL(*(grid->getData(0)), *(grid->getData(lower))); RESULT CHECK(operator[]/1/2) (*grid)[3 + 11 * 3 + 11 * 11 * 3] = 1.2345; lower.set(3.0, 3.0, 3.0); TEST_EQUAL((*grid)[3 + 11 * 3 + 11 * 11 * 3], (*grid)[lower]); RESULT CHECK(getGridCoordinates/1) lower = grid->getGridCoordinates(0, 0, 0); TEST_REAL_EQUAL(lower.x, 0.0) TEST_REAL_EQUAL(lower.y, 0.0) TEST_REAL_EQUAL(lower.z, 0.0) RESULT CHECK(getGridCoordinates/2) lower = grid->getGridCoordinates(2 + 2 * 11 + 2 * 11 * 11); TEST_REAL_EQUAL(lower.x, 2.0) TEST_REAL_EQUAL(lower.y, 2.0) TEST_REAL_EQUAL(lower.z, 2.0) RESULT CHECK(getGridCoordinates/3) upper.set(3.999999, 4.0, 3.0001); lower = grid->getGridCoordinates(upper); TEST_REAL_EQUAL(lower.x, 3.0) TEST_REAL_EQUAL(lower.y, 4.0) TEST_REAL_EQUAL(lower.z, 3.0) RESULT CHECK(getBoxIndices) lower.set(2, 2, 2); Position p1, p2, p3, p4, p5, p6, p7, p8; g.getBoxIndices(lower, p1, p2, p3, p4, p5, p6, p7, p8); TEST_EQUAL(p1, 266); TEST_EQUAL(p2, 267); TEST_EQUAL(p3, 277); TEST_EQUAL(p4, 278); TEST_EQUAL(p5, 387); TEST_EQUAL(p6, 388); TEST_EQUAL(p7, 398); TEST_EQUAL(p8, 399); lower.set(2.1, 2.1, 2.1); g.getBoxIndices(lower, p1, p2, p3, p4, p5, p6, p7, p8); TEST_EQUAL(p1, 266); TEST_EQUAL(p2, 267); TEST_EQUAL(p3, 277); TEST_EQUAL(p4, 278); TEST_EQUAL(p5, 387); TEST_EQUAL(p6, 388); TEST_EQUAL(p7, 398); TEST_EQUAL(p8, 399); lower.set(10.1, 2.1, 2.1); TEST_EXCEPTION(Exception::OutOfGrid, g.getBoxIndices(lower, p1, p2, p3, p4, p5, p6, p7, p8)) RESULT CHECK(getBoxData) lower.set(2, 2, 2); float p1, p2, p3, p4, p5, p6, p7, p8; g[266] = 1; g[267] = 2; g[277] = 3; g[278] = 4; g[387] = 5; g[388] = 6; g[398] = 7; g[399] = 8; g.getBoxData(lower, p1, p2, p3, p4, p5, p6, p7, p8); TEST_EQUAL(p1, 1); TEST_EQUAL(p2, 2); TEST_EQUAL(p3, 3); TEST_EQUAL(p4, 4); TEST_EQUAL(p5, 5); TEST_EQUAL(p6, 6); TEST_EQUAL(p7, 7); TEST_EQUAL(p8, 8); lower.set(10.1, 2.1, 2.1); TEST_EXCEPTION(Exception::OutOfGrid, g.getBoxData(lower, p1, p2, p3, p4, p5, p6, p7, p8)) RESULT CHECK(getOrigin) lower = grid->getOrigin(); TEST_REAL_EQUAL(lower.x, 0.0) TEST_REAL_EQUAL(lower.y, 0.0) TEST_REAL_EQUAL(lower.z, 0.0) RESULT CHECK(setOrigin/1) grid->setOrigin(1.0, 1.0, 1.0); lower = grid->getOrigin(); TEST_REAL_EQUAL(lower.x, 1.0) TEST_REAL_EQUAL(lower.y, 1.0) TEST_REAL_EQUAL(lower.z, 1.0) index = grid->getIndex(3.49, 3.51, 3.0); TEST_EQUAL(index.x, 2) TEST_EQUAL(index.y, 3) TEST_EQUAL(index.z, 2) RESULT CHECK(setOrigin/2) lower.set(2.0, 2.0, 2.0); grid->setOrigin(lower); lower = grid->getOrigin(); TEST_REAL_EQUAL(lower.x, 2.0) TEST_REAL_EQUAL(lower.y, 2.0) TEST_REAL_EQUAL(lower.z, 2.0) index = grid->getIndex(3.49, 3.51, 3.0); TEST_EQUAL(index.x, 1) TEST_EQUAL(index.y, 2) TEST_EQUAL(index.z, 1) RESULT CHECK(getDimension) TEST_REAL_EQUAL(grid->getDimension().x, 10.0) TEST_REAL_EQUAL(grid->getDimension().y, 10.0) TEST_REAL_EQUAL(grid->getDimension().z, 10.0) RESULT CHECK(getInterpolatedValue) lower.set(2, 2, 2); TEST_EQUAL(g.getInterpolatedValue(lower), 1) lower.set(0, 0, 0); TEST_EQUAL(g.getInterpolatedValue(lower), 0) lower.set(3, 3, 3); TEST_EQUAL(g.getInterpolatedValue(lower), 8) lower.set(10.1, 0, 0); TEST_EXCEPTION(Exception::OutOfGrid, g.getInterpolatedValue(lower)) RESULT RegularData3D<float> grid2 = *grid; CHECK(clear()) grid2.clear(); TEST_EQUAL(grid2.isValid(), false) TEST_EQUAL(grid2.data, 0) RESULT CHECK(operator ==) grid2 = *grid; TEST_EQUAL(*grid == grid2, true) grid2[5] = -99.9; TEST_EQUAL(*grid == grid2, false) RESULT CHECK(operator !=) TEST_EQUAL(*grid != grid2, true) grid2[5] = (*grid)[5]; TEST_EQUAL(*grid != grid2, false) RESULT CHECK(has()1/1) RegularData3D<float> g(0, 0, 0, 10, 10, 10, 11, 11, 11); TEST_EQUAL(g.has(0, 0, 0), true) Vector3 v(0, 0, 0); TEST_EQUAL(g.has(v), true) TEST_EQUAL(g.has(10, 10, 10), true) v = Vector3(10, 10, 10); TEST_EQUAL(g.has(v), true) TEST_EQUAL(g.has(10.1, 10, 10), false) v = Vector3(10, 10, 10.1); TEST_EQUAL(g.has(v), false) TEST_EQUAL(g.has(0, 0, -0.1), false) v = Vector3(0, 0, -0.1); TEST_EQUAL(g.has(v), false) RegularData3D<float> h; TEST_EQUAL(h.isValid(), false) TEST_EQUAL(h.has(0, 0, 0), false) v = Vector3(0, 0, 0); TEST_EQUAL(h.has(v), false) RESULT ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST <commit_msg>fixed: integers where floating point numbers were expected lead to unresolvable overloading ambiguities (Tru64/cxx)<commit_after>// $Id: RegularData3D_test.C,v 1.2 2001/05/10 16:46:09 oliver Exp $ #include <BALL/CONCEPT/classTest.h> #include <BALL/DATATYPE/regularData3D.h> START_TEST(RegularData3D, "$Id: RegularData3D_test.C,v 1.2 2001/05/10 16:46:09 oliver Exp $") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// using namespace BALL; using namespace std; String filename; using BALL::RegularData3D; RegularData3D<float>* grid; CHECK(RegularData3D<T>()) grid = new RegularData3D<float>(); TEST_NOT_EQUAL(grid, 0) RESULT CHECK(~RegularData3D<T>()) delete grid; RESULT CHECK(RegularData3D<T>(float, float, float, float, float, float, Size, Size, Size)) grid = new RegularData3D<float>(0.0, 0.0, 0.0, 10.0, 10.0, 10.0, 11, 11, 11); TEST_NOT_EQUAL(grid, 0) TEST_EQUAL(grid->getSize(), 1331) delete grid; RESULT using BALL::Vector3; Vector3 lower(0.0, 0.0, 0.0); Vector3 upper(10.0, 10.0, 10.0); CHECK(RegularData3D<T>(const Vector3& lower, const Vector3& upper, float spacing)) grid = new RegularData3D<float>(lower, upper, 1.0); TEST_NOT_EQUAL(grid, 0) TEST_EQUAL(grid->getSize(), 1331) delete grid; RESULT CHECK(RegularData3D<T>(const Vector3& lower, const Vector3& upper, Size, Size, Size)) grid = new RegularData3D<float>(lower, upper, 11, 11, 11); TEST_NOT_EQUAL(grid, 0) RESULT CHECK(getSize()) TEST_EQUAL(grid->getSize(), 1331) RESULT RegularData3D<float> g(0.0, 0.0, 0.0, 10.0, 10.0, 10.0, 11, 11, 11); CHECK(set(const RegularData3D<T>& grid)) RegularData3D<float> g1; g1.set(g); TEST_EQUAL(g1.getSize(), 1331) RESULT CHECK(operator = (const RegularData3D<T>& grid)) RegularData3D<float> g1; g1 = g; TEST_EQUAL(g1.getSize(), 1331) RESULT CHECK(dump()) String filename; NEW_TMP_FILE(filename) std::ofstream outfile(filename.c_str(), File::OUT); // fill g with zero! for (Position k = 0; k < g.getSize(); k++) { g[k] = 0.0; } g.dump(outfile); outfile.close(); TEST_FILE(filename.c_str(), "data/RegularData3D_test.txt", true) RESULT CHECK(isValid()) TEST_EQUAL(g.isValid(), true) RESULT CHECK(getMaxX()) TEST_REAL_EQUAL(grid->getMaxX(), 10.0) RESULT CHECK(getMaxY()) TEST_REAL_EQUAL(grid->getMaxY(), 10.0) RESULT CHECK(getMaxZ()) TEST_REAL_EQUAL(grid->getMaxZ(), 10.0) RESULT CHECK(getMinX()) TEST_REAL_EQUAL(grid->getMinX(), 0.0) RESULT CHECK(getMinY()) TEST_REAL_EQUAL(grid->getMinY(), 0.0) RESULT CHECK(getMinZ()) TEST_REAL_EQUAL(grid->getMinZ(), 0.0) RESULT CHECK(getMaxXIndex()) TEST_EQUAL(grid->getMaxXIndex(), 10) RESULT CHECK(getMaxYIndex()) TEST_EQUAL(grid->getMaxYIndex(), 10) RESULT CHECK(getMaxZIndex()) TEST_EQUAL(grid->getMaxZIndex(), 10) RESULT CHECK(getXSpacing()) TEST_REAL_EQUAL(grid->getXSpacing(), 1.0) RESULT CHECK(getYSpacing()) TEST_REAL_EQUAL(grid->getYSpacing(), 1.0) RESULT CHECK(getZSpacing()) TEST_REAL_EQUAL(grid->getZSpacing(), 1.0) RESULT BALL::RegularData3D<float>::GridIndex index; CHECK(getIndex(const Vector3& vector)) lower.set(3.49, 3.51, 3.0); index = grid->getIndex(lower); TEST_EQUAL(index.x, 3) TEST_EQUAL(index.y, 4) TEST_EQUAL(index.z, 3) RESULT CHECK(getIndex(float, float, float)) index = grid->getIndex(3.49, 3.51, 3.0); TEST_EQUAL(index.x, 3) TEST_EQUAL(index.y, 4) TEST_EQUAL(index.z, 3) RESULT CHECK(getData(Position)) *(grid->getData(0, 0, 0)) = 5.4321; lower = grid->getOrigin(); TEST_REAL_EQUAL(*(grid->getData(0)), 5.4321); TEST_REAL_EQUAL(*(grid->getData(0)), *(grid->getData(lower))); RESULT CHECK(operator[]/1/2) (*grid)[3 + 11 * 3 + 11 * 11 * 3] = 1.2345; lower.set(3.0, 3.0, 3.0); TEST_EQUAL((*grid)[3 + 11 * 3 + 11 * 11 * 3], (*grid)[lower]); RESULT CHECK(getGridCoordinates/1) lower = grid->getGridCoordinates(0, 0, 0); TEST_REAL_EQUAL(lower.x, 0.0) TEST_REAL_EQUAL(lower.y, 0.0) TEST_REAL_EQUAL(lower.z, 0.0) RESULT CHECK(getGridCoordinates/2) lower = grid->getGridCoordinates(2 + 2 * 11 + 2 * 11 * 11); TEST_REAL_EQUAL(lower.x, 2.0) TEST_REAL_EQUAL(lower.y, 2.0) TEST_REAL_EQUAL(lower.z, 2.0) RESULT CHECK(getGridCoordinates/3) upper.set(3.999999, 4.0, 3.0001); lower = grid->getGridCoordinates(upper); TEST_REAL_EQUAL(lower.x, 3.0) TEST_REAL_EQUAL(lower.y, 4.0) TEST_REAL_EQUAL(lower.z, 3.0) RESULT CHECK(getBoxIndices) lower.set(2, 2, 2); Position p1, p2, p3, p4, p5, p6, p7, p8; g.getBoxIndices(lower, p1, p2, p3, p4, p5, p6, p7, p8); TEST_EQUAL(p1, 266); TEST_EQUAL(p2, 267); TEST_EQUAL(p3, 277); TEST_EQUAL(p4, 278); TEST_EQUAL(p5, 387); TEST_EQUAL(p6, 388); TEST_EQUAL(p7, 398); TEST_EQUAL(p8, 399); lower.set(2.1, 2.1, 2.1); g.getBoxIndices(lower, p1, p2, p3, p4, p5, p6, p7, p8); TEST_EQUAL(p1, 266); TEST_EQUAL(p2, 267); TEST_EQUAL(p3, 277); TEST_EQUAL(p4, 278); TEST_EQUAL(p5, 387); TEST_EQUAL(p6, 388); TEST_EQUAL(p7, 398); TEST_EQUAL(p8, 399); lower.set(10.1, 2.1, 2.1); TEST_EXCEPTION(Exception::OutOfGrid, g.getBoxIndices(lower, p1, p2, p3, p4, p5, p6, p7, p8)) RESULT CHECK(getBoxData) lower.set(2, 2, 2); float p1, p2, p3, p4, p5, p6, p7, p8; g[266] = 1; g[267] = 2; g[277] = 3; g[278] = 4; g[387] = 5; g[388] = 6; g[398] = 7; g[399] = 8; g.getBoxData(lower, p1, p2, p3, p4, p5, p6, p7, p8); TEST_EQUAL(p1, 1); TEST_EQUAL(p2, 2); TEST_EQUAL(p3, 3); TEST_EQUAL(p4, 4); TEST_EQUAL(p5, 5); TEST_EQUAL(p6, 6); TEST_EQUAL(p7, 7); TEST_EQUAL(p8, 8); lower.set(10.1, 2.1, 2.1); TEST_EXCEPTION(Exception::OutOfGrid, g.getBoxData(lower, p1, p2, p3, p4, p5, p6, p7, p8)) RESULT CHECK(getOrigin) lower = grid->getOrigin(); TEST_REAL_EQUAL(lower.x, 0.0) TEST_REAL_EQUAL(lower.y, 0.0) TEST_REAL_EQUAL(lower.z, 0.0) RESULT CHECK(setOrigin/1) grid->setOrigin(1.0, 1.0, 1.0); lower = grid->getOrigin(); TEST_REAL_EQUAL(lower.x, 1.0) TEST_REAL_EQUAL(lower.y, 1.0) TEST_REAL_EQUAL(lower.z, 1.0) index = grid->getIndex(3.49, 3.51, 3.0); TEST_EQUAL(index.x, 2) TEST_EQUAL(index.y, 3) TEST_EQUAL(index.z, 2) RESULT CHECK(setOrigin/2) lower.set(2.0, 2.0, 2.0); grid->setOrigin(lower); lower = grid->getOrigin(); TEST_REAL_EQUAL(lower.x, 2.0) TEST_REAL_EQUAL(lower.y, 2.0) TEST_REAL_EQUAL(lower.z, 2.0) index = grid->getIndex(3.49, 3.51, 3.0); TEST_EQUAL(index.x, 1) TEST_EQUAL(index.y, 2) TEST_EQUAL(index.z, 1) RESULT CHECK(getDimension) TEST_REAL_EQUAL(grid->getDimension().x, 10.0) TEST_REAL_EQUAL(grid->getDimension().y, 10.0) TEST_REAL_EQUAL(grid->getDimension().z, 10.0) RESULT CHECK(getInterpolatedValue) lower.set(2, 2, 2); TEST_EQUAL(g.getInterpolatedValue(lower), 1) lower.set(0, 0, 0); TEST_EQUAL(g.getInterpolatedValue(lower), 0) lower.set(3, 3, 3); TEST_EQUAL(g.getInterpolatedValue(lower), 8) lower.set(10.1, 0, 0); TEST_EXCEPTION(Exception::OutOfGrid, g.getInterpolatedValue(lower)) RESULT RegularData3D<float> grid2 = *grid; CHECK(clear()) grid2.clear(); TEST_EQUAL(grid2.isValid(), false) TEST_EQUAL(grid2.data, 0) RESULT CHECK(operator ==) grid2 = *grid; TEST_EQUAL(*grid == grid2, true) grid2[5] = -99.9; TEST_EQUAL(*grid == grid2, false) RESULT CHECK(operator !=) TEST_EQUAL(*grid != grid2, true) grid2[5] = (*grid)[5]; TEST_EQUAL(*grid != grid2, false) RESULT CHECK(has()1/1) RegularData3D<float> g(0.0, 0.0, 0.0, 10.0, 10.0, 10.0, 11, 11, 11); TEST_EQUAL(g.has(0.0, 0.0, 0.0), true) Vector3 v(0.0, 0.0, 0.0); TEST_EQUAL(g.has(v), true) TEST_EQUAL(g.has(10.0, 10.0, 10.0), true) v = Vector3(10.0, 10.0, 10.0); TEST_EQUAL(g.has(v), true) TEST_EQUAL(g.has(10.1, 10.0, 10.0), false) v = Vector3(10.0, 10.0, 10.1); TEST_EQUAL(g.has(v), false) TEST_EQUAL(g.has(0.0, 0.0, -0.1), false) v = Vector3(0.0, 0.0, -0.1); TEST_EQUAL(g.has(v), false) RegularData3D<float> h; TEST_EQUAL(h.isValid(), false) TEST_EQUAL(h.has(0.0, 0.0, 0.0), false) v = Vector3(0.0, 0.0, 0.0); TEST_EQUAL(h.has(v), false) RESULT ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST <|endoftext|>
<commit_before>#include <boost/python.hpp> #include "ModelInterface.h" #include "pyToCppModelInterfaceCache.h" #include <boost/python/stl_iterator.hpp> #include <iostream> #include <stdexcept> #include <boost/python/numeric.hpp> #include <boost/python/tuple.hpp> #include <boost/python/module.hpp> #include <boost/python/def.hpp> #include <numpy/noprefix.h> namespace threeML { template<typename T> inline std::vector<T> to_std_vector(const boost::python::object &iterable) { return std::vector<T>(boost::python::stl_input_iterator<T>(iterable), boost::python::stl_input_iterator<T>()); } void pyToCppModelInterfaceCache::setPtsSourceSpectrum(const int id, const boost::python::numeric::array& spectrum) { // These are both n_points in size PyArrayObject* spectrum__ = (PyArrayObject*) spectrum.ptr(); unsigned int n_energies = (unsigned int) *(spectrum__->dimensions); double* spectrum_ = (double *) spectrum__->data; m_ptsSources[id].assign(spectrum_, spectrum_ + n_energies); } void pyToCppModelInterfaceCache::setPtsSourcePosition(const int id, const float lon, const float lat) { m_ptsSourcesPos[id] = SkyCoord(lon, lat); } void pyToCppModelInterfaceCache::setExtSourceBoundaries(const int id, const float lon_min, const float lon_max, const float lat_min, const float lat_max) { BoundingBox this_boundingBox; this_boundingBox.lon_min = lon_min; this_boundingBox.lon_max = lon_max; this_boundingBox.lat_min = lat_min; this_boundingBox.lat_max = lat_max; m_boundingBoxes[id] = this_boundingBox; } void pyToCppModelInterfaceCache::setExtSourceCube(const int id, const boost::python::numeric::array &cube, const boost::python::numeric::array &lon, const boost::python::numeric::array &lat) { // Add an extended source to the cache (a map) PyArrayObject* cube__ = (PyArrayObject*) cube.ptr(); unsigned int n_points = (unsigned int) *(cube__->dimensions); unsigned int n_energies = (unsigned int) *(cube__->dimensions+1); // This is n_points * n_energies in size double* cube_ = (double *) cube__->data; // These are both n_points in size double* lon_ = (double *) ((PyArrayObject*) lon.ptr())->data; double* lat_ = (double *) ((PyArrayObject*) lat.ptr())->data; ExtSrcCube this_srcCube; for(unsigned int i=0; i < n_points; ++i) { float this_lon = (float) lon_[i]; float this_lat = (float) lat_[i]; SkyCoord this_coord(this_lon, this_lat); // A little of pointer algebra int this_data_start = i * n_energies; int this_data_stop = this_data_start + n_energies; // Note how this construct avoid the double copy which would // occur if we were to first create a vector and then // copy it into a standard map. Here instead the operator // [] creates an empty vector, which is then filled with // the assign method this_srcCube[this_coord].assign(cube_ + this_data_start, cube_ + this_data_stop); } // Finally add to the map m_extSources[id] = this_srcCube; } bool pyToCppModelInterfaceCache::isInsideAnyExtendedSource(double j2000_ra, double j2000_dec) const { return true; } int pyToCppModelInterfaceCache::getNumberOfPointSources() const { return m_ptsSourcesPos.size(); } void pyToCppModelInterfaceCache::getPointSourcePosition(int srcid, double *j2000_ra, double *j2000_dec) const { try { SkyCoord this_position = m_ptsSourcesPos.at(srcid); *j2000_ra = this_position.first; *j2000_dec = this_position.second; } catch (...) { std::stringstream name; name << "Point source " << srcid << " not found in position cache"; throw std::runtime_error(name.str()); } } void pyToCppModelInterfaceCache::reset() { //Empty the cache m_extSources.clear(); m_ptsSources.clear(); /* m_boundingBoxes.clear(); m_nExtSources = 0; m_nPtSources = 0;*/ } std::vector<double> pyToCppModelInterfaceCache::getPointSourceFluxes(int srcid, std::vector<double> energies) const { if (m_ptsSources.count(srcid) == 0) { // This happens during the construction of LikeHAWC because there is a energy reweighting // At that moment the cache is still empty, so let's just return the energy array which // has the right size. /* std::stringstream name; name << "Point source " << srcid << " not found in spectrum cache"; throw std::runtime_error(name.str());*/ std::cerr << "Point source " << srcid << " not found in spectrum cache" << std::endl; return energies; } else { return m_ptsSources.at(srcid); } } int pyToCppModelInterfaceCache::getNumberOfExtendedSources() const { // We use the size of bounding boxes and not of m_extSources because the latter // could get filled in a second moment return m_boundingBoxes.size(); } std::vector<double> pyToCppModelInterfaceCache::getExtendedSourceFluxes(int srcid, double j2000_ra, double j2000_dec, std::vector<double> energies) const { SkyCoord sky_pos(j2000_ra, j2000_dec); return m_extSources.at(srcid).at(sky_pos); } std::vector<double> pyToCppModelInterfaceCache::getExtendedSourceFluxes_test(int srcid, double j2000_ra, double j2000_dec) const { SkyCoord sky_pos(j2000_ra, j2000_dec); return m_extSources.at(srcid).at(sky_pos); } std::string pyToCppModelInterfaceCache::getPointSourceName(int srcid) const { //TODO: implement a mechanism to actually keep the true name std::stringstream name; name << "Point source " << srcid; return name.str(); } std::string pyToCppModelInterfaceCache::getExtendedSourceName(int srcid) const { //TODO: implement a mechanism to actually keep the true name std::stringstream name; name << "Extended source " << srcid; return name.str(); } void pyToCppModelInterfaceCache::getExtendedSourceBoundaries(int srcid, double *j2000_ra_min, double *j2000_ra_max, double *j2000_dec_min, double *j2000_dec_max) const { const BoundingBox *this_boundingBox = &m_boundingBoxes.at(srcid); *j2000_ra_min = this_boundingBox->lon_min; *j2000_ra_max = this_boundingBox->lon_max; *j2000_dec_min = this_boundingBox->lat_min; *j2000_dec_max = this_boundingBox->lat_max; } } using namespace threeML; using namespace boost::python; //This is needed to wrap the interface (i.e., all methods are virtual) //contained in ModelInterface.h struct ModelInterfaceCacheWrap: ModelInterface, wrapper<ModelInterface> { int getNumberOfPointSources() const { return this->get_override("getNumberOfPointSources")(); } void getPointSourcePosition(int srcid, double *j2000_ra, double *j2000_dec) const { this->get_override("getPointSourcePosition")(); } std::vector<double> getPointSourceFluxes(int srcid, std::vector<double> energies) const { return this->get_override("getPointSourceFluxes")(); } std::string getPointSourceName(int srcid) const { return this->get_override("getPointSourceName")(); } int getNumberOfExtendedSources() const { return this->get_override("getNumberOfExtendedSources")(); } std::vector<double> getExtendedSourceFluxes(int srcid, double j2000_ra, double j2000_dec, std::vector<double> energies) const { return this->get_override("getExtendedSourceFluxes")(); } std::string getExtendedSourceName(int srcid) const { return this->get_override("getExtendedSourceName")(); } bool isInsideAnyExtendedSource(double j2000_ra, double j2000_dec) const { return this->get_override("isInsideAnyExtendedSource")(); } void getExtendedSourceBoundaries(int srcid, double *j2000_ra_min, double *j2000_ra_max, double *j2000_dec_min, double *j2000_dec_max) const { this->get_override("getExtendedSourceBoundaries")(); } }; template<class T> struct VecToList { static PyObject *convert(const std::vector<T> &vec) { boost::python::list *l = new boost::python::list(); for (size_t i = 0; i < vec.size(); i++) (*l).append(vec[i]); return l->ptr(); } }; BOOST_PYTHON_MODULE (pyModelInterfaceCache) { //hello to_python_converter<std::vector<double, std::allocator<double> >, VecToList<double> >(); class_<ModelInterfaceCacheWrap, boost::noncopyable>("ModelInterface") .def("getNumberOfPointSources", pure_virtual(&ModelInterface::getNumberOfPointSources)) .def("getPointSourcePosition", pure_virtual(&ModelInterface::getPointSourcePosition)) .def("getPointSourceFluxes", pure_virtual(&ModelInterface::getPointSourceFluxes)) .def("getPointSourceName", pure_virtual(&ModelInterface::getPointSourceName)) .def("getNumberOfExtendedSources", pure_virtual(&ModelInterface::getNumberOfExtendedSources)) .def("getExtendedSourceFluxes", pure_virtual(&ModelInterface::getExtendedSourceFluxes)) .def("getExtendedSourceName", pure_virtual(&ModelInterface::getExtendedSourceName)) .def("isInsideAnyExtendedSource", pure_virtual(&ModelInterface::isInsideAnyExtendedSource)) .def("getExtendedSourceBoundaries", pure_virtual(&ModelInterface::getExtendedSourceBoundaries)); boost::python::numeric::array::set_module_and_type("numpy", "ndarray"); class_<pyToCppModelInterfaceCache, bases<ModelInterface> >("pyToCppModelInterfaceCache", init< >()) .def("getNumberOfPointSources", &pyToCppModelInterfaceCache::getNumberOfPointSources) .def("getPointSourcePosition", &pyToCppModelInterfaceCache::getPointSourcePosition) .def("getPointSourceFluxes", &pyToCppModelInterfaceCache::getPointSourceFluxes) .def("getPointSourceName", &pyToCppModelInterfaceCache::getPointSourceName) .def("getNumberOfExtendedSources", &pyToCppModelInterfaceCache::getNumberOfExtendedSources) .def("getExtendedSourceFluxes", &pyToCppModelInterfaceCache::getExtendedSourceFluxes) .def("getExtendedSourceName", &pyToCppModelInterfaceCache::getExtendedSourceName) .def("isInsideAnyExtendedSource", &pyToCppModelInterfaceCache::isInsideAnyExtendedSource) .def("getExtendedSourceBoundaries", &pyToCppModelInterfaceCache::getExtendedSourceBoundaries) .def("setExtSourceBoundaries", &pyToCppModelInterfaceCache::setExtSourceBoundaries) .def("setExtSourceCube",&pyToCppModelInterfaceCache::setExtSourceCube) .def("getExtendedSourceFluxes_test",&pyToCppModelInterfaceCache::getExtendedSourceFluxes_test) .def("reset",&pyToCppModelInterfaceCache::reset) .def("setPtsSourceSpectrum",&pyToCppModelInterfaceCache::setPtsSourceSpectrum) .def("setPtsSourcePosition",&pyToCppModelInterfaceCache::setPtsSourcePosition); } <commit_msg>Porting to new boost::python::numpy instead of boost::python::numeric<commit_after>#include <boost/python.hpp> #include "ModelInterface.h" #include "pyToCppModelInterfaceCache.h" #include <boost/python/stl_iterator.hpp> #include <iostream> #include <stdexcept> #include <boost/python/numpy.hpp> #include <boost/python/tuple.hpp> #include <boost/python/module.hpp> #include <boost/python/def.hpp> #include <numpy/noprefix.h> namespace threeML { template<typename T> inline std::vector<T> to_std_vector(const boost::python::object &iterable) { return std::vector<T>(boost::python::stl_input_iterator<T>(iterable), boost::python::stl_input_iterator<T>()); } void pyToCppModelInterfaceCache::setPtsSourceSpectrum(const int id, const boost::python::numpy::array& spectrum) { // These are both n_points in size PyArrayObject* spectrum__ = (PyArrayObject*) spectrum.ptr(); unsigned int n_energies = (unsigned int) *(spectrum__->dimensions); double* spectrum_ = (double *) spectrum__->data; m_ptsSources[id].assign(spectrum_, spectrum_ + n_energies); } void pyToCppModelInterfaceCache::setPtsSourcePosition(const int id, const float lon, const float lat) { m_ptsSourcesPos[id] = SkyCoord(lon, lat); } void pyToCppModelInterfaceCache::setExtSourceBoundaries(const int id, const float lon_min, const float lon_max, const float lat_min, const float lat_max) { BoundingBox this_boundingBox; this_boundingBox.lon_min = lon_min; this_boundingBox.lon_max = lon_max; this_boundingBox.lat_min = lat_min; this_boundingBox.lat_max = lat_max; m_boundingBoxes[id] = this_boundingBox; } void pyToCppModelInterfaceCache::setExtSourceCube(const int id, const boost::python::numpy::array &cube, const boost::python::numpy::array &lon, const boost::python::numpy::array &lat) { // Add an extended source to the cache (a map) PyArrayObject* cube__ = (PyArrayObject*) cube.ptr(); unsigned int n_points = (unsigned int) *(cube__->dimensions); unsigned int n_energies = (unsigned int) *(cube__->dimensions+1); // This is n_points * n_energies in size double* cube_ = (double *) cube__->data; // These are both n_points in size double* lon_ = (double *) ((PyArrayObject*) lon.ptr())->data; double* lat_ = (double *) ((PyArrayObject*) lat.ptr())->data; ExtSrcCube this_srcCube; for(unsigned int i=0; i < n_points; ++i) { float this_lon = (float) lon_[i]; float this_lat = (float) lat_[i]; SkyCoord this_coord(this_lon, this_lat); // A little of pointer algebra int this_data_start = i * n_energies; int this_data_stop = this_data_start + n_energies; // Note how this construct avoid the double copy which would // occur if we were to first create a vector and then // copy it into a standard map. Here instead the operator // [] creates an empty vector, which is then filled with // the assign method this_srcCube[this_coord].assign(cube_ + this_data_start, cube_ + this_data_stop); } // Finally add to the map m_extSources[id] = this_srcCube; } bool pyToCppModelInterfaceCache::isInsideAnyExtendedSource(double j2000_ra, double j2000_dec) const { return true; } int pyToCppModelInterfaceCache::getNumberOfPointSources() const { return m_ptsSourcesPos.size(); } void pyToCppModelInterfaceCache::getPointSourcePosition(int srcid, double *j2000_ra, double *j2000_dec) const { try { SkyCoord this_position = m_ptsSourcesPos.at(srcid); *j2000_ra = this_position.first; *j2000_dec = this_position.second; } catch (...) { std::stringstream name; name << "Point source " << srcid << " not found in position cache"; throw std::runtime_error(name.str()); } } void pyToCppModelInterfaceCache::reset() { //Empty the cache m_extSources.clear(); m_ptsSources.clear(); /* m_boundingBoxes.clear(); m_nExtSources = 0; m_nPtSources = 0;*/ } std::vector<double> pyToCppModelInterfaceCache::getPointSourceFluxes(int srcid, std::vector<double> energies) const { if (m_ptsSources.count(srcid) == 0) { // This happens during the construction of LikeHAWC because there is a energy reweighting // At that moment the cache is still empty, so let's just return the energy array which // has the right size. /* std::stringstream name; name << "Point source " << srcid << " not found in spectrum cache"; throw std::runtime_error(name.str());*/ std::cerr << "Point source " << srcid << " not found in spectrum cache" << std::endl; return energies; } else { return m_ptsSources.at(srcid); } } int pyToCppModelInterfaceCache::getNumberOfExtendedSources() const { // We use the size of bounding boxes and not of m_extSources because the latter // could get filled in a second moment return m_boundingBoxes.size(); } std::vector<double> pyToCppModelInterfaceCache::getExtendedSourceFluxes(int srcid, double j2000_ra, double j2000_dec, std::vector<double> energies) const { SkyCoord sky_pos(j2000_ra, j2000_dec); return m_extSources.at(srcid).at(sky_pos); } std::vector<double> pyToCppModelInterfaceCache::getExtendedSourceFluxes_test(int srcid, double j2000_ra, double j2000_dec) const { SkyCoord sky_pos(j2000_ra, j2000_dec); return m_extSources.at(srcid).at(sky_pos); } std::string pyToCppModelInterfaceCache::getPointSourceName(int srcid) const { //TODO: implement a mechanism to actually keep the true name std::stringstream name; name << "Point source " << srcid; return name.str(); } std::string pyToCppModelInterfaceCache::getExtendedSourceName(int srcid) const { //TODO: implement a mechanism to actually keep the true name std::stringstream name; name << "Extended source " << srcid; return name.str(); } void pyToCppModelInterfaceCache::getExtendedSourceBoundaries(int srcid, double *j2000_ra_min, double *j2000_ra_max, double *j2000_dec_min, double *j2000_dec_max) const { const BoundingBox *this_boundingBox = &m_boundingBoxes.at(srcid); *j2000_ra_min = this_boundingBox->lon_min; *j2000_ra_max = this_boundingBox->lon_max; *j2000_dec_min = this_boundingBox->lat_min; *j2000_dec_max = this_boundingBox->lat_max; } } using namespace threeML; using namespace boost::python; //This is needed to wrap the interface (i.e., all methods are virtual) //contained in ModelInterface.h struct ModelInterfaceCacheWrap: ModelInterface, wrapper<ModelInterface> { int getNumberOfPointSources() const { return this->get_override("getNumberOfPointSources")(); } void getPointSourcePosition(int srcid, double *j2000_ra, double *j2000_dec) const { this->get_override("getPointSourcePosition")(); } std::vector<double> getPointSourceFluxes(int srcid, std::vector<double> energies) const { return this->get_override("getPointSourceFluxes")(); } std::string getPointSourceName(int srcid) const { return this->get_override("getPointSourceName")(); } int getNumberOfExtendedSources() const { return this->get_override("getNumberOfExtendedSources")(); } std::vector<double> getExtendedSourceFluxes(int srcid, double j2000_ra, double j2000_dec, std::vector<double> energies) const { return this->get_override("getExtendedSourceFluxes")(); } std::string getExtendedSourceName(int srcid) const { return this->get_override("getExtendedSourceName")(); } bool isInsideAnyExtendedSource(double j2000_ra, double j2000_dec) const { return this->get_override("isInsideAnyExtendedSource")(); } void getExtendedSourceBoundaries(int srcid, double *j2000_ra_min, double *j2000_ra_max, double *j2000_dec_min, double *j2000_dec_max) const { this->get_override("getExtendedSourceBoundaries")(); } }; template<class T> struct VecToList { static PyObject *convert(const std::vector<T> &vec) { boost::python::list *l = new boost::python::list(); for (size_t i = 0; i < vec.size(); i++) (*l).append(vec[i]); return l->ptr(); } }; BOOST_PYTHON_MODULE (pyModelInterfaceCache) { //hello to_python_converter<std::vector<double, std::allocator<double> >, VecToList<double> >(); class_<ModelInterfaceCacheWrap, boost::noncopyable>("ModelInterface") .def("getNumberOfPointSources", pure_virtual(&ModelInterface::getNumberOfPointSources)) .def("getPointSourcePosition", pure_virtual(&ModelInterface::getPointSourcePosition)) .def("getPointSourceFluxes", pure_virtual(&ModelInterface::getPointSourceFluxes)) .def("getPointSourceName", pure_virtual(&ModelInterface::getPointSourceName)) .def("getNumberOfExtendedSources", pure_virtual(&ModelInterface::getNumberOfExtendedSources)) .def("getExtendedSourceFluxes", pure_virtual(&ModelInterface::getExtendedSourceFluxes)) .def("getExtendedSourceName", pure_virtual(&ModelInterface::getExtendedSourceName)) .def("isInsideAnyExtendedSource", pure_virtual(&ModelInterface::isInsideAnyExtendedSource)) .def("getExtendedSourceBoundaries", pure_virtual(&ModelInterface::getExtendedSourceBoundaries)); boost::python::numpy::array::set_module_and_type("numpy", "ndarray"); class_<pyToCppModelInterfaceCache, bases<ModelInterface> >("pyToCppModelInterfaceCache", init< >()) .def("getNumberOfPointSources", &pyToCppModelInterfaceCache::getNumberOfPointSources) .def("getPointSourcePosition", &pyToCppModelInterfaceCache::getPointSourcePosition) .def("getPointSourceFluxes", &pyToCppModelInterfaceCache::getPointSourceFluxes) .def("getPointSourceName", &pyToCppModelInterfaceCache::getPointSourceName) .def("getNumberOfExtendedSources", &pyToCppModelInterfaceCache::getNumberOfExtendedSources) .def("getExtendedSourceFluxes", &pyToCppModelInterfaceCache::getExtendedSourceFluxes) .def("getExtendedSourceName", &pyToCppModelInterfaceCache::getExtendedSourceName) .def("isInsideAnyExtendedSource", &pyToCppModelInterfaceCache::isInsideAnyExtendedSource) .def("getExtendedSourceBoundaries", &pyToCppModelInterfaceCache::getExtendedSourceBoundaries) .def("setExtSourceBoundaries", &pyToCppModelInterfaceCache::setExtSourceBoundaries) .def("setExtSourceCube",&pyToCppModelInterfaceCache::setExtSourceCube) .def("getExtendedSourceFluxes_test",&pyToCppModelInterfaceCache::getExtendedSourceFluxes_test) .def("reset",&pyToCppModelInterfaceCache::reset) .def("setPtsSourceSpectrum",&pyToCppModelInterfaceCache::setPtsSourceSpectrum) .def("setPtsSourcePosition",&pyToCppModelInterfaceCache::setPtsSourcePosition); } <|endoftext|>
<commit_before>// Copyright (c) 2012 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 <vector> #include "base/file_path.h" #include "base/file_util.h" #include "base/stringprintf.h" #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/browser/extensions/extension_function_test_utils.h" #include "chrome/browser/extensions/extension_install_dialog.h" #include "chrome/browser/extensions/extension_install_ui.h" #include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/extensions/extension_webstore_private_api.h" #include "chrome/browser/extensions/webstore_installer.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" #include "chrome/common/chrome_notification_types.h" #include "chrome/common/chrome_switches.h" #include "chrome/test/base/test_launcher_utils.h" #include "chrome/test/base/ui_test_utils.h" #include "content/browser/gpu/gpu_blacklist.h" #include "content/public/browser/notification_observer.h" #include "content/public/browser/notification_registrar.h" #include "net/base/mock_host_resolver.h" #include "ui/gfx/gl/gl_switches.h" using namespace extension_function_test_utils; namespace { class WebstoreInstallListener : public WebstoreInstaller::Delegate { public: WebstoreInstallListener() : received_failure_(false), received_success_(false), waiting_(false) {} void OnExtensionInstallSuccess(const std::string& id) OVERRIDE; void OnExtensionInstallFailure(const std::string& id, const std::string& error) OVERRIDE; void Wait(); bool received_failure() const { return received_failure_; } bool received_success() const { return received_success_; } const std::string& id() const { return id_; } const std::string& error() const { return error_; } private: bool received_failure_; bool received_success_; bool waiting_; std::string id_; std::string error_; }; void WebstoreInstallListener::OnExtensionInstallSuccess(const std::string& id) { received_success_ = true; id_ = id; if (waiting_) { waiting_ = false; MessageLoopForUI::current()->Quit(); } } void WebstoreInstallListener::OnExtensionInstallFailure( const std::string& id, const std::string& error) { received_failure_ = true; id_ = id; error_ = error; if (waiting_) { waiting_ = false; MessageLoopForUI::current()->Quit(); } } void WebstoreInstallListener::Wait() { if (received_success_ || received_failure_) return; waiting_ = true; ui_test_utils::RunMessageLoop(); } } // namespace // A base class for tests below. class ExtensionWebstorePrivateApiTest : public ExtensionApiTest { public: void SetUpCommandLine(CommandLine* command_line) OVERRIDE { ExtensionApiTest::SetUpCommandLine(command_line); command_line->AppendSwitchASCII( switches::kAppsGalleryURL, "http://www.example.com"); command_line->AppendSwitchASCII( switches::kAppsGalleryInstallAutoConfirmForTests, "accept"); } void SetUpInProcessBrowserTestFixture() OVERRIDE { // Start up the test server and get us ready for calling the install // API functions. host_resolver()->AddRule("www.example.com", "127.0.0.1"); ASSERT_TRUE(test_server()->Start()); ExtensionInstallUI::DisableFailureUIForTests(); } protected: // Returns a test server URL, but with host 'www.example.com' so it matches // the web store app's extent that we set up via command line flags. GURL GetTestServerURL(const std::string& path) { GURL url = test_server()->GetURL( std::string("files/extensions/api_test/webstore_private/") + path); // Replace the host with 'www.example.com' so it matches the web store // app's extent. GURL::Replacements replace_host; std::string host_str("www.example.com"); replace_host.SetHostStr(host_str); return url.ReplaceComponents(replace_host); } // Navigates to |page| and runs the Extension API test there. Any downloads // of extensions will return the contents of |crx_file|. bool RunInstallTest(const std::string& page, const std::string& crx_file) { GURL crx_url = GetTestServerURL(crx_file); CommandLine::ForCurrentProcess()->AppendSwitchASCII( switches::kAppsGalleryUpdateURL, crx_url.spec()); GURL page_url = GetTestServerURL(page); return RunPageTest(page_url.spec()); } ExtensionService* service() { return browser()->profile()->GetExtensionService(); } }; class ExtensionWebstorePrivateBundleTest : public ExtensionWebstorePrivateApiTest { public: void SetUpInProcessBrowserTestFixture() OVERRIDE { ExtensionWebstorePrivateApiTest::SetUpInProcessBrowserTestFixture(); // The test server needs to have already started, so setup the switch here // rather than in SetUpCommandLine. CommandLine::ForCurrentProcess()->AppendSwitchASCII( switches::kAppsGalleryDownloadURL, GetTestServerURL("bundle/%s.crx").spec()); PackCRX("begfmnajjkbjdgmffnjaojchoncnmngg"); PackCRX("bmfoocgfinpmkmlbjhcbofejhkhlbchk"); PackCRX("mpneghmdnmaolkljkipbhaienajcflfe"); } void TearDownInProcessBrowserTestFixture() OVERRIDE { ExtensionWebstorePrivateApiTest::TearDownInProcessBrowserTestFixture(); for (size_t i = 0; i < test_crx_.size(); ++i) ASSERT_TRUE(file_util::Delete(test_crx_[i], false)); } private: void PackCRX(const std::string& id) { FilePath data_path = test_data_dir_.AppendASCII("webstore_private/bundle"); FilePath dir_path = data_path.AppendASCII(id); FilePath pem_path = data_path.AppendASCII(id + ".pem"); FilePath crx_path = data_path.AppendASCII(id + ".crx"); FilePath destination = PackExtensionWithOptions( dir_path, crx_path, pem_path, FilePath()); ASSERT_FALSE(destination.empty()); ASSERT_EQ(destination, crx_path); test_crx_.push_back(destination); } std::vector<FilePath> test_crx_; }; class ExtensionWebstoreGetWebGLStatusTest : public InProcessBrowserTest { public: void SetUpCommandLine(CommandLine* command_line) OVERRIDE { // In linux, we need to launch GPU process to decide if WebGL is allowed. // Run it on top of osmesa to avoid bot driver issues. #if defined(OS_LINUX) CHECK(test_launcher_utils::OverrideGLImplementation( command_line, gfx::kGLImplementationOSMesaName)) << "kUseGL must not be set multiple times!"; #endif } protected: void RunTest(bool webgl_allowed) { static const char kEmptyArgs[] = "[]"; static const char kWebGLStatusAllowed[] = "webgl_allowed"; static const char kWebGLStatusBlocked[] = "webgl_blocked"; scoped_ptr<base::Value> result(RunFunctionAndReturnResult( new GetWebGLStatusFunction(), kEmptyArgs, browser())); EXPECT_EQ(base::Value::TYPE_STRING, result->GetType()); StringValue* value = static_cast<StringValue*>(result.get()); std::string webgl_status = ""; EXPECT_TRUE(value && value->GetAsString(&webgl_status)); EXPECT_STREQ(webgl_allowed ? kWebGLStatusAllowed : kWebGLStatusBlocked, webgl_status.c_str()); } }; // Test cases where the user accepts the install confirmation dialog. IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTest, InstallAccepted) { ASSERT_TRUE(RunInstallTest("accepted.html", "extension.crx")); } // Test having the default download directory missing. IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTest, MissingDownloadDir) { // Set a non-existent directory as the download path. ScopedTempDir temp_dir; EXPECT_TRUE(temp_dir.CreateUniqueTempDir()); FilePath missing_directory = temp_dir.Take(); EXPECT_TRUE(file_util::Delete(missing_directory, true)); WebstoreInstaller::SetDownloadDirectoryForTests(&missing_directory); // Now run the install test, which should succeed. ASSERT_TRUE(RunInstallTest("accepted.html", "extension.crx")); // Cleanup. if (file_util::DirectoryExists(missing_directory)) EXPECT_TRUE(file_util::Delete(missing_directory, true)); } // Tests passing a localized name. IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTest, InstallLocalized) { ASSERT_TRUE(RunInstallTest("localized.html", "localized_extension.crx")); } // Now test the case where the user cancels the confirmation dialog. IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTest, InstallCancelled) { CommandLine::ForCurrentProcess()->AppendSwitchASCII( switches::kAppsGalleryInstallAutoConfirmForTests, "cancel"); ASSERT_TRUE(RunInstallTest("cancelled.html", "extension.crx")); } IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTest, IncorrectManifest1) { WebstoreInstallListener listener; WebstorePrivateApi::SetWebstoreInstallerDelegateForTesting(&listener); ASSERT_TRUE(RunInstallTest("incorrect_manifest1.html", "extension.crx")); listener.Wait(); ASSERT_TRUE(listener.received_failure()); ASSERT_EQ("Manifest file is invalid.", listener.error()); } IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTest, IncorrectManifest2) { WebstoreInstallListener listener; WebstorePrivateApi::SetWebstoreInstallerDelegateForTesting(&listener); ASSERT_TRUE(RunInstallTest("incorrect_manifest2.html", "extension.crx")); listener.Wait(); EXPECT_TRUE(listener.received_failure()); ASSERT_EQ("Manifest file is invalid.", listener.error()); } // Tests that we can request an app installed bubble (instead of the default // UI when an app is installed). IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTest, AppInstallBubble) { WebstoreInstallListener listener; WebstorePrivateApi::SetWebstoreInstallerDelegateForTesting(&listener); ASSERT_TRUE(RunInstallTest("app_install_bubble.html", "app.crx")); listener.Wait(); ASSERT_TRUE(listener.received_success()); ASSERT_EQ("iladmdjkfniedhfhcfoefgojhgaiaccc", listener.id()); } // Tests using the iconUrl parameter to the install function. IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTest, IconUrl) { ASSERT_TRUE(RunInstallTest("icon_url.html", "extension.crx")); } // Tests using silentlyInstall to install extensions. IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateBundleTest, SilentlyInstall) { WebstorePrivateApi::SetTrustTestIDsForTesting(true); ASSERT_TRUE(RunPageTest(GetTestServerURL("silently_install.html").spec())); } // Tests getWebGLStatus function when WebGL is allowed. IN_PROC_BROWSER_TEST_F(ExtensionWebstoreGetWebGLStatusTest, Allowed) { bool webgl_allowed = true; RunTest(webgl_allowed); } // Tests getWebGLStatus function when WebGL is blacklisted. IN_PROC_BROWSER_TEST_F(ExtensionWebstoreGetWebGLStatusTest, Blocked) { static const std::string json_blacklist = "{\n" " \"name\": \"gpu blacklist\",\n" " \"version\": \"1.0\",\n" " \"entries\": [\n" " {\n" " \"id\": 1,\n" " \"blacklist\": [\n" " \"webgl\"\n" " ]\n" " }\n" " ]\n" "}"; scoped_ptr<Version> os_version(Version::GetVersionFromString("1.0")); GpuBlacklist* blacklist = new GpuBlacklist("1.0"); ASSERT_TRUE(blacklist->LoadGpuBlacklist( json_blacklist, GpuBlacklist::kAllOs)); GpuDataManager::GetInstance()->SetGpuBlacklist(blacklist); GpuFeatureFlags flags = GpuDataManager::GetInstance()->GetGpuFeatureFlags(); EXPECT_EQ( flags.flags(), static_cast<uint32>(GpuFeatureFlags::kGpuFeatureWebgl)); bool webgl_allowed = false; RunTest(webgl_allowed); } <commit_msg>Attempt to fix the ExtensionWebstorePrivateApiTest.* tests.<commit_after>// Copyright (c) 2012 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 <vector> #include "base/file_path.h" #include "base/file_util.h" #include "base/stringprintf.h" #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/browser/extensions/extension_function_test_utils.h" #include "chrome/browser/extensions/extension_install_dialog.h" #include "chrome/browser/extensions/extension_install_ui.h" #include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/extensions/extension_webstore_private_api.h" #include "chrome/browser/extensions/webstore_installer.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" #include "chrome/common/chrome_notification_types.h" #include "chrome/common/chrome_switches.h" #include "chrome/test/base/test_launcher_utils.h" #include "chrome/test/base/ui_test_utils.h" #include "content/browser/gpu/gpu_blacklist.h" #include "content/public/browser/notification_observer.h" #include "content/public/browser/notification_registrar.h" #include "net/base/mock_host_resolver.h" #include "ui/gfx/gl/gl_switches.h" using namespace extension_function_test_utils; namespace { class WebstoreInstallListener : public WebstoreInstaller::Delegate { public: WebstoreInstallListener() : received_failure_(false), received_success_(false), waiting_(false) {} void OnExtensionInstallSuccess(const std::string& id) OVERRIDE; void OnExtensionInstallFailure(const std::string& id, const std::string& error) OVERRIDE; void Wait(); bool received_failure() const { return received_failure_; } bool received_success() const { return received_success_; } const std::string& id() const { return id_; } const std::string& error() const { return error_; } private: bool received_failure_; bool received_success_; bool waiting_; std::string id_; std::string error_; }; void WebstoreInstallListener::OnExtensionInstallSuccess(const std::string& id) { received_success_ = true; id_ = id; if (waiting_) { waiting_ = false; MessageLoopForUI::current()->Quit(); } } void WebstoreInstallListener::OnExtensionInstallFailure( const std::string& id, const std::string& error) { received_failure_ = true; id_ = id; error_ = error; if (waiting_) { waiting_ = false; MessageLoopForUI::current()->Quit(); } } void WebstoreInstallListener::Wait() { if (received_success_ || received_failure_) return; waiting_ = true; ui_test_utils::RunMessageLoop(); } } // namespace // A base class for tests below. class ExtensionWebstorePrivateApiTest : public ExtensionApiTest { public: void SetUpCommandLine(CommandLine* command_line) OVERRIDE { ExtensionApiTest::SetUpCommandLine(command_line); command_line->AppendSwitchASCII( switches::kAppsGalleryURL, "http://www.example.com"); command_line->AppendSwitchASCII( switches::kAppsGalleryInstallAutoConfirmForTests, "accept"); } void SetUpInProcessBrowserTestFixture() OVERRIDE { // Start up the test server and get us ready for calling the install // API functions. host_resolver()->AddRule("www.example.com", "127.0.0.1"); ASSERT_TRUE(test_server()->Start()); ExtensionInstallUI::DisableFailureUIForTests(); } protected: // Returns a test server URL, but with host 'www.example.com' so it matches // the web store app's extent that we set up via command line flags. GURL GetTestServerURL(const std::string& path) { GURL url = test_server()->GetURL( std::string("files/extensions/api_test/webstore_private/") + path); // Replace the host with 'www.example.com' so it matches the web store // app's extent. GURL::Replacements replace_host; std::string host_str("www.example.com"); replace_host.SetHostStr(host_str); return url.ReplaceComponents(replace_host); } // Navigates to |page| and runs the Extension API test there. Any downloads // of extensions will return the contents of |crx_file|. bool RunInstallTest(const std::string& page, const std::string& crx_file) { GURL crx_url = GetTestServerURL(crx_file); CommandLine::ForCurrentProcess()->AppendSwitchASCII( switches::kAppsGalleryUpdateURL, crx_url.spec()); GURL page_url = GetTestServerURL(page); return RunPageTest(page_url.spec()); } ExtensionService* service() { return browser()->profile()->GetExtensionService(); } }; class ExtensionWebstorePrivateBundleTest : public ExtensionWebstorePrivateApiTest { public: void SetUpInProcessBrowserTestFixture() OVERRIDE { ExtensionWebstorePrivateApiTest::SetUpInProcessBrowserTestFixture(); // The test server needs to have already started, so setup the switch here // rather than in SetUpCommandLine. CommandLine::ForCurrentProcess()->AppendSwitchASCII( switches::kAppsGalleryDownloadURL, GetTestServerURL("bundle/%s.crx").spec()); PackCRX("begfmnajjkbjdgmffnjaojchoncnmngg"); PackCRX("bmfoocgfinpmkmlbjhcbofejhkhlbchk"); PackCRX("mpneghmdnmaolkljkipbhaienajcflfe"); } void TearDownInProcessBrowserTestFixture() OVERRIDE { ExtensionWebstorePrivateApiTest::TearDownInProcessBrowserTestFixture(); for (size_t i = 0; i < test_crx_.size(); ++i) ASSERT_TRUE(file_util::Delete(test_crx_[i], false)); } private: void PackCRX(const std::string& id) { FilePath data_path = test_data_dir_.AppendASCII("webstore_private/bundle"); FilePath dir_path = data_path.AppendASCII(id); FilePath pem_path = data_path.AppendASCII(id + ".pem"); FilePath crx_path = data_path.AppendASCII(id + ".crx"); FilePath destination = PackExtensionWithOptions( dir_path, crx_path, pem_path, FilePath()); ASSERT_FALSE(destination.empty()); ASSERT_EQ(destination, crx_path); test_crx_.push_back(destination); } std::vector<FilePath> test_crx_; }; class ExtensionWebstoreGetWebGLStatusTest : public InProcessBrowserTest { public: void SetUpCommandLine(CommandLine* command_line) OVERRIDE { // In linux, we need to launch GPU process to decide if WebGL is allowed. // Run it on top of osmesa to avoid bot driver issues. #if defined(OS_LINUX) CHECK(test_launcher_utils::OverrideGLImplementation( command_line, gfx::kGLImplementationOSMesaName)) << "kUseGL must not be set multiple times!"; #endif } protected: void RunTest(bool webgl_allowed) { static const char kEmptyArgs[] = "[]"; static const char kWebGLStatusAllowed[] = "webgl_allowed"; static const char kWebGLStatusBlocked[] = "webgl_blocked"; scoped_ptr<base::Value> result(RunFunctionAndReturnResult( new GetWebGLStatusFunction(), kEmptyArgs, browser())); EXPECT_EQ(base::Value::TYPE_STRING, result->GetType()); StringValue* value = static_cast<StringValue*>(result.get()); std::string webgl_status = ""; EXPECT_TRUE(value && value->GetAsString(&webgl_status)); EXPECT_STREQ(webgl_allowed ? kWebGLStatusAllowed : kWebGLStatusBlocked, webgl_status.c_str()); } }; // Test cases where the user accepts the install confirmation dialog. IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTest, InstallAccepted) { ScopedTempDir temp_dir; ASSERT_TRUE(temp_dir.CreateUniqueTempDir()); FilePath temp_path = temp_dir.path(); WebstoreInstaller::SetDownloadDirectoryForTests(&temp_path); ASSERT_TRUE(RunInstallTest("accepted.html", "extension.crx")); } // Test having the default download directory missing. IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTest, MissingDownloadDir) { // Set a non-existent directory as the download path. ScopedTempDir temp_dir; EXPECT_TRUE(temp_dir.CreateUniqueTempDir()); FilePath missing_directory = temp_dir.Take(); EXPECT_TRUE(file_util::Delete(missing_directory, true)); WebstoreInstaller::SetDownloadDirectoryForTests(&missing_directory); // Now run the install test, which should succeed. ASSERT_TRUE(RunInstallTest("accepted.html", "extension.crx")); // Cleanup. if (file_util::DirectoryExists(missing_directory)) EXPECT_TRUE(file_util::Delete(missing_directory, true)); } // Tests passing a localized name. IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTest, InstallLocalized) { ASSERT_TRUE(RunInstallTest("localized.html", "localized_extension.crx")); } // Now test the case where the user cancels the confirmation dialog. IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTest, InstallCancelled) { CommandLine::ForCurrentProcess()->AppendSwitchASCII( switches::kAppsGalleryInstallAutoConfirmForTests, "cancel"); ASSERT_TRUE(RunInstallTest("cancelled.html", "extension.crx")); } IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTest, IncorrectManifest1) { ScopedTempDir temp_dir; ASSERT_TRUE(temp_dir.CreateUniqueTempDir()); FilePath temp_path = temp_dir.path(); WebstoreInstaller::SetDownloadDirectoryForTests(&temp_path); WebstoreInstallListener listener; WebstorePrivateApi::SetWebstoreInstallerDelegateForTesting(&listener); ASSERT_TRUE(RunInstallTest("incorrect_manifest1.html", "extension.crx")); listener.Wait(); ASSERT_TRUE(listener.received_failure()); ASSERT_EQ("Manifest file is invalid.", listener.error()); } IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTest, IncorrectManifest2) { ScopedTempDir temp_dir; ASSERT_TRUE(temp_dir.CreateUniqueTempDir()); FilePath temp_path = temp_dir.path(); WebstoreInstaller::SetDownloadDirectoryForTests(&temp_path); WebstoreInstallListener listener; WebstorePrivateApi::SetWebstoreInstallerDelegateForTesting(&listener); ASSERT_TRUE(RunInstallTest("incorrect_manifest2.html", "extension.crx")); listener.Wait(); EXPECT_TRUE(listener.received_failure()); ASSERT_EQ("Manifest file is invalid.", listener.error()); } // Tests that we can request an app installed bubble (instead of the default // UI when an app is installed). IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTest, AppInstallBubble) { WebstoreInstallListener listener; WebstorePrivateApi::SetWebstoreInstallerDelegateForTesting(&listener); ASSERT_TRUE(RunInstallTest("app_install_bubble.html", "app.crx")); listener.Wait(); ASSERT_TRUE(listener.received_success()); ASSERT_EQ("iladmdjkfniedhfhcfoefgojhgaiaccc", listener.id()); } // Tests using the iconUrl parameter to the install function. IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTest, IconUrl) { ASSERT_TRUE(RunInstallTest("icon_url.html", "extension.crx")); } // Tests using silentlyInstall to install extensions. IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateBundleTest, SilentlyInstall) { WebstorePrivateApi::SetTrustTestIDsForTesting(true); ASSERT_TRUE(RunPageTest(GetTestServerURL("silently_install.html").spec())); } // Tests getWebGLStatus function when WebGL is allowed. IN_PROC_BROWSER_TEST_F(ExtensionWebstoreGetWebGLStatusTest, Allowed) { bool webgl_allowed = true; RunTest(webgl_allowed); } // Tests getWebGLStatus function when WebGL is blacklisted. IN_PROC_BROWSER_TEST_F(ExtensionWebstoreGetWebGLStatusTest, Blocked) { static const std::string json_blacklist = "{\n" " \"name\": \"gpu blacklist\",\n" " \"version\": \"1.0\",\n" " \"entries\": [\n" " {\n" " \"id\": 1,\n" " \"blacklist\": [\n" " \"webgl\"\n" " ]\n" " }\n" " ]\n" "}"; scoped_ptr<Version> os_version(Version::GetVersionFromString("1.0")); GpuBlacklist* blacklist = new GpuBlacklist("1.0"); ASSERT_TRUE(blacklist->LoadGpuBlacklist( json_blacklist, GpuBlacklist::kAllOs)); GpuDataManager::GetInstance()->SetGpuBlacklist(blacklist); GpuFeatureFlags flags = GpuDataManager::GetInstance()->GetGpuFeatureFlags(); EXPECT_EQ( flags.flags(), static_cast<uint32>(GpuFeatureFlags::kGpuFeatureWebgl)); bool webgl_allowed = false; RunTest(webgl_allowed); } <|endoftext|>
<commit_before>// Copyright 2014 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/extensions/proxy_overridden_bubble_controller.h" #include "base/metrics/histogram.h" #include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/extensions/extension_toolbar_model.h" #include "chrome/browser/extensions/settings_api_helpers.h" #include "chrome/browser/profiles/profile.h" #include "chrome/common/url_constants.h" #include "chrome/grit/generated_resources.h" #include "extensions/browser/extension_registry.h" #include "extensions/browser/extension_system.h" #include "grit/components_strings.h" #include "ui/base/l10n/l10n_util.h" namespace extensions { namespace { // The minimum time to wait (since the extension was installed) before notifying // the user about it. const int kDaysSinceInstallMin = 7; //////////////////////////////////////////////////////////////////////////////// // ProxyOverriddenBubbleDelegate class ProxyOverriddenBubbleDelegate : public ExtensionMessageBubbleController::Delegate { public: ProxyOverriddenBubbleDelegate(ExtensionService* service, Profile* profile); virtual ~ProxyOverriddenBubbleDelegate(); // ExtensionMessageBubbleController::Delegate methods. virtual bool ShouldIncludeExtension(const std::string& extension_id) OVERRIDE; virtual void AcknowledgeExtension( const std::string& extension_id, ExtensionMessageBubbleController::BubbleAction user_action) OVERRIDE; virtual void PerformAction(const ExtensionIdList& list) OVERRIDE; virtual void OnClose() OVERRIDE; virtual base::string16 GetTitle() const OVERRIDE; virtual base::string16 GetMessageBody( bool anchored_to_browser_action) const OVERRIDE; virtual base::string16 GetOverflowText( const base::string16& overflow_count) const OVERRIDE; virtual base::string16 GetLearnMoreLabel() const OVERRIDE; virtual GURL GetLearnMoreUrl() const OVERRIDE; virtual base::string16 GetActionButtonLabel() const OVERRIDE; virtual base::string16 GetDismissButtonLabel() const OVERRIDE; virtual bool ShouldShowExtensionList() const OVERRIDE; virtual void RestrictToSingleExtension( const std::string& extension_id) OVERRIDE; virtual void LogExtensionCount(size_t count) OVERRIDE; virtual void LogAction( ExtensionMessageBubbleController::BubbleAction action) OVERRIDE; private: // Our extension service. Weak, not owned by us. ExtensionService* service_; // A weak pointer to the profile we are associated with. Not owned by us. Profile* profile_; // The ID of the extension we are showing the bubble for. std::string extension_id_; DISALLOW_COPY_AND_ASSIGN(ProxyOverriddenBubbleDelegate); }; ProxyOverriddenBubbleDelegate::ProxyOverriddenBubbleDelegate( ExtensionService* service, Profile* profile) : service_(service), profile_(profile) {} ProxyOverriddenBubbleDelegate::~ProxyOverriddenBubbleDelegate() {} bool ProxyOverriddenBubbleDelegate::ShouldIncludeExtension( const std::string& extension_id) { if (!extension_id_.empty() && extension_id_ != extension_id) return false; const Extension* extension = ExtensionRegistry::Get(profile_)->enabled_extensions().GetByID( extension_id); if (!extension) return false; // The extension provided is no longer enabled. const Extension* overriding = GetExtensionOverridingProxy(profile_); if (!overriding || overriding->id() != extension_id) return false; ExtensionPrefs* prefs = ExtensionPrefs::Get(profile_); base::TimeDelta since_install = base::Time::Now() - prefs->GetInstallTime(extension->id()); if (since_install.InDays() < kDaysSinceInstallMin) return false; if (ExtensionPrefs::Get(profile_)->HasProxyOverriddenBubbleBeenAcknowledged( extension_id)) return false; return true; } void ProxyOverriddenBubbleDelegate::AcknowledgeExtension( const std::string& extension_id, ExtensionMessageBubbleController::BubbleAction user_action) { if (user_action != ExtensionMessageBubbleController::ACTION_EXECUTE) { ExtensionPrefs::Get(profile_)->SetProxyOverriddenBubbleBeenAcknowledged( extension_id, true); } } void ProxyOverriddenBubbleDelegate::PerformAction(const ExtensionIdList& list) { for (size_t i = 0; i < list.size(); ++i) service_->DisableExtension(list[i], Extension::DISABLE_USER_ACTION); } void ProxyOverriddenBubbleDelegate::OnClose() { ExtensionToolbarModel* toolbar_model = ExtensionToolbarModel::Get(profile_); if (toolbar_model) toolbar_model->StopHighlighting(); } base::string16 ProxyOverriddenBubbleDelegate::GetTitle() const { return l10n_util::GetStringUTF16( IDS_EXTENSIONS_PROXY_CONTROLLED_TITLE_HOME_PAGE_BUBBLE); } base::string16 ProxyOverriddenBubbleDelegate::GetMessageBody( bool anchored_to_browser_action) const { if (anchored_to_browser_action) { return l10n_util::GetStringUTF16( IDS_EXTENSIONS_PROXY_CONTROLLED_FIRST_LINE_EXTENSION_SPECIFIC); } else { return l10n_util::GetStringUTF16( IDS_EXTENSIONS_PROXY_CONTROLLED_FIRST_LINE); } } base::string16 ProxyOverriddenBubbleDelegate::GetOverflowText( const base::string16& overflow_count) const { // Does not have more than one extension in the list at a time. NOTREACHED(); return base::string16(); } base::string16 ProxyOverriddenBubbleDelegate::GetLearnMoreLabel() const { return l10n_util::GetStringUTF16(IDS_LEARN_MORE); } GURL ProxyOverriddenBubbleDelegate::GetLearnMoreUrl() const { return GURL(chrome::kExtensionControlledSettingLearnMoreURL); } base::string16 ProxyOverriddenBubbleDelegate::GetActionButtonLabel() const { return l10n_util::GetStringUTF16(IDS_EXTENSION_CONTROLLED_RESTORE_SETTINGS); } base::string16 ProxyOverriddenBubbleDelegate::GetDismissButtonLabel() const { return l10n_util::GetStringUTF16(IDS_EXTENSION_CONTROLLED_KEEP_CHANGES); } bool ProxyOverriddenBubbleDelegate::ShouldShowExtensionList() const { return false; } void ProxyOverriddenBubbleDelegate::RestrictToSingleExtension( const std::string& extension_id) { extension_id_ = extension_id; } void ProxyOverriddenBubbleDelegate::LogExtensionCount(size_t count) { UMA_HISTOGRAM_COUNTS_100("ProxyOverriddenBubble.ExtensionCount", count); } void ProxyOverriddenBubbleDelegate::LogAction( ExtensionMessageBubbleController::BubbleAction action) { UMA_HISTOGRAM_ENUMERATION("ProxyOverriddenBubble.UserSelection", action, ExtensionMessageBubbleController::ACTION_BOUNDARY); } } // namespace //////////////////////////////////////////////////////////////////////////////// // ProxyOverriddenBubbleController ProxyOverriddenBubbleController::ProxyOverriddenBubbleController( Profile* profile) : ExtensionMessageBubbleController( new ProxyOverriddenBubbleDelegate( ExtensionSystem::Get(profile)->extension_service(), profile), profile), profile_(profile) {} ProxyOverriddenBubbleController::~ProxyOverriddenBubbleController() {} bool ProxyOverriddenBubbleController::ShouldShow( const std::string& extension_id) { if (!delegate()->ShouldIncludeExtension(extension_id)) return false; delegate()->RestrictToSingleExtension(extension_id); return true; } bool ProxyOverriddenBubbleController::CloseOnDeactivate() { return true; } } // namespace extensions <commit_msg>Make the proxy override bubble sticky (not dismiss on focus-loss).<commit_after>// Copyright 2014 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/extensions/proxy_overridden_bubble_controller.h" #include "base/metrics/histogram.h" #include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/extensions/extension_toolbar_model.h" #include "chrome/browser/extensions/settings_api_helpers.h" #include "chrome/browser/profiles/profile.h" #include "chrome/common/url_constants.h" #include "chrome/grit/generated_resources.h" #include "extensions/browser/extension_registry.h" #include "extensions/browser/extension_system.h" #include "grit/components_strings.h" #include "ui/base/l10n/l10n_util.h" namespace extensions { namespace { // The minimum time to wait (since the extension was installed) before notifying // the user about it. const int kDaysSinceInstallMin = 7; //////////////////////////////////////////////////////////////////////////////// // ProxyOverriddenBubbleDelegate class ProxyOverriddenBubbleDelegate : public ExtensionMessageBubbleController::Delegate { public: ProxyOverriddenBubbleDelegate(ExtensionService* service, Profile* profile); virtual ~ProxyOverriddenBubbleDelegate(); // ExtensionMessageBubbleController::Delegate methods. virtual bool ShouldIncludeExtension(const std::string& extension_id) OVERRIDE; virtual void AcknowledgeExtension( const std::string& extension_id, ExtensionMessageBubbleController::BubbleAction user_action) OVERRIDE; virtual void PerformAction(const ExtensionIdList& list) OVERRIDE; virtual void OnClose() OVERRIDE; virtual base::string16 GetTitle() const OVERRIDE; virtual base::string16 GetMessageBody( bool anchored_to_browser_action) const OVERRIDE; virtual base::string16 GetOverflowText( const base::string16& overflow_count) const OVERRIDE; virtual base::string16 GetLearnMoreLabel() const OVERRIDE; virtual GURL GetLearnMoreUrl() const OVERRIDE; virtual base::string16 GetActionButtonLabel() const OVERRIDE; virtual base::string16 GetDismissButtonLabel() const OVERRIDE; virtual bool ShouldShowExtensionList() const OVERRIDE; virtual void RestrictToSingleExtension( const std::string& extension_id) OVERRIDE; virtual void LogExtensionCount(size_t count) OVERRIDE; virtual void LogAction( ExtensionMessageBubbleController::BubbleAction action) OVERRIDE; private: // Our extension service. Weak, not owned by us. ExtensionService* service_; // A weak pointer to the profile we are associated with. Not owned by us. Profile* profile_; // The ID of the extension we are showing the bubble for. std::string extension_id_; DISALLOW_COPY_AND_ASSIGN(ProxyOverriddenBubbleDelegate); }; ProxyOverriddenBubbleDelegate::ProxyOverriddenBubbleDelegate( ExtensionService* service, Profile* profile) : service_(service), profile_(profile) {} ProxyOverriddenBubbleDelegate::~ProxyOverriddenBubbleDelegate() {} bool ProxyOverriddenBubbleDelegate::ShouldIncludeExtension( const std::string& extension_id) { if (!extension_id_.empty() && extension_id_ != extension_id) return false; const Extension* extension = ExtensionRegistry::Get(profile_)->enabled_extensions().GetByID( extension_id); if (!extension) return false; // The extension provided is no longer enabled. const Extension* overriding = GetExtensionOverridingProxy(profile_); if (!overriding || overriding->id() != extension_id) return false; ExtensionPrefs* prefs = ExtensionPrefs::Get(profile_); base::TimeDelta since_install = base::Time::Now() - prefs->GetInstallTime(extension->id()); if (since_install.InDays() < kDaysSinceInstallMin) return false; if (ExtensionPrefs::Get(profile_)->HasProxyOverriddenBubbleBeenAcknowledged( extension_id)) return false; return true; } void ProxyOverriddenBubbleDelegate::AcknowledgeExtension( const std::string& extension_id, ExtensionMessageBubbleController::BubbleAction user_action) { if (user_action != ExtensionMessageBubbleController::ACTION_EXECUTE) { ExtensionPrefs::Get(profile_)->SetProxyOverriddenBubbleBeenAcknowledged( extension_id, true); } } void ProxyOverriddenBubbleDelegate::PerformAction(const ExtensionIdList& list) { for (size_t i = 0; i < list.size(); ++i) service_->DisableExtension(list[i], Extension::DISABLE_USER_ACTION); } void ProxyOverriddenBubbleDelegate::OnClose() { ExtensionToolbarModel* toolbar_model = ExtensionToolbarModel::Get(profile_); if (toolbar_model) toolbar_model->StopHighlighting(); } base::string16 ProxyOverriddenBubbleDelegate::GetTitle() const { return l10n_util::GetStringUTF16( IDS_EXTENSIONS_PROXY_CONTROLLED_TITLE_HOME_PAGE_BUBBLE); } base::string16 ProxyOverriddenBubbleDelegate::GetMessageBody( bool anchored_to_browser_action) const { if (anchored_to_browser_action) { return l10n_util::GetStringUTF16( IDS_EXTENSIONS_PROXY_CONTROLLED_FIRST_LINE_EXTENSION_SPECIFIC); } else { return l10n_util::GetStringUTF16( IDS_EXTENSIONS_PROXY_CONTROLLED_FIRST_LINE); } } base::string16 ProxyOverriddenBubbleDelegate::GetOverflowText( const base::string16& overflow_count) const { // Does not have more than one extension in the list at a time. NOTREACHED(); return base::string16(); } base::string16 ProxyOverriddenBubbleDelegate::GetLearnMoreLabel() const { return l10n_util::GetStringUTF16(IDS_LEARN_MORE); } GURL ProxyOverriddenBubbleDelegate::GetLearnMoreUrl() const { return GURL(chrome::kExtensionControlledSettingLearnMoreURL); } base::string16 ProxyOverriddenBubbleDelegate::GetActionButtonLabel() const { return l10n_util::GetStringUTF16(IDS_EXTENSION_CONTROLLED_RESTORE_SETTINGS); } base::string16 ProxyOverriddenBubbleDelegate::GetDismissButtonLabel() const { return l10n_util::GetStringUTF16(IDS_EXTENSION_CONTROLLED_KEEP_CHANGES); } bool ProxyOverriddenBubbleDelegate::ShouldShowExtensionList() const { return false; } void ProxyOverriddenBubbleDelegate::RestrictToSingleExtension( const std::string& extension_id) { extension_id_ = extension_id; } void ProxyOverriddenBubbleDelegate::LogExtensionCount(size_t count) { UMA_HISTOGRAM_COUNTS_100("ProxyOverriddenBubble.ExtensionCount", count); } void ProxyOverriddenBubbleDelegate::LogAction( ExtensionMessageBubbleController::BubbleAction action) { UMA_HISTOGRAM_ENUMERATION("ProxyOverriddenBubble.UserSelection", action, ExtensionMessageBubbleController::ACTION_BOUNDARY); } } // namespace //////////////////////////////////////////////////////////////////////////////// // ProxyOverriddenBubbleController ProxyOverriddenBubbleController::ProxyOverriddenBubbleController( Profile* profile) : ExtensionMessageBubbleController( new ProxyOverriddenBubbleDelegate( ExtensionSystem::Get(profile)->extension_service(), profile), profile), profile_(profile) {} ProxyOverriddenBubbleController::~ProxyOverriddenBubbleController() {} bool ProxyOverriddenBubbleController::ShouldShow( const std::string& extension_id) { if (!delegate()->ShouldIncludeExtension(extension_id)) return false; delegate()->RestrictToSingleExtension(extension_id); return true; } bool ProxyOverriddenBubbleController::CloseOnDeactivate() { return false; } } // namespace extensions <|endoftext|>
<commit_before>// Copyright (c) 2012 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/profiles/off_the_record_profile_impl.h" #include "base/prefs/pref_registry_simple.h" #include "base/prefs/pref_service.h" #include "base/prefs/scoped_user_pref_update.h" #include "base/run_loop.h" #include "chrome/browser/net/ssl_config_service_manager.h" #include "chrome/browser/prefs/browser_prefs.h" #include "chrome/common/pref_names.h" #include "chrome/test/base/browser_with_test_window_test.h" #include "chrome/test/base/testing_browser_process.h" #include "chrome/test/base/testing_io_thread_state.h" #include "chrome/test/base/testing_pref_service_syncable.h" #include "chrome/test/base/testing_profile.h" #include "chrome/test/base/testing_profile_manager.h" #include "content/public/browser/host_zoom_map.h" #include "content/public/common/page_zoom.h" #include "net/dns/mock_host_resolver.h" using content::HostZoomMap; namespace { class TestingProfileWithHostZoomMap : public TestingProfile { public: TestingProfileWithHostZoomMap() { zoom_subscription_ = HostZoomMap::GetForBrowserContext(this)->AddZoomLevelChangedCallback( base::Bind(&TestingProfileWithHostZoomMap::OnZoomLevelChanged, base::Unretained(this))); } virtual ~TestingProfileWithHostZoomMap() {} // Profile overrides: virtual PrefService* GetOffTheRecordPrefs() OVERRIDE { return GetPrefs(); } private: void OnZoomLevelChanged(const HostZoomMap::ZoomLevelChange& change) { if (change.mode != HostZoomMap::ZOOM_CHANGED_FOR_HOST) return; HostZoomMap* host_zoom_map = HostZoomMap::GetForBrowserContext(this); double level = change.zoom_level; DictionaryPrefUpdate update(prefs_.get(), prefs::kPerHostZoomLevels); base::DictionaryValue* host_zoom_dictionary = update.Get(); if (content::ZoomValuesEqual(level, host_zoom_map->GetDefaultZoomLevel())) { host_zoom_dictionary->RemoveWithoutPathExpansion(change.host, NULL); } else { host_zoom_dictionary->SetWithoutPathExpansion( change.host, new base::FundamentalValue(level)); } } scoped_ptr<SSLConfigServiceManager> ssl_config_service_manager_; scoped_ptr<HostZoomMap::Subscription> zoom_subscription_; DISALLOW_COPY_AND_ASSIGN(TestingProfileWithHostZoomMap); }; } // namespace // We need to have a BrowserProcess in g_browser_process variable, since // OffTheRecordProfileImpl ctor uses it in // ProfileIOData::InitializeProfileParams. class OffTheRecordProfileImplTest : public BrowserWithTestWindowTest { protected: OffTheRecordProfileImplTest() {} virtual ~OffTheRecordProfileImplTest() {} // testing::Test overrides: virtual void SetUp() OVERRIDE { profile_manager_.reset(new TestingProfileManager(browser_process())); ASSERT_TRUE(profile_manager_->SetUp()); testing_io_thread_state_.reset(new chrome::TestingIOThreadState()); testing_io_thread_state_->io_thread_state()->globals()->host_resolver.reset( new net::MockHostResolver()); BrowserWithTestWindowTest::SetUp(); } virtual void TearDown() OVERRIDE { BrowserWithTestWindowTest::TearDown(); testing_io_thread_state_.reset(); profile_manager_.reset(); } // BrowserWithTestWindowTest overrides: virtual TestingProfile* CreateProfile() OVERRIDE { return new TestingProfileWithHostZoomMap; } private: TestingBrowserProcess* browser_process() { return TestingBrowserProcess::GetGlobal(); } scoped_ptr<TestingProfileManager> profile_manager_; scoped_ptr<chrome::TestingIOThreadState> testing_io_thread_state_; DISALLOW_COPY_AND_ASSIGN(OffTheRecordProfileImplTest); }; // Test four things: // 1. Host zoom maps of parent profile and child profile are different. // 2. Child host zoom map inherites zoom level at construction. // 3. Change of zoom level doesn't propagate from child to parent. // 4. Change of zoom level propagate from parent to child. TEST_F(OffTheRecordProfileImplTest, GetHostZoomMap) { // Constants for test case. const std::string host("example.com"); const double zoom_level_25 = 2.5; const double zoom_level_30 = 3.0; const double zoom_level_40 = 4.0; // The TestingProfile from CreateProfile above is the parent. TestingProfile* parent_profile = GetProfile(); ASSERT_TRUE(parent_profile); ASSERT_TRUE(parent_profile->GetPrefs()); ASSERT_TRUE(parent_profile->GetOffTheRecordPrefs()); // Prepare parent host zoom map. HostZoomMap* parent_zoom_map = HostZoomMap::GetForBrowserContext(parent_profile); ASSERT_TRUE(parent_zoom_map); parent_zoom_map->SetZoomLevelForHost(host, zoom_level_25); ASSERT_EQ(parent_zoom_map->GetZoomLevelForHostAndScheme("http", host), zoom_level_25); // TODO(yosin) We need to wait ProfileImpl::Observe done for // OnZoomLevelChanged. // Prepare an off the record profile owned by the parent profile. parent_profile->SetOffTheRecordProfile( scoped_ptr<Profile>(new OffTheRecordProfileImpl(parent_profile))); OffTheRecordProfileImpl* child_profile = static_cast<OffTheRecordProfileImpl*>( parent_profile->GetOffTheRecordProfile()); child_profile->InitIoData(); child_profile->InitHostZoomMap(); // Prepare child host zoom map. HostZoomMap* child_zoom_map = HostZoomMap::GetForBrowserContext(child_profile); ASSERT_TRUE(child_zoom_map); // Verify. EXPECT_NE(parent_zoom_map, child_zoom_map); EXPECT_EQ(parent_zoom_map->GetZoomLevelForHostAndScheme("http", host), child_zoom_map->GetZoomLevelForHostAndScheme("http", host)) << "Child must inherit from parent."; child_zoom_map->SetZoomLevelForHost(host, zoom_level_30); ASSERT_EQ( child_zoom_map->GetZoomLevelForHostAndScheme("http", host), zoom_level_30); EXPECT_NE(parent_zoom_map->GetZoomLevelForHostAndScheme("http", host), child_zoom_map->GetZoomLevelForHostAndScheme("http", host)) << "Child change must not propagate to parent."; parent_zoom_map->SetZoomLevelForHost(host, zoom_level_40); ASSERT_EQ( parent_zoom_map->GetZoomLevelForHostAndScheme("http", host), zoom_level_40); EXPECT_EQ(parent_zoom_map->GetZoomLevelForHostAndScheme("http", host), child_zoom_map->GetZoomLevelForHostAndScheme("http", host)) << "Parent change should propagate to child."; base::RunLoop().RunUntilIdle(); } <commit_msg>Remove unused var from OffTheRecordProfileImplTest.GetHostZoomMap<commit_after>// Copyright (c) 2012 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/profiles/off_the_record_profile_impl.h" #include "base/prefs/pref_registry_simple.h" #include "base/prefs/pref_service.h" #include "base/prefs/scoped_user_pref_update.h" #include "base/run_loop.h" #include "chrome/browser/prefs/browser_prefs.h" #include "chrome/common/pref_names.h" #include "chrome/test/base/browser_with_test_window_test.h" #include "chrome/test/base/testing_browser_process.h" #include "chrome/test/base/testing_io_thread_state.h" #include "chrome/test/base/testing_pref_service_syncable.h" #include "chrome/test/base/testing_profile.h" #include "chrome/test/base/testing_profile_manager.h" #include "content/public/browser/host_zoom_map.h" #include "content/public/common/page_zoom.h" #include "net/dns/mock_host_resolver.h" using content::HostZoomMap; namespace { class TestingProfileWithHostZoomMap : public TestingProfile { public: TestingProfileWithHostZoomMap() { zoom_subscription_ = HostZoomMap::GetForBrowserContext(this)->AddZoomLevelChangedCallback( base::Bind(&TestingProfileWithHostZoomMap::OnZoomLevelChanged, base::Unretained(this))); } virtual ~TestingProfileWithHostZoomMap() {} // Profile overrides: virtual PrefService* GetOffTheRecordPrefs() OVERRIDE { return GetPrefs(); } private: void OnZoomLevelChanged(const HostZoomMap::ZoomLevelChange& change) { if (change.mode != HostZoomMap::ZOOM_CHANGED_FOR_HOST) return; HostZoomMap* host_zoom_map = HostZoomMap::GetForBrowserContext(this); double level = change.zoom_level; DictionaryPrefUpdate update(prefs_.get(), prefs::kPerHostZoomLevels); base::DictionaryValue* host_zoom_dictionary = update.Get(); if (content::ZoomValuesEqual(level, host_zoom_map->GetDefaultZoomLevel())) { host_zoom_dictionary->RemoveWithoutPathExpansion(change.host, NULL); } else { host_zoom_dictionary->SetWithoutPathExpansion( change.host, new base::FundamentalValue(level)); } } scoped_ptr<HostZoomMap::Subscription> zoom_subscription_; DISALLOW_COPY_AND_ASSIGN(TestingProfileWithHostZoomMap); }; } // namespace // We need to have a BrowserProcess in g_browser_process variable, since // OffTheRecordProfileImpl ctor uses it in // ProfileIOData::InitializeProfileParams. class OffTheRecordProfileImplTest : public BrowserWithTestWindowTest { protected: OffTheRecordProfileImplTest() {} virtual ~OffTheRecordProfileImplTest() {} // testing::Test overrides: virtual void SetUp() OVERRIDE { profile_manager_.reset(new TestingProfileManager(browser_process())); ASSERT_TRUE(profile_manager_->SetUp()); testing_io_thread_state_.reset(new chrome::TestingIOThreadState()); testing_io_thread_state_->io_thread_state()->globals()->host_resolver.reset( new net::MockHostResolver()); BrowserWithTestWindowTest::SetUp(); } virtual void TearDown() OVERRIDE { BrowserWithTestWindowTest::TearDown(); testing_io_thread_state_.reset(); profile_manager_.reset(); } // BrowserWithTestWindowTest overrides: virtual TestingProfile* CreateProfile() OVERRIDE { return new TestingProfileWithHostZoomMap; } private: TestingBrowserProcess* browser_process() { return TestingBrowserProcess::GetGlobal(); } scoped_ptr<TestingProfileManager> profile_manager_; scoped_ptr<chrome::TestingIOThreadState> testing_io_thread_state_; DISALLOW_COPY_AND_ASSIGN(OffTheRecordProfileImplTest); }; // Test four things: // 1. Host zoom maps of parent profile and child profile are different. // 2. Child host zoom map inherites zoom level at construction. // 3. Change of zoom level doesn't propagate from child to parent. // 4. Change of zoom level propagate from parent to child. TEST_F(OffTheRecordProfileImplTest, GetHostZoomMap) { // Constants for test case. const std::string host("example.com"); const double zoom_level_25 = 2.5; const double zoom_level_30 = 3.0; const double zoom_level_40 = 4.0; // The TestingProfile from CreateProfile above is the parent. TestingProfile* parent_profile = GetProfile(); ASSERT_TRUE(parent_profile); ASSERT_TRUE(parent_profile->GetPrefs()); ASSERT_TRUE(parent_profile->GetOffTheRecordPrefs()); // Prepare parent host zoom map. HostZoomMap* parent_zoom_map = HostZoomMap::GetForBrowserContext(parent_profile); ASSERT_TRUE(parent_zoom_map); parent_zoom_map->SetZoomLevelForHost(host, zoom_level_25); ASSERT_EQ(parent_zoom_map->GetZoomLevelForHostAndScheme("http", host), zoom_level_25); // TODO(yosin) We need to wait ProfileImpl::Observe done for // OnZoomLevelChanged. // Prepare an off the record profile owned by the parent profile. parent_profile->SetOffTheRecordProfile( scoped_ptr<Profile>(new OffTheRecordProfileImpl(parent_profile))); OffTheRecordProfileImpl* child_profile = static_cast<OffTheRecordProfileImpl*>( parent_profile->GetOffTheRecordProfile()); child_profile->InitIoData(); child_profile->InitHostZoomMap(); // Prepare child host zoom map. HostZoomMap* child_zoom_map = HostZoomMap::GetForBrowserContext(child_profile); ASSERT_TRUE(child_zoom_map); // Verify. EXPECT_NE(parent_zoom_map, child_zoom_map); EXPECT_EQ(parent_zoom_map->GetZoomLevelForHostAndScheme("http", host), child_zoom_map->GetZoomLevelForHostAndScheme("http", host)) << "Child must inherit from parent."; child_zoom_map->SetZoomLevelForHost(host, zoom_level_30); ASSERT_EQ( child_zoom_map->GetZoomLevelForHostAndScheme("http", host), zoom_level_30); EXPECT_NE(parent_zoom_map->GetZoomLevelForHostAndScheme("http", host), child_zoom_map->GetZoomLevelForHostAndScheme("http", host)) << "Child change must not propagate to parent."; parent_zoom_map->SetZoomLevelForHost(host, zoom_level_40); ASSERT_EQ( parent_zoom_map->GetZoomLevelForHostAndScheme("http", host), zoom_level_40); EXPECT_EQ(parent_zoom_map->GetZoomLevelForHostAndScheme("http", host), child_zoom_map->GetZoomLevelForHostAndScheme("http", host)) << "Parent change should propagate to child."; base::RunLoop().RunUntilIdle(); } <|endoftext|>
<commit_before>/*********************************************************************** filename: RendererBase.cpp created: Tue Apr 30 2013 authors: Paul D Turner <paul@cegui.org.uk> Lukas E Meindl *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2013 Paul D Turner & The CEGUI Development Team * * 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 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 <GL/glew.h> #include "CEGUI/RendererModules/OpenGL/RendererBase.h" #include "CEGUI/RendererModules/OpenGL/Texture.h" #include "CEGUI/RendererModules/OpenGL/TextureTarget.h" #include "CEGUI/RendererModules/OpenGL/ViewportTarget.h" #include "CEGUI/RendererModules/OpenGL/GeometryBufferBase.h" #include "CEGUI/RendererModules/OpenGL/GlmPimpl.h" #include "CEGUI/Exceptions.h" #include "CEGUI/ImageCodec.h" #include "CEGUI/DynamicModule.h" #include "CEGUI/System.h" #include "CEGUI/Logger.h" #include <sstream> #include <algorithm> namespace CEGUI { //----------------------------------------------------------------------------// String OpenGLRendererBase::d_rendererID("--- subclass did not set ID: Fix this!"); //----------------------------------------------------------------------------// OpenGLRendererBase::OpenGLRendererBase() : d_displayDPI(96, 96), d_initExtraStates(false), d_activeBlendMode(BM_INVALID), d_viewProjectionMatrix(new mat4Pimpl()), d_activeRenderTarget(0) { initialiseMaxTextureSize(); initialiseDisplaySizeWithViewportSize(); d_defaultTarget = CEGUI_NEW_AO OpenGLViewportTarget(*this); } //----------------------------------------------------------------------------// OpenGLRendererBase::OpenGLRendererBase(const Sizef& display_size) : d_displaySize(display_size), d_displayDPI(96, 96), d_initExtraStates(false), d_activeBlendMode(BM_INVALID), d_viewProjectionMatrix(new mat4Pimpl()), d_activeRenderTarget(0) { initialiseMaxTextureSize(); d_defaultTarget = CEGUI_NEW_AO OpenGLViewportTarget(*this); } //----------------------------------------------------------------------------// OpenGLRendererBase::~OpenGLRendererBase() { destroyAllGeometryBuffers(); destroyAllTextureTargets(); destroyAllTextures(); CEGUI_DELETE_AO d_defaultTarget; delete d_viewProjectionMatrix; } //----------------------------------------------------------------------------// void OpenGLRendererBase::initialiseDisplaySizeWithViewportSize() { GLint vp[4]; glGetIntegerv(GL_VIEWPORT, vp); d_displaySize = Sizef(static_cast<float>(vp[2]), static_cast<float>(vp[3])); } //----------------------------------------------------------------------------// void OpenGLRendererBase::initialiseMaxTextureSize() { GLint max_tex_size; glGetIntegerv(GL_MAX_TEXTURE_SIZE, &max_tex_size); d_maxTextureSize = max_tex_size; } //----------------------------------------------------------------------------// RenderTarget& OpenGLRendererBase::getDefaultRenderTarget() { return *d_defaultTarget; } //----------------------------------------------------------------------------// GeometryBuffer& OpenGLRendererBase::createGeometryBufferTextured(CEGUI::RefCounted<RenderMaterial> renderMaterial) { OpenGLGeometryBufferBase* b = createGeometryBuffer_impl(renderMaterial); b->appendVertexAttribute(VAT_POSITION0); b->appendVertexAttribute(VAT_COLOUR0); b->appendVertexAttribute(VAT_TEXCOORD0); b->finaliseVertexAttributes(); d_geometryBuffers.push_back(b); return *b; } //----------------------------------------------------------------------------// GeometryBuffer& OpenGLRendererBase::createGeometryBufferColoured(CEGUI::RefCounted<RenderMaterial> renderMaterial) { OpenGLGeometryBufferBase* b = createGeometryBuffer_impl(renderMaterial); b->appendVertexAttribute(VAT_POSITION0); b->appendVertexAttribute(VAT_COLOUR0); b->finaliseVertexAttributes(); d_geometryBuffers.push_back(b); return *b; } //----------------------------------------------------------------------------// void OpenGLRendererBase::destroyGeometryBuffer(const GeometryBuffer& buffer) { GeometryBufferList::iterator i = std::find(d_geometryBuffers.begin(), d_geometryBuffers.end(), &buffer); if (d_geometryBuffers.end() != i) { d_geometryBuffers.erase(i); CEGUI_DELETE_AO &buffer; } } //----------------------------------------------------------------------------// void OpenGLRendererBase::destroyAllGeometryBuffers() { while (!d_geometryBuffers.empty()) destroyGeometryBuffer(**d_geometryBuffers.begin()); } //----------------------------------------------------------------------------// TextureTarget* OpenGLRendererBase::createTextureTarget() { TextureTarget* t = createTextureTarget_impl(); if (t) d_textureTargets.push_back(t); return t; } //----------------------------------------------------------------------------// void OpenGLRendererBase::destroyTextureTarget(TextureTarget* target) { TextureTargetList::iterator i = std::find(d_textureTargets.begin(), d_textureTargets.end(), target); if (d_textureTargets.end() != i) { d_textureTargets.erase(i); CEGUI_DELETE_AO target; } } //----------------------------------------------------------------------------// void OpenGLRendererBase::destroyAllTextureTargets() { while (!d_textureTargets.empty()) destroyTextureTarget(*d_textureTargets.begin()); } //----------------------------------------------------------------------------// Texture& OpenGLRendererBase::createTexture(const String& name) { if (d_textures.find(name) != d_textures.end()) CEGUI_THROW(AlreadyExistsException( "A texture named '" + name + "' already exists.")); OpenGLTexture* tex = CEGUI_NEW_AO OpenGLTexture(*this, name); d_textures[name] = tex; logTextureCreation(name); return *tex; } //----------------------------------------------------------------------------// Texture& OpenGLRendererBase::createTexture(const String& name, const String& filename, const String& resourceGroup) { if (d_textures.find(name) != d_textures.end()) CEGUI_THROW(AlreadyExistsException( "A texture named '" + name + "' already exists.")); OpenGLTexture* tex = CEGUI_NEW_AO OpenGLTexture(*this, name, filename, resourceGroup); d_textures[name] = tex; logTextureCreation(name); return *tex; } //----------------------------------------------------------------------------// Texture& OpenGLRendererBase::createTexture(const String& name, const Sizef& size) { if (d_textures.find(name) != d_textures.end()) CEGUI_THROW(AlreadyExistsException( "A texture named '" + name + "' already exists.")); OpenGLTexture* tex = CEGUI_NEW_AO OpenGLTexture(*this, name, size); d_textures[name] = tex; logTextureCreation(name); return *tex; } //----------------------------------------------------------------------------// void OpenGLRendererBase::logTextureCreation(const String& name) { Logger* logger = Logger::getSingletonPtr(); if (logger) logger->logEvent("[OpenGLRenderer] Created texture: " + name); } //----------------------------------------------------------------------------// void OpenGLRendererBase::destroyTexture(Texture& texture) { destroyTexture(texture.getName()); } //----------------------------------------------------------------------------// void OpenGLRendererBase::destroyTexture(const String& name) { TextureMap::iterator i = d_textures.find(name); if (d_textures.end() != i) { logTextureDestruction(name); CEGUI_DELETE_AO i->second; d_textures.erase(i); } } //----------------------------------------------------------------------------// void OpenGLRendererBase::logTextureDestruction(const String& name) { Logger* logger = Logger::getSingletonPtr(); if (logger) logger->logEvent("[OpenGLRenderer] Destroyed texture: " + name); } //----------------------------------------------------------------------------// void OpenGLRendererBase::destroyAllTextures() { while (!d_textures.empty()) destroyTexture(d_textures.begin()->first); } //----------------------------------------------------------------------------// Texture& OpenGLRendererBase::getTexture(const String& name) const { TextureMap::const_iterator i = d_textures.find(name); if (i == d_textures.end()) CEGUI_THROW(UnknownObjectException( "No texture named '" + name + "' is available.")); return *i->second; } //----------------------------------------------------------------------------// bool OpenGLRendererBase::isTextureDefined(const String& name) const { return d_textures.find(name) != d_textures.end(); } //----------------------------------------------------------------------------// const Sizef& OpenGLRendererBase::getDisplaySize() const { return d_displaySize; } //----------------------------------------------------------------------------// const Vector2f& OpenGLRendererBase::getDisplayDPI() const { return d_displayDPI; } //----------------------------------------------------------------------------// uint OpenGLRendererBase::getMaxTextureSize() const { return d_maxTextureSize; } //----------------------------------------------------------------------------// const String& OpenGLRendererBase::getIdentifierString() const { return d_rendererID; } //----------------------------------------------------------------------------// Texture& OpenGLRendererBase::createTexture(const String& name, GLuint tex, const Sizef& sz) { if (d_textures.find(name) != d_textures.end()) CEGUI_THROW(AlreadyExistsException( "A texture named '" + name + "' already exists.")); OpenGLTexture* t = CEGUI_NEW_AO OpenGLTexture(*this, name, tex, sz); d_textures[name] = t; logTextureCreation(name); return *t; } //----------------------------------------------------------------------------// void OpenGLRendererBase::setDisplaySize(const Sizef& sz) { if (sz != d_displaySize) { d_displaySize = sz; // update the default target's area Rectf area(d_defaultTarget->getArea()); area.setSize(sz); d_defaultTarget->setArea(area); } } //----------------------------------------------------------------------------// void OpenGLRendererBase::enableExtraStateSettings(bool setting) { d_initExtraStates = setting; } //----------------------------------------------------------------------------// void OpenGLRendererBase::grabTextures() { // perform grab operations for texture targets TextureTargetList::iterator target_iterator = d_textureTargets.begin(); for (; target_iterator != d_textureTargets.end(); ++target_iterator) static_cast<OpenGLTextureTarget*>(*target_iterator)->grabTexture(); // perform grab on regular textures TextureMap::iterator texture_iterator = d_textures.begin(); for (; texture_iterator != d_textures.end(); ++texture_iterator) texture_iterator->second->grabTexture(); } //----------------------------------------------------------------------------// void OpenGLRendererBase::restoreTextures() { // perform restore on textures TextureMap::iterator texture_iterator = d_textures.begin(); for (; texture_iterator != d_textures.end(); ++texture_iterator) texture_iterator->second->restoreTexture(); // perform restore operations for texture targets TextureTargetList::iterator target_iterator = d_textureTargets.begin(); for (; target_iterator != d_textureTargets.end(); ++target_iterator) static_cast<OpenGLTextureTarget*>(*target_iterator)->restoreTexture(); } //----------------------------------------------------------------------------// Sizef OpenGLRendererBase::getAdjustedTextureSize(const Sizef& sz) const { Sizef out(sz); // if we can't support non power of two sizes, get appropriate POT values. if (!GLEW_ARB_texture_non_power_of_two) { out.d_width = getNextPOTSize(out.d_width); out.d_height = getNextPOTSize(out.d_height); } return out; } //----------------------------------------------------------------------------// float OpenGLRendererBase::getNextPOTSize(const float f) { uint size = static_cast<uint>(f); // if not power of 2 if ((size & (size - 1)) || !size) { int log = 0; // get integer log of 'size' to base 2 while (size >>= 1) ++log; // use log to calculate value to use as size. size = (2 << log); } return static_cast<float>(size); } //----------------------------------------------------------------------------// const mat4Pimpl* OpenGLRendererBase::getViewProjectionMatrix() { return d_viewProjectionMatrix; } //----------------------------------------------------------------------------// void OpenGLRendererBase::setViewProjectionMatrix(const mat4Pimpl* viewProjectionMatrix) { *d_viewProjectionMatrix = *viewProjectionMatrix; } //----------------------------------------------------------------------------// const CEGUI::Rectf& OpenGLRendererBase::getActiveViewPort() { return d_activeRenderTarget->getArea(); } //----------------------------------------------------------------------------// void OpenGLRendererBase::setActiveRenderTarget(RenderTarget* renderTarget) { d_activeRenderTarget = renderTarget; } //----------------------------------------------------------------------------// RenderTarget* OpenGLRendererBase::getActiveRenderTarget() { return d_activeRenderTarget; } //----------------------------------------------------------------------------// } <commit_msg>MOD: Fixing renamed function calls<commit_after>/*********************************************************************** filename: RendererBase.cpp created: Tue Apr 30 2013 authors: Paul D Turner <paul@cegui.org.uk> Lukas E Meindl *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2013 Paul D Turner & The CEGUI Development Team * * 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 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 <GL/glew.h> #include "CEGUI/RendererModules/OpenGL/RendererBase.h" #include "CEGUI/RendererModules/OpenGL/Texture.h" #include "CEGUI/RendererModules/OpenGL/TextureTarget.h" #include "CEGUI/RendererModules/OpenGL/ViewportTarget.h" #include "CEGUI/RendererModules/OpenGL/GeometryBufferBase.h" #include "CEGUI/RendererModules/OpenGL/GlmPimpl.h" #include "CEGUI/Exceptions.h" #include "CEGUI/ImageCodec.h" #include "CEGUI/DynamicModule.h" #include "CEGUI/System.h" #include "CEGUI/Logger.h" #include <sstream> #include <algorithm> namespace CEGUI { //----------------------------------------------------------------------------// String OpenGLRendererBase::d_rendererID("--- subclass did not set ID: Fix this!"); //----------------------------------------------------------------------------// OpenGLRendererBase::OpenGLRendererBase() : d_displayDPI(96, 96), d_initExtraStates(false), d_activeBlendMode(BM_INVALID), d_viewProjectionMatrix(new mat4Pimpl()), d_activeRenderTarget(0) { initialiseMaxTextureSize(); initialiseDisplaySizeWithViewportSize(); d_defaultTarget = CEGUI_NEW_AO OpenGLViewportTarget(*this); } //----------------------------------------------------------------------------// OpenGLRendererBase::OpenGLRendererBase(const Sizef& display_size) : d_displaySize(display_size), d_displayDPI(96, 96), d_initExtraStates(false), d_activeBlendMode(BM_INVALID), d_viewProjectionMatrix(new mat4Pimpl()), d_activeRenderTarget(0) { initialiseMaxTextureSize(); d_defaultTarget = CEGUI_NEW_AO OpenGLViewportTarget(*this); } //----------------------------------------------------------------------------// OpenGLRendererBase::~OpenGLRendererBase() { destroyAllGeometryBuffers(); destroyAllTextureTargets(); destroyAllTextures(); CEGUI_DELETE_AO d_defaultTarget; delete d_viewProjectionMatrix; } //----------------------------------------------------------------------------// void OpenGLRendererBase::initialiseDisplaySizeWithViewportSize() { GLint vp[4]; glGetIntegerv(GL_VIEWPORT, vp); d_displaySize = Sizef(static_cast<float>(vp[2]), static_cast<float>(vp[3])); } //----------------------------------------------------------------------------// void OpenGLRendererBase::initialiseMaxTextureSize() { GLint max_tex_size; glGetIntegerv(GL_MAX_TEXTURE_SIZE, &max_tex_size); d_maxTextureSize = max_tex_size; } //----------------------------------------------------------------------------// RenderTarget& OpenGLRendererBase::getDefaultRenderTarget() { return *d_defaultTarget; } //----------------------------------------------------------------------------// GeometryBuffer& OpenGLRendererBase::createGeometryBufferTextured(CEGUI::RefCounted<RenderMaterial> renderMaterial) { OpenGLGeometryBufferBase* b = createGeometryBuffer_impl(renderMaterial); b->addVertexAttribute(VAT_POSITION0); b->addVertexAttribute(VAT_COLOUR0); b->addVertexAttribute(VAT_TEXCOORD0); b->finaliseVertexAttributes(); d_geometryBuffers.push_back(b); return *b; } //----------------------------------------------------------------------------// GeometryBuffer& OpenGLRendererBase::createGeometryBufferColoured(CEGUI::RefCounted<RenderMaterial> renderMaterial) { OpenGLGeometryBufferBase* b = createGeometryBuffer_impl(renderMaterial); b->addVertexAttribute(VAT_POSITION0); b->addVertexAttribute(VAT_COLOUR0); b->finaliseVertexAttributes(); d_geometryBuffers.push_back(b); return *b; } //----------------------------------------------------------------------------// void OpenGLRendererBase::destroyGeometryBuffer(const GeometryBuffer& buffer) { GeometryBufferList::iterator i = std::find(d_geometryBuffers.begin(), d_geometryBuffers.end(), &buffer); if (d_geometryBuffers.end() != i) { d_geometryBuffers.erase(i); CEGUI_DELETE_AO &buffer; } } //----------------------------------------------------------------------------// void OpenGLRendererBase::destroyAllGeometryBuffers() { while (!d_geometryBuffers.empty()) destroyGeometryBuffer(**d_geometryBuffers.begin()); } //----------------------------------------------------------------------------// TextureTarget* OpenGLRendererBase::createTextureTarget() { TextureTarget* t = createTextureTarget_impl(); if (t) d_textureTargets.push_back(t); return t; } //----------------------------------------------------------------------------// void OpenGLRendererBase::destroyTextureTarget(TextureTarget* target) { TextureTargetList::iterator i = std::find(d_textureTargets.begin(), d_textureTargets.end(), target); if (d_textureTargets.end() != i) { d_textureTargets.erase(i); CEGUI_DELETE_AO target; } } //----------------------------------------------------------------------------// void OpenGLRendererBase::destroyAllTextureTargets() { while (!d_textureTargets.empty()) destroyTextureTarget(*d_textureTargets.begin()); } //----------------------------------------------------------------------------// Texture& OpenGLRendererBase::createTexture(const String& name) { if (d_textures.find(name) != d_textures.end()) CEGUI_THROW(AlreadyExistsException( "A texture named '" + name + "' already exists.")); OpenGLTexture* tex = CEGUI_NEW_AO OpenGLTexture(*this, name); d_textures[name] = tex; logTextureCreation(name); return *tex; } //----------------------------------------------------------------------------// Texture& OpenGLRendererBase::createTexture(const String& name, const String& filename, const String& resourceGroup) { if (d_textures.find(name) != d_textures.end()) CEGUI_THROW(AlreadyExistsException( "A texture named '" + name + "' already exists.")); OpenGLTexture* tex = CEGUI_NEW_AO OpenGLTexture(*this, name, filename, resourceGroup); d_textures[name] = tex; logTextureCreation(name); return *tex; } //----------------------------------------------------------------------------// Texture& OpenGLRendererBase::createTexture(const String& name, const Sizef& size) { if (d_textures.find(name) != d_textures.end()) CEGUI_THROW(AlreadyExistsException( "A texture named '" + name + "' already exists.")); OpenGLTexture* tex = CEGUI_NEW_AO OpenGLTexture(*this, name, size); d_textures[name] = tex; logTextureCreation(name); return *tex; } //----------------------------------------------------------------------------// void OpenGLRendererBase::logTextureCreation(const String& name) { Logger* logger = Logger::getSingletonPtr(); if (logger) logger->logEvent("[OpenGLRenderer] Created texture: " + name); } //----------------------------------------------------------------------------// void OpenGLRendererBase::destroyTexture(Texture& texture) { destroyTexture(texture.getName()); } //----------------------------------------------------------------------------// void OpenGLRendererBase::destroyTexture(const String& name) { TextureMap::iterator i = d_textures.find(name); if (d_textures.end() != i) { logTextureDestruction(name); CEGUI_DELETE_AO i->second; d_textures.erase(i); } } //----------------------------------------------------------------------------// void OpenGLRendererBase::logTextureDestruction(const String& name) { Logger* logger = Logger::getSingletonPtr(); if (logger) logger->logEvent("[OpenGLRenderer] Destroyed texture: " + name); } //----------------------------------------------------------------------------// void OpenGLRendererBase::destroyAllTextures() { while (!d_textures.empty()) destroyTexture(d_textures.begin()->first); } //----------------------------------------------------------------------------// Texture& OpenGLRendererBase::getTexture(const String& name) const { TextureMap::const_iterator i = d_textures.find(name); if (i == d_textures.end()) CEGUI_THROW(UnknownObjectException( "No texture named '" + name + "' is available.")); return *i->second; } //----------------------------------------------------------------------------// bool OpenGLRendererBase::isTextureDefined(const String& name) const { return d_textures.find(name) != d_textures.end(); } //----------------------------------------------------------------------------// const Sizef& OpenGLRendererBase::getDisplaySize() const { return d_displaySize; } //----------------------------------------------------------------------------// const Vector2f& OpenGLRendererBase::getDisplayDPI() const { return d_displayDPI; } //----------------------------------------------------------------------------// uint OpenGLRendererBase::getMaxTextureSize() const { return d_maxTextureSize; } //----------------------------------------------------------------------------// const String& OpenGLRendererBase::getIdentifierString() const { return d_rendererID; } //----------------------------------------------------------------------------// Texture& OpenGLRendererBase::createTexture(const String& name, GLuint tex, const Sizef& sz) { if (d_textures.find(name) != d_textures.end()) CEGUI_THROW(AlreadyExistsException( "A texture named '" + name + "' already exists.")); OpenGLTexture* t = CEGUI_NEW_AO OpenGLTexture(*this, name, tex, sz); d_textures[name] = t; logTextureCreation(name); return *t; } //----------------------------------------------------------------------------// void OpenGLRendererBase::setDisplaySize(const Sizef& sz) { if (sz != d_displaySize) { d_displaySize = sz; // update the default target's area Rectf area(d_defaultTarget->getArea()); area.setSize(sz); d_defaultTarget->setArea(area); } } //----------------------------------------------------------------------------// void OpenGLRendererBase::enableExtraStateSettings(bool setting) { d_initExtraStates = setting; } //----------------------------------------------------------------------------// void OpenGLRendererBase::grabTextures() { // perform grab operations for texture targets TextureTargetList::iterator target_iterator = d_textureTargets.begin(); for (; target_iterator != d_textureTargets.end(); ++target_iterator) static_cast<OpenGLTextureTarget*>(*target_iterator)->grabTexture(); // perform grab on regular textures TextureMap::iterator texture_iterator = d_textures.begin(); for (; texture_iterator != d_textures.end(); ++texture_iterator) texture_iterator->second->grabTexture(); } //----------------------------------------------------------------------------// void OpenGLRendererBase::restoreTextures() { // perform restore on textures TextureMap::iterator texture_iterator = d_textures.begin(); for (; texture_iterator != d_textures.end(); ++texture_iterator) texture_iterator->second->restoreTexture(); // perform restore operations for texture targets TextureTargetList::iterator target_iterator = d_textureTargets.begin(); for (; target_iterator != d_textureTargets.end(); ++target_iterator) static_cast<OpenGLTextureTarget*>(*target_iterator)->restoreTexture(); } //----------------------------------------------------------------------------// Sizef OpenGLRendererBase::getAdjustedTextureSize(const Sizef& sz) const { Sizef out(sz); // if we can't support non power of two sizes, get appropriate POT values. if (!GLEW_ARB_texture_non_power_of_two) { out.d_width = getNextPOTSize(out.d_width); out.d_height = getNextPOTSize(out.d_height); } return out; } //----------------------------------------------------------------------------// float OpenGLRendererBase::getNextPOTSize(const float f) { uint size = static_cast<uint>(f); // if not power of 2 if ((size & (size - 1)) || !size) { int log = 0; // get integer log of 'size' to base 2 while (size >>= 1) ++log; // use log to calculate value to use as size. size = (2 << log); } return static_cast<float>(size); } //----------------------------------------------------------------------------// const mat4Pimpl* OpenGLRendererBase::getViewProjectionMatrix() { return d_viewProjectionMatrix; } //----------------------------------------------------------------------------// void OpenGLRendererBase::setViewProjectionMatrix(const mat4Pimpl* viewProjectionMatrix) { *d_viewProjectionMatrix = *viewProjectionMatrix; } //----------------------------------------------------------------------------// const CEGUI::Rectf& OpenGLRendererBase::getActiveViewPort() { return d_activeRenderTarget->getArea(); } //----------------------------------------------------------------------------// void OpenGLRendererBase::setActiveRenderTarget(RenderTarget* renderTarget) { d_activeRenderTarget = renderTarget; } //----------------------------------------------------------------------------// RenderTarget* OpenGLRendererBase::getActiveRenderTarget() { return d_activeRenderTarget; } //----------------------------------------------------------------------------// } <|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 <oleacc.h> #include "app/l10n_util.h" #include "base/scoped_comptr_win.h" #include "chrome/browser/browser.h" #include "chrome/browser/browser_window.h" #include "chrome/browser/view_ids.h" #include "chrome/browser/views/bookmark_bar_view.h" #include "chrome/browser/views/frame/browser_view.h" #include "chrome/browser/views/toolbar_view.h" #include "chrome/common/url_constants.h" #include "chrome/test/in_process_browser_test.h" #include "chrome/test/ui_test_utils.h" #include "grit/chromium_strings.h" #include "grit/generated_resources.h" #include "views/accessibility/view_accessibility_wrapper.h" #include "views/widget/root_view.h" #include "views/widget/widget_win.h" #include "views/window/window.h" namespace { VARIANT id_self = {VT_I4, CHILDID_SELF}; // Dummy class to force creation of ATL module, needed by COM to instantiate // ViewAccessibility. class TestAtlModule : public CAtlDllModuleT< TestAtlModule > {}; TestAtlModule test_atl_module_; class BrowserViewsAccessibilityTest : public InProcessBrowserTest { public: BrowserViewsAccessibilityTest() { ::CoInitialize(NULL); } ~BrowserViewsAccessibilityTest() { ::CoUninitialize(); } // Retrieves an instance of BrowserWindowTesting BrowserWindowTesting* GetBrowserWindowTesting() { BrowserWindow* browser_window = browser()->window(); if (!browser_window) return NULL; return browser_window->GetBrowserWindowTesting(); } // Retrieve an instance of BrowserView BrowserView* GetBrowserView() { return BrowserView::GetBrowserViewForNativeWindow( browser()->window()->GetNativeHandle()); } // Retrieves and initializes an instance of LocationBarView. LocationBarView* GetLocationBarView() { BrowserWindowTesting* browser_window_testing = GetBrowserWindowTesting(); if (!browser_window_testing) return NULL; return GetBrowserWindowTesting()->GetLocationBarView(); } // Retrieves and initializes an instance of ToolbarView. ToolbarView* GetToolbarView() { BrowserWindowTesting* browser_window_testing = GetBrowserWindowTesting(); if (!browser_window_testing) return NULL; return browser_window_testing->GetToolbarView(); } // Retrieves and initializes an instance of BookmarkBarView. BookmarkBarView* GetBookmarkBarView() { BrowserWindowTesting* browser_window_testing = GetBrowserWindowTesting(); if (!browser_window_testing) return NULL; return browser_window_testing->GetBookmarkBarView(); } // Retrieves and verifies the accessibility object for the given View. void TestViewAccessibilityObject(views::View* view, std::wstring name, int32 role) { ASSERT_TRUE(NULL != view); IAccessible* acc_obj = NULL; HRESULT hr = view->GetViewAccessibilityWrapper()->GetInstance( IID_IAccessible, reinterpret_cast<void**>(&acc_obj)); ASSERT_EQ(S_OK, hr); ASSERT_TRUE(NULL != acc_obj); TestAccessibilityInfo(acc_obj, name, role); } // Verifies MSAA Name and Role properties of the given IAccessible. void TestAccessibilityInfo(IAccessible* acc_obj, std::wstring name, int32 role) { // Verify MSAA Name property. BSTR acc_name; HRESULT hr = acc_obj->get_accName(id_self, &acc_name); ASSERT_EQ(S_OK, hr); EXPECT_STREQ(acc_name, name.c_str()); // Verify MSAA Role property. VARIANT acc_role; ::VariantInit(&acc_role); hr = acc_obj->get_accRole(id_self, &acc_role); ASSERT_EQ(S_OK, hr); EXPECT_EQ(VT_I4, acc_role.vt); EXPECT_EQ(role, acc_role.lVal); ::VariantClear(&acc_role); ::SysFreeString(acc_name); } }; // Retrieve accessibility object for main window and verify accessibility info. // Fails, http://crbug.com/44486. IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, FAILS_TestChromeWindowAccObj) { BrowserWindow* browser_window = browser()->window(); ASSERT_TRUE(NULL != browser_window); HWND hwnd = browser_window->GetNativeHandle(); ASSERT_TRUE(NULL != hwnd); // Get accessibility object. ScopedComPtr<IAccessible> acc_obj; HRESULT hr = ::AccessibleObjectFromWindow(hwnd, OBJID_WINDOW, IID_IAccessible, reinterpret_cast<void**>(&acc_obj)); ASSERT_EQ(S_OK, hr); ASSERT_TRUE(NULL != acc_obj); ui_test_utils::NavigateToURL(browser(), GURL(chrome::kAboutBlankURL)); std::wstring title = l10n_util::GetStringF(IDS_BROWSER_WINDOW_TITLE_FORMAT, ASCIIToWide(chrome::kAboutBlankURL)); TestAccessibilityInfo(acc_obj, title, ROLE_SYSTEM_WINDOW); } // Retrieve accessibility object for non client view and verify accessibility // info. IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestNonClientViewAccObj) { views::View* non_client_view = GetBrowserView()->GetWindow()->GetNonClientView(); TestViewAccessibilityObject(non_client_view, l10n_util::GetString(IDS_PRODUCT_NAME), ROLE_SYSTEM_WINDOW); } // Retrieve accessibility object for browser root view and verify // accessibility info. IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestBrowserRootViewAccObj) { views::View* browser_root_view = GetBrowserView()->frame()->GetFrameView()->GetRootView(); TestViewAccessibilityObject(browser_root_view, l10n_util::GetString(IDS_PRODUCT_NAME), ROLE_SYSTEM_APPLICATION); } // Retrieve accessibility object for browser view and verify accessibility info. IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestBrowserViewAccObj) { // Verify root view MSAA name and role. TestViewAccessibilityObject(GetBrowserView(), l10n_util::GetString(IDS_PRODUCT_NAME), ROLE_SYSTEM_CLIENT); } // Retrieve accessibility object for toolbar view and verify accessibility info. IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestToolbarViewAccObj) { // Verify toolbar MSAA name and role. TestViewAccessibilityObject(GetToolbarView(), l10n_util::GetString(IDS_ACCNAME_TOOLBAR), ROLE_SYSTEM_TOOLBAR); } // Retrieve accessibility object for Back button and verify accessibility info. IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestBackButtonAccObj) { // Verify Back button MSAA name and role. TestViewAccessibilityObject( GetToolbarView()->GetViewByID(VIEW_ID_BACK_BUTTON), l10n_util::GetString(IDS_ACCNAME_BACK), ROLE_SYSTEM_BUTTONDROPDOWN); } // Retrieve accessibility object for Forward button and verify accessibility // info. IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestForwardButtonAccObj) { // Verify Forward button MSAA name and role. TestViewAccessibilityObject( GetToolbarView()->GetViewByID(VIEW_ID_FORWARD_BUTTON), l10n_util::GetString(IDS_ACCNAME_FORWARD), ROLE_SYSTEM_BUTTONDROPDOWN); } // Retrieve accessibility object for Reload button and verify accessibility // info. IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestReloadButtonAccObj) { // Verify Reload button MSAA name and role. TestViewAccessibilityObject( GetToolbarView()->GetViewByID(VIEW_ID_RELOAD_BUTTON), l10n_util::GetString(IDS_ACCNAME_RELOAD), ROLE_SYSTEM_PUSHBUTTON); } // Retrieve accessibility object for Home button and verify accessibility info. IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestHomeButtonAccObj) { // Verify Home button MSAA name and role. TestViewAccessibilityObject( GetToolbarView()->GetViewByID(VIEW_ID_HOME_BUTTON), l10n_util::GetString(IDS_ACCNAME_HOME), ROLE_SYSTEM_PUSHBUTTON); } // Retrieve accessibility object for Star button and verify accessibility info. IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestStarButtonAccObj) { // Verify Star button MSAA name and role. TestViewAccessibilityObject( GetToolbarView()->GetViewByID(VIEW_ID_STAR_BUTTON), l10n_util::GetString(IDS_ACCNAME_STAR), ROLE_SYSTEM_PUSHBUTTON); } // Retrieve accessibility object for location bar view and verify accessibility // info. IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestLocationBarViewAccObj) { // Verify location bar MSAA name and role. TestViewAccessibilityObject(GetLocationBarView(), l10n_util::GetString(IDS_ACCNAME_LOCATION), ROLE_SYSTEM_GROUPING); } // Retrieve accessibility object for Go button and verify accessibility info. IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestGoButtonAccObj) { // Verify Go button MSAA name and role. TestViewAccessibilityObject(GetToolbarView()->GetViewByID(VIEW_ID_GO_BUTTON), l10n_util::GetString(IDS_ACCNAME_GO), ROLE_SYSTEM_PUSHBUTTON); } // Retrieve accessibility object for Page menu button and verify accessibility // info. IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestPageMenuAccObj) { // Verify Page menu button MSAA name and role. TestViewAccessibilityObject(GetToolbarView()->GetViewByID(VIEW_ID_PAGE_MENU), l10n_util::GetString(IDS_ACCNAME_PAGE), ROLE_SYSTEM_BUTTONMENU); } // Retrieve accessibility object for App menu button and verify accessibility // info. IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestAppMenuAccObj) { // Verify App menu button MSAA name and role. TestViewAccessibilityObject(GetToolbarView()->GetViewByID(VIEW_ID_APP_MENU), l10n_util::GetString(IDS_ACCNAME_APP), ROLE_SYSTEM_BUTTONMENU); } IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestBookmarkBarViewAccObj) { TestViewAccessibilityObject(GetBookmarkBarView(), l10n_util::GetString(IDS_ACCNAME_BOOKMARKS), ROLE_SYSTEM_TOOLBAR); } IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestAboutChromeViewAccObj) { // Firstly, test that the WindowDelegate got updated. views::Window* aboutChromeWindow = GetBrowserView()->ShowAboutChromeDialog(); EXPECT_STREQ(aboutChromeWindow->GetDelegate()->GetWindowTitle().c_str(), l10n_util::GetString(IDS_ABOUT_CHROME_TITLE).c_str()); EXPECT_EQ(aboutChromeWindow->GetDelegate()->accessible_role(), AccessibilityTypes::ROLE_DIALOG); // Also test the accessibility object directly. IAccessible* acc_obj = NULL; HRESULT hr = ::AccessibleObjectFromWindow(aboutChromeWindow->GetNativeWindow(), OBJID_CLIENT, IID_IAccessible, reinterpret_cast<void**>(&acc_obj)); ASSERT_EQ(S_OK, hr); ASSERT_TRUE(NULL != acc_obj); TestAccessibilityInfo(acc_obj, l10n_util::GetString(IDS_ABOUT_CHROME_TITLE), ROLE_SYSTEM_DIALOG); acc_obj->Release(); } } // Namespace. <commit_msg>Re-enabling TestChromeWindowAccObj.<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 <oleacc.h> #include "app/l10n_util.h" #include "base/scoped_comptr_win.h" #include "chrome/browser/browser.h" #include "chrome/browser/browser_window.h" #include "chrome/browser/view_ids.h" #include "chrome/browser/views/bookmark_bar_view.h" #include "chrome/browser/views/frame/browser_view.h" #include "chrome/browser/views/toolbar_view.h" #include "chrome/common/url_constants.h" #include "chrome/test/in_process_browser_test.h" #include "chrome/test/ui_test_utils.h" #include "grit/chromium_strings.h" #include "grit/generated_resources.h" #include "views/accessibility/view_accessibility_wrapper.h" #include "views/widget/root_view.h" #include "views/widget/widget_win.h" #include "views/window/window.h" namespace { VARIANT id_self = {VT_I4, CHILDID_SELF}; // Dummy class to force creation of ATL module, needed by COM to instantiate // ViewAccessibility. class TestAtlModule : public CAtlDllModuleT< TestAtlModule > {}; TestAtlModule test_atl_module_; class BrowserViewsAccessibilityTest : public InProcessBrowserTest { public: BrowserViewsAccessibilityTest() { ::CoInitialize(NULL); } ~BrowserViewsAccessibilityTest() { ::CoUninitialize(); } // Retrieves an instance of BrowserWindowTesting BrowserWindowTesting* GetBrowserWindowTesting() { BrowserWindow* browser_window = browser()->window(); if (!browser_window) return NULL; return browser_window->GetBrowserWindowTesting(); } // Retrieve an instance of BrowserView BrowserView* GetBrowserView() { return BrowserView::GetBrowserViewForNativeWindow( browser()->window()->GetNativeHandle()); } // Retrieves and initializes an instance of LocationBarView. LocationBarView* GetLocationBarView() { BrowserWindowTesting* browser_window_testing = GetBrowserWindowTesting(); if (!browser_window_testing) return NULL; return GetBrowserWindowTesting()->GetLocationBarView(); } // Retrieves and initializes an instance of ToolbarView. ToolbarView* GetToolbarView() { BrowserWindowTesting* browser_window_testing = GetBrowserWindowTesting(); if (!browser_window_testing) return NULL; return browser_window_testing->GetToolbarView(); } // Retrieves and initializes an instance of BookmarkBarView. BookmarkBarView* GetBookmarkBarView() { BrowserWindowTesting* browser_window_testing = GetBrowserWindowTesting(); if (!browser_window_testing) return NULL; return browser_window_testing->GetBookmarkBarView(); } // Retrieves and verifies the accessibility object for the given View. void TestViewAccessibilityObject(views::View* view, std::wstring name, int32 role) { ASSERT_TRUE(NULL != view); IAccessible* acc_obj = NULL; HRESULT hr = view->GetViewAccessibilityWrapper()->GetInstance( IID_IAccessible, reinterpret_cast<void**>(&acc_obj)); ASSERT_EQ(S_OK, hr); ASSERT_TRUE(NULL != acc_obj); TestAccessibilityInfo(acc_obj, name, role); } // Verifies MSAA Name and Role properties of the given IAccessible. void TestAccessibilityInfo(IAccessible* acc_obj, std::wstring name, int32 role) { // Verify MSAA Name property. BSTR acc_name; HRESULT hr = acc_obj->get_accName(id_self, &acc_name); ASSERT_EQ(S_OK, hr); EXPECT_STREQ(acc_name, name.c_str()); // Verify MSAA Role property. VARIANT acc_role; ::VariantInit(&acc_role); hr = acc_obj->get_accRole(id_self, &acc_role); ASSERT_EQ(S_OK, hr); EXPECT_EQ(VT_I4, acc_role.vt); EXPECT_EQ(role, acc_role.lVal); ::VariantClear(&acc_role); ::SysFreeString(acc_name); } }; // Retrieve accessibility object for main window and verify accessibility info. IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestChromeWindowAccObj) { BrowserWindow* browser_window = browser()->window(); ASSERT_TRUE(NULL != browser_window); HWND hwnd = browser_window->GetNativeHandle(); ASSERT_TRUE(NULL != hwnd); // Get accessibility object. ScopedComPtr<IAccessible> acc_obj; HRESULT hr = ::AccessibleObjectFromWindow(hwnd, OBJID_WINDOW, IID_IAccessible, reinterpret_cast<void**>(&acc_obj)); ASSERT_EQ(S_OK, hr); ASSERT_TRUE(NULL != acc_obj); ui_test_utils::NavigateToURL(browser(), GURL(chrome::kAboutBlankURL)); std::wstring title = l10n_util::GetStringF(IDS_BROWSER_WINDOW_TITLE_FORMAT, ASCIIToWide(chrome::kAboutBlankURL)); TestAccessibilityInfo(acc_obj, title, ROLE_SYSTEM_WINDOW); } // Retrieve accessibility object for non client view and verify accessibility // info. IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestNonClientViewAccObj) { views::View* non_client_view = GetBrowserView()->GetWindow()->GetNonClientView(); TestViewAccessibilityObject(non_client_view, l10n_util::GetString(IDS_PRODUCT_NAME), ROLE_SYSTEM_WINDOW); } // Retrieve accessibility object for browser root view and verify // accessibility info. IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestBrowserRootViewAccObj) { views::View* browser_root_view = GetBrowserView()->frame()->GetFrameView()->GetRootView(); TestViewAccessibilityObject(browser_root_view, l10n_util::GetString(IDS_PRODUCT_NAME), ROLE_SYSTEM_APPLICATION); } // Retrieve accessibility object for browser view and verify accessibility info. IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestBrowserViewAccObj) { // Verify root view MSAA name and role. TestViewAccessibilityObject(GetBrowserView(), l10n_util::GetString(IDS_PRODUCT_NAME), ROLE_SYSTEM_CLIENT); } // Retrieve accessibility object for toolbar view and verify accessibility info. IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestToolbarViewAccObj) { // Verify toolbar MSAA name and role. TestViewAccessibilityObject(GetToolbarView(), l10n_util::GetString(IDS_ACCNAME_TOOLBAR), ROLE_SYSTEM_TOOLBAR); } // Retrieve accessibility object for Back button and verify accessibility info. IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestBackButtonAccObj) { // Verify Back button MSAA name and role. TestViewAccessibilityObject( GetToolbarView()->GetViewByID(VIEW_ID_BACK_BUTTON), l10n_util::GetString(IDS_ACCNAME_BACK), ROLE_SYSTEM_BUTTONDROPDOWN); } // Retrieve accessibility object for Forward button and verify accessibility // info. IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestForwardButtonAccObj) { // Verify Forward button MSAA name and role. TestViewAccessibilityObject( GetToolbarView()->GetViewByID(VIEW_ID_FORWARD_BUTTON), l10n_util::GetString(IDS_ACCNAME_FORWARD), ROLE_SYSTEM_BUTTONDROPDOWN); } // Retrieve accessibility object for Reload button and verify accessibility // info. IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestReloadButtonAccObj) { // Verify Reload button MSAA name and role. TestViewAccessibilityObject( GetToolbarView()->GetViewByID(VIEW_ID_RELOAD_BUTTON), l10n_util::GetString(IDS_ACCNAME_RELOAD), ROLE_SYSTEM_PUSHBUTTON); } // Retrieve accessibility object for Home button and verify accessibility info. IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestHomeButtonAccObj) { // Verify Home button MSAA name and role. TestViewAccessibilityObject( GetToolbarView()->GetViewByID(VIEW_ID_HOME_BUTTON), l10n_util::GetString(IDS_ACCNAME_HOME), ROLE_SYSTEM_PUSHBUTTON); } // Retrieve accessibility object for Star button and verify accessibility info. IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestStarButtonAccObj) { // Verify Star button MSAA name and role. TestViewAccessibilityObject( GetToolbarView()->GetViewByID(VIEW_ID_STAR_BUTTON), l10n_util::GetString(IDS_ACCNAME_STAR), ROLE_SYSTEM_PUSHBUTTON); } // Retrieve accessibility object for location bar view and verify accessibility // info. IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestLocationBarViewAccObj) { // Verify location bar MSAA name and role. TestViewAccessibilityObject(GetLocationBarView(), l10n_util::GetString(IDS_ACCNAME_LOCATION), ROLE_SYSTEM_GROUPING); } // Retrieve accessibility object for Go button and verify accessibility info. IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestGoButtonAccObj) { // Verify Go button MSAA name and role. TestViewAccessibilityObject(GetToolbarView()->GetViewByID(VIEW_ID_GO_BUTTON), l10n_util::GetString(IDS_ACCNAME_GO), ROLE_SYSTEM_PUSHBUTTON); } // Retrieve accessibility object for Page menu button and verify accessibility // info. IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestPageMenuAccObj) { // Verify Page menu button MSAA name and role. TestViewAccessibilityObject(GetToolbarView()->GetViewByID(VIEW_ID_PAGE_MENU), l10n_util::GetString(IDS_ACCNAME_PAGE), ROLE_SYSTEM_BUTTONMENU); } // Retrieve accessibility object for App menu button and verify accessibility // info. IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestAppMenuAccObj) { // Verify App menu button MSAA name and role. TestViewAccessibilityObject(GetToolbarView()->GetViewByID(VIEW_ID_APP_MENU), l10n_util::GetString(IDS_ACCNAME_APP), ROLE_SYSTEM_BUTTONMENU); } IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestBookmarkBarViewAccObj) { TestViewAccessibilityObject(GetBookmarkBarView(), l10n_util::GetString(IDS_ACCNAME_BOOKMARKS), ROLE_SYSTEM_TOOLBAR); } IN_PROC_BROWSER_TEST_F(BrowserViewsAccessibilityTest, TestAboutChromeViewAccObj) { // Firstly, test that the WindowDelegate got updated. views::Window* aboutChromeWindow = GetBrowserView()->ShowAboutChromeDialog(); EXPECT_STREQ(aboutChromeWindow->GetDelegate()->GetWindowTitle().c_str(), l10n_util::GetString(IDS_ABOUT_CHROME_TITLE).c_str()); EXPECT_EQ(aboutChromeWindow->GetDelegate()->accessible_role(), AccessibilityTypes::ROLE_DIALOG); // Also test the accessibility object directly. IAccessible* acc_obj = NULL; HRESULT hr = ::AccessibleObjectFromWindow(aboutChromeWindow->GetNativeWindow(), OBJID_CLIENT, IID_IAccessible, reinterpret_cast<void**>(&acc_obj)); ASSERT_EQ(S_OK, hr); ASSERT_TRUE(NULL != acc_obj); TestAccessibilityInfo(acc_obj, l10n_util::GetString(IDS_ABOUT_CHROME_TITLE), ROLE_SYSTEM_DIALOG); acc_obj->Release(); } } // Namespace. <|endoftext|>
<commit_before>#ifndef ALEPH_SIMPLEX_HH__ #define ALEPH_SIMPLEX_HH__ #include <algorithm> #include <initializer_list> #include <iosfwd> #include <stdexcept> #include <vector> #include <boost/functional/hash.hpp> #include <boost/iterator/iterator_adaptor.hpp> #include <boost/iterator/filter_iterator.hpp> namespace aleph { template < class DataType, class VertexType = unsigned short > class Simplex { public: // Aliases & declarations ------------------------------------------- // // Note that these aliases follow the STL conventions in order to make it // easier to use the class with STL algorithms. using data_type = DataType; using vertex_type = VertexType; using vertex_container_type = std::vector<vertex_type>; using vertex_iterator = typename vertex_container_type::iterator; using const_vertex_iterator = typename vertex_container_type::const_iterator; using reverse_vertex_iterator = typename vertex_container_type::reverse_iterator; using const_reverse_vertex_iterator = typename vertex_container_type::const_reverse_iterator; // I cannot describe the class inline because boost::iterator_adaptor expects // a _complete_ class. class boundary_iterator; // Constructors ------------------------------------------------------ /** Creates an empty simplex */ Simplex() : _data( Data() ) { } /** Creates a new 0-simplex from the given vertex. @param u Vertex @param data Data to assign to simplex */ Simplex( VertexType u, DataType data = DataType() ) : _vertices( 1, u ) , _data( data ) { } /** Creates a new simplex from another simplex while setting the data for the new simplex. This is handy for copying the vertices but not the data of a given simplex, which occurs in cases where the data for the new simplex is \i not determined by the simplex that is to be copied. @param simplex Simplex to copy vertices from @param data Data to assign new simplex */ explicit Simplex( const Simplex<DataType, VertexType>& simplex, DataType data ) : _vertices( simplex._vertices ) , _data( data ) { } /** Creates a new simplex from a range of vertices. The input iterators are supposed to belong to a range of vertices for the simplex. This range need not be ordered. Note that the simplex will \b not check for duplicate values. @param begin Iterator to begin of vertex range @param end Iterator to end of vertex range @param data Data to assign to simplex */ template <class InputIterator> Simplex( InputIterator begin, InputIterator end, DataType data = Data() ) : _vertices( begin, end ) , _data( data ) { std::sort( _vertices.begin(), _vertices.end(), std::greater<VertexType>() ); } /** Creates a new simplex from a range of vertices. The vertices are not assumed to be ordered. It must be possible for me to convert them to the vertex type of the simplex. @param vertices Vertices @param data Data to assign to simplex */ template <class VertexType> Simplex( const std::initializer_list<VertexType>& vertices, DataType data = Data() ) : Simplex( vertices.begin(), vertices.end(), data ) { } // vertices ---------------------------------------------------------- /** @returns Iterator to begin of simplex vertex range */ const_vertex_iterator begin() const { return _vertices.begin(); } /** @returns Iterator to end of simplex vertex range */ const_vertex_iterator end() const { return _vertices.end(); } /** @returns Reverse begin iterator of simplex vertex range */ const_reverse_vertex_iterator rbegin() const { return _vertices.rbegin(); } /** @returns Reverse end iterator of simplex vertex range */ const_reverse_vertex_iterator rend() const { return _vertices.rend(); } /** Checks whether the current simplex contains a given vertex. This is required for intersection queries, for example. @param vertex Vertex to search for @returns true if the simplex contains the current vertex at least once, else false. */ bool contains( VertexType vertex ) const { return std::find( this->begin(), this->end(), vertex ) != this->end(); } // boundary ---------------------------------------------------------- /** @returns Boundary iterator to begin of boundary */ boundary_iterator begin_boundary() const { // Check dimension directly in order to handle the empty simplex if( _vertices.empty() || _vertices.size() <= 1 ) return this->end_boundary(); return boundary_iterator( _vertices.begin(), _vertices); } /** @returns Boundary iterator to end of boundary */ boundary_iterator end_boundary() const { return boundary_iterator( _vertices.end(), _vertices); } // Data -------------------------------------------------------------- /** Assigns the simplex a new value for its data object. This function does not perform any sanity checks. The value is simply copied and stored. @param data Data to assign */ void setData( DataType data = DataType() ) { _data = data; } /** @returns Current value of simplex data object */ DataType data() const { return _data; } // Attribute access -------------------------------------------------- /** @returns true if the simplex is empty, i.e. it has no vertices */ bool empty() const { return _vertices.empty(); } /** @returns true if the simplex is valid, i.e. it is not empty. This function allows the simplex class to be used in expressions such as this one: @code Simplex<double> mySimplex( 2, 2.0 ); // 0-simplex if( mySimplex ) { // Do stuff with a valid simplex. } @endcode */ explicit operator bool() const { // A bit verbose but more readable :) return this->empty() ? false : true; } /** @returns Dimension of simplex @throws std::runtime_error if the dimension of the empty simplex is queried. If you do this, it's your own fault. */ std::size_t dimension() const { if( _vertices.empty() ) throw std::runtime_error( "Querying dimension of empty simplex" ); else return _vertices.size() - 1; } /** @returns Number of vertices of the simplex */ std::size_t size() const { return _vertices.size(); } /** Returns a vertex (specified by an index) of the current simplex. @param index Index of vertex in simplex @returns Vertex of simplex, specified by an index. @throws std::out_of_range if the index is out of range. */ VertexType operator[]( std::size_t index ) const { return _vertices.at( index ); } // Comparison operators ---------------------------------------------- /** Checks whether two simplices are equal. Two simplices are considered equal if their vertices are being equal. Simplex data is \b not checked by this function as this would complicate simplex queries in a simplicial complex. @param other Simplex to check for equality @returns true if the two simplices are equal (see above), else false. */ bool operator==( const Simplex& other ) const { return this->_vertices == other._vertices; } /** Checks whether two simplices are inequal. This function is simply the negation of operator==. @param other Simplex to check for inequality @returns true if the two simplices differ, else false. */ bool operator!=( const Simplex& other ) const { return !this->operator==( other ); } /** Comparison operator for simplices. Uses lexicographical comparison to obtain a weak ordering of the simplices. This is used in many algorithms. @param other Simplex to compare current simplex to @returns true if current simplex is to be sorted before other simplex. */ bool operator<( const Simplex& other ) const { return std::lexicographical_compare( this->_vertices.begin(), this->_vertices.end(), other._vertices.begin(), other._vertices.end() ); } // Convenience functions --------------------------------------------- template <class D> friend std::size_t hash_value( const Simplex<D>& s ); template <class D, class V> friend std::size_t hash_value( const Simplex<D,V>& s ); private: /** The vertices making up the current simplex. Their values are irrelevant, though it is assumed that the vertices represent some data points stored _outside_ the simplex. */ vertex_container_type _vertices; /** Data stored within the simplex. The type and semantics of this member variable depend on the template parameters of the simplex class. For example, a \c double value is used at several places in order to add a \i weight or a \i distance for the simplex. */ DataType _data; }; // --------------------------------------------------------------------- /** Outputs a simplex to an ostream. This is used for debugging purposes. @param o Output stream @param s Simplex to be added to o @returns Output stream with information about simplex s. */ template <class DataType, class VertexType> std::ostream& operator<<( std::ostream& o, const Simplex<DataType, VertexType>& s ) { auto numVertices = s.size(); o << "{"; for( decltype(numVertices) i = 0; i < numVertices; i++ ) { if( i != 0 ) o << " "; o << s[i]; } if( s.data() != DataType() ) o << " (" << s.data() << ")"; o << "}"; return o; } template <class DataType> std::ostream& operator<<( std::ostream& o, const Simplex<DataType>& s ) { return ::operator<< <DataType, typename Simplex<DataType>::vertex_type>( o, s ); } // --------------------------------------------------------------------- template <class DataType, class VertexType> std::size_t hash_value( const Simplex<DataType, VertexType>& s ) { boost::hash< typename Simplex<DataType, VertexType>::vertex_container_type > hasher; return hasher( s._vertices ); } template <class DataType> std::size_t hash_value( const Simplex<DataType>& s ) { return ::hash_value<DataType, typename Simplex<DataType>::vertex_type>( s ); } // --------------------------------------------------------------------- /** @class boundary_iterator @brief Iterator for traversing the boundary of a given simplex This iterator, inspired by Dmitriy Morozov's "Dionysus" framework, calculates the boundary of a given simplex while traversing it. Since the boundary simplices are created from scratch, they will _not_ have the correct weights set. Hence, the boundary iterator is only useful if some kind of lookup of generated simplices exists---as is the case for a simplicial complex, for example. */ template < class DataType, class VertexType > class Simplex<DataType, VertexType>::boundary_iterator : public boost::iterator_adaptor<boundary_iterator, const_vertex_iterator, Simplex<DataType, VertexType>, boost::use_default, Simplex<DataType, VertexType> > { public: using Iterator = const_vertex_iterator ; using Parent = boost::iterator_adaptor<boundary_iterator, Iterator, Simplex<DataType, VertexType>, boost::use_default, Simplex<DataType, VertexType> >; /** Creates a new boundary iterator from a parent iterator (i.e. a simplex) and a set of vertices (i.e. the vertices of the parent simplex). @param it Parent iterator @param vertices VertexType set */ explicit boundary_iterator( Iterator it, const vertex_container_type& vertices ) : Parent(it) , _vertices(vertices) { } private: friend class boost::iterator_core_access; /** @returns Current boundary simplex */ Simplex<DataType, VertexType> dereference() const { // This returns a new simplex. The simplex is created from a set of // vertices, which in turn is created by applying a filter to the set of // vertices stored in this iterator: Namely, the filter iterator will // return all vertices that are _not_ equal to its current position. vertex_container_type vertices( boost::make_filter_iterator( std::bind2nd( std::not_equal_to<vertex_type>(), *( this->base() ) ), _vertices.begin(), _vertices.end() ), boost::make_filter_iterator( std::bind2nd( std::not_equal_to<vertex_type>(), *( this->base() ) ), _vertices.end(), _vertices.end() ) ); return Simplex<DataType, VertexType>( vertices.begin(), vertices.end() ); } /** Reference to vertex set; this is required because the boundary iterator iterates over a set of vertices and may thus not exist without one. */ const vertex_container_type& _vertices; }; } #endif <commit_msg>Fixes for simplex class<commit_after>#ifndef ALEPH_SIMPLEX_HH__ #define ALEPH_SIMPLEX_HH__ #include <algorithm> #include <initializer_list> #include <iosfwd> #include <stdexcept> #include <vector> #include <boost/functional/hash.hpp> #include <boost/iterator/iterator_adaptor.hpp> #include <boost/iterator/filter_iterator.hpp> namespace aleph { template < class DataType, class VertexType = unsigned short > class Simplex { public: // Aliases & declarations ------------------------------------------- // // Note that these aliases follow the STL conventions in order to make it // easier to use the class with STL algorithms. using data_type = DataType; using vertex_type = VertexType; using vertex_container_type = std::vector<vertex_type>; using vertex_iterator = typename vertex_container_type::iterator; using const_vertex_iterator = typename vertex_container_type::const_iterator; using reverse_vertex_iterator = typename vertex_container_type::reverse_iterator; using const_reverse_vertex_iterator = typename vertex_container_type::const_reverse_iterator; // I cannot describe the class inline because boost::iterator_adaptor expects // a _complete_ class. class boundary_iterator; // Constructors ------------------------------------------------------ /** Creates an empty simplex */ Simplex() : _data( DataType() ) { } /** Creates a new 0-simplex from the given vertex. @param u Vertex @param data Data to assign to simplex */ Simplex( VertexType u, DataType data = DataType() ) : _vertices( 1, u ) , _data( data ) { } /** Creates a new simplex from another simplex while setting the data for the new simplex. This is handy for copying the vertices but not the data of a given simplex, which occurs in cases where the data for the new simplex is \i not determined by the simplex that is to be copied. @param simplex Simplex to copy vertices from @param data Data to assign new simplex */ explicit Simplex( const Simplex<DataType, VertexType>& simplex, DataType data ) : _vertices( simplex._vertices ) , _data( data ) { } /** Creates a new simplex from a range of vertices. The input iterators are supposed to belong to a range of vertices for the simplex. This range need not be ordered. Note that the simplex will \b not check for duplicate values. @param begin Iterator to begin of vertex range @param end Iterator to end of vertex range @param data Data to assign to simplex */ template <class InputIterator> Simplex( InputIterator begin, InputIterator end, DataType data = DataType() ) : _vertices( begin, end ) , _data( data ) { std::sort( _vertices.begin(), _vertices.end(), std::greater<VertexType>() ); } /** Creates a new simplex from a range of vertices. The vertices are not assumed to be ordered. It must be possible for me to convert them to the vertex type of the simplex. @param vertices Vertices @param data Data to assign to simplex */ template <class Vertex> Simplex( const std::initializer_list<Vertex>& vertices, DataType data = DataType() ) : Simplex( vertices.begin(), vertices.end(), data ) { } // vertices ---------------------------------------------------------- /** @returns Iterator to begin of simplex vertex range */ const_vertex_iterator begin() const { return _vertices.begin(); } /** @returns Iterator to end of simplex vertex range */ const_vertex_iterator end() const { return _vertices.end(); } /** @returns Reverse begin iterator of simplex vertex range */ const_reverse_vertex_iterator rbegin() const { return _vertices.rbegin(); } /** @returns Reverse end iterator of simplex vertex range */ const_reverse_vertex_iterator rend() const { return _vertices.rend(); } /** Checks whether the current simplex contains a given vertex. This is required for intersection queries, for example. @param vertex Vertex to search for @returns true if the simplex contains the current vertex at least once, else false. */ bool contains( VertexType vertex ) const { return std::find( this->begin(), this->end(), vertex ) != this->end(); } // boundary ---------------------------------------------------------- /** @returns Boundary iterator to begin of boundary */ boundary_iterator begin_boundary() const { // Check dimension directly in order to handle the empty simplex if( _vertices.empty() || _vertices.size() <= 1 ) return this->end_boundary(); return boundary_iterator( _vertices.begin(), _vertices); } /** @returns Boundary iterator to end of boundary */ boundary_iterator end_boundary() const { return boundary_iterator( _vertices.end(), _vertices); } // Data -------------------------------------------------------------- /** Assigns the simplex a new value for its data object. This function does not perform any sanity checks. The value is simply copied and stored. @param data Data to assign */ void setData( DataType data = DataType() ) { _data = data; } /** @returns Current value of simplex data object */ DataType data() const { return _data; } // Attribute access -------------------------------------------------- /** @returns true if the simplex is empty, i.e. it has no vertices */ bool empty() const { return _vertices.empty(); } /** @returns true if the simplex is valid, i.e. it is not empty. This function allows the simplex class to be used in expressions such as this one: @code Simplex<double> mySimplex( 2, 2.0 ); // 0-simplex if( mySimplex ) { // Do stuff with a valid simplex. } @endcode */ explicit operator bool() const { // A bit verbose but more readable :) return this->empty() ? false : true; } /** @returns Dimension of simplex @throws std::runtime_error if the dimension of the empty simplex is queried. If you do this, it's your own fault. */ std::size_t dimension() const { if( _vertices.empty() ) throw std::runtime_error( "Querying dimension of empty simplex" ); else return _vertices.size() - 1; } /** @returns Number of vertices of the simplex */ std::size_t size() const { return _vertices.size(); } /** Returns a vertex (specified by an index) of the current simplex. @param index Index of vertex in simplex @returns Vertex of simplex, specified by an index. @throws std::out_of_range if the index is out of range. */ VertexType operator[]( std::size_t index ) const { return _vertices.at( index ); } // Comparison operators ---------------------------------------------- /** Checks whether two simplices are equal. Two simplices are considered equal if their vertices are being equal. Simplex data is \b not checked by this function as this would complicate simplex queries in a simplicial complex. @param other Simplex to check for equality @returns true if the two simplices are equal (see above), else false. */ bool operator==( const Simplex& other ) const { return this->_vertices == other._vertices; } /** Checks whether two simplices are inequal. This function is simply the negation of operator==. @param other Simplex to check for inequality @returns true if the two simplices differ, else false. */ bool operator!=( const Simplex& other ) const { return !this->operator==( other ); } /** Comparison operator for simplices. Uses lexicographical comparison to obtain a weak ordering of the simplices. This is used in many algorithms. @param other Simplex to compare current simplex to @returns true if current simplex is to be sorted before other simplex. */ bool operator<( const Simplex& other ) const { return std::lexicographical_compare( this->_vertices.begin(), this->_vertices.end(), other._vertices.begin(), other._vertices.end() ); } // Convenience functions --------------------------------------------- template <class D> friend std::size_t hash_value( const Simplex<D>& s ); template <class D, class V> friend std::size_t hash_value( const Simplex<D,V>& s ); private: /** The vertices making up the current simplex. Their values are irrelevant, though it is assumed that the vertices represent some data points stored _outside_ the simplex. */ vertex_container_type _vertices; /** Data stored within the simplex. The type and semantics of this member variable depend on the template parameters of the simplex class. For example, a \c double value is used at several places in order to add a \i weight or a \i distance for the simplex. */ DataType _data; }; // --------------------------------------------------------------------- /** Outputs a simplex to an ostream. This is used for debugging purposes. @param o Output stream @param s Simplex to be added to o @returns Output stream with information about simplex s. */ template <class DataType, class VertexType> std::ostream& operator<<( std::ostream& o, const Simplex<DataType, VertexType>& s ) { auto numVertices = s.size(); o << "{"; for( decltype(numVertices) i = 0; i < numVertices; i++ ) { if( i != 0 ) o << " "; o << s[i]; } if( s.data() != DataType() ) o << " (" << s.data() << ")"; o << "}"; return o; } template <class DataType> std::ostream& operator<<( std::ostream& o, const Simplex<DataType>& s ) { return operator<< <DataType, typename Simplex<DataType>::vertex_type>( o, s ); } // --------------------------------------------------------------------- template <class DataType, class VertexType> std::size_t hash_value( const Simplex<DataType, VertexType>& s ) { boost::hash< typename Simplex<DataType, VertexType>::vertex_container_type > hasher; return hasher( s._vertices ); } template <class DataType> std::size_t hash_value( const Simplex<DataType>& s ) { return hash_value<DataType, typename Simplex<DataType>::vertex_type>( s ); } // --------------------------------------------------------------------- /** @class boundary_iterator @brief Iterator for traversing the boundary of a given simplex This iterator, inspired by Dmitriy Morozov's "Dionysus" framework, calculates the boundary of a given simplex while traversing it. Since the boundary simplices are created from scratch, they will _not_ have the correct weights set. Hence, the boundary iterator is only useful if some kind of lookup of generated simplices exists---as is the case for a simplicial complex, for example. */ template < class DataType, class VertexType > class Simplex<DataType, VertexType>::boundary_iterator : public boost::iterator_adaptor<boundary_iterator, const_vertex_iterator, Simplex<DataType, VertexType>, boost::use_default, Simplex<DataType, VertexType> > { public: using Iterator = const_vertex_iterator ; using Parent = boost::iterator_adaptor<boundary_iterator, Iterator, Simplex<DataType, VertexType>, boost::use_default, Simplex<DataType, VertexType> >; /** Creates a new boundary iterator from a parent iterator (i.e. a simplex) and a set of vertices (i.e. the vertices of the parent simplex). @param it Parent iterator @param vertices VertexType set */ explicit boundary_iterator( Iterator it, const vertex_container_type& vertices ) : Parent(it) , _vertices(vertices) { } private: friend class boost::iterator_core_access; /** @returns Current boundary simplex */ Simplex<DataType, VertexType> dereference() const { // This returns a new simplex. The simplex is created from a set of // vertices, which in turn is created by applying a filter to the set of // vertices stored in this iterator: Namely, the filter iterator will // return all vertices that are _not_ equal to its current position. vertex_container_type vertices( boost::make_filter_iterator( std::bind2nd( std::not_equal_to<vertex_type>(), *( this->base() ) ), _vertices.begin(), _vertices.end() ), boost::make_filter_iterator( std::bind2nd( std::not_equal_to<vertex_type>(), *( this->base() ) ), _vertices.end(), _vertices.end() ) ); return Simplex<DataType, VertexType>( vertices.begin(), vertices.end() ); } /** Reference to vertex set; this is required because the boundary iterator iterates over a set of vertices and may thus not exist without one. */ const vertex_container_type& _vertices; }; } #endif <|endoftext|>
<commit_before>/* * Copyright 2012 BrewPi/Elco Jacobs. * * This file is part of BrewPi. * * BrewPi 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. * * BrewPi 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 BrewPi. If not, see <http://www.gnu.org/licenses/>. */ #include "SpiLcd.h" #include <Arduino.h> #include <stdio.h> #include <string.h> #include <inttypes.h> #include <util/delay.h> void SpiLcd::init(uint8_t latchPin) { _latchPin = latchPin; pinMode(_latchPin, OUTPUT); _displayfunction = LCD_FUNCTIONSET | LCD_4BITMODE; initSpi(); for(uint8_t i = 0; i<4; i++){ for(uint8_t j = 0; j<20; j++){ content[i][j]=' '; // initialize on all spaces } content[i][20]='\0'; // NULL terminate string } } void SpiLcd::begin(uint8_t cols, uint8_t lines) { _numlines = lines; _currline = 0; _currpos = 0; // Set all outputs of shift register to low, this turns the backlight ON. _spiByte = 0x00; spiOut(); // The following initialization sequence should be compatible with: // - Newhaven OLED displays // - Standard HD44780 or S6A0069 LCD displays delayMicroseconds(50000); // wait 50 ms just to be sure that the lcd is initialized write4bits(0x03); //set to 8-bit delayMicroseconds(50000); // wait > 4.1ms write4bits(0x03); //set to 8-bit delayMicroseconds(1000); // wait > 100us write4bits(0x03); //set to 8-bit delayMicroseconds(50000); // wait for execution write4bits(0x02); //set to 4-bit delayMicroseconds(50000); // wait for execution command(0x28); // set to 4-bit, 2-line clear(); // display clear // Entry Mode Set: leftToRight(); noAutoscroll(); home(); //noCursor(); display(); } /********** high level commands, for the user! */ void SpiLcd::clear() { command(LCD_CLEARDISPLAY); // clear display, set cursor position to zero } void SpiLcd::home() { command(LCD_RETURNHOME); // set cursor position to zero _currline = 0; _currpos = 0; } void SpiLcd::setCursor(uint8_t col, uint8_t row) { uint8_t row_offsets[] = { 0x00, 0x40, 0x14, 0x54 }; if ( row >= _numlines ) { row = 0; //write to first line if out off bounds } _currline = row; _currpos = col; command(LCD_SETDDRAMADDR | (col + row_offsets[row])); } // Turn the display on/off (quickly) void SpiLcd::noDisplay() { _displaycontrol &= ~LCD_DISPLAYON; command(LCD_DISPLAYCONTROL | _displaycontrol); } void SpiLcd::display() { _displaycontrol |= LCD_DISPLAYON; command(LCD_DISPLAYCONTROL | _displaycontrol); } // Turns the underline cursor on/off void SpiLcd::noCursor() { _displaycontrol &= ~LCD_CURSORON; command(LCD_DISPLAYCONTROL | _displaycontrol); } void SpiLcd::cursor() { _displaycontrol |= LCD_CURSORON; command(LCD_DISPLAYCONTROL | _displaycontrol); } // Turn on and off the blinking cursor void SpiLcd::noBlink() { _displaycontrol &= ~LCD_BLINKON; command(LCD_DISPLAYCONTROL | _displaycontrol); } void SpiLcd::blink() { _displaycontrol |= LCD_BLINKON; command(LCD_DISPLAYCONTROL | _displaycontrol); } // These commands scroll the display without changing the RAM void SpiLcd::scrollDisplayLeft(void) { command(LCD_CURSORSHIFT | LCD_DISPLAYMOVE | LCD_MOVELEFT); } void SpiLcd::scrollDisplayRight(void) { command(LCD_CURSORSHIFT | LCD_DISPLAYMOVE | LCD_MOVERIGHT); } // This is for text that flows Left to Right void SpiLcd::leftToRight(void) { _displaymode |= LCD_ENTRYLEFT; command(LCD_ENTRYMODESET | _displaymode); } // This is for text that flows Right to Left void SpiLcd::rightToLeft(void) { _displaymode &= ~LCD_ENTRYLEFT; command(LCD_ENTRYMODESET | _displaymode); } // This will 'right justify' text from the cursor void SpiLcd::autoscroll(void) { _displaymode |= LCD_ENTRYSHIFTINCREMENT; command(LCD_ENTRYMODESET | _displaymode); } // This will 'left justify' text from the cursor void SpiLcd::noAutoscroll(void) { _displaymode &= ~LCD_ENTRYSHIFTINCREMENT; command(LCD_ENTRYMODESET | _displaymode); } // Allows us to fill the first 8 CGRAM locations // with custom characters void SpiLcd::createChar(uint8_t location, uint8_t charmap[]) { location &= 0x7; // we only have 8 locations 0-7 command(LCD_SETCGRAMADDR | (location << 3)); for (int i=0; i<8; i++) { write(charmap[i]); } } /*********** mid level commands, for sending data/cmds */ inline void SpiLcd::command(uint8_t value) { send(value, LOW); waitBusy(); } inline size_t SpiLcd::write(uint8_t value) { send(value, HIGH); content[_currline][_currpos] = value; _currpos++; waitBusy(); return 1; } /************ low level data pushing commands **********/ void SpiLcd::initSpi(void){ // Set MOSI and CLK to output pinMode(MOSI, OUTPUT); pinMode(SCK, OUTPUT); // The most significant bit should be sent out by the SPI port first. // equals SPI.setBitOrder(MSBFIRST); SPCR &= ~_BV(DORD); // Here you can set the clock speed of the SPI port. Default is DIV4, which is 4MHz with a 16Mhz system clock. // If you encounter problems due to long wires, try lowering the SPI clock. // equals SPI.setClockDivider(SPI_CLOCK_DIV4); SPCR = (SPCR & 0b11111000); SPSR = (SPSR & 0b11111110); // Set clock polarity and phase for shift registers (Mode 3) SPCR |= _BV(CPOL); SPCR |= _BV(CPHA); // Warning: if the SS pin ever becomes a LOW INPUT then SPI // automatically switches to Slave, so the data direction of // The SS pin MUST be kept as OUTPUT. // On the Arduino Leonardo it is connected to the RX status LED, on the Uno we are using it as latch pin. // Set SPI as master and enable SPI SPCR |= _BV(MSTR); SPCR |= _BV(SPE); } // Update the pins of the shift register void SpiLcd::spiOut(void){ digitalWrite(_latchPin, LOW); SPDR = _spiByte; // Send the byte to the SPI // wait for send to finish while (!(SPSR & _BV(SPIF))); digitalWrite(_latchPin, HIGH); } // write either command or data void SpiLcd::send(uint8_t value, uint8_t mode) { if(mode){ bitSet(_spiByte, LCD_SHIFT_RS); } else{ bitClear(_spiByte, LCD_SHIFT_RS); } spiOut(); write4bits(value>>4); write4bits(value); } void SpiLcd::pulseEnable(void) { bitSet(_spiByte, LCD_SHIFT_ENABLE); spiOut(); delayMicroseconds(1); // enable pulse must be >450ns bitClear(_spiByte, LCD_SHIFT_ENABLE); spiOut(); } void SpiLcd::write4bits(uint8_t value) { _spiByte = (_spiByte & ~LCD_SHIFT_DATA_MASK) | (value << 4); spiOut(); pulseEnable(); } void SpiLcd::waitBusy(void) { // we cannot read the busy pin, so just wait 1 ms _delay_ms(1); } void SpiLcd::getLine(uint8_t lineNumber, char * buffer){ for(uint8_t i =0;i<20;i++){ if(content[lineNumber][i] == 0b11011111){ buffer[i] = 0xB0; // correct degree sign } else{ buffer[i] = content[lineNumber][i]; // copy to string buffer } } buffer[20] = '\0'; // NULL terminate string }<commit_msg>Lowered SPI clock frequency. High clock is not needed and lower clock is better for longer cables.<commit_after>/* * Copyright 2012 BrewPi/Elco Jacobs. * * This file is part of BrewPi. * * BrewPi 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. * * BrewPi 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 BrewPi. If not, see <http://www.gnu.org/licenses/>. */ #include "SpiLcd.h" #include <Arduino.h> #include <stdio.h> #include <string.h> #include <inttypes.h> #include <util/delay.h> void SpiLcd::init(uint8_t latchPin) { _latchPin = latchPin; pinMode(_latchPin, OUTPUT); _displayfunction = LCD_FUNCTIONSET | LCD_4BITMODE; initSpi(); for(uint8_t i = 0; i<4; i++){ for(uint8_t j = 0; j<20; j++){ content[i][j]=' '; // initialize on all spaces } content[i][20]='\0'; // NULL terminate string } } void SpiLcd::begin(uint8_t cols, uint8_t lines) { _numlines = lines; _currline = 0; _currpos = 0; // Set all outputs of shift register to low, this turns the backlight ON. _spiByte = 0x00; spiOut(); // The following initialization sequence should be compatible with: // - Newhaven OLED displays // - Standard HD44780 or S6A0069 LCD displays delayMicroseconds(50000); // wait 50 ms just to be sure that the lcd is initialized write4bits(0x03); //set to 8-bit delayMicroseconds(50000); // wait > 4.1ms write4bits(0x03); //set to 8-bit delayMicroseconds(1000); // wait > 100us write4bits(0x03); //set to 8-bit delayMicroseconds(50000); // wait for execution write4bits(0x02); //set to 4-bit delayMicroseconds(50000); // wait for execution command(0x28); // set to 4-bit, 2-line clear(); // display clear // Entry Mode Set: leftToRight(); noAutoscroll(); home(); //noCursor(); display(); } /********** high level commands, for the user! */ void SpiLcd::clear() { command(LCD_CLEARDISPLAY); // clear display, set cursor position to zero } void SpiLcd::home() { command(LCD_RETURNHOME); // set cursor position to zero _currline = 0; _currpos = 0; } void SpiLcd::setCursor(uint8_t col, uint8_t row) { uint8_t row_offsets[] = { 0x00, 0x40, 0x14, 0x54 }; if ( row >= _numlines ) { row = 0; //write to first line if out off bounds } _currline = row; _currpos = col; command(LCD_SETDDRAMADDR | (col + row_offsets[row])); } // Turn the display on/off (quickly) void SpiLcd::noDisplay() { _displaycontrol &= ~LCD_DISPLAYON; command(LCD_DISPLAYCONTROL | _displaycontrol); } void SpiLcd::display() { _displaycontrol |= LCD_DISPLAYON; command(LCD_DISPLAYCONTROL | _displaycontrol); } // Turns the underline cursor on/off void SpiLcd::noCursor() { _displaycontrol &= ~LCD_CURSORON; command(LCD_DISPLAYCONTROL | _displaycontrol); } void SpiLcd::cursor() { _displaycontrol |= LCD_CURSORON; command(LCD_DISPLAYCONTROL | _displaycontrol); } // Turn on and off the blinking cursor void SpiLcd::noBlink() { _displaycontrol &= ~LCD_BLINKON; command(LCD_DISPLAYCONTROL | _displaycontrol); } void SpiLcd::blink() { _displaycontrol |= LCD_BLINKON; command(LCD_DISPLAYCONTROL | _displaycontrol); } // These commands scroll the display without changing the RAM void SpiLcd::scrollDisplayLeft(void) { command(LCD_CURSORSHIFT | LCD_DISPLAYMOVE | LCD_MOVELEFT); } void SpiLcd::scrollDisplayRight(void) { command(LCD_CURSORSHIFT | LCD_DISPLAYMOVE | LCD_MOVERIGHT); } // This is for text that flows Left to Right void SpiLcd::leftToRight(void) { _displaymode |= LCD_ENTRYLEFT; command(LCD_ENTRYMODESET | _displaymode); } // This is for text that flows Right to Left void SpiLcd::rightToLeft(void) { _displaymode &= ~LCD_ENTRYLEFT; command(LCD_ENTRYMODESET | _displaymode); } // This will 'right justify' text from the cursor void SpiLcd::autoscroll(void) { _displaymode |= LCD_ENTRYSHIFTINCREMENT; command(LCD_ENTRYMODESET | _displaymode); } // This will 'left justify' text from the cursor void SpiLcd::noAutoscroll(void) { _displaymode &= ~LCD_ENTRYSHIFTINCREMENT; command(LCD_ENTRYMODESET | _displaymode); } // Allows us to fill the first 8 CGRAM locations // with custom characters void SpiLcd::createChar(uint8_t location, uint8_t charmap[]) { location &= 0x7; // we only have 8 locations 0-7 command(LCD_SETCGRAMADDR | (location << 3)); for (int i=0; i<8; i++) { write(charmap[i]); } } /*********** mid level commands, for sending data/cmds */ inline void SpiLcd::command(uint8_t value) { send(value, LOW); waitBusy(); } inline size_t SpiLcd::write(uint8_t value) { send(value, HIGH); content[_currline][_currpos] = value; _currpos++; waitBusy(); return 1; } /************ low level data pushing commands **********/ void SpiLcd::initSpi(void){ // Set MOSI and CLK to output pinMode(MOSI, OUTPUT); pinMode(SCK, OUTPUT); // The most significant bit should be sent out by the SPI port first. // equals SPI.setBitOrder(MSBFIRST); SPCR &= ~_BV(DORD); // Set the SPI clock to Fosc/128, the slowest option. This prevents problems with long cables. SPCR |= _BV(SPR1); SPSR |= _BV(SPR0); // Set clock polarity and phase for shift registers (Mode 3) SPCR |= _BV(CPOL); SPCR |= _BV(CPHA); // Warning: if the SS pin ever becomes a LOW INPUT then SPI // automatically switches to Slave, so the data direction of // The SS pin MUST be kept as OUTPUT. // On the Arduino Leonardo it is connected to the RX status LED, on the Uno we are using it as latch pin. // Set SPI as master and enable SPI SPCR |= _BV(MSTR); SPCR |= _BV(SPE); } // Update the pins of the shift register void SpiLcd::spiOut(void){ digitalWrite(_latchPin, LOW); SPDR = _spiByte; // Send the byte to the SPI // wait for send to finish while (!(SPSR & _BV(SPIF))); digitalWrite(_latchPin, HIGH); } // write either command or data void SpiLcd::send(uint8_t value, uint8_t mode) { if(mode){ bitSet(_spiByte, LCD_SHIFT_RS); } else{ bitClear(_spiByte, LCD_SHIFT_RS); } spiOut(); write4bits(value>>4); write4bits(value); } void SpiLcd::pulseEnable(void) { bitSet(_spiByte, LCD_SHIFT_ENABLE); spiOut(); delayMicroseconds(1); // enable pulse must be >450ns bitClear(_spiByte, LCD_SHIFT_ENABLE); spiOut(); } void SpiLcd::write4bits(uint8_t value) { _spiByte = (_spiByte & ~LCD_SHIFT_DATA_MASK) | (value << 4); spiOut(); pulseEnable(); } void SpiLcd::waitBusy(void) { // we cannot read the busy pin, so just wait 1 ms _delay_ms(1); } void SpiLcd::getLine(uint8_t lineNumber, char * buffer){ for(uint8_t i =0;i<20;i++){ if(content[lineNumber][i] == 0b11011111){ buffer[i] = 0xB0; // correct degree sign } else{ buffer[i] = content[lineNumber][i]; // copy to string buffer } } buffer[20] = '\0'; // NULL terminate string }<|endoftext|>
<commit_before>//csvmap.hpp //Copyright (c) 2019 mmYYmmdd //WINDOWS ONLY #pragma once #include <sstream> #include <stringapiset.h> //CSV}bv //[U[g֐ mymd::map_csv namespace mymd { inline void code_convert_append(std::wstring& target, char const* begin, char const* end, UINT codepage) { if (begin < end) { auto const targetlen = target.length(); target.resize(targetlen + end - begin, L'\0'); auto re = ::MultiByteToWideChar(codepage, MB_ERR_INVALID_CHARS, begin, static_cast<int>(end - begin), &target[targetlen], static_cast<int>(1 + end - begin)); target.resize(targetlen + (re? re: 0)); } } inline void code_convert_append(std::wstring& target, std::string const& source, UINT codepage) { code_convert_append(target, source.data(), source.data() + source.length(), codepage); } inline void code_convert_append(std::wstring& target, std::wstring const& source, UINT) { target += source; } inline void code_convert_append(std::string& target, std::string const& source, UINT) { target += source; } namespace detail { inline char quote_(char) { return '"'; } inline wchar_t quote_(wchar_t) { return L'"'; } inline char endl_(char) { return '\n'; } inline wchar_t endl_(wchar_t) { return L'\n'; } template<typename R> std::size_t quote_count(std::basic_string<R> const & buf) { const R quote{quote_(R{})}; std::size_t q_count{0}; for (auto i = buf.cbegin(); i < buf.cend(); ++i) if (*i == quote) ++q_count; return q_count; } template <typename R> std::basic_string<R> make_elem(typename std::basic_string<R>::const_iterator b, typename std::basic_string<R>::const_iterator e, R quote) { std::basic_string<R> w(b, e); auto wlen = w.length(); if (2 <= wlen) { if (w[0] == quote) { w.erase(wlen-1, 1); w.erase(0, 1); } auto i = static_cast<int>(wlen - 2); while (0 <= i) { if (w[i] == quote) { if (w[i+1] == quote) { w.erase(i+1, 1); wlen -= 1; i -= 2; } else i -= 1; } else i -= 2; } } return w; }; //------------------------------------------- template<typename R, typename F> std::size_t map_csv_imple_elem(std::basic_string<R> const& buf, R delimiter, F&& func) { const R quote{detail::quote_(R{})}; std::size_t count{0}, q_count{0}; auto i = buf.cbegin(); auto j = i; while ( j != buf.cend() ) { if (*j == quote) { ++q_count; ++j; } else if (*j == delimiter && 0 == (q_count % 2)) { //R[obN֐1vfn std::forward<F>(func)(count, make_elem(i, j, quote)); i = j + 1; j = i; ++count; } else ++j; } //R[obN֐1vfn std::forward<F>(func)(count, make_elem(i, j, quote)); return count + 1; } template<typename R, typename S, typename Traits, typename F> std::size_t map_csv_imple(std::basic_istream<S, Traits>& stream, R delimiter, F&& func, std::basic_string<R>& buf, std::basic_string<R>& buf2, std::basic_string<S>& tmp, UINT codepage) { std::getline(stream, tmp); buf.clear(); code_convert_append(buf, tmp, codepage); std::size_t q_count = quote_count(buf); while ((q_count % 2) && stream.good()) { std::getline(stream, tmp); buf2.clear(); code_convert_append(buf2, tmp, codepage); buf += endl_(R{}); buf += buf2; q_count += quote_count(buf2); } //R[obNisǏIj return map_csv_imple_elem(buf, delimiter, std::forward<F>(func)); } } //[U[g֐ // stream : ̓Xg[ifstream ܂ stringstream z j // R : o͂镶^iwchar_tzj // S : Ώstream̕^it@CcodeconvertOȂstringzj // delimiter : ؂蕶iɂČ^R 肳j // elem_func : vf̃R[obN@@[&](std::size_t count, std::wstring&& expr) A (ڔԍ, vf) // record_func : 1R[hǏĨR[obN@[&](std::size_t count, std::size_t size)@A(sԍ, Ys̍ڐ) // codepage : CP_UTF8, CP_ACP Ȃ // Ԃl : ǂ񂾍sieLXgt@C̏ꍇ͍Ō̋sJEgj template<typename R, typename S, typename Traits, typename EF, typename RF> std::size_t map_csv(std::basic_istream<S, Traits>& stream, R delimiter, EF&& elem_func, RF&& record_func, UINT codepage) { std::basic_string<R> buf, buf2; std::basic_string<S> tmp; std::size_t rcount{0}; while (stream.good()) { auto size = detail::map_csv_imple(stream, delimiter, std::forward<EF>(elem_func), buf, buf2, tmp, codepage); std::forward<RF>(record_func)(rcount, size); ++rcount; } return rcount; } } <commit_msg>行コールバック関数の仕様変更<commit_after>//csvmap.hpp //Copyright (c) 2019 mmYYmmdd //WINDOWS ONLY #pragma once #include <sstream> #include <stringapiset.h> //CSV}bv //[U[g֐ mymd::map_csv namespace mymd { inline void code_convert_append(std::wstring& target, char const* begin, char const* end, UINT codepage) { if (begin < end) { auto const targetlen = target.length(); target.resize(targetlen + end - begin, L'\0'); auto re = ::MultiByteToWideChar(codepage, MB_ERR_INVALID_CHARS, begin, static_cast<int>(end - begin), &target[targetlen], static_cast<int>(1 + end - begin)); target.resize(targetlen + (re? re: 0)); } } inline void code_convert_append(std::wstring& target, std::string const& source, UINT codepage) { code_convert_append(target, source.data(), source.data() + source.length(), codepage); } inline void code_convert_append(std::wstring& target, std::wstring const& source, UINT) { target += source; } inline void code_convert_append(std::string& target, std::string const& source, UINT) { target += source; } namespace detail { inline char quote_(char) { return '"'; } inline wchar_t quote_(wchar_t) { return L'"'; } inline char endl_(char) { return '\n'; } inline wchar_t endl_(wchar_t) { return L'\n'; } template<typename R> std::size_t quote_count(std::basic_string<R> const & buf) { const R quote{quote_(R{})}; std::size_t q_count{0}; for (auto i = buf.cbegin(); i < buf.cend(); ++i) if (*i == quote) ++q_count; return q_count; } template <typename R> std::basic_string<R> make_elem(typename std::basic_string<R>::const_iterator b, typename std::basic_string<R>::const_iterator e, R quote) { std::basic_string<R> w(b, e); auto wlen = w.length(); if (2 <= wlen) { if (w[0] == quote) { w.erase(wlen-1, 1); w.erase(0, 1); } auto i = static_cast<int>(wlen - 2); while (0 <= i) { if (w[i] == quote) { if (w[i+1] == quote) { w.erase(i+1, 1); wlen -= 1; i -= 2; } else i -= 1; } else i -= 2; } } return w; }; //------------------------------------------- template<typename R, typename F> std::size_t map_csv_imple_elem(std::basic_string<R> const& buf, R delimiter, F&& func) { const R quote{detail::quote_(R{})}; std::size_t count{0}, q_count{0}; auto i = buf.cbegin(); auto j = i; while ( j != buf.cend() ) { if (*j == quote) { ++q_count; ++j; } else if (*j == delimiter && 0 == (q_count % 2)) { //R[obN֐1vfn std::forward<F>(func)(count, make_elem(i, j, quote)); i = j + 1; j = i; ++count; } else ++j; } //R[obN֐1vfn std::forward<F>(func)(count, make_elem(i, j, quote)); return count + 1; } template<typename R, typename S, typename Traits, typename F> std::size_t map_csv_imple(std::basic_istream<S, Traits>& stream, R delimiter, F&& func, std::basic_string<R>& buf, std::basic_string<R>& buf2, std::basic_string<S>& tmp, UINT codepage) { std::getline(stream, tmp); buf.clear(); code_convert_append(buf, tmp, codepage); std::size_t q_count = quote_count(buf); while ((q_count % 2) && stream.good()) { std::getline(stream, tmp); buf2.clear(); code_convert_append(buf2, tmp, codepage); buf += endl_(R{}); buf += buf2; q_count += quote_count(buf2); } return map_csv_imple_elem(buf, delimiter, std::forward<F>(func)); } } //[U[g֐ // stream : ̓Xg[ifstream ܂ stringstream z j // R : o͂镶^iwchar_tzj // S : Ώstream̕^it@CcodeconvertOȂstringzj // delimiter : ؂蕶iɂČ^R 肳j // elem_func : vf̃R[obN@@[&](std::size_t count, std::wstring&& expr) A (ڔԍ, vf) // record_func : 1R[hǏĨR[obN@[&](std::size_t count, std::size_t size)@A(sԍ, Ys̍ڐ) // codepage : CP_UTF8, CP_ACP Ȃ // Ԃl : ǂ񂾍sieLXgt@C̏ꍇ͍Ō̋sJEgj template<typename R, typename S, typename Traits, typename EF, typename RF> std::size_t map_csv(std::basic_istream<S, Traits>& stream, R delimiter, EF&& elem_func, RF&& record_func, UINT codepage) { std::basic_string<R> buf, buf2; std::basic_string<S> tmp; std::size_t rcount{0}; while (stream.good()) { auto size = detail::map_csv_imple(stream, delimiter, std::forward<EF>(elem_func), buf, buf2, tmp, codepage); //R[obNisǏIj auto b = std::forward<RF>(record_func)(rcount++, size); if (!b) break; } return rcount; } } <|endoftext|>
<commit_before>#include "Grid.h" #include <algorithm> Grid::Grid(int size, float cellSize, glm::vec3 origin) : m_data(std::vector<std::vector<Metaball*>>(size * size * size)) , m_size(size) , m_cellSize(cellSize) , m_frontBottomLeft(origin) { for (auto& it : m_data) { it = std::vector<Metaball*>(); } } Grid::~Grid(){} std::vector<Metaball*>& Grid::getMetaballs(glm::ivec3 gridCoords) { return m_data[toIndex(gridCoords)]; } std::vector<Metaball*>& Grid::getMetaballs(int index) { return m_data[index]; } std::vector<Metaball*> Grid::getNeighbors(Metaball& metaball) { std::vector<Metaball*> neighbors{}; glm::ivec3 coords(cellCoords(metaball)); for (int xx = -1; xx <= 1; xx++) for (int yy = -1; yy <= 1; yy++) for (int zz = -1; zz <= 1; zz++) { glm::ivec3 neighborCoords = coords + glm::ivec3(xx, yy, zz); if (!isInGrid(neighborCoords)) continue; neighbors.insert( neighbors.end(), getMetaballs(neighborCoords).begin(), getMetaballs(neighborCoords).end()); } neighbors.erase(std::remove(neighbors.begin(), neighbors.end(), &metaball), neighbors.end()); return neighbors; } void Grid::addMetaball(Metaball& metaball) { glm::ivec3 coords = cellCoords(metaball); addMetaball(metaball, coords); } void Grid::addMetaball(Metaball& metaball, glm::vec3 coords) { m_data[toIndex(coords)].push_back(&metaball); } void Grid::removeMetaball(Metaball& metaball) { glm::ivec3 coords = cellCoords(metaball); removeMetaball(metaball, coords); } void Grid::removeMetaball(Metaball& metaball, glm::vec3 coords) { std::vector<Metaball*> cell = getMetaballs(coords); //for (auto it = cell.begin(); it != cell.end(); it++) //{ // if ( (*it) == &metaball) // { // cell.erase(it); // return; // } //} cell.erase(std::remove(cell.begin(), cell.end(), &metaball), cell.end()); } void Grid::updateMetaball(Metaball& metaball, glm::vec3& newPosition) { glm::ivec3 oldCoords = cellCoords(metaball); metaball.position = newPosition; glm::ivec3 newCoords = cellCoords(metaball); if (oldCoords != newCoords) { removeMetaball(metaball, oldCoords); addMetaball(metaball, newCoords); } } glm::ivec3 Grid::cellCoords(Metaball& metaball) const { glm::vec3 coords = metaball.position; //grid coords coords -= m_frontBottomLeft; coords /= m_cellSize; return glm::ivec3( clampToGrid(static_cast<int>(floor(coords.x))), clampToGrid(static_cast<int>(floor(coords.y))), clampToGrid(static_cast<int>(floor(coords.z)))); } int Grid::toIndex(glm::ivec3 gridCoords) const { return m_size * m_size * gridCoords.x + m_size * gridCoords.y + gridCoords.z; } bool Grid::isInGrid(glm::ivec3 gridCoords) const { if ((gridCoords.x < 0 || gridCoords.x >= m_size) || (gridCoords.y < 0 || gridCoords.y >= m_size) || (gridCoords.z < 0 || gridCoords.z >= m_size)) return false; return true; } int Grid::clampToGrid(int value) const { if (value < 0) return 0; else if (value >= m_size) return m_size - 1; return value; } float Grid::front() { return m_frontBottomLeft.z; } float Grid::back() { return m_frontBottomLeft.z + m_cellSize * m_size; } float Grid::left() { return m_frontBottomLeft.x; } float Grid::right() { return m_frontBottomLeft.x + m_cellSize * m_size; } float Grid::bottom() { return m_frontBottomLeft.y; } float Grid::top() { return m_frontBottomLeft.y + m_cellSize * m_size; } <commit_msg>fixed dissappearing metaballs again<commit_after>#include "Grid.h" #include <algorithm> Grid::Grid(int size, float cellSize, glm::vec3 origin) : m_data(std::vector<std::vector<Metaball*>>(size * size * size)) , m_size(size) , m_cellSize(cellSize) , m_frontBottomLeft(origin) { for (auto& it : m_data) { it = std::vector<Metaball*>(); } } Grid::~Grid(){} std::vector<Metaball*>& Grid::getMetaballs(glm::ivec3 gridCoords) { return m_data[toIndex(gridCoords)]; } std::vector<Metaball*>& Grid::getMetaballs(int index) { return m_data[index]; } std::vector<Metaball*> Grid::getNeighbors(Metaball& metaball) { std::vector<Metaball*> neighbors{}; glm::ivec3 coords(cellCoords(metaball)); for (int xx = -1; xx <= 1; xx++) for (int yy = -1; yy <= 1; yy++) for (int zz = -1; zz <= 1; zz++) { glm::ivec3 neighborCoords = coords + glm::ivec3(xx, yy, zz); if (!isInGrid(neighborCoords)) continue; neighbors.insert( neighbors.end(), getMetaballs(neighborCoords).begin(), getMetaballs(neighborCoords).end()); } neighbors.erase(std::remove(neighbors.begin(), neighbors.end(), &metaball), neighbors.end()); return neighbors; } void Grid::addMetaball(Metaball& metaball) { glm::ivec3 coords = cellCoords(metaball); addMetaball(metaball, coords); } void Grid::addMetaball(Metaball& metaball, glm::vec3 coords) { m_data[toIndex(coords)].push_back(&metaball); } void Grid::removeMetaball(Metaball& metaball) { glm::ivec3 coords = cellCoords(metaball); removeMetaball(metaball, coords); } void Grid::removeMetaball(Metaball& metaball, glm::vec3 coords) { std::vector<Metaball*>& cell = getMetaballs(coords); cell.erase(std::remove(cell.begin(), cell.end(), &metaball), cell.end()); } void Grid::updateMetaball(Metaball& metaball, glm::vec3& newPosition) { glm::ivec3 oldCoords = cellCoords(metaball); metaball.position = newPosition; glm::ivec3 newCoords = cellCoords(metaball); if (oldCoords != newCoords) { removeMetaball(metaball, oldCoords); addMetaball(metaball, newCoords); } } glm::ivec3 Grid::cellCoords(Metaball& metaball) const { glm::vec3 coords = metaball.position; //grid coords coords -= m_frontBottomLeft; coords /= m_cellSize; return glm::ivec3( clampToGrid(static_cast<int>(floor(coords.x))), clampToGrid(static_cast<int>(floor(coords.y))), clampToGrid(static_cast<int>(floor(coords.z)))); } int Grid::toIndex(glm::ivec3 gridCoords) const { return m_size * m_size * gridCoords.x + m_size * gridCoords.y + gridCoords.z; } bool Grid::isInGrid(glm::ivec3 gridCoords) const { if ((gridCoords.x < 0 || gridCoords.x >= m_size) || (gridCoords.y < 0 || gridCoords.y >= m_size) || (gridCoords.z < 0 || gridCoords.z >= m_size)) return false; return true; } int Grid::clampToGrid(int value) const { if (value < 0) return 0; else if (value >= m_size) return m_size - 1; return value; } float Grid::front() { return m_frontBottomLeft.z; } float Grid::back() { return m_frontBottomLeft.z + m_cellSize * m_size; } float Grid::left() { return m_frontBottomLeft.x; } float Grid::right() { return m_frontBottomLeft.x + m_cellSize * m_size; } float Grid::bottom() { return m_frontBottomLeft.y; } float Grid::top() { return m_frontBottomLeft.y + m_cellSize * m_size; } <|endoftext|>
<commit_before>#include "WifiHandler.h" // initialize static members WifiState WifiHandler::_targetState = DISCONNECTED; WifiState WifiHandler::_currentState = DISCONNECTED; WiFiServer WifiHandler::_server; IPAddress WifiHandler::_ip; IPAddress WifiHandler::_gateway; IPAddress WifiHandler::_subnet; uint16_t WifiHandler::_serverPort; char* WifiHandler::_ssid; char* WifiHandler::_wifiPassword; void WifiHandler::onWiFiEvent(WiFiEvent_t event) { switch (event) { case SYSTEM_EVENT_WIFI_READY: printf("Wifi ready.\n"); _currentState = DISCONNECTED; break; case SYSTEM_EVENT_SCAN_DONE: printf("Wifi scan done.\n"); break; case SYSTEM_EVENT_STA_START: printf("Wifi started...\n"); _currentState = DISCONNECTED; break; case SYSTEM_EVENT_STA_STOP: printf("Wifi disconnected.\n"); _currentState = DISCONNECTED; break; case SYSTEM_EVENT_STA_CONNECTED: printf("Wifi connected.\n"); _currentState = CONNECTED; break; case SYSTEM_EVENT_STA_AUTHMODE_CHANGE: printf("Authmode of Access Point has changed.\n"); _currentState = DISCONNECTED; break; case SYSTEM_EVENT_STA_GOT_IP: printf("IP address: %s\n", WiFi.localIP().toString().c_str()); _currentState = CONNECTED_WITH_IP; break; case SYSTEM_EVENT_STA_DISCONNECTED: printf("WiFi lost connection.\n"); _currentState = DISCONNECTED; break; default: printf("[WiFi-event] Unhandled event: %d\n", event); break; } } void WifiHandler::init(IPAddress ip, IPAddress gateway, IPAddress subnet, uint16_t serverPort, char* ssid, char* wifiPassword) { _ip = ip; _gateway = gateway; _subnet = subnet; _serverPort = serverPort; _ssid = ssid; _wifiPassword = wifiPassword; _targetState = DISCONNECTED; _currentState = DISCONNECTED; _server = WiFiServer(serverPort); WiFi.onEvent(onWiFiEvent); } void WifiHandler::setTargetState(WifiState targetState){ _targetState = targetState; } WifiState WifiHandler::getState() { return _currentState; } void WifiHandler::loop(){ if (_currentState == _targetState){ return; } switch(_currentState){ case DISCONNECTED: WiFi.mode(WIFI_STA); // "station" mode WiFi.disconnect(); // to be on the safe side WiFi.config(_ip, _gateway, _subnet); // set specific ip... WiFi.begin(_ssid, _wifiPassword); // connect to router break; case CONNECTED: break; case CONNECTED_WITH_IP: break; case SERVER_LISTENING: break; case CLIENT_CONNECTED: break; case DATA_AVAILABLE: break; default: break; } } <commit_msg>need to wait for connected<commit_after>#include "WifiHandler.h" // initialize static members WifiState WifiHandler::_targetState = DISCONNECTED; WifiState WifiHandler::_currentState = DISCONNECTED; WiFiServer WifiHandler::_server; IPAddress WifiHandler::_ip; IPAddress WifiHandler::_gateway; IPAddress WifiHandler::_subnet; uint16_t WifiHandler::_serverPort; char* WifiHandler::_ssid; char* WifiHandler::_wifiPassword; void WifiHandler::onWiFiEvent(WiFiEvent_t event) { switch (event) { case SYSTEM_EVENT_WIFI_READY: printf("Wifi ready.\n"); _currentState = DISCONNECTED; break; case SYSTEM_EVENT_SCAN_DONE: printf("Wifi scan done.\n"); break; case SYSTEM_EVENT_STA_START: printf("Wifi started...\n"); _currentState = DISCONNECTED; break; case SYSTEM_EVENT_STA_STOP: printf("Wifi disconnected.\n"); _currentState = DISCONNECTED; break; case SYSTEM_EVENT_STA_CONNECTED: printf("Wifi connected.\n"); _currentState = CONNECTED; break; case SYSTEM_EVENT_STA_AUTHMODE_CHANGE: printf("Authmode of Access Point has changed.\n"); _currentState = DISCONNECTED; break; case SYSTEM_EVENT_STA_GOT_IP: printf("IP address: %s\n", WiFi.localIP().toString().c_str()); _currentState = CONNECTED_WITH_IP; break; case SYSTEM_EVENT_STA_DISCONNECTED: printf("WiFi lost connection.\n"); _currentState = DISCONNECTED; break; default: printf("[WiFi-event] Unhandled event: %d\n", event); break; } } void WifiHandler::init(IPAddress ip, IPAddress gateway, IPAddress subnet, uint16_t serverPort, char* ssid, char* wifiPassword) { _ip = ip; _gateway = gateway; _subnet = subnet; _serverPort = serverPort; _ssid = ssid; _wifiPassword = wifiPassword; _targetState = DISCONNECTED; _currentState = DISCONNECTED; _server = WiFiServer(serverPort); WiFi.onEvent(onWiFiEvent); } void WifiHandler::setTargetState(WifiState targetState){ _targetState = targetState; } WifiState WifiHandler::getState() { return _currentState; } void WifiHandler::loop(){ if (_currentState == _targetState){ return; } switch(_currentState){ case DISCONNECTED: WiFi.mode(WIFI_STA); // "station" mode WiFi.disconnect(); // to be on the safe side WiFi.config(_ip, _gateway, _subnet); // set specific ip... WiFi.begin(_ssid, _wifiPassword); // connect to router while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } break; case CONNECTED: break; case CONNECTED_WITH_IP: break; case SERVER_LISTENING: break; case CLIENT_CONNECTED: break; case DATA_AVAILABLE: break; default: break; } } <|endoftext|>
<commit_before>// // Aspia Project // Copyright (C) 2020 Dmitry Chapyshev <dmitry@aspia.ru> // // 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 <https://www.gnu.org/licenses/>. // #include "router/shared_key_pool.h" #include "base/logging.h" #include <map> namespace router { class SharedKeyPool::Impl { public: explicit Impl(Delegate* delegate); ~Impl() = default; void dettach(); void addKey(const std::string& host, uint16_t port, const proto::RelayKey& key); std::optional<Credentials> takeCredentials(); void removeKeysForRelay(const std::string& host); void clear(); size_t countForRelay(const std::string& host) const; size_t count() const; bool isEmpty() const; private: struct RelayInfo { explicit RelayInfo(uint16_t port) : port(port) { // Nothing } uint16_t port = 0; std::vector<proto::RelayKey> keys; }; std::map<std::string, RelayInfo> pool_; Delegate* delegate_; DISALLOW_COPY_AND_ASSIGN(Impl); }; SharedKeyPool::Impl::Impl(Delegate* delegate) : delegate_(delegate) { DCHECK(delegate_); } void SharedKeyPool::Impl::dettach() { delegate_ = nullptr; } void SharedKeyPool::Impl::addKey(const std::string& host, uint16_t port, const proto::RelayKey& key) { if (host.empty() || !port) { LOG(LS_ERROR) << "Empty host name or invalid port"; return; } auto relay = pool_.find(host); if (relay == pool_.end()) { LOG(LS_INFO) << "Host not found in pool. It will be added"; relay = pool_.emplace(host, RelayInfo(port)).first; } relay->second.keys.emplace_back(std::move(key)); } std::optional<SharedKeyPool::Credentials> SharedKeyPool::Impl::takeCredentials() { if (pool_.empty()) { LOG(LS_WARNING) << "Empty key pool"; return std::nullopt; } auto preffered_relay = pool_.end(); size_t max_count = 0; for (auto it = pool_.begin(); it != pool_.end(); ++it) { size_t count = it->second.keys.size(); if (count > max_count) { preffered_relay = it; max_count = count; } } if (preffered_relay == pool_.end()) { LOG(LS_WARNING) << "Empty key pool"; return std::nullopt; } LOG(LS_INFO) << "Preffered relay: " << preffered_relay->first; if (preffered_relay->second.keys.empty()) { LOG(LS_ERROR) << "Empty key pool for relay"; return std::nullopt; } Credentials credentials; credentials.host = preffered_relay->first; credentials.port = preffered_relay->second.port; credentials.key = std::move(preffered_relay->second.keys.back()); // Removing the key from the pool. preffered_relay->second.keys.pop_back(); if (preffered_relay->second.keys.empty()) { LOG(LS_INFO) << "Last key in the pool for relay. The relay will be removed from the pool"; pool_.erase(preffered_relay->first); } if (delegate_) delegate_->onPoolKeyUsed(credentials.host, credentials.key.key_id()); return credentials; } void SharedKeyPool::Impl::removeKeysForRelay(const std::string& host) { pool_.erase(host); } void SharedKeyPool::Impl::clear() { pool_.clear(); } size_t SharedKeyPool::Impl::countForRelay(const std::string& host) const { auto result = pool_.find(host); if (result == pool_.end()) return 0; return result->second.keys.size(); } size_t SharedKeyPool::Impl::count() const { size_t result = 0; for (const auto& relay : pool_) result += relay.second.keys.size(); return result; } bool SharedKeyPool::Impl::isEmpty() const { return pool_.empty(); } SharedKeyPool::SharedKeyPool(Delegate* delegate) : impl_(std::make_shared<Impl>(delegate)), is_primary_(true) { // Nothing } SharedKeyPool::SharedKeyPool(std::shared_ptr<Impl> impl) : impl_(std::move(impl)), is_primary_(false) { // Nothing } SharedKeyPool::~SharedKeyPool() { if (is_primary_) impl_->dettach(); } std::unique_ptr<SharedKeyPool> SharedKeyPool::share() { return std::unique_ptr<SharedKeyPool>(new SharedKeyPool(impl_)); } void SharedKeyPool::addKey(const std::string& host, uint16_t port, const proto::RelayKey& key) { impl_->addKey(host, port, key); } std::optional<SharedKeyPool::Credentials> SharedKeyPool::takeCredentials() { return impl_->takeCredentials(); } void SharedKeyPool::removeKeysForRelay(const std::string& host) { impl_->removeKeysForRelay(host); } void SharedKeyPool::clear() { impl_->clear(); } size_t SharedKeyPool::countForRelay(const std::string& host) const { return impl_->countForRelay(host); } size_t SharedKeyPool::count() const { return impl_->count(); } bool SharedKeyPool::isEmpty() const { return impl_->isEmpty(); } } // namespace router <commit_msg>Added debug messages.<commit_after>// // Aspia Project // Copyright (C) 2020 Dmitry Chapyshev <dmitry@aspia.ru> // // 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 <https://www.gnu.org/licenses/>. // #include "router/shared_key_pool.h" #include "base/logging.h" #include <map> namespace router { class SharedKeyPool::Impl { public: explicit Impl(Delegate* delegate); ~Impl() = default; void dettach(); void addKey(const std::string& host, uint16_t port, const proto::RelayKey& key); std::optional<Credentials> takeCredentials(); void removeKeysForRelay(const std::string& host); void clear(); size_t countForRelay(const std::string& host) const; size_t count() const; bool isEmpty() const; private: struct RelayInfo { explicit RelayInfo(uint16_t port) : port(port) { // Nothing } uint16_t port = 0; std::vector<proto::RelayKey> keys; }; std::map<std::string, RelayInfo> pool_; Delegate* delegate_; DISALLOW_COPY_AND_ASSIGN(Impl); }; SharedKeyPool::Impl::Impl(Delegate* delegate) : delegate_(delegate) { DCHECK(delegate_); } void SharedKeyPool::Impl::dettach() { delegate_ = nullptr; } void SharedKeyPool::Impl::addKey(const std::string& host, uint16_t port, const proto::RelayKey& key) { if (host.empty() || !port) { LOG(LS_ERROR) << "Empty host name or invalid port"; return; } auto relay = pool_.find(host); if (relay == pool_.end()) { LOG(LS_INFO) << "Host not found in pool. It will be added"; relay = pool_.emplace(host, RelayInfo(port)).first; } LOG(LS_INFO) << "Added key with id " << key.key_id() << " for host '" << host << "'"; relay->second.keys.emplace_back(std::move(key)); } std::optional<SharedKeyPool::Credentials> SharedKeyPool::Impl::takeCredentials() { if (pool_.empty()) { LOG(LS_WARNING) << "Empty key pool"; return std::nullopt; } auto preffered_relay = pool_.end(); size_t max_count = 0; for (auto it = pool_.begin(); it != pool_.end(); ++it) { size_t count = it->second.keys.size(); if (count > max_count) { preffered_relay = it; max_count = count; } } if (preffered_relay == pool_.end()) { LOG(LS_WARNING) << "Empty key pool"; return std::nullopt; } LOG(LS_INFO) << "Preffered relay: " << preffered_relay->first; if (preffered_relay->second.keys.empty()) { LOG(LS_ERROR) << "Empty key pool for relay"; return std::nullopt; } Credentials credentials; credentials.host = preffered_relay->first; credentials.port = preffered_relay->second.port; credentials.key = std::move(preffered_relay->second.keys.back()); // Removing the key from the pool. preffered_relay->second.keys.pop_back(); if (preffered_relay->second.keys.empty()) { LOG(LS_INFO) << "Last key in the pool for relay. The relay will be removed from the pool"; pool_.erase(preffered_relay->first); } if (delegate_) delegate_->onPoolKeyUsed(credentials.host, credentials.key.key_id()); return credentials; } void SharedKeyPool::Impl::removeKeysForRelay(const std::string& host) { LOG(LS_INFO) << "All keys for relay '" << host << "' removed"; pool_.erase(host); } void SharedKeyPool::Impl::clear() { LOG(LS_INFO) << "Key pool cleared"; pool_.clear(); } size_t SharedKeyPool::Impl::countForRelay(const std::string& host) const { auto result = pool_.find(host); if (result == pool_.end()) return 0; return result->second.keys.size(); } size_t SharedKeyPool::Impl::count() const { size_t result = 0; for (const auto& relay : pool_) result += relay.second.keys.size(); return result; } bool SharedKeyPool::Impl::isEmpty() const { return pool_.empty(); } SharedKeyPool::SharedKeyPool(Delegate* delegate) : impl_(std::make_shared<Impl>(delegate)), is_primary_(true) { // Nothing } SharedKeyPool::SharedKeyPool(std::shared_ptr<Impl> impl) : impl_(std::move(impl)), is_primary_(false) { // Nothing } SharedKeyPool::~SharedKeyPool() { if (is_primary_) impl_->dettach(); } std::unique_ptr<SharedKeyPool> SharedKeyPool::share() { return std::unique_ptr<SharedKeyPool>(new SharedKeyPool(impl_)); } void SharedKeyPool::addKey(const std::string& host, uint16_t port, const proto::RelayKey& key) { impl_->addKey(host, port, key); } std::optional<SharedKeyPool::Credentials> SharedKeyPool::takeCredentials() { return impl_->takeCredentials(); } void SharedKeyPool::removeKeysForRelay(const std::string& host) { impl_->removeKeysForRelay(host); } void SharedKeyPool::clear() { impl_->clear(); } size_t SharedKeyPool::countForRelay(const std::string& host) const { return impl_->countForRelay(host); } size_t SharedKeyPool::count() const { return impl_->count(); } bool SharedKeyPool::isEmpty() const { return impl_->isEmpty(); } } // namespace router <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: ScatterChartType.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: obo $ $Date: 2006-09-17 13:20:31 $ * * 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 * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_chart2.hxx" #include "ScatterChartType.hxx" #include "PropertyHelper.hxx" #include "algohelper.hxx" #include "macros.hxx" #ifndef _COM_SUN_STAR_BEANS_PROPERTYATTRIBUTE_HPP_ #include <com/sun/star/beans/PropertyAttribute.hpp> #endif #ifndef _COM_SUN_STAR_CHART2_CURVESTYLE_HPP_ #include <com/sun/star/chart2/CurveStyle.hpp> #endif using namespace ::com::sun::star; using ::rtl::OUString; using ::com::sun::star::beans::Property; using ::com::sun::star::uno::Sequence; using ::com::sun::star::uno::Reference; using ::com::sun::star::uno::Any; using ::osl::MutexGuard; namespace { enum { PROP_SCATTERCHARTTYPE_DIMENSION, PROP_SCATTERCHARTTYPE_CURVE_STYLE, PROP_SCATTERCHARTTYPE_CURVE_RESOLUTION, PROP_SCATTERCHARTTYPE_SPLINE_ORDER }; void lcl_AddPropertiesToVector( ::std::vector< Property > & rOutProperties ) { rOutProperties.push_back( Property( C2U( "Dimension" ), PROP_SCATTERCHARTTYPE_DIMENSION, ::getCppuType( reinterpret_cast< const sal_Int32 * >(0)), beans::PropertyAttribute::BOUND | beans::PropertyAttribute::MAYBEDEFAULT )); rOutProperties.push_back( Property( C2U( "CurveStyle" ), PROP_SCATTERCHARTTYPE_CURVE_STYLE, ::getCppuType( reinterpret_cast< const chart2::CurveStyle * >(0)), beans::PropertyAttribute::BOUND | beans::PropertyAttribute::MAYBEDEFAULT )); rOutProperties.push_back( Property( C2U( "CurveResolution" ), PROP_SCATTERCHARTTYPE_CURVE_RESOLUTION, ::getCppuType( reinterpret_cast< const sal_Int32 * >(0)), beans::PropertyAttribute::BOUND | beans::PropertyAttribute::MAYBEDEFAULT )); rOutProperties.push_back( Property( C2U( "SplineOrder" ), PROP_SCATTERCHARTTYPE_SPLINE_ORDER, ::getCppuType( reinterpret_cast< const sal_Int32 * >(0)), beans::PropertyAttribute::BOUND | beans::PropertyAttribute::MAYBEDEFAULT )); } void lcl_AddDefaultsToMap( ::chart::helper::tPropertyValueMap & rOutMap ) { // must match default in CTOR! OSL_ASSERT( rOutMap.end() == rOutMap.find( PROP_SCATTERCHARTTYPE_DIMENSION )); rOutMap[ PROP_SCATTERCHARTTYPE_DIMENSION ] = uno::makeAny( sal_Int32( 2 ) ); OSL_ASSERT( rOutMap.end() == rOutMap.find( PROP_SCATTERCHARTTYPE_CURVE_STYLE )); rOutMap[ PROP_SCATTERCHARTTYPE_CURVE_STYLE ] = uno::makeAny( chart2::CurveStyle_LINES ); OSL_ASSERT( rOutMap.end() == rOutMap.find( PROP_SCATTERCHARTTYPE_CURVE_RESOLUTION )); rOutMap[ PROP_SCATTERCHARTTYPE_CURVE_RESOLUTION ] = uno::makeAny( sal_Int32( 20 ) ); // todo: check whether order 3 means polygons of order 3 or 2. (see // http://www.people.nnov.ru/fractal/Splines/Basis.htm ) OSL_ASSERT( rOutMap.end() == rOutMap.find( PROP_SCATTERCHARTTYPE_SPLINE_ORDER )); rOutMap[ PROP_SCATTERCHARTTYPE_SPLINE_ORDER ] = uno::makeAny( sal_Int32( 3 ) ); } const Sequence< Property > & lcl_GetPropertySequence() { static Sequence< Property > aPropSeq; // /-- ::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() ); if( 0 == aPropSeq.getLength() ) { // get properties ::std::vector< ::com::sun::star::beans::Property > aProperties; lcl_AddPropertiesToVector( aProperties ); // and sort them for access via bsearch ::std::sort( aProperties.begin(), aProperties.end(), ::chart::helper::PropertyNameLess() ); // transfer result to static Sequence aPropSeq = ::chart::helper::VectorToSequence( aProperties ); } return aPropSeq; } } // anonymous namespace namespace chart { ScatterChartType::ScatterChartType( sal_Int32 nDim /* = 2 */, chart2::CurveStyle eCurveStyle /* chart2::CurveStyle_LINES */ , sal_Int32 nResolution /* = 20 */, sal_Int32 nOrder /* = 3 */ ) : ChartType( nDim ) { if( eCurveStyle != chart2::CurveStyle_LINES ) setFastPropertyValue_NoBroadcast( PROP_SCATTERCHARTTYPE_CURVE_STYLE, uno::makeAny( eCurveStyle )); if( nResolution != 20 ) setFastPropertyValue_NoBroadcast( PROP_SCATTERCHARTTYPE_CURVE_RESOLUTION, uno::makeAny( nResolution )); if( nOrder != 3 ) setFastPropertyValue_NoBroadcast( PROP_SCATTERCHARTTYPE_SPLINE_ORDER, uno::makeAny( nOrder )); } ScatterChartType::~ScatterChartType() {} // ____ XChartType ____ ::rtl::OUString SAL_CALL ScatterChartType::getChartType() throw (uno::RuntimeException) { return ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.chart2.ScatterChart" )); } // ____ OPropertySet ____ uno::Any ScatterChartType::GetDefaultValue( sal_Int32 nHandle ) const throw(beans::UnknownPropertyException) { static helper::tPropertyValueMap aStaticDefaults; // /-- ::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() ); if( 0 == aStaticDefaults.size() ) { // initialize defaults lcl_AddDefaultsToMap( aStaticDefaults ); } helper::tPropertyValueMap::const_iterator aFound( aStaticDefaults.find( nHandle )); if( aFound == aStaticDefaults.end()) return uno::Any(); return (*aFound).second; // \-- } // ____ OPropertySet ____ ::cppu::IPropertyArrayHelper & SAL_CALL ScatterChartType::getInfoHelper() { static ::cppu::OPropertyArrayHelper aArrayHelper( lcl_GetPropertySequence(), /* bSorted = */ sal_True ); return aArrayHelper; } // ____ XPropertySet ____ uno::Reference< beans::XPropertySetInfo > SAL_CALL ScatterChartType::getPropertySetInfo() throw (uno::RuntimeException) { static uno::Reference< beans::XPropertySetInfo > xInfo; // /-- ::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() ); if( !xInfo.is()) { xInfo = ::cppu::OPropertySetHelper::createPropertySetInfo( getInfoHelper()); } return xInfo; // \-- } } // namespace chart <commit_msg>INTEGRATION: CWS chart2mst3 (1.3.4); FILE MERGED 2006/10/18 17:14:53 bm 1.3.4.16: RESYNC: (1.4-1.5); FILE MERGED 2006/04/10 12:25:14 iha 1.3.4.15: api restructure axis, grids, scales and increments 2006/03/29 22:24:45 iha 1.3.4.14: restructure legend entry creation + legend entries in data labels 2005/11/25 16:21:36 iha 1.3.4.13: correct labels at z axis for deep stacking 2005/11/14 13:47:45 iha 1.3.4.12: createCoordinateSystem without categories for scatter chart 2005/10/07 12:05:33 bm 1.3.4.11: RESYNC: (1.3-1.4); FILE MERGED 2005/08/03 16:36:25 bm 1.3.4.10: algohelper.hxx split up into CommonFunctors.hxx ContainerHelper.hxx CloneHelper.hxx 2005/04/11 09:38:48 iha 1.3.4.9: defines for servicenames for charttypes (fixed apply to 2nd axis again) 2005/03/30 16:31:13 bm 1.3.4.8: make model cloneable (+first undo implementation) 2004/09/16 14:42:47 bm 1.3.4.7: API simplification 2004/09/16 12:27:29 bm 1.3.4.6: API simplification 2004/05/27 17:41:54 bm 1.3.4.5: error-bars not supported yet 2004/04/01 10:53:12 bm 1.3.4.4: XChartType: may return a coordinate system now 2004/03/19 16:44:10 bm 1.3.4.3: symbols in legend 2004/03/02 09:49:19 bm 1.3.4.2: XChartTypeInterface changed 2004/02/13 16:51:44 bm 1.3.4.1: join from changes on branch bm_post_chart01<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: ScatterChartType.cxx,v $ * * $Revision: 1.6 $ * * last change: $Author: vg $ $Date: 2007-05-22 18:51:37 $ * * 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 * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_chart2.hxx" #include "ScatterChartType.hxx" #include "PropertyHelper.hxx" #include "macros.hxx" #include "servicenames_charttypes.hxx" #include "ContainerHelper.hxx" #include "CartesianCoordinateSystem.hxx" #include "Scaling.hxx" #include "AxisIndexDefines.hxx" #ifndef _COM_SUN_STAR_BEANS_PROPERTYATTRIBUTE_HPP_ #include <com/sun/star/beans/PropertyAttribute.hpp> #endif #ifndef _COM_SUN_STAR_CHART2_AXISTYPE_HPP_ #include <com/sun/star/chart2/AxisType.hpp> #endif #ifndef _COM_SUN_STAR_CHART2_CURVESTYLE_HPP_ #include <com/sun/star/chart2/CurveStyle.hpp> #endif using namespace ::com::sun::star; using ::rtl::OUString; using ::com::sun::star::beans::Property; using ::com::sun::star::uno::Sequence; using ::com::sun::star::uno::Reference; using ::com::sun::star::uno::Any; using ::osl::MutexGuard; namespace { enum { PROP_SCATTERCHARTTYPE_CURVE_STYLE, PROP_SCATTERCHARTTYPE_CURVE_RESOLUTION, PROP_SCATTERCHARTTYPE_SPLINE_ORDER }; void lcl_AddPropertiesToVector( ::std::vector< Property > & rOutProperties ) { rOutProperties.push_back( Property( C2U( "CurveStyle" ), PROP_SCATTERCHARTTYPE_CURVE_STYLE, ::getCppuType( reinterpret_cast< const chart2::CurveStyle * >(0)), beans::PropertyAttribute::BOUND | beans::PropertyAttribute::MAYBEDEFAULT )); rOutProperties.push_back( Property( C2U( "CurveResolution" ), PROP_SCATTERCHARTTYPE_CURVE_RESOLUTION, ::getCppuType( reinterpret_cast< const sal_Int32 * >(0)), beans::PropertyAttribute::BOUND | beans::PropertyAttribute::MAYBEDEFAULT )); rOutProperties.push_back( Property( C2U( "SplineOrder" ), PROP_SCATTERCHARTTYPE_SPLINE_ORDER, ::getCppuType( reinterpret_cast< const sal_Int32 * >(0)), beans::PropertyAttribute::BOUND | beans::PropertyAttribute::MAYBEDEFAULT )); } void lcl_AddDefaultsToMap( ::chart::tPropertyValueMap & rOutMap ) { OSL_ASSERT( rOutMap.end() == rOutMap.find( PROP_SCATTERCHARTTYPE_CURVE_STYLE )); rOutMap[ PROP_SCATTERCHARTTYPE_CURVE_STYLE ] = uno::makeAny( chart2::CurveStyle_LINES ); OSL_ASSERT( rOutMap.end() == rOutMap.find( PROP_SCATTERCHARTTYPE_CURVE_RESOLUTION )); rOutMap[ PROP_SCATTERCHARTTYPE_CURVE_RESOLUTION ] = uno::makeAny( sal_Int32( 20 ) ); // todo: check whether order 3 means polygons of order 3 or 2. (see // http://www.people.nnov.ru/fractal/Splines/Basis.htm ) OSL_ASSERT( rOutMap.end() == rOutMap.find( PROP_SCATTERCHARTTYPE_SPLINE_ORDER )); rOutMap[ PROP_SCATTERCHARTTYPE_SPLINE_ORDER ] = uno::makeAny( sal_Int32( 3 ) ); } const Sequence< Property > & lcl_GetPropertySequence() { static Sequence< Property > aPropSeq; // /-- ::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() ); if( 0 == aPropSeq.getLength() ) { // get properties ::std::vector< ::com::sun::star::beans::Property > aProperties; lcl_AddPropertiesToVector( aProperties ); // and sort them for access via bsearch ::std::sort( aProperties.begin(), aProperties.end(), ::chart::PropertyNameLess() ); // transfer result to static Sequence aPropSeq = ::chart::ContainerHelper::ContainerToSequence( aProperties ); } return aPropSeq; } } // anonymous namespace namespace chart { ScatterChartType::ScatterChartType( const uno::Reference< uno::XComponentContext > & xContext, chart2::CurveStyle eCurveStyle /* chart2::CurveStyle_LINES */ , sal_Int32 nResolution /* = 20 */, sal_Int32 nOrder /* = 3 */ ) : ChartType( xContext ) { if( eCurveStyle != chart2::CurveStyle_LINES ) setFastPropertyValue_NoBroadcast( PROP_SCATTERCHARTTYPE_CURVE_STYLE, uno::makeAny( eCurveStyle )); if( nResolution != 20 ) setFastPropertyValue_NoBroadcast( PROP_SCATTERCHARTTYPE_CURVE_RESOLUTION, uno::makeAny( nResolution )); if( nOrder != 3 ) setFastPropertyValue_NoBroadcast( PROP_SCATTERCHARTTYPE_SPLINE_ORDER, uno::makeAny( nOrder )); } ScatterChartType::ScatterChartType( const ScatterChartType & rOther ) : ChartType( rOther ) { } ScatterChartType::~ScatterChartType() {} // ____ XCloneable ____ uno::Reference< util::XCloneable > SAL_CALL ScatterChartType::createClone() throw (uno::RuntimeException) { return uno::Reference< util::XCloneable >( new ScatterChartType( *this )); } // ____ XChartType ____ // ____ XChartType ____ Reference< chart2::XCoordinateSystem > SAL_CALL ScatterChartType::createCoordinateSystem( ::sal_Int32 DimensionCount ) throw (lang::IllegalArgumentException, uno::RuntimeException) { Reference< chart2::XCoordinateSystem > xResult( new CartesianCoordinateSystem( GetComponentContext(), DimensionCount, /* bSwapXAndYAxis */ sal_False )); for( sal_Int32 i=0; i<DimensionCount; ++i ) { Reference< chart2::XAxis > xAxis( xResult->getAxisByDimension( i, MAIN_AXIS_INDEX ) ); if( !xAxis.is() ) { OSL_ENSURE(false,"a created coordinate system should have an axis for each dimension"); continue; } chart2::ScaleData aScaleData = xAxis->getScaleData(); aScaleData.Orientation = chart2::AxisOrientation_MATHEMATICAL; aScaleData.Scaling = new LinearScaling( 1.0, 0.0 ); if( i == 2 ) aScaleData.AxisType = chart2::AxisType::SERIES; else aScaleData.AxisType = chart2::AxisType::REALNUMBER; xAxis->setScaleData( aScaleData ); } return xResult; } ::rtl::OUString SAL_CALL ScatterChartType::getChartType() throw (uno::RuntimeException) { return CHART2_SERVICE_NAME_CHARTTYPE_SCATTER; } uno::Sequence< ::rtl::OUString > SAL_CALL ScatterChartType::getSupportedMandatoryRoles() throw (uno::RuntimeException) { static uno::Sequence< ::rtl::OUString > aMandRolesSeq; if( aMandRolesSeq.getLength() == 0 ) { aMandRolesSeq.realloc( 3 ); aMandRolesSeq[0] = C2U( "label" ); aMandRolesSeq[1] = C2U( "values-x" ); aMandRolesSeq[2] = C2U( "values-y" ); } return aMandRolesSeq; } uno::Sequence< ::rtl::OUString > SAL_CALL ScatterChartType::getSupportedOptionalRoles() throw (uno::RuntimeException) { static uno::Sequence< ::rtl::OUString > aOptRolesSeq; // if( aOptRolesSeq.getLength() == 0 ) // { // aOptRolesSeq.realloc( 2 ); // aOptRolesSeq[0] = C2U( "error-bars-x" ); // aOptRolesSeq[1] = C2U( "error-bars-y" ); // } return aOptRolesSeq; } // ____ OPropertySet ____ uno::Any ScatterChartType::GetDefaultValue( sal_Int32 nHandle ) const throw(beans::UnknownPropertyException) { static tPropertyValueMap aStaticDefaults; // /-- ::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() ); if( 0 == aStaticDefaults.size() ) { // initialize defaults lcl_AddDefaultsToMap( aStaticDefaults ); } tPropertyValueMap::const_iterator aFound( aStaticDefaults.find( nHandle )); if( aFound == aStaticDefaults.end()) return uno::Any(); return (*aFound).second; // \-- } // ____ OPropertySet ____ ::cppu::IPropertyArrayHelper & SAL_CALL ScatterChartType::getInfoHelper() { static ::cppu::OPropertyArrayHelper aArrayHelper( lcl_GetPropertySequence(), /* bSorted = */ sal_True ); return aArrayHelper; } // ____ XPropertySet ____ uno::Reference< beans::XPropertySetInfo > SAL_CALL ScatterChartType::getPropertySetInfo() throw (uno::RuntimeException) { static uno::Reference< beans::XPropertySetInfo > xInfo; // /-- ::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() ); if( !xInfo.is()) { xInfo = ::cppu::OPropertySetHelper::createPropertySetInfo( getInfoHelper()); } return xInfo; // \-- } uno::Sequence< ::rtl::OUString > ScatterChartType::getSupportedServiceNames_Static() { uno::Sequence< ::rtl::OUString > aServices( 3 ); aServices[ 0 ] = CHART2_SERVICE_NAME_CHARTTYPE_SCATTER; aServices[ 1 ] = C2U( "com.sun.star.chart2.ChartType" ); aServices[ 2 ] = C2U( "com.sun.star.beans.PropertySet" ); return aServices; } // implement XServiceInfo methods basing upon getSupportedServiceNames_Static APPHELPER_XSERVICEINFO_IMPL( ScatterChartType, C2U( "com.sun.star.comp.chart.ScatterChartType" )); } // namespace chart <|endoftext|>
<commit_before>#include "RiggedDrawable.h" #include <glbinding/gl/enum.h> #include <globjects/Buffer.h> #include <globjects/VertexArray.h> #include <globjects/VertexAttributeBinding.h> #include <gloperate/primitives/PolygonalGeometry.h> using namespace gl; RiggedDrawable::RiggedDrawable(const gloperate::PolygonalGeometry &geometry) : gloperate::PolygonalDrawable(geometry) { if (geometry.isRigged()) { m_vertexBoneIndices = new globjects::Buffer; m_vertexBoneIndices->setData(geometry.vertexBoneIndices(), GL_STATIC_DRAW); m_vertexBoneWeights = new globjects::Buffer; m_vertexBoneWeights->setData(geometry.vertexBoneWeights(), GL_STATIC_DRAW); m_bindTransforms = geometry.bindTransforms(); m_boneMapping = geometry.boneMapping(); } m_vao->bind(); if (geometry.isRigged()) { auto vertexBinding = m_vao->binding(3); vertexBinding->setAttribute(3); vertexBinding->setBuffer(m_vertexBoneIndices,0,sizeof(glm::ivec4)); vertexBinding->setFormat(4, gl::GL_INT64_NV); m_vao->enable(3); vertexBinding = m_vao->binding(4); vertexBinding->setAttribute(4); vertexBinding->setBuffer(m_vertexBoneWeights,0,sizeof(glm::vec4)); vertexBinding->setFormat(4, gl::GL_FLOAT); m_vao->enable(4); } m_vao->unbind(); } <commit_msg>properly passing in integers<commit_after>#include "RiggedDrawable.h" #include <glbinding/gl/enum.h> #include <globjects/Buffer.h> #include <globjects/VertexArray.h> #include <globjects/VertexAttributeBinding.h> #include <gloperate/primitives/PolygonalGeometry.h> using namespace gl; RiggedDrawable::RiggedDrawable(const gloperate::PolygonalGeometry &geometry) : gloperate::PolygonalDrawable(geometry) { if (geometry.isRigged()) { m_vertexBoneIndices = new globjects::Buffer; m_vertexBoneIndices->setData(geometry.vertexBoneIndices(), GL_STATIC_DRAW); m_vertexBoneWeights = new globjects::Buffer; m_vertexBoneWeights->setData(geometry.vertexBoneWeights(), GL_STATIC_DRAW); m_bindTransforms = geometry.bindTransforms(); m_boneMapping = geometry.boneMapping(); } m_vao->bind(); if (geometry.isRigged()) { auto vertexBinding = m_vao->binding(3); vertexBinding->setAttribute(3); auto length = sizeof(glm::ivec4); length = length; vertexBinding->setBuffer(m_vertexBoneIndices,0,sizeof(glm::ivec4)); vertexBinding->setIFormat(4, gl::GL_INT, 0); m_vao->enable(3); vertexBinding = m_vao->binding(4); vertexBinding->setAttribute(4); vertexBinding->setBuffer(m_vertexBoneWeights,0,sizeof(glm::vec4)); vertexBinding->setFormat(4, gl::GL_FLOAT); m_vao->enable(4); } m_vao->unbind(); } <|endoftext|>
<commit_before>/* * SerialTopLvlProtocoll.cpp * * Created on: 18.05.2017 * Author: aca619 */ #include <cstring> #include "SerialProtocoll.h" #include "ITopLvlProtocoll.h" #include "../../Tests/Serial/SerialTestStub.h" #include <string.h> #include <Logger.h> #include <Logscope.h> #include "PuckSignal.h" using namespace Serial_n; /** * This is an unidirectional Protocoll over Serial * One must always be the Sender of Pucks * One must always be the receiver Pucks * @param mode Be receiver or sender? */ SerialProtocoll::SerialProtocoll(Serial_mode mode) { // TODO mode is not implemented } SerialProtocoll::~SerialProtocoll() { // TODO Auto-generated destructor stub } pulse SerialProtocoll::convToPulse(void *buff) { pulse resu; ser_proto_msg msg_in = *(ser_proto_msg*)buff; resu.code = SER_IN; switch(msg_in){ case ACCEPT_SER: case STOP_SER: case RESUME_SER: case INVALID_SER: case RECEIVED_SER: case SLIDE_FULL_SER: case POL_SER: case ERROR_SER: case ESTOP_SER: case SLIDE_EMTPY_SER: resu.value = msg_in; break; case TRANSM_SER: { resu.code = TRANSM_IN; ISerializable *obj = new PuckSignal::PuckType; obj->deserialize(((char*)buff) + sizeof(ser_proto_msg)); //cast to char* because void* cant be used in arith resu.value = (uint32_t) obj; } break; default: LOG_WARNING << "[SerialProtocoll] convToPulse() Got an undefined messages: " << (int)msg_in << endl; break; //TODO ERROR } return resu; } serialized SerialProtocoll::wrapInFrame(int8_t code, int32_t value) { serialized resu; switch(code){ case SER_IN: //Inout nothing needs to be done case SER_OUT : { int32_t* msg_type = new int32_t; *msg_type = value; resu.size = sizeof(int32_t); resu.obj = msg_type; break; } case TRANSM_IN: case TRANSM_OUT: { serialized tmp; ISerializable* obj = (ISerializable*) value; tmp = obj->serialize(); char* frame = new char[tmp.size+ sizeof(ser_proto_msg)]; //make space for msg type memcpy((frame+sizeof(ser_proto_msg)), tmp.obj, tmp.size); ser_proto_msg *msg_ptr = (ser_proto_msg *) frame; *msg_ptr = TRANSM_SER; resu.obj = frame; resu.size = tmp.size + sizeof(ser_proto_msg); break; } default: //TODO error handler LOG_WARNING << "[SerialProtocoll] Trying to wrap unknown code: " << (int)msg_in << endl; break; } return resu; } pulse SerialProtocoll::protocollState(int8_t int8, int32_t int32) { pulse empty; //TODO Fill with logic return empty; } <commit_msg>snap<commit_after>/* * SerialTopLvlProtocoll.cpp * * Created on: 18.05.2017 * Author: aca619 */ #include <cstring> #include "SerialProtocoll.h" #include "ITopLvlProtocoll.h" #include "../../Tests/Serial/SerialTestStub.h" #include <string.h> #include <Logger.h> #include <Logscope.h> #include "PuckSignal.h" using namespace Serial_n; /** * This is an unidirectional Protocoll over Serial * One must always be the Sender of Pucks * One must always be the receiver Pucks * @param mode Be receiver or sender? */ SerialProtocoll::SerialProtocoll(Serial_mode mode) { // TODO mode is not implemented } SerialProtocoll::~SerialProtocoll() { // TODO Auto-generated destructor stub } pulse SerialProtocoll::convToPulse(void *buff) { pulse resu; ser_proto_msg msg_in = *(ser_proto_msg*)buff; resu.code = SER_IN; switch(msg_in){ case ACCEPT_SER: case STOP_SER: case RESUME_SER: case INVALID_SER: case RECEIVED_SER: case SLIDE_FULL_SER: case POL_SER: case ERROR_SER: case ESTOP_SER: case SLIDE_EMTPY_SER: resu.value = msg_in; break; case TRANSM_SER: { resu.code = TRANSM_IN; ISerializable *obj = new PuckSignal::PuckType; obj->deserialize(((char*)buff) + sizeof(ser_proto_msg)); //cast to char* because void* cant be used in arith resu.value = (uint32_t) obj; } break; default: LOG_WARNING << "[SerialProtocoll] convToPulse() Got an undefined messages: " << (int)msg_in << endl; break; //TODO ERROR } return resu; } serialized SerialProtocoll::wrapInFrame(int8_t code, int32_t value) { serialized resu; switch(code){ case SER_IN: //Inout nothing needs to be done case SER_OUT : { int32_t* msg_type = new int32_t; *msg_type = value; resu.size = sizeof(int32_t); resu.obj = msg_type; break; } case TRANSM_IN: case TRANSM_OUT: { serialized tmp; ISerializable* obj = (ISerializable*) value; tmp = obj->serialize(); char* frame = new char[tmp.size+ sizeof(ser_proto_msg)]; //make space for msg type memcpy((frame+sizeof(ser_proto_msg)), tmp.obj, tmp.size); ser_proto_msg *msg_ptr = (ser_proto_msg *) frame; *msg_ptr = TRANSM_SER; resu.obj = frame; resu.size = tmp.size + sizeof(ser_proto_msg); break; } default: //TODO error handler LOG_WARNING << "[SerialProtocoll] Trying to wrap unknown code: " << (int)code << endl; break; } return resu; } pulse SerialProtocoll::protocollState(int8_t int8, int32_t int32) { pulse empty; //TODO Fill with logic return empty; } <|endoftext|>
<commit_before>/** * @file block_mapped.hxx * @author Muhammad Osama (mosama@ucdavis.edu) * @brief * @version 0.1 * @date 2020-10-20 * * @copyright Copyright (c) 2020 * */ #pragma once #include <gunrock/util/math.hxx> #include <gunrock/cuda/cuda.hxx> #include <gunrock/framework/operators/configs.hxx> #include <thrust/transform_scan.h> #include <thrust/iterator/discard_iterator.h> #include <cub/block/block_load.cuh> #include <cub/block/block_scan.cuh> #include <cooperative_groups.h> namespace gunrock { namespace operators { namespace advance { namespace block_mapped { template <unsigned int THREADS_PER_BLOCK, unsigned int ITEMS_PER_THREAD, advance_io_type_t input_type, advance_io_type_t output_type, typename graph_t, typename frontier_t, typename offset_counter_t, typename operator_t> void __global__ block_mapped_kernel(graph_t const G, operator_t op, frontier_t* input, frontier_t* output, std::size_t input_size, offset_counter_t* block_offsets) { using vertex_t = typename graph_t::vertex_type; using edge_t = typename graph_t::edge_type; // TODO: accept gunrock::frontier_t instead of typename frontier_t::type_t. using type_t = frontier_t; // Specialize Block Scan for 1D block of THREADS_PER_BLOCK. using block_scan_t = cub::BlockScan<edge_t, THREADS_PER_BLOCK>; auto global_idx = cuda::thread::global::id::x(); auto local_idx = cuda::thread::local::id::x(); /// thrust::counting_iterator<type_t> all_vertices(0); __shared__ typename block_scan_t::TempStorage scan; __shared__ offset_counter_t offset[1]; /// 1. Load input data to shared/register memory. __shared__ vertex_t vertices[THREADS_PER_BLOCK]; __shared__ edge_t degrees[THREADS_PER_BLOCK]; __shared__ edge_t sedges[THREADS_PER_BLOCK]; edge_t th_deg[ITEMS_PER_THREAD]; if (global_idx < input_size) { vertex_t v = (input_type == advance_io_type_t::graph) ? all_vertices[global_idx] : input[global_idx]; vertices[local_idx] = v; if (gunrock::util::limits::is_valid(v)) { sedges[local_idx] = G.get_starting_edge(v); th_deg[0] = G.get_number_of_neighbors(v); } else { th_deg[0] = 0; } } else { vertices[local_idx] = gunrock::numeric_limits<vertex_t>::invalid(); th_deg[0] = 0; } __syncthreads(); /// 2. Exclusive sum of degrees to find total work items per block. edge_t aggregate_degree_per_block; block_scan_t(scan).ExclusiveSum(th_deg, th_deg, aggregate_degree_per_block); __syncthreads(); // Store back to shared memory (to later use in the binary search). degrees[local_idx] = th_deg[0]; /// 3. Compute block offsets if there's an output frontier. if (output_type != advance_io_type_t::none) { // Accumulate the output size to global memory, only done once per block by // threadIdx.x == 0, and retrieve the previously stored value from the // global memory. The previous value is now current block's starting offset. // All writes from this block will be after this offset. Note: this does not // guarantee that the data written will be in any specific order. if (local_idx == 0) offset[0] = math::atomic::add( &block_offsets[0], (offset_counter_t)aggregate_degree_per_block); // Old method reads from precomputed segments instead of the atomic add // above. /* if (local_idx == 0) if ((cuda::block::id::x() * cuda::block::size::x()) < input_size) offset[0] = segments[cuda::block::id::x() * cuda::block::size::x()]; */ } auto length = global_idx - local_idx + cuda::block::size::x(); if (input_size < length) length = input_size; length -= global_idx - local_idx; /// 4. Compute. Using binary search, find the source vertex each thread is /// processing, and the corresponding edge, neighbor and weight tuple. Passed /// to the user-defined lambda operator to process. If there's an output, the /// resultant neighbor or invalid vertex is written to the output frontier. for (edge_t i = local_idx; // threadIdx.x i < aggregate_degree_per_block; // total degree to process i += cuda::block::size::x() // increment by blockDim.x ) { // Binary search to find which vertex id to work on. int id = search::binary::rightmost(degrees, i, length); // If the id is greater than the width of the block or the input size, we // exit. if (id >= length) continue; // Fetch the vertex corresponding to the id. vertex_t v = vertices[id]; if (!gunrock::util::limits::is_valid(v)) continue; // If the vertex is valid, get its edge, neighbor and edge weight. auto e = sedges[id] + i - degrees[id]; auto n = G.get_destination_vertex(e); auto w = G.get_edge_weight(e); // Use-defined advance condition. bool cond = op(v, n, e, w); // Store [neighbor] into the output frontier. if (output_type != advance_io_type_t::none) { __syncthreads(); output[offset[0] + i] = (cond && n != v) ? n : gunrock::numeric_limits<vertex_t>::invalid(); } } } template <advance_direction_t direction, advance_io_type_t input_type, advance_io_type_t output_type, typename graph_t, typename operator_t, typename frontier_t, typename work_tiles_t> void execute(graph_t& G, operator_t op, frontier_t* input, frontier_t* output, work_tiles_t& segments, cuda::standard_context_t& context) { if constexpr (output_type != advance_io_type_t::none) { auto size_of_output = compute_output_length(G, *input, context); // If output frontier is empty, resize and return. if (size_of_output <= 0) { output->set_number_of_elements(0); return; } // <todo> Resize the output (inactive) buffer to the new size. // Can be hidden within the frontier struct. if (output->get_capacity() < size_of_output) output->reserve(size_of_output); output->set_number_of_elements(size_of_output); } std::size_t num_elements = (input_type == advance_io_type_t::graph) ? G.get_number_of_vertices() : input->get_number_of_elements(); // Set-up and launch block-mapped advance. using namespace cuda::launch_box; using launch_t = launch_box_t<launch_params_dynamic_grid_t<fallback, dim3_t<128>>>; launch_t launch_box; launch_box.calculate_grid_dimensions_strided(num_elements); auto __bm = block_mapped_kernel< // kernel launch_box.block_dimensions.x, // threas per block 1, // items per thread input_type, output_type, // i/o parameters graph_t, // graph type typename frontier_t::type_t, // frontier value type typename work_tiles_t::value_type, // segments value type operator_t // lambda type >; thrust::device_vector<typename work_tiles_t::value_type> block_offsets(1); launch_box.calculate_grid_dimensions_strided(num_elements); launch_box.launch(context, __bm, G, op, input->data(), output->data(), num_elements, block_offsets.data().get()); context.synchronize(); } } // namespace block_mapped } // namespace advance } // namespace operators } // namespace gunrock <commit_msg>Possibly working (complete) implementation using only one prefix-sum (block::)<commit_after>/** * @file block_mapped.hxx * @author Muhammad Osama (mosama@ucdavis.edu) * @brief * @version 0.1 * @date 2020-10-20 * * @copyright Copyright (c) 2020 * */ #pragma once #include <gunrock/util/math.hxx> #include <gunrock/cuda/cuda.hxx> #include <gunrock/framework/operators/configs.hxx> #include <thrust/transform_scan.h> #include <thrust/iterator/discard_iterator.h> #include <cub/block/block_load.cuh> #include <cub/block/block_scan.cuh> namespace gunrock { namespace operators { namespace advance { namespace block_mapped { template <unsigned int THREADS_PER_BLOCK, unsigned int ITEMS_PER_THREAD, advance_io_type_t input_type, advance_io_type_t output_type, typename graph_t, typename frontier_t, typename offset_counter_t, typename operator_t> __global__ void __launch_bounds__(THREADS_PER_BLOCK, 2) block_mapped_kernel(graph_t const G, operator_t op, frontier_t* input, frontier_t* output, std::size_t input_size, offset_counter_t* block_offsets) { using vertex_t = typename graph_t::vertex_type; using edge_t = typename graph_t::edge_type; // TODO: accept gunrock::frontier_t instead of typename frontier_t::type_t. using type_t = frontier_t; // Specialize Block Scan for 1D block of THREADS_PER_BLOCK. using block_scan_t = cub::BlockScan<edge_t, THREADS_PER_BLOCK>; auto global_idx = cuda::thread::global::id::x(); auto local_idx = cuda::thread::local::id::x(); thrust::counting_iterator<type_t> all_vertices(0); __shared__ typename block_scan_t::TempStorage scan; __shared__ uint64_t offset[1]; /// 1. Load input data to shared/register memory. __shared__ vertex_t vertices[THREADS_PER_BLOCK]; __shared__ edge_t degrees[THREADS_PER_BLOCK]; __shared__ edge_t sedges[THREADS_PER_BLOCK]; edge_t th_deg[ITEMS_PER_THREAD]; if (global_idx < input_size) { vertex_t v = (input_type == advance_io_type_t::graph) ? all_vertices[global_idx] : input[global_idx]; vertices[local_idx] = v; if (gunrock::util::limits::is_valid(v)) { sedges[local_idx] = G.get_starting_edge(v); th_deg[0] = G.get_number_of_neighbors(v); } else { th_deg[0] = 0; } } else { vertices[local_idx] = gunrock::numeric_limits<vertex_t>::invalid(); th_deg[0] = 0; } __syncthreads(); /// 2. Exclusive sum of degrees to find total work items per block. edge_t aggregate_degree_per_block; block_scan_t(scan).ExclusiveSum(th_deg, th_deg, aggregate_degree_per_block); __syncthreads(); // Store back to shared memory (to later use in the binary search). degrees[local_idx] = th_deg[0]; /// 3. Compute block offsets if there's an output frontier. if (output_type != advance_io_type_t::none) { // Accumulate the output size to global memory, only done once per block by // threadIdx.x == 0, and retrieve the previously stored value from the // global memory. The previous value is now current block's starting offset. // All writes from this block will be after this offset. Note: this does not // guarantee that the data written will be in any specific order. if (local_idx == 0) offset[0] = math::atomic::add( &block_offsets[0], (offset_counter_t)aggregate_degree_per_block); __syncthreads(); } auto length = global_idx - local_idx + cuda::block::size::x(); if (input_size < length) length = input_size; length -= global_idx - local_idx; /// 4. Compute. Using binary search, find the source vertex each thread is /// processing, and the corresponding edge, neighbor and weight tuple. Passed /// to the user-defined lambda operator to process. If there's an output, the /// resultant neighbor or invalid vertex is written to the output frontier. for (edge_t i = local_idx; // threadIdx.x i < aggregate_degree_per_block; // total degree to process i += cuda::block::size::x() // increment by blockDim.x ) { // Binary search to find which vertex id to work on. int id = search::binary::rightmost(degrees, i, length); // If the id is greater than the width of the block or the input size, we // exit. if (id >= length) continue; // Fetch the vertex corresponding to the id. vertex_t v = vertices[id]; if (!gunrock::util::limits::is_valid(v)) continue; // If the vertex is valid, get its edge, neighbor and edge weight. auto e = sedges[id] + i - degrees[id]; auto n = G.get_destination_vertex(e); auto w = G.get_edge_weight(e); // Use-defined advance condition. bool cond = op(v, n, e, w); // Store [neighbor] into the output frontier. if (output_type != advance_io_type_t::none) { output[offset[0] + i] = (cond && n != v) ? n : gunrock::numeric_limits<vertex_t>::invalid(); } } } template <advance_direction_t direction, advance_io_type_t input_type, advance_io_type_t output_type, typename graph_t, typename operator_t, typename frontier_t> void execute(graph_t& G, operator_t op, frontier_t& input, frontier_t& output, cuda::standard_context_t& context) { if constexpr (output_type != advance_io_type_t::none) { auto size_of_output = compute_output_length(G, input, context); // If output frontier is empty, resize and return. if (size_of_output <= 0) { output.set_number_of_elements(0); return; } /// @todo Resize the output (inactive) buffer to the new size. /// Can be hidden within the frontier struct. if (output.get_capacity() < size_of_output) output.reserve(size_of_output); output.set_number_of_elements(size_of_output); } std::size_t num_elements = (input_type == advance_io_type_t::graph) ? G.get_number_of_vertices() : input.get_number_of_elements(); // Set-up and launch block-mapped advance. using namespace cuda::launch_box; using launch_t = launch_box_t<launch_params_dynamic_grid_t<fallback, dim3_t<256>>>; launch_t launch_box; launch_box.calculate_grid_dimensions_strided(num_elements); auto kernel = block_mapped_kernel< // kernel launch_box.block_dimensions.x, // threas per block 1, // items per thread input_type, output_type, // i/o parameters graph_t, // graph type typename frontier_t::type_t, // frontier value type typename frontier_t::offset_t, // segments value type operator_t // lambda type >; /// @todo Is there a better place to create block_offsets? This is always a /// one element array. thrust::device_vector<typename frontier_t::offset_t> block_offsets(1); launch_box.calculate_grid_dimensions_strided(num_elements); launch_box.launch(context, kernel, G, op, input.data(), output.data(), num_elements, block_offsets.data().get()); context.synchronize(); } } // namespace block_mapped } // namespace advance } // namespace operators } // namespace gunrock <|endoftext|>
<commit_before><commit_msg>fix potential deadlocks in Node<commit_after><|endoftext|>
<commit_before>/* -*- Mode: C; indent-tabs-mode: s; c-basic-offset: 4; tab-width: 4 -*- */ /* vim:set et ai sw=4 ts=4 sts=4: tw=80 cino="(0,W2s,i2s,t0,l1,:0" */ #include "batterywidget.h" #include "batteryimage.h" #include "batterybusinesslogic.h" #include "dcpbattery.h" #include "slidercontainer.h" #include "timecontainer.h" #include <QGraphicsLinearLayout> #include <QTimer> #include <MButton> #include <MContainer> #include <MGridLayoutPolicy> #include <MLayout> #include <MLinearLayoutPolicy> #define DEBUG #include "../debug.h" BatteryWidget::BatteryWidget (QGraphicsWidget *parent) : DcpWidget (parent), m_logic (0), m_UILocked (false), batteryImage (0), PSMButton (0), m_MainLayout (0), sliderContainer (0), standByTimeContainer (0), talkTimeContainer (0) { SYS_DEBUG ("Starting in %p", this); /* * One can assume, that when the applet is started the power save mode is * not active. This way we show a value that makes sense even if the DBus * interface to the sysuid is not usable. */ m_PSMButtonToggle = false; initWidget (); } BatteryWidget::~BatteryWidget () { SYS_DEBUG ("Destroying %p", this); if (m_logic) { delete m_logic; m_logic = 0; } } bool BatteryWidget::back () { return true; // back is handled by main window by default } void BatteryWidget::initWidget () { SYS_DEBUG ("Start"); // instantiate the batterybusinesslogic m_logic = new BatteryBusinessLogic; // battery image batteryImage = new BatteryImage; // talkTimeContainer //% "Estimated talk time:" talkTimeContainer = new TimeContainer ( qtTrId ("qtn_ener_tt"), batteryImage); // standByTimeContainer //% "Estimated stand-by time:" standByTimeContainer = new TimeContainer ( qtTrId ("qtn_ener_st"), new MImageWidget); //"qgn_ener_standby" ^ /* * PSMButton is used to immediately turn the power save mode on/off. */ PSMButton = new MButton; updatePSMButton (); connect (PSMButton, SIGNAL (released ()), this, SLOT (PSMButtonReleased ())); // sliderContainer sliderContainer = new SliderContainer; connect (sliderContainer, SIGNAL (PSMAutoToggled (bool)), this, SLOT (PSMAutoToggled (bool))); connect (sliderContainer, SIGNAL (PSMThresholdValueChanged (int)), m_logic, SLOT (setPSMThresholdValue (int))); // mainContainer m_MainLayout = new MLayout; MGridLayoutPolicy *landscapeLayoutPolicy = new MGridLayoutPolicy (m_MainLayout); landscapeLayoutPolicy->addItem (talkTimeContainer, 0, 0); landscapeLayoutPolicy->addItem (standByTimeContainer, 0, 1); landscapeLayoutPolicy->setColumnStretchFactor (0, 2); landscapeLayoutPolicy->setColumnStretchFactor (1, 2); landscapeLayoutPolicy->addItem (sliderContainer, 1, 0, 1, 2); landscapeLayoutPolicy->addItem (PSMButton, 2, 0, 1, 2); landscapeLayoutPolicy->setSpacing (10); m_MainLayout->setLandscapePolicy (landscapeLayoutPolicy); MLinearLayoutPolicy *portraitLayoutPolicy = new MLinearLayoutPolicy (m_MainLayout, Qt::Vertical); portraitLayoutPolicy->addItem (talkTimeContainer, Qt::AlignLeft); portraitLayoutPolicy->addItem (standByTimeContainer, Qt::AlignLeft); portraitLayoutPolicy->setStretchFactor (talkTimeContainer, 2); portraitLayoutPolicy->setStretchFactor (standByTimeContainer, 2); portraitLayoutPolicy->addItem (sliderContainer, Qt::AlignLeft); portraitLayoutPolicy->addItem (PSMButton, Qt::AlignCenter); portraitLayoutPolicy->setSpacing (10); m_MainLayout->setPortraitPolicy (portraitLayoutPolicy); MContainer *mainContainer = new MContainer; mainContainer->setHeaderVisible (false); mainContainer->centralWidget ()->setLayout (m_MainLayout); // connect the value receive signals connect (m_logic, SIGNAL (remainingTimeValuesChanged (QStringList)), this, SLOT (remainingTimeValuesReceived (QStringList))); /* * Connect the batteryImage slots. */ connect (m_logic, SIGNAL (batteryCharging (int)), batteryImage, SLOT (startCharging (int))); connect (m_logic, SIGNAL (batteryBarValueReceived (int)), batteryImage, SLOT (updateBatteryLevel (int))); connect (m_logic, SIGNAL (PSMValueReceived (bool)), batteryImage, SLOT (setPSMValue (bool))); connect (m_logic, SIGNAL (PSMValueReceived (bool)), this, SLOT (PSMValueReceived (bool))); /* * SliderContainer signals and slots, * and initialization */ sliderContainer->initPSMAutoButton (m_logic->PSMAutoValue ()); sliderContainer->initSlider (m_logic->PSMThresholdValues ()); sliderContainer->updateSlider (m_logic->PSMThresholdValue ()); // mainLayout QGraphicsLinearLayout *mainLayout = new QGraphicsLinearLayout (Qt::Vertical); mainLayout->setContentsMargins (0, 0, 0, 0); mainLayout->addItem (mainContainer); mainLayout->addStretch (); setLayout (mainLayout); // Initialize the values from the business logic QTimer::singleShot (0, m_logic, SLOT (requestValues ())); SYS_DEBUG ("End"); } /*! * This function is called when the user clicked on the 'power save mode' button * that activates and disactivates the power saving mode. The function will call * the battery interface, but the UI will be changed only when the sysuid * reports the change. */ void BatteryWidget::PSMButtonReleased () { bool newPSMValue = !m_PSMButtonToggle; SYS_DEBUG ("Setting PSMvalue to %s", SYS_BOOL(newPSMValue)); if (newPSMValue) { m_UILocked = true; sliderContainer->setVisible (!m_PSMButtonToggle); m_UILocked = false; } m_logic->setPSMValue (newPSMValue); } /*! * This slot is called when the psm auto switch is toggled. */ void BatteryWidget::PSMAutoToggled ( bool PSMAutoEnabled) { SYS_DEBUG ("*** PSMAutoEnabled = %s", SYS_BOOL(PSMAutoEnabled)); if (m_UILocked) { SYS_WARNING ("The UI is locked."); } else { m_logic->setPSMAutoValue (PSMAutoEnabled); if (PSMAutoEnabled) { /* * QmSystem returns 0 when PSMAuto is disabled, * so when we're enabling it, we've to re-query * the proper value */ sliderContainer->updateSlider (m_logic->PSMThresholdValue ()); } } } void BatteryWidget::updatePSMButton () { if (m_PSMButtonToggle) { //% "Deactivate power save now" PSMButton->setText (qtTrId ("qtn_ener_dps")); } else { //% "Activate power save now" PSMButton->setText (qtTrId ("qtn_ener_aps")); } } void BatteryWidget::remainingTimeValuesReceived(const QStringList &timeValues) { SYS_DEBUG ("timevalues = %s, %s", SYS_STR (timeValues.at (0)), SYS_STR (timeValues.at (1))); talkTimeContainer->updateTimeLabel (timeValues.at (0)); standByTimeContainer->updateTimeLabel (timeValues.at (1)); } void BatteryWidget::PSMValueReceived ( bool PSMEnabled) { SYS_DEBUG ("*** PSMEnabled = %s", SYS_BOOL (PSMEnabled)); if (m_PSMButtonToggle == PSMEnabled) { SYS_DEBUG ("toggle already set"); return; } m_PSMButtonToggle = PSMEnabled; updatePSMButton (); m_UILocked = true; SYS_DEBUG ("Hiding sliderContainer"); sliderContainer->setVisible (!m_PSMButtonToggle); m_UILocked = false; m_MainLayout->invalidate (); } void BatteryWidget::retranslateUi () { // This call will reload the translated text on PSButton updatePSMButton (); // This call will retranslate the label (infoText) sliderContainer->retranslate (); talkTimeContainer->setText(qtTrId ("qtn_ener_tt")); standByTimeContainer->setText (qtTrId ("qtn_ener_st")); m_logic->remainingTimeValuesRequired (); } <commit_msg>Changes: a testability fix...<commit_after>/* -*- Mode: C; indent-tabs-mode: s; c-basic-offset: 4; tab-width: 4 -*- */ /* vim:set et ai sw=4 ts=4 sts=4: tw=80 cino="(0,W2s,i2s,t0,l1,:0" */ #include "batterywidget.h" #include "batteryimage.h" #include "batterybusinesslogic.h" #include "dcpbattery.h" #include "slidercontainer.h" #include "timecontainer.h" #include <QGraphicsLinearLayout> #include <QTimer> #include <MButton> #include <MContainer> #include <MGridLayoutPolicy> #include <MLayout> #include <MLinearLayoutPolicy> #define DEBUG #include "../debug.h" BatteryWidget::BatteryWidget (QGraphicsWidget *parent) : DcpWidget (parent), m_logic (0), m_UILocked (false), batteryImage (0), PSMButton (0), m_MainLayout (0), sliderContainer (0), standByTimeContainer (0), talkTimeContainer (0) { SYS_DEBUG ("Starting in %p", this); /* * One can assume, that when the applet is started the power save mode is * not active. This way we show a value that makes sense even if the DBus * interface to the sysuid is not usable. */ m_PSMButtonToggle = false; initWidget (); } BatteryWidget::~BatteryWidget () { SYS_DEBUG ("Destroying %p", this); if (m_logic) { delete m_logic; m_logic = 0; } } bool BatteryWidget::back () { return true; // back is handled by main window by default } void BatteryWidget::initWidget () { SYS_DEBUG ("Start"); // instantiate the batterybusinesslogic m_logic = new BatteryBusinessLogic; // battery image batteryImage = new BatteryImage; // talkTimeContainer //% "Estimated talk time:" talkTimeContainer = new TimeContainer ( qtTrId ("qtn_ener_tt"), batteryImage); // standByTimeContainer //% "Estimated stand-by time:" standByTimeContainer = new TimeContainer ( qtTrId ("qtn_ener_st"), new MImageWidget); //"qgn_ener_standby" ^ /* * PSMButton is used to immediately turn the power save mode on/off. */ PSMButton = new MButton; PSMButton->setObjectName ("PSMButton"); updatePSMButton (); connect (PSMButton, SIGNAL (released ()), this, SLOT (PSMButtonReleased ())); // sliderContainer sliderContainer = new SliderContainer; connect (sliderContainer, SIGNAL (PSMAutoToggled (bool)), this, SLOT (PSMAutoToggled (bool))); connect (sliderContainer, SIGNAL (PSMThresholdValueChanged (int)), m_logic, SLOT (setPSMThresholdValue (int))); // mainContainer m_MainLayout = new MLayout; MGridLayoutPolicy *landscapeLayoutPolicy = new MGridLayoutPolicy (m_MainLayout); landscapeLayoutPolicy->addItem (talkTimeContainer, 0, 0); landscapeLayoutPolicy->addItem (standByTimeContainer, 0, 1); landscapeLayoutPolicy->setColumnStretchFactor (0, 2); landscapeLayoutPolicy->setColumnStretchFactor (1, 2); landscapeLayoutPolicy->addItem (sliderContainer, 1, 0, 1, 2); landscapeLayoutPolicy->addItem (PSMButton, 2, 0, 1, 2); landscapeLayoutPolicy->setSpacing (10); m_MainLayout->setLandscapePolicy (landscapeLayoutPolicy); MLinearLayoutPolicy *portraitLayoutPolicy = new MLinearLayoutPolicy (m_MainLayout, Qt::Vertical); portraitLayoutPolicy->addItem (talkTimeContainer, Qt::AlignLeft); portraitLayoutPolicy->addItem (standByTimeContainer, Qt::AlignLeft); portraitLayoutPolicy->setStretchFactor (talkTimeContainer, 2); portraitLayoutPolicy->setStretchFactor (standByTimeContainer, 2); portraitLayoutPolicy->addItem (sliderContainer, Qt::AlignLeft); portraitLayoutPolicy->addItem (PSMButton, Qt::AlignCenter); portraitLayoutPolicy->setSpacing (10); m_MainLayout->setPortraitPolicy (portraitLayoutPolicy); MContainer *mainContainer = new MContainer; mainContainer->setHeaderVisible (false); mainContainer->centralWidget ()->setLayout (m_MainLayout); // connect the value receive signals connect (m_logic, SIGNAL (remainingTimeValuesChanged (QStringList)), this, SLOT (remainingTimeValuesReceived (QStringList))); /* * Connect the batteryImage slots. */ connect (m_logic, SIGNAL (batteryCharging (int)), batteryImage, SLOT (startCharging (int))); connect (m_logic, SIGNAL (batteryBarValueReceived (int)), batteryImage, SLOT (updateBatteryLevel (int))); connect (m_logic, SIGNAL (PSMValueReceived (bool)), batteryImage, SLOT (setPSMValue (bool))); connect (m_logic, SIGNAL (PSMValueReceived (bool)), this, SLOT (PSMValueReceived (bool))); /* * SliderContainer signals and slots, * and initialization */ sliderContainer->initPSMAutoButton (m_logic->PSMAutoValue ()); sliderContainer->initSlider (m_logic->PSMThresholdValues ()); sliderContainer->updateSlider (m_logic->PSMThresholdValue ()); // mainLayout QGraphicsLinearLayout *mainLayout = new QGraphicsLinearLayout (Qt::Vertical); mainLayout->setContentsMargins (0, 0, 0, 0); mainLayout->addItem (mainContainer); mainLayout->addStretch (); setLayout (mainLayout); // Initialize the values from the business logic QTimer::singleShot (0, m_logic, SLOT (requestValues ())); SYS_DEBUG ("End"); } /*! * This function is called when the user clicked on the 'power save mode' button * that activates and disactivates the power saving mode. The function will call * the battery interface, but the UI will be changed only when the sysuid * reports the change. */ void BatteryWidget::PSMButtonReleased () { bool newPSMValue = !m_PSMButtonToggle; SYS_DEBUG ("Setting PSMvalue to %s", SYS_BOOL(newPSMValue)); if (newPSMValue) { m_UILocked = true; sliderContainer->setVisible (!m_PSMButtonToggle); m_UILocked = false; } m_logic->setPSMValue (newPSMValue); } /*! * This slot is called when the psm auto switch is toggled. */ void BatteryWidget::PSMAutoToggled ( bool PSMAutoEnabled) { SYS_DEBUG ("*** PSMAutoEnabled = %s", SYS_BOOL(PSMAutoEnabled)); if (m_UILocked) { SYS_WARNING ("The UI is locked."); } else { m_logic->setPSMAutoValue (PSMAutoEnabled); if (PSMAutoEnabled) { /* * QmSystem returns 0 when PSMAuto is disabled, * so when we're enabling it, we've to re-query * the proper value */ sliderContainer->updateSlider (m_logic->PSMThresholdValue ()); } } } void BatteryWidget::updatePSMButton () { if (m_PSMButtonToggle) { //% "Deactivate power save now" PSMButton->setText (qtTrId ("qtn_ener_dps")); } else { //% "Activate power save now" PSMButton->setText (qtTrId ("qtn_ener_aps")); } } void BatteryWidget::remainingTimeValuesReceived(const QStringList &timeValues) { SYS_DEBUG ("timevalues = %s, %s", SYS_STR (timeValues.at (0)), SYS_STR (timeValues.at (1))); talkTimeContainer->updateTimeLabel (timeValues.at (0)); standByTimeContainer->updateTimeLabel (timeValues.at (1)); } void BatteryWidget::PSMValueReceived ( bool PSMEnabled) { SYS_DEBUG ("*** PSMEnabled = %s", SYS_BOOL (PSMEnabled)); if (m_PSMButtonToggle == PSMEnabled) { SYS_DEBUG ("toggle already set"); return; } m_PSMButtonToggle = PSMEnabled; updatePSMButton (); m_UILocked = true; SYS_DEBUG ("Hiding sliderContainer"); sliderContainer->setVisible (!m_PSMButtonToggle); m_UILocked = false; m_MainLayout->invalidate (); } void BatteryWidget::retranslateUi () { // This call will reload the translated text on PSButton updatePSMButton (); // This call will retranslate the label (infoText) sliderContainer->retranslate (); talkTimeContainer->setText(qtTrId ("qtn_ener_tt")); standByTimeContainer->setText (qtTrId ("qtn_ener_st")); m_logic->remainingTimeValuesRequired (); } <|endoftext|>
<commit_before>/** * @file block_mapped.hxx * @author Muhammad Osama (mosama@ucdavis.edu) * @brief * @version 0.1 * @date 2020-10-20 * * @copyright Copyright (c) 2020 * */ #pragma once #include <gunrock/util/math.hxx> #include <gunrock/cuda/cuda.hxx> #include <gunrock/framework/operators/configs.hxx> #include <thrust/transform_scan.h> #include <thrust/iterator/discard_iterator.h> #include <cub/block/block_load.cuh> #include <cub/block/block_scan.cuh> namespace gunrock { namespace operators { namespace advance { namespace block_mapped { template <unsigned int THREADS_PER_BLOCK, unsigned int ITEMS_PER_THREAD, advance_io_type_t input_type, advance_io_type_t output_type, typename graph_t, typename frontier_t, typename offset_counter_t, typename operator_t> __global__ void __launch_bounds__(THREADS_PER_BLOCK, 2) block_mapped_kernel(graph_t const G, operator_t op, frontier_t* input, frontier_t* output, std::size_t input_size, offset_counter_t* block_offsets) { using vertex_t = typename graph_t::vertex_type; using edge_t = typename graph_t::edge_type; // TODO: accept gunrock::frontier_t instead of typename frontier_t::type_t. using type_t = frontier_t; // Specialize Block Scan for 1D block of THREADS_PER_BLOCK. using block_scan_t = cub::BlockScan<edge_t, THREADS_PER_BLOCK>; auto global_idx = gcuda::thread::global::id::x(); auto local_idx = gcuda::thread::local::id::x(); thrust::counting_iterator<type_t> all_vertices(0); __shared__ typename block_scan_t::TempStorage scan; __shared__ uint64_t offset[1]; /// 1. Load input data to shared/register memory. __shared__ vertex_t vertices[THREADS_PER_BLOCK]; __shared__ edge_t degrees[THREADS_PER_BLOCK]; __shared__ edge_t sedges[THREADS_PER_BLOCK]; edge_t th_deg[ITEMS_PER_THREAD]; if (global_idx < input_size) { vertex_t v = (input_type == advance_io_type_t::graph) ? all_vertices[global_idx] : input[global_idx]; vertices[local_idx] = v; if (gunrock::util::limits::is_valid(v)) { sedges[local_idx] = G.get_starting_edge(v); th_deg[0] = G.get_number_of_neighbors(v); } else { th_deg[0] = 0; } } else { vertices[local_idx] = gunrock::numeric_limits<vertex_t>::invalid(); th_deg[0] = 0; } __syncthreads(); /// 2. Exclusive sum of degrees to find total work items per block. edge_t aggregate_degree_per_block; block_scan_t(scan).ExclusiveSum(th_deg, th_deg, aggregate_degree_per_block); __syncthreads(); // Store back to shared memory (to later use in the binary search). degrees[local_idx] = th_deg[0]; /// 3. Compute block offsets if there's an output frontier. if constexpr (output_type != advance_io_type_t::none) { // Accumulate the output size to global memory, only done once per block by // threadIdx.x == 0, and retrieve the previously stored value from the // global memory. The previous value is now current block's starting offset. // All writes from this block will be after this offset. Note: this does not // guarantee that the data written will be in any specific order. if (local_idx == 0) offset[0] = math::atomic::add( &block_offsets[0], (offset_counter_t)aggregate_degree_per_block); __syncthreads(); } auto length = global_idx - local_idx + gcuda::block::size::x(); if (input_size < length) length = input_size; length -= global_idx - local_idx; /// 4. Compute. Using binary search, find the source vertex each thread is /// processing, and the corresponding edge, neighbor and weight tuple. Passed /// to the user-defined lambda operator to process. If there's an output, the /// resultant neighbor or invalid vertex is written to the output frontier. for (edge_t i = local_idx; // threadIdx.x i < aggregate_degree_per_block; // total degree to process i += gcuda::block::size::x() // increment by blockDim.x ) { // Binary search to find which vertex id to work on. int id = search::binary::rightmost(degrees, i, length); // If the id is greater than the width of the block or the input size, we // exit. if (id >= length) continue; // Fetch the vertex corresponding to the id. vertex_t v = vertices[id]; if (!gunrock::util::limits::is_valid(v)) continue; // If the vertex is valid, get its edge, neighbor and edge weight. auto e = sedges[id] + i - degrees[id]; auto n = G.get_destination_vertex(e); auto w = G.get_edge_weight(e); // Use-defined advance condition. bool cond = op(v, n, e, w); // Store [neighbor] into the output frontier. if constexpr (output_type != advance_io_type_t::none) { output[offset[0] + i] = (cond && n != v) ? n : gunrock::numeric_limits<vertex_t>::invalid(); } } } template <advance_direction_t direction, advance_io_type_t input_type, advance_io_type_t output_type, typename graph_t, typename operator_t, typename frontier_t> void execute(graph_t& G, operator_t op, frontier_t& input, frontier_t& output, gcuda::standard_context_t& context) { if constexpr (output_type != advance_io_type_t::none) { auto size_of_output = compute_output_length(G, input, context); // If output frontier is empty, resize and return. if (size_of_output <= 0) { output.set_number_of_elements(0); return; } /// @todo Resize the output (inactive) buffer to the new size. /// Can be hidden within the frontier struct. if (output.get_capacity() < size_of_output) output.reserve(size_of_output); output.set_number_of_elements(size_of_output); } std::size_t num_elements = (input_type == advance_io_type_t::graph) ? G.get_number_of_vertices() : input.get_number_of_elements(); // Set-up and launch block-mapped advance. using namespace gcuda::launch_box; using launch_t = launch_box_t<launch_params_dynamic_grid_t<fallback, dim3_t<256>>>; launch_t launch_box; launch_box.calculate_grid_dimensions_strided(num_elements); auto kernel = block_mapped_kernel< // kernel launch_box.block_dimensions.x, // threas per block 1, // items per thread input_type, output_type, // i/o parameters graph_t, // graph type typename frontier_t::type_t, // frontier value type typename frontier_t::offset_t, // segments value type operator_t // lambda type >; /// @todo Is there a better place to create block_offsets? This is always a /// one element array. thrust::device_vector<typename frontier_t::offset_t> block_offsets(1); launch_box.calculate_grid_dimensions_strided(num_elements); launch_box.launch(context, kernel, G, op, input.data(), output.data(), num_elements, block_offsets.data().get()); context.synchronize(); } } // namespace block_mapped } // namespace advance } // namespace operators } // namespace gunrock <commit_msg>Move `syncthreads` to correct location<commit_after>/** * @file block_mapped.hxx * @author Muhammad Osama (mosama@ucdavis.edu) * @brief * @version 0.1 * @date 2020-10-20 * * @copyright Copyright (c) 2020 * */ #pragma once #include <gunrock/util/math.hxx> #include <gunrock/cuda/cuda.hxx> #include <gunrock/framework/operators/configs.hxx> #include <thrust/transform_scan.h> #include <thrust/iterator/discard_iterator.h> #include <cub/block/block_load.cuh> #include <cub/block/block_scan.cuh> namespace gunrock { namespace operators { namespace advance { namespace block_mapped { template <unsigned int THREADS_PER_BLOCK, unsigned int ITEMS_PER_THREAD, advance_io_type_t input_type, advance_io_type_t output_type, typename graph_t, typename frontier_t, typename offset_counter_t, typename operator_t> __global__ void __launch_bounds__(THREADS_PER_BLOCK, 2) block_mapped_kernel(graph_t const G, operator_t op, frontier_t* input, frontier_t* output, std::size_t input_size, offset_counter_t* block_offsets) { using vertex_t = typename graph_t::vertex_type; using edge_t = typename graph_t::edge_type; // TODO: accept gunrock::frontier_t instead of typename frontier_t::type_t. using type_t = frontier_t; // Specialize Block Scan for 1D block of THREADS_PER_BLOCK. using block_scan_t = cub::BlockScan<edge_t, THREADS_PER_BLOCK>; auto global_idx = gcuda::thread::global::id::x(); auto local_idx = gcuda::thread::local::id::x(); thrust::counting_iterator<type_t> all_vertices(0); __shared__ typename block_scan_t::TempStorage scan; __shared__ uint64_t offset[1]; /// 1. Load input data to shared/register memory. __shared__ vertex_t vertices[THREADS_PER_BLOCK]; __shared__ edge_t degrees[THREADS_PER_BLOCK]; __shared__ edge_t sedges[THREADS_PER_BLOCK]; edge_t th_deg[ITEMS_PER_THREAD]; if (global_idx < input_size) { vertex_t v = (input_type == advance_io_type_t::graph) ? all_vertices[global_idx] : input[global_idx]; vertices[local_idx] = v; if (gunrock::util::limits::is_valid(v)) { sedges[local_idx] = G.get_starting_edge(v); th_deg[0] = G.get_number_of_neighbors(v); } else { th_deg[0] = 0; } } else { vertices[local_idx] = gunrock::numeric_limits<vertex_t>::invalid(); th_deg[0] = 0; } __syncthreads(); /// 2. Exclusive sum of degrees to find total work items per block. edge_t aggregate_degree_per_block; block_scan_t(scan).ExclusiveSum(th_deg, th_deg, aggregate_degree_per_block); __syncthreads(); // Store back to shared memory (to later use in the binary search). degrees[local_idx] = th_deg[0]; /// 3. Compute block offsets if there's an output frontier. if constexpr (output_type != advance_io_type_t::none) { // Accumulate the output size to global memory, only done once per block by // threadIdx.x == 0, and retrieve the previously stored value from the // global memory. The previous value is now current block's starting offset. // All writes from this block will be after this offset. Note: this does not // guarantee that the data written will be in any specific order. if (local_idx == 0) offset[0] = math::atomic::add( &block_offsets[0], (offset_counter_t)aggregate_degree_per_block); } __syncthreads(); auto length = global_idx - local_idx + gcuda::block::size::x(); if (input_size < length) length = input_size; length -= global_idx - local_idx; /// 4. Compute. Using binary search, find the source vertex each thread is /// processing, and the corresponding edge, neighbor and weight tuple. Passed /// to the user-defined lambda operator to process. If there's an output, the /// resultant neighbor or invalid vertex is written to the output frontier. for (edge_t i = local_idx; // threadIdx.x i < aggregate_degree_per_block; // total degree to process i += gcuda::block::size::x() // increment by blockDim.x ) { // Binary search to find which vertex id to work on. int id = search::binary::rightmost(degrees, i, length); // If the id is greater than the width of the block or the input size, we // exit. if (id >= length) continue; // Fetch the vertex corresponding to the id. vertex_t v = vertices[id]; if (!gunrock::util::limits::is_valid(v)) continue; // If the vertex is valid, get its edge, neighbor and edge weight. auto e = sedges[id] + i - degrees[id]; auto n = G.get_destination_vertex(e); auto w = G.get_edge_weight(e); // Use-defined advance condition. bool cond = op(v, n, e, w); // Store [neighbor] into the output frontier. if constexpr (output_type != advance_io_type_t::none) { output[offset[0] + i] = (cond && n != v) ? n : gunrock::numeric_limits<vertex_t>::invalid(); } } } template <advance_direction_t direction, advance_io_type_t input_type, advance_io_type_t output_type, typename graph_t, typename operator_t, typename frontier_t> void execute(graph_t& G, operator_t op, frontier_t& input, frontier_t& output, gcuda::standard_context_t& context) { if constexpr (output_type != advance_io_type_t::none) { auto size_of_output = compute_output_length(G, input, context); // If output frontier is empty, resize and return. if (size_of_output <= 0) { output.set_number_of_elements(0); return; } /// @todo Resize the output (inactive) buffer to the new size. /// Can be hidden within the frontier struct. if (output.get_capacity() < size_of_output) output.reserve(size_of_output); output.set_number_of_elements(size_of_output); } std::size_t num_elements = (input_type == advance_io_type_t::graph) ? G.get_number_of_vertices() : input.get_number_of_elements(); // Set-up and launch block-mapped advance. using namespace gcuda::launch_box; using launch_t = launch_box_t<launch_params_dynamic_grid_t<fallback, dim3_t<256>>>; launch_t launch_box; launch_box.calculate_grid_dimensions_strided(num_elements); auto kernel = block_mapped_kernel< // kernel launch_box.block_dimensions.x, // threas per block 1, // items per thread input_type, output_type, // i/o parameters graph_t, // graph type typename frontier_t::type_t, // frontier value type typename frontier_t::offset_t, // segments value type operator_t // lambda type >; /// @todo Is there a better place to create block_offsets? This is always a /// one element array. thrust::device_vector<typename frontier_t::offset_t> block_offsets(1); launch_box.calculate_grid_dimensions_strided(num_elements); launch_box.launch(context, kernel, G, op, input.data(), output.data(), num_elements, block_offsets.data().get()); context.synchronize(); } } // namespace block_mapped } // namespace advance } // namespace operators } // namespace gunrock <|endoftext|>
<commit_before> #include <iostream> #include <glbinding/gl/gl.h> #include <globjects/logging.h> #include <common/Window.h> #include <common/ContextFormat.h> #include <common/Context.h> #include <common/WindowEventHandler.h> #include <common/events.h> using namespace gl; using namespace globjects; class EventHandler : public WindowEventHandler { public: EventHandler() { } virtual ~EventHandler() { } virtual void paintEvent(PaintEvent & event) override { WindowEventHandler::paintEvent(event); glClearColor( static_cast<float>(rand()) / static_cast<float>(RAND_MAX), static_cast<float>(rand()) / static_cast<float>(RAND_MAX), static_cast<float>(rand()) / static_cast<float>(RAND_MAX), 1.f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); } }; /** This example shows how to create multiple windows with each having its own OpenGL context. Further, the events of all windows are handled within a single event handler. This allows, e.g., reuse of painting functionality with minor, windows specific variations (e.g., different views). */ int main(int /*argc*/, char * /*argv*/[]) { info() << "Usage:"; info() << "\t" << "ESC" << "\t\t" << "Close example"; info() << "\t" << "ALT + Enter" << "\t" << "Toggle fullscreen"; info() << "\t" << "F11" << "\t\t" << "Toggle fullscreen"; info() << "\t" << "F10" << "\t\t" << "Toggle vertical sync"; ContextFormat format; format.setVersion(3, 1); format.setForwardCompatible(true); Window::init(); Window windows[8]; for (int i = 0; i < 8; ++i) { windows[i].setEventHandler(new EventHandler()); if (!windows[i].create(format, "Multiple Contexts Example", 320, 240)) return 1; windows[i].setQuitOnDestroy(i == 0 || rand() % 4 == 0); windows[i].show(); } return MainLoop::run(); } <commit_msg>Fix CID #89083<commit_after> #include <iostream> #include <glm/gtx/random.hpp> #include <glbinding/gl/gl.h> #include <globjects/logging.h> #include <common/Window.h> #include <common/ContextFormat.h> #include <common/Context.h> #include <common/WindowEventHandler.h> #include <common/events.h> using namespace gl; using namespace globjects; class EventHandler : public WindowEventHandler { public: EventHandler() { } virtual ~EventHandler() { } virtual void paintEvent(PaintEvent & event) override { WindowEventHandler::paintEvent(event); glClearColor( glm::linearRand<float>(0.0f, 1.0f), glm::linearRand<float>(0.0f, 1.0f), glm::linearRand<float>(0.0f, 1.0f), 1.f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); } }; /** This example shows how to create multiple windows with each having its own OpenGL context. Further, the events of all windows are handled within a single event handler. This allows, e.g., reuse of painting functionality with minor, windows specific variations (e.g., different views). */ int main(int /*argc*/, char * /*argv*/[]) { info() << "Usage:"; info() << "\t" << "ESC" << "\t\t" << "Close example"; info() << "\t" << "ALT + Enter" << "\t" << "Toggle fullscreen"; info() << "\t" << "F11" << "\t\t" << "Toggle fullscreen"; info() << "\t" << "F10" << "\t\t" << "Toggle vertical sync"; ContextFormat format; format.setVersion(3, 1); format.setForwardCompatible(true); Window::init(); Window windows[8]; for (int i = 0; i < 8; ++i) { windows[i].setEventHandler(new EventHandler()); if (!windows[i].create(format, "Multiple Contexts Example", 320, 240)) return 1; windows[i].setQuitOnDestroy(i == 0 || glm::linearRand<float>(0.0f, 3.0f) < 1.0); windows[i].show(); } return MainLoop::run(); } <|endoftext|>
<commit_before>// Copyright (c) 2011 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/login/touch_login_view.h" #include "chrome/browser/chromeos/status/status_area_view.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/renderer_host/render_widget_host_view_views.h" #include "chrome/browser/ui/touch/frame/keyboard_container_view.h" #include "chrome/browser/ui/views/tab_contents/tab_contents_view_touch.h" #include "chrome/browser/ui/views/dom_view.h" #include "chrome/common/chrome_notification_types.h" #include "content/browser/tab_contents/tab_contents.h" #include "content/common/notification_service.h" #include "ui/base/animation/slide_animation.h" #include "ui/gfx/transform.h" #include "views/controls/textfield/textfield.h" #include "views/widget/widget.h" namespace { const char kViewClassName[] = "browser/chromeos/login/TouchLoginView"; const int kDefaultKeyboardHeight = 300; const int kKeyboardSlideDuration = 300; // In milliseconds PropertyAccessor<bool>* GetFocusedStateAccessor() { static PropertyAccessor<bool> state; return &state; } bool TabContentsHasFocus(const TabContents* contents) { views::View* view = static_cast<TabContentsViewTouch*>(contents->view()); return view->Contains(view->GetFocusManager()->GetFocusedView()); } } // namespace namespace chromeos { // TouchLoginView public: ------------------------------------------------------ TouchLoginView::TouchLoginView() : WebUILoginView(), keyboard_showing_(false), keyboard_height_(kDefaultKeyboardHeight), focus_listener_added_(false), keyboard_(NULL) { } TouchLoginView::~TouchLoginView() { } void TouchLoginView::Init() { WebUILoginView::Init(); InitStatusArea(); InitVirtualKeyboard(); Source<TabContents> tab_contents(webui_login_->tab_contents())); registrar_.Add(this, content::NOTIFICATION_FOCUS_CHANGED_IN_PAGE, tab_contents); registrar_.Add(this, content::NOTIFICATION_TAB_CONTENTS_DESTROYED, tab_contents); registrar_.Add(this, chrome::NOTIFICATION_HIDE_KEYBOARD_INVOKED, NotificationService::AllSources()); registrar_.Add(this, chrome::NOTIFICATION_SET_KEYBOARD_HEIGHT_INVOKED, NotificationService::AllSources()); } std::string TouchLoginView::GetClassName() const { return kViewClassName; } void TouchLoginView::FocusWillChange(views::View* focused_before, views::View* focused_now) { VirtualKeyboardType before = DecideKeyboardStateForView(focused_before); VirtualKeyboardType now = DecideKeyboardStateForView(focused_now); if (before != now) { // TODO(varunjain): support other types of keyboard. UpdateKeyboardAndLayout(now == GENERIC); } } void TouchLoginView::OnWindowCreated() { } // TouchLoginView protected: --------------------------------------------------- void TouchLoginView::Layout() { WebUILoginView::Layout(); DCHECK(status_area_); // Layout the Status Area up in the right corner. This should always be done. gfx::Size status_area_size = status_area_->GetPreferredSize(); status_area_->SetBounds( width() - status_area_size.width() - WebUILoginView::kStatusAreaCornerPadding, WebUILoginView::kStatusAreaCornerPadding, status_area_size.width(), status_area_size.height()); if (!keyboard_) return; // We are not resizing the DOMView here, so the keyboard is going to occlude // the login screen partially. It is the responsibility of the UX layer to // handle this. // Lastly layout the keyboard bool display_keyboard = (keyboard_showing_ || animation_->is_animating()); keyboard_->SetVisible(display_keyboard); gfx::Rect keyboard_bounds = bounds(); int keyboard_height = display_keyboard ? keyboard_height_ : 0; keyboard_bounds.set_y(keyboard_bounds.height() - keyboard_height); keyboard_bounds.set_height(keyboard_height); keyboard_->SetBoundsRect(keyboard_bounds); } void TouchLoginView::InitStatusArea() { if (status_area_) return; status_area_ = new StatusAreaView(this); status_area_->Init(); AddChildView(status_area_); } // TouchLoginView private: ----------------------------------------------------- void TouchLoginView::InitVirtualKeyboard() { keyboard_ = new KeyboardContainerView(profile_, NULL); keyboard_->SetVisible(false); AddChildView(keyboard_); animation_.reset(new ui::SlideAnimation(this)); animation_->SetTweenType(ui::Tween::LINEAR); animation_->SetSlideDuration(kKeyboardSlideDuration); } void TouchLoginView::UpdateKeyboardAndLayout(bool should_show_keyboard) { DCHECK(keyboard_); if (should_show_keyboard == keyboard_showing_) return; keyboard_showing_ = should_show_keyboard; if (keyboard_showing_) { ui::Transform transform; transform.SetTranslateY(-keyboard_height_); keyboard_->SetTransform(transform); Layout(); animation_->Show(); } else { ui::Transform transform; keyboard_->SetTransform(transform); animation_->Hide(); Layout(); } } TouchLoginView::VirtualKeyboardType TouchLoginView::DecideKeyboardStateForView(views::View* view) { if (!view) return NONE; std::string cname = view->GetClassName(); if (cname == views::Textfield::kViewClassName) { return GENERIC; } else if (cname == RenderWidgetHostViewViews::kViewClassName) { TabContents* contents = webui_login_->tab_contents(); bool* editable = contents ? GetFocusedStateAccessor()->GetProperty( contents->property_bag()) : NULL; if (editable && *editable) return GENERIC; } return NONE; } void TouchLoginView::Observe(int type, const NotificationSource& source, const NotificationDetails& details) { if (type == content::NOTIFICATION_FOCUS_CHANGED_IN_PAGE) { // Only modify the keyboard state if the currently active tab sent the // notification. const TabContents* current_tab = webui_login_->tab_contents(); TabContents* source_tab = Source<TabContents>(source).ptr(); const bool editable = *Details<const bool>(details).ptr(); if (current_tab == source_tab && TabContentsHasFocus(source_tab)) UpdateKeyboardAndLayout(editable); // Save the state of the focused field so that the keyboard visibility // can be determined after tab switching. GetFocusedStateAccessor()->SetProperty( source_tab->property_bag(), editable); } else if (type == content::NOTIFICATION_TAB_CONTENTS_DESTROYED) { GetFocusedStateAccessor()->DeleteProperty( Source<TabContents>(source).ptr()->property_bag()); } else if (type == chrome::NOTIFICATION_HIDE_KEYBOARD_INVOKED) { UpdateKeyboardAndLayout(false); } else if (type == chrome::NOTIFICATION_SET_KEYBOARD_HEIGHT_INVOKED) { // TODO(penghuang) Allow extension conrtol the virtual keyboard directly // instead of using Notification. int height = *(Details<int>(details).ptr()); if (height != keyboard_height_) { DCHECK_GE(height, 0) << "Height of the keyboard is less than 0."; DCHECK_LE(height, View::height()) << "Height of the keyboard is greater " "than the height of containing view."; keyboard_height_ = height; Layout(); } } } // ui::AnimationDelegate implementation ---------------------------------------- void TouchLoginView::AnimationProgressed(const ui::Animation* anim) { ui::Transform transform; transform.SetTranslateY( ui::Tween::ValueBetween(anim->GetCurrentValue(), keyboard_height_, 0)); keyboard_->SetTransform(transform); } void TouchLoginView::AnimationEnded(const ui::Animation* animation) { if (keyboard_showing_) { Layout(); } else { // Notify the keyboard that it is hidden now. keyboard_->SetVisible(false); } } } // namespace chromeos <commit_msg>Fixed a broken TOUCH_UI build.<commit_after>// Copyright (c) 2011 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/login/touch_login_view.h" #include "chrome/browser/chromeos/status/status_area_view.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/renderer_host/render_widget_host_view_views.h" #include "chrome/browser/ui/touch/frame/keyboard_container_view.h" #include "chrome/browser/ui/views/tab_contents/tab_contents_view_touch.h" #include "chrome/browser/ui/views/dom_view.h" #include "chrome/common/chrome_notification_types.h" #include "content/browser/tab_contents/tab_contents.h" #include "content/common/notification_service.h" #include "ui/base/animation/slide_animation.h" #include "ui/gfx/transform.h" #include "views/controls/textfield/textfield.h" #include "views/widget/widget.h" namespace { const char kViewClassName[] = "browser/chromeos/login/TouchLoginView"; const int kDefaultKeyboardHeight = 300; const int kKeyboardSlideDuration = 300; // In milliseconds PropertyAccessor<bool>* GetFocusedStateAccessor() { static PropertyAccessor<bool> state; return &state; } bool TabContentsHasFocus(const TabContents* contents) { views::View* view = static_cast<TabContentsViewTouch*>(contents->view()); return view->Contains(view->GetFocusManager()->GetFocusedView()); } } // namespace namespace chromeos { // TouchLoginView public: ------------------------------------------------------ TouchLoginView::TouchLoginView() : WebUILoginView(), keyboard_showing_(false), keyboard_height_(kDefaultKeyboardHeight), focus_listener_added_(false), keyboard_(NULL) { } TouchLoginView::~TouchLoginView() { } void TouchLoginView::Init() { WebUILoginView::Init(); InitStatusArea(); InitVirtualKeyboard(); Source<TabContents> tab_contents(webui_login_->tab_contents()); registrar_.Add(this, content::NOTIFICATION_FOCUS_CHANGED_IN_PAGE, tab_contents); registrar_.Add(this, content::NOTIFICATION_TAB_CONTENTS_DESTROYED, tab_contents); registrar_.Add(this, chrome::NOTIFICATION_HIDE_KEYBOARD_INVOKED, NotificationService::AllSources()); registrar_.Add(this, chrome::NOTIFICATION_SET_KEYBOARD_HEIGHT_INVOKED, NotificationService::AllSources()); } std::string TouchLoginView::GetClassName() const { return kViewClassName; } void TouchLoginView::FocusWillChange(views::View* focused_before, views::View* focused_now) { VirtualKeyboardType before = DecideKeyboardStateForView(focused_before); VirtualKeyboardType now = DecideKeyboardStateForView(focused_now); if (before != now) { // TODO(varunjain): support other types of keyboard. UpdateKeyboardAndLayout(now == GENERIC); } } void TouchLoginView::OnWindowCreated() { } // TouchLoginView protected: --------------------------------------------------- void TouchLoginView::Layout() { WebUILoginView::Layout(); DCHECK(status_area_); // Layout the Status Area up in the right corner. This should always be done. gfx::Size status_area_size = status_area_->GetPreferredSize(); status_area_->SetBounds( width() - status_area_size.width() - WebUILoginView::kStatusAreaCornerPadding, WebUILoginView::kStatusAreaCornerPadding, status_area_size.width(), status_area_size.height()); if (!keyboard_) return; // We are not resizing the DOMView here, so the keyboard is going to occlude // the login screen partially. It is the responsibility of the UX layer to // handle this. // Lastly layout the keyboard bool display_keyboard = (keyboard_showing_ || animation_->is_animating()); keyboard_->SetVisible(display_keyboard); gfx::Rect keyboard_bounds = bounds(); int keyboard_height = display_keyboard ? keyboard_height_ : 0; keyboard_bounds.set_y(keyboard_bounds.height() - keyboard_height); keyboard_bounds.set_height(keyboard_height); keyboard_->SetBoundsRect(keyboard_bounds); } void TouchLoginView::InitStatusArea() { if (status_area_) return; status_area_ = new StatusAreaView(this); status_area_->Init(); AddChildView(status_area_); } // TouchLoginView private: ----------------------------------------------------- void TouchLoginView::InitVirtualKeyboard() { keyboard_ = new KeyboardContainerView(profile_, NULL); keyboard_->SetVisible(false); AddChildView(keyboard_); animation_.reset(new ui::SlideAnimation(this)); animation_->SetTweenType(ui::Tween::LINEAR); animation_->SetSlideDuration(kKeyboardSlideDuration); } void TouchLoginView::UpdateKeyboardAndLayout(bool should_show_keyboard) { DCHECK(keyboard_); if (should_show_keyboard == keyboard_showing_) return; keyboard_showing_ = should_show_keyboard; if (keyboard_showing_) { ui::Transform transform; transform.SetTranslateY(-keyboard_height_); keyboard_->SetTransform(transform); Layout(); animation_->Show(); } else { ui::Transform transform; keyboard_->SetTransform(transform); animation_->Hide(); Layout(); } } TouchLoginView::VirtualKeyboardType TouchLoginView::DecideKeyboardStateForView(views::View* view) { if (!view) return NONE; std::string cname = view->GetClassName(); if (cname == views::Textfield::kViewClassName) { return GENERIC; } else if (cname == RenderWidgetHostViewViews::kViewClassName) { TabContents* contents = webui_login_->tab_contents(); bool* editable = contents ? GetFocusedStateAccessor()->GetProperty( contents->property_bag()) : NULL; if (editable && *editable) return GENERIC; } return NONE; } void TouchLoginView::Observe(int type, const NotificationSource& source, const NotificationDetails& details) { if (type == content::NOTIFICATION_FOCUS_CHANGED_IN_PAGE) { // Only modify the keyboard state if the currently active tab sent the // notification. const TabContents* current_tab = webui_login_->tab_contents(); TabContents* source_tab = Source<TabContents>(source).ptr(); const bool editable = *Details<const bool>(details).ptr(); if (current_tab == source_tab && TabContentsHasFocus(source_tab)) UpdateKeyboardAndLayout(editable); // Save the state of the focused field so that the keyboard visibility // can be determined after tab switching. GetFocusedStateAccessor()->SetProperty( source_tab->property_bag(), editable); } else if (type == content::NOTIFICATION_TAB_CONTENTS_DESTROYED) { GetFocusedStateAccessor()->DeleteProperty( Source<TabContents>(source).ptr()->property_bag()); } else if (type == chrome::NOTIFICATION_HIDE_KEYBOARD_INVOKED) { UpdateKeyboardAndLayout(false); } else if (type == chrome::NOTIFICATION_SET_KEYBOARD_HEIGHT_INVOKED) { // TODO(penghuang) Allow extension conrtol the virtual keyboard directly // instead of using Notification. int height = *(Details<int>(details).ptr()); if (height != keyboard_height_) { DCHECK_GE(height, 0) << "Height of the keyboard is less than 0."; DCHECK_LE(height, View::height()) << "Height of the keyboard is greater " "than the height of containing view."; keyboard_height_ = height; Layout(); } } } // ui::AnimationDelegate implementation ---------------------------------------- void TouchLoginView::AnimationProgressed(const ui::Animation* anim) { ui::Transform transform; transform.SetTranslateY( ui::Tween::ValueBetween(anim->GetCurrentValue(), keyboard_height_, 0)); keyboard_->SetTransform(transform); } void TouchLoginView::AnimationEnded(const ui::Animation* animation) { if (keyboard_showing_) { Layout(); } else { // Notify the keyboard that it is hidden now. keyboard_->SetVisible(false); } } } // namespace chromeos <|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2014 Artem Pavlenko * * 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 St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #ifndef MAPNIK_RENDERER_COMMON_PROCESS_RASTER_SYMBOLIZER_HPP #define MAPNIK_RENDERER_COMMON_PROCESS_RASTER_SYMBOLIZER_HPP // mapnik #include <mapnik/warp.hpp> #include <mapnik/raster.hpp> #include <mapnik/symbolizer.hpp> #include <mapnik/raster_colorizer.hpp> #include <mapnik/proj_transform.hpp> #include <mapnik/feature.hpp> // agg #include "agg_rendering_buffer.h" #include "agg_pixfmt_rgba.h" #include "agg_pixfmt_gray.h" #include "agg_rasterizer_scanline_aa.h" #include "agg_scanline_u.h" #include "agg_renderer_scanline.h" namespace mapnik { namespace detail { template <typename F> struct image_data_dispatcher : util::static_visitor<void> { using composite_function = F; image_data_dispatcher(int start_x, int start_y, int width, int height, double scale_x, double scale_y, scaling_method_e method, double filter_factor, double opacity, composite_mode_e comp_op, raster_symbolizer const& sym, feature_impl const& feature, F & composite, boost::optional<double> const& nodata) : start_x_(start_x), start_y_(start_y), width_(width), height_(height), scale_x_(scale_x), scale_y_(scale_y), method_(method), filter_factor_(filter_factor), opacity_(opacity), comp_op_(comp_op), sym_(sym), feature_(feature), composite_(composite), nodata_(nodata) {} void operator() (image_data_null const& data_in) const {} //no-op void operator() (image_data_rgba8 const& data_in) const { image_data_rgba8 data_out(width_, height_); scale_image_agg(data_out, data_in, method_, scale_x_, scale_y_, 0.0, 0.0, filter_factor_); composite_(data_out, comp_op_, opacity_, start_x_, start_y_); } template <typename T> void operator() (T const& data_in) const { using image_data_type = T; image_data_type data_out(width_, height_); scale_image_agg(data_out, data_in, method_, scale_x_, scale_y_, 0.0, 0.0, filter_factor_); image_data_rgba8 dst(width_, height_); raster_colorizer_ptr colorizer = get<raster_colorizer_ptr>(sym_, keys::colorizer); if (colorizer) colorizer->colorize(dst, data_out, nodata_, feature_); composite_(dst, comp_op_, opacity_, start_x_, start_y_); } private: int start_x_; int start_y_; int width_; int height_; double scale_x_; double scale_y_; scaling_method_e method_; double filter_factor_; double opacity_; composite_mode_e comp_op_; raster_symbolizer const& sym_; feature_impl const& feature_; composite_function & composite_; boost::optional<double> const& nodata_; }; template <typename F> struct image_data_warp_dispatcher : util::static_visitor<void> { using composite_function = F; image_data_warp_dispatcher(proj_transform const& prj_trans, int start_x, int start_y, int width, int height, box2d<double> const& target_ext, box2d<double> const& source_ext, double offset_x, double offset_y, unsigned mesh_size, scaling_method_e scaling_method, double filter_factor, double opacity, composite_mode_e comp_op, raster_symbolizer const& sym, feature_impl const& feature, F & composite, boost::optional<double> const& nodata) : prj_trans_(prj_trans), start_x_(start_x), start_y_(start_y), width_(width), height_(height), target_ext_(target_ext), source_ext_(source_ext), offset_x_(offset_x), offset_y_(offset_y), mesh_size_(mesh_size), scaling_method_(scaling_method), filter_factor_(filter_factor), opacity_(opacity), comp_op_(comp_op), sym_(sym), feature_(feature), composite_(composite), nodata_(nodata) {} void operator() (image_data_null const& data_in) const {} //no-op void operator() (image_data_rgba8 const& data_in) const { image_data_rgba8 data_out(width_, height_); if (nodata_) data_out.set(*nodata_); warp_image(data_out, data_in, prj_trans_, target_ext_, source_ext_, offset_x_, offset_y_, mesh_size_, scaling_method_, filter_factor_); composite_(data_out, comp_op_, opacity_, start_x_, start_y_); } template <typename T> void operator() (T const& data_in) const { using image_data_type = T; image_data_type data_out(width_, height_); if (nodata_) data_out.set(*nodata_); warp_image(data_out, data_in, prj_trans_, target_ext_, source_ext_, offset_x_, offset_y_, mesh_size_, scaling_method_, filter_factor_); image_data_rgba8 dst(width_, height_); raster_colorizer_ptr colorizer = get<raster_colorizer_ptr>(sym_, keys::colorizer); if (colorizer) colorizer->colorize(dst, data_out, nodata_, feature_); composite_(dst, comp_op_, opacity_, start_x_, start_y_); } private: proj_transform const& prj_trans_; int start_x_; int start_y_; int width_; int height_; box2d<double> const& target_ext_; box2d<double> const& source_ext_; double offset_x_; double offset_y_; unsigned mesh_size_; scaling_method_e scaling_method_; double filter_factor_; double opacity_; composite_mode_e comp_op_; raster_symbolizer const& sym_; feature_impl const& feature_; composite_function & composite_; boost::optional<double> const& nodata_; }; } template <typename F> void render_raster_symbolizer(raster_symbolizer const& sym, mapnik::feature_impl& feature, proj_transform const& prj_trans, renderer_common& common, F composite) { raster_ptr const& source = feature.get_raster(); if (source) { box2d<double> target_ext = box2d<double>(source->ext_); prj_trans.backward(target_ext, PROJ_ENVELOPE_POINTS); box2d<double> ext = common.t_.forward(target_ext); int start_x = static_cast<int>(std::floor(ext.minx()+.5)); int start_y = static_cast<int>(std::floor(ext.miny()+.5)); int end_x = static_cast<int>(std::floor(ext.maxx()+.5)); int end_y = static_cast<int>(std::floor(ext.maxy()+.5)); int raster_width = end_x - start_x; int raster_height = end_y - start_y; if (raster_width > 0 && raster_height > 0) { scaling_method_e scaling_method = get<scaling_method_e>(sym, keys::scaling, feature, common.vars_, SCALING_NEAR); composite_mode_e comp_op = get<composite_mode_e>(sym, keys::comp_op, feature, common.vars_, src_over); double opacity = get<double>(sym,keys::opacity,feature, common.vars_, 1.0); // only premultiply rgba8 images if (source->data_.is<image_data_rgba8>()) { bool premultiply_source = !source->premultiplied_alpha_; auto is_premultiplied = get_optional<bool>(sym, keys::premultiplied, feature, common.vars_); if (is_premultiplied) { if (*is_premultiplied) premultiply_source = false; else premultiply_source = true; } if (premultiply_source) { agg::rendering_buffer buffer(source->data_.getBytes(), source->data_.width(), source->data_.height(), source->data_.width() * 4); agg::pixfmt_rgba32 pixf(buffer); pixf.premultiply(); } } if (!prj_trans.equal()) { double offset_x = ext.minx() - start_x; double offset_y = ext.miny() - start_y; unsigned mesh_size = static_cast<unsigned>(get<value_integer>(sym,keys::mesh_size,feature, common.vars_, 16)); detail::image_data_warp_dispatcher<F> dispatcher(prj_trans, start_x, start_y, raster_width, raster_height, target_ext, source->ext_, offset_x, offset_y, mesh_size, scaling_method, source->get_filter_factor(), opacity, comp_op, sym, feature, composite, source->nodata()); util::apply_visitor(dispatcher, source->data_); } else { double image_ratio_x = ext.width() / source->data_.width(); double image_ratio_y = ext.height() / source->data_.height(); double eps = 1e-5; if ( (std::fabs(image_ratio_x - 1.0) <= eps) && (std::fabs(image_ratio_y - 1.0) <= eps) && (std::abs(start_x) <= eps) && (std::abs(start_y) <= eps) ) { if (source->data_.is<image_data_rgba8>()) { composite(util::get<image_data_rgba8>(source->data_), comp_op, opacity, start_x, start_y); } } else { detail::image_data_dispatcher<F> dispatcher(start_x, start_y, raster_width, raster_height, image_ratio_x, image_ratio_y, scaling_method, source->get_filter_factor(), opacity, comp_op, sym, feature, composite, source->nodata()); util::apply_visitor(dispatcher, source->data_); } } } } } } // namespace mapnik #endif // MAPNIK_RENDERER_COMMON_PROCESS_RASTER_SYMBOLIZER_HPP <commit_msg>dont set nodata for image_data_rgba8: fixes tiff_reprojection-1 visual test<commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2014 Artem Pavlenko * * 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 St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #ifndef MAPNIK_RENDERER_COMMON_PROCESS_RASTER_SYMBOLIZER_HPP #define MAPNIK_RENDERER_COMMON_PROCESS_RASTER_SYMBOLIZER_HPP // mapnik #include <mapnik/warp.hpp> #include <mapnik/raster.hpp> #include <mapnik/symbolizer.hpp> #include <mapnik/raster_colorizer.hpp> #include <mapnik/proj_transform.hpp> #include <mapnik/feature.hpp> // agg #include "agg_rendering_buffer.h" #include "agg_pixfmt_rgba.h" #include "agg_pixfmt_gray.h" #include "agg_rasterizer_scanline_aa.h" #include "agg_scanline_u.h" #include "agg_renderer_scanline.h" namespace mapnik { namespace detail { template <typename F> struct image_data_dispatcher : util::static_visitor<void> { using composite_function = F; image_data_dispatcher(int start_x, int start_y, int width, int height, double scale_x, double scale_y, scaling_method_e method, double filter_factor, double opacity, composite_mode_e comp_op, raster_symbolizer const& sym, feature_impl const& feature, F & composite, boost::optional<double> const& nodata) : start_x_(start_x), start_y_(start_y), width_(width), height_(height), scale_x_(scale_x), scale_y_(scale_y), method_(method), filter_factor_(filter_factor), opacity_(opacity), comp_op_(comp_op), sym_(sym), feature_(feature), composite_(composite), nodata_(nodata) {} void operator() (image_data_null const& data_in) const {} //no-op void operator() (image_data_rgba8 const& data_in) const { image_data_rgba8 data_out(width_, height_); scale_image_agg(data_out, data_in, method_, scale_x_, scale_y_, 0.0, 0.0, filter_factor_); composite_(data_out, comp_op_, opacity_, start_x_, start_y_); } template <typename T> void operator() (T const& data_in) const { using image_data_type = T; image_data_type data_out(width_, height_); scale_image_agg(data_out, data_in, method_, scale_x_, scale_y_, 0.0, 0.0, filter_factor_); image_data_rgba8 dst(width_, height_); raster_colorizer_ptr colorizer = get<raster_colorizer_ptr>(sym_, keys::colorizer); if (colorizer) colorizer->colorize(dst, data_out, nodata_, feature_); composite_(dst, comp_op_, opacity_, start_x_, start_y_); } private: int start_x_; int start_y_; int width_; int height_; double scale_x_; double scale_y_; scaling_method_e method_; double filter_factor_; double opacity_; composite_mode_e comp_op_; raster_symbolizer const& sym_; feature_impl const& feature_; composite_function & composite_; boost::optional<double> const& nodata_; }; template <typename F> struct image_data_warp_dispatcher : util::static_visitor<void> { using composite_function = F; image_data_warp_dispatcher(proj_transform const& prj_trans, int start_x, int start_y, int width, int height, box2d<double> const& target_ext, box2d<double> const& source_ext, double offset_x, double offset_y, unsigned mesh_size, scaling_method_e scaling_method, double filter_factor, double opacity, composite_mode_e comp_op, raster_symbolizer const& sym, feature_impl const& feature, F & composite, boost::optional<double> const& nodata) : prj_trans_(prj_trans), start_x_(start_x), start_y_(start_y), width_(width), height_(height), target_ext_(target_ext), source_ext_(source_ext), offset_x_(offset_x), offset_y_(offset_y), mesh_size_(mesh_size), scaling_method_(scaling_method), filter_factor_(filter_factor), opacity_(opacity), comp_op_(comp_op), sym_(sym), feature_(feature), composite_(composite), nodata_(nodata) {} void operator() (image_data_null const& data_in) const {} //no-op void operator() (image_data_rgba8 const& data_in) const { image_data_rgba8 data_out(width_, height_); warp_image(data_out, data_in, prj_trans_, target_ext_, source_ext_, offset_x_, offset_y_, mesh_size_, scaling_method_, filter_factor_); composite_(data_out, comp_op_, opacity_, start_x_, start_y_); } template <typename T> void operator() (T const& data_in) const { using image_data_type = T; image_data_type data_out(width_, height_); if (nodata_) data_out.set(*nodata_); warp_image(data_out, data_in, prj_trans_, target_ext_, source_ext_, offset_x_, offset_y_, mesh_size_, scaling_method_, filter_factor_); image_data_rgba8 dst(width_, height_); raster_colorizer_ptr colorizer = get<raster_colorizer_ptr>(sym_, keys::colorizer); if (colorizer) colorizer->colorize(dst, data_out, nodata_, feature_); composite_(dst, comp_op_, opacity_, start_x_, start_y_); } private: proj_transform const& prj_trans_; int start_x_; int start_y_; int width_; int height_; box2d<double> const& target_ext_; box2d<double> const& source_ext_; double offset_x_; double offset_y_; unsigned mesh_size_; scaling_method_e scaling_method_; double filter_factor_; double opacity_; composite_mode_e comp_op_; raster_symbolizer const& sym_; feature_impl const& feature_; composite_function & composite_; boost::optional<double> const& nodata_; }; } template <typename F> void render_raster_symbolizer(raster_symbolizer const& sym, mapnik::feature_impl& feature, proj_transform const& prj_trans, renderer_common& common, F composite) { raster_ptr const& source = feature.get_raster(); if (source) { box2d<double> target_ext = box2d<double>(source->ext_); prj_trans.backward(target_ext, PROJ_ENVELOPE_POINTS); box2d<double> ext = common.t_.forward(target_ext); int start_x = static_cast<int>(std::floor(ext.minx()+.5)); int start_y = static_cast<int>(std::floor(ext.miny()+.5)); int end_x = static_cast<int>(std::floor(ext.maxx()+.5)); int end_y = static_cast<int>(std::floor(ext.maxy()+.5)); int raster_width = end_x - start_x; int raster_height = end_y - start_y; if (raster_width > 0 && raster_height > 0) { scaling_method_e scaling_method = get<scaling_method_e>(sym, keys::scaling, feature, common.vars_, SCALING_NEAR); composite_mode_e comp_op = get<composite_mode_e>(sym, keys::comp_op, feature, common.vars_, src_over); double opacity = get<double>(sym,keys::opacity,feature, common.vars_, 1.0); // only premultiply rgba8 images if (source->data_.is<image_data_rgba8>()) { bool premultiply_source = !source->premultiplied_alpha_; auto is_premultiplied = get_optional<bool>(sym, keys::premultiplied, feature, common.vars_); if (is_premultiplied) { if (*is_premultiplied) premultiply_source = false; else premultiply_source = true; } if (premultiply_source) { agg::rendering_buffer buffer(source->data_.getBytes(), source->data_.width(), source->data_.height(), source->data_.width() * 4); agg::pixfmt_rgba32 pixf(buffer); pixf.premultiply(); } } if (!prj_trans.equal()) { double offset_x = ext.minx() - start_x; double offset_y = ext.miny() - start_y; unsigned mesh_size = static_cast<unsigned>(get<value_integer>(sym,keys::mesh_size,feature, common.vars_, 16)); detail::image_data_warp_dispatcher<F> dispatcher(prj_trans, start_x, start_y, raster_width, raster_height, target_ext, source->ext_, offset_x, offset_y, mesh_size, scaling_method, source->get_filter_factor(), opacity, comp_op, sym, feature, composite, source->nodata()); util::apply_visitor(dispatcher, source->data_); } else { double image_ratio_x = ext.width() / source->data_.width(); double image_ratio_y = ext.height() / source->data_.height(); double eps = 1e-5; if ( (std::fabs(image_ratio_x - 1.0) <= eps) && (std::fabs(image_ratio_y - 1.0) <= eps) && (std::abs(start_x) <= eps) && (std::abs(start_y) <= eps) ) { if (source->data_.is<image_data_rgba8>()) { composite(util::get<image_data_rgba8>(source->data_), comp_op, opacity, start_x, start_y); } } else { detail::image_data_dispatcher<F> dispatcher(start_x, start_y, raster_width, raster_height, image_ratio_x, image_ratio_y, scaling_method, source->get_filter_factor(), opacity, comp_op, sym, feature, composite, source->nodata()); util::apply_visitor(dispatcher, source->data_); } } } } } } // namespace mapnik #endif // MAPNIK_RENDERER_COMMON_PROCESS_RASTER_SYMBOLIZER_HPP <|endoftext|>
<commit_before>#include <string> #include "Main.h" using namespace std; int main(string userAccountIn, string availableTicketIn, string dailyTransaction, string userAccountOut, string availableTicketOut) { return 0; } <commit_msg>TODO: We need to think how "int main()" is going to parse command line arguments<commit_after>#include <string> #include "Main.h" using namespace std; // Stupid VP // main takes argc and argv // We have to parse argv to get the file names // int main (int argc, char** argv) int main(string userAccountIn, string availableTicketIn, string dailyTransaction, string userAccountOut, string availableTicketOut) { return 0; } <|endoftext|>
<commit_before>/* Copyright 2017 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 <deque> #include "tensorflow/core/common_runtime/process_function_library_runtime.h" #include "tensorflow/core/framework/function.h" #include "tensorflow/core/framework/op_kernel.h" #include "tensorflow/core/framework/resource_op_kernel.h" #include "tensorflow/core/lib/core/threadpool.h" #include "tensorflow/core/lib/random/random.h" #include "tensorflow/core/util/device_name_utils.h" namespace tensorflow { struct BufferElement { // The producer sets `status` if getting the input element fails. Status status; // The buffered data element. std::vector<Tensor> value; }; using FunctionBufferCallback = std::function<void(const BufferElement&)>; class FunctionBufferingResource : public ResourceBase { public: FunctionBufferingResource(FunctionLibraryRuntime* lib, const NameAttrList& func, int64 buffer_size, const string& source_device, const string& target_device, const std::vector<Tensor>& func_args, int64 thread_pool_size) : lib_(lib), func_(func), buffer_size_(buffer_size), source_device_(source_device), target_device_(target_device), func_args_(func_args), thread_pool_(new thread::ThreadPool(Env::Default(), ThreadOptions(), "buffer_resource", thread_pool_size, false /* low_latency_hint */)), handle_(kInvalidHandle), is_buffering_(false), end_of_sequence_(false), cancelled_(false) { runner_ = [this](std::function<void()> c) { thread_pool_->Schedule(std::move(c)); }; } ~FunctionBufferingResource() override { Cancel(); { mutex_lock l(mu_); while (is_buffering_) { cond_var_.wait(l); } } delete thread_pool_; } string DebugString() override { return strings::StrCat("FunctionBufferingResource. Size: ", buffer_size_, "; target_device: ", target_device_); } // Instantiates the function the first time it's called. After that it caches // the handle. Status Instantiate() LOCKS_EXCLUDED(mu_) { mutex_lock l(mu_); // Re-use existing handle if it's been set, effectively caching it. if (handle_ != kInvalidHandle) { return Status::OK(); } AttrValueMap attr_values = func_.attr(); FunctionLibraryRuntime::InstantiateOptions opts; opts.target = target_device_; return lib_->Instantiate(func_.name(), AttrSlice(&attr_values), opts, &handle_); } // Returns true if we've got to the end of the sequence and exhausted the // buffer. bool Finished() LOCKS_EXCLUDED(mu_) { mutex_lock l(mu_); return end_of_sequence_ && buffer_.empty(); } // Cancels any buffering / prefetching going on. void Cancel() LOCKS_EXCLUDED(mu_) { mutex_lock l(mu_); cancelled_ = true; } // If the buffer has anything, runs `callback` on the first element in the // buffer, else schedules the `callback` to be called. Requires `args` and // `lib` in case more function calls need to be scheduled. void MaybeGet(FunctionBufferCallback callback) LOCKS_EXCLUDED(mu_) { bool start_buffering = false; bool produced_output = false; BufferElement buffer_element; { mutex_lock l(mu_); if (!is_buffering_ && !end_of_sequence_) { start_buffering = true; } if (!buffer_.empty()) { produced_output = true; std::swap(buffer_element, buffer_.front()); buffer_.pop_front(); } else { produced_output = false; requests_.push_back(std::move(callback)); } } if (produced_output) { callback(buffer_element); } if (start_buffering) { FillBuffer(); } } private: void FillBuffer() LOCKS_EXCLUDED(mu_) { FunctionLibraryRuntime::Handle handle; std::vector<FunctionBufferCallback> cancellation_callbacks; std::vector<BufferElement> cancellation_buffer_elements; bool cancelled = false; { mutex_lock l(mu_); handle = handle_; if (cancelled_) { cancelled = true; // Run through and fulfill all pending requests, if possible. while (!requests_.empty()) { if (!buffer_.empty()) { cancellation_buffer_elements.push_back(std::move(buffer_.front())); buffer_.pop_front(); cancellation_callbacks.push_back(std::move(requests_.front())); requests_.pop_front(); } else { LOG(ERROR) << "Buffer ran out of elements and we couldn't satisfy: " << requests_.size() << " requests"; break; } } is_buffering_ = false; } else { is_buffering_ = true; } } if (cancelled) { for (int i = 0; i < cancellation_callbacks.size(); ++i) { cancellation_callbacks[i](cancellation_buffer_elements[i]); } // We only wait on cond_var_ in the destructor, so there would atmost be // one waiter to notify. cond_var_.notify_one(); return; } FunctionLibraryRuntime::Options opts; // Copied from CapturedFunction::generate_step_id(); opts.step_id = -std::abs(static_cast<int64>(random::New64())); opts.runner = &runner_; opts.source_device = source_device_; AllocatorAttributes arg_alloc_attr; arg_alloc_attr.set_on_host(true); opts.args_alloc_attrs.push_back(arg_alloc_attr); if (opts.source_device != target_device_) { opts.remote_execution = true; } opts.create_rendezvous = true; auto* rets = new std::vector<Tensor>; lib_->Run(opts, handle, func_args_, rets, [this, rets](const Status& status) { FunctionBufferCallback callback = nullptr; BufferElement buffer_front; bool restart_buffering = false; { mutex_lock l(mu_); BufferElement buffer_element; buffer_element.status = status; if (!status.ok()) { end_of_sequence_ = true; is_buffering_ = false; buffer_.push_back(std::move(buffer_element)); return; } buffer_element.value.swap(*rets); buffer_.push_back(std::move(buffer_element)); if (!requests_.empty()) { buffer_front = std::move(buffer_.front()); buffer_.pop_front(); callback = std::move(requests_.front()); requests_.pop_front(); } if (buffer_.size() < buffer_size_) { restart_buffering = true; } else { is_buffering_ = false; } } if (callback != nullptr) { callback(buffer_front); } if (restart_buffering) { FillBuffer(); } }); } mutex mu_; FunctionLibraryRuntime* lib_; NameAttrList func_; const int64 buffer_size_; const string source_device_; const string target_device_; const std::vector<Tensor> func_args_; thread::ThreadPool* thread_pool_; FunctionLibraryRuntime::Handle handle_ GUARDED_BY(mu_); std::deque<BufferElement> buffer_ GUARDED_BY(mu_); std::deque<FunctionBufferCallback> requests_ GUARDED_BY(mu_); std::function<void(std::function<void()>)> runner_ = nullptr; bool is_buffering_ GUARDED_BY(mu_); bool end_of_sequence_ GUARDED_BY(mu_); bool cancelled_ GUARDED_BY(mu_); condition_variable cond_var_; }; class FunctionBufferResourceHandleOp : public OpKernel { public: explicit FunctionBufferResourceHandleOp(OpKernelConstruction* ctx) : OpKernel(ctx), flib_def_(nullptr), pflr_(nullptr) { OP_REQUIRES_OK(ctx, ctx->GetAttr("f", &func_)); OP_REQUIRES_OK(ctx, ctx->GetAttr("buffer_size", &buffer_size_)); OP_REQUIRES_OK(ctx, ctx->GetAttr("container", &container_)); OP_REQUIRES_OK(ctx, ctx->GetAttr("shared_name", &name_)); OP_REQUIRES_OK(ctx, ctx->GetAttr("thread_pool_size", &thread_pool_size_)); } ~FunctionBufferResourceHandleOp() override { if (cinfo_.resource_is_private_to_kernel()) { if (!cinfo_.resource_manager() ->Delete<FunctionBufferingResource>(cinfo_.container(), cinfo_.name()) .ok()) { // Do nothing; the resource can have been deleted by session resets. } } } void Compute(OpKernelContext* ctx) override { const Tensor* string_arg; OP_REQUIRES_OK(ctx, ctx->input("string_arg", &string_arg)); std::vector<Tensor> func_args; func_args.push_back(*string_arg); // Obtain and canonicalize target_device. const Tensor* target_arg; OP_REQUIRES_OK(ctx, ctx->input("target_device", &target_arg)); const string& target_device = DeviceNameUtils::CanonicalizeDeviceName(target_arg->scalar<string>()()); FunctionLibraryRuntime* lib = ctx->function_library(); OP_REQUIRES(ctx, lib != nullptr, errors::Internal("No function library is provided.")); const string& source_device = ctx->device()->name(); mutex_lock l(mu_); if (!initialized_) { OP_REQUIRES_OK(ctx, cinfo_.Init(ctx->resource_manager(), def())); FunctionLibraryRuntime* clone_lib; OP_REQUIRES_OK(ctx, lib->Clone(&flib_def_, &pflr_, &clone_lib)); // Create the resource. FunctionBufferingResource* buffer; OP_REQUIRES_OK( ctx, ctx->resource_manager()->LookupOrCreate<FunctionBufferingResource>( cinfo_.container(), cinfo_.name(), &buffer, [clone_lib, &source_device, &target_device, func_args, this](FunctionBufferingResource** ptr) { *ptr = new FunctionBufferingResource( clone_lib, func_, buffer_size_, source_device, target_device, func_args, thread_pool_size_); return Status::OK(); })); OP_REQUIRES_OK(ctx, buffer->Instantiate()); initialized_ = true; } OP_REQUIRES_OK(ctx, MakeResourceHandleToOutput( ctx, 0, cinfo_.container(), cinfo_.name(), MakeTypeIndex<FunctionBufferingResource>())); } private: mutex mu_; ContainerInfo cinfo_ GUARDED_BY(mu_); bool initialized_ GUARDED_BY(mu_) = false; std::unique_ptr<FunctionLibraryDefinition> flib_def_; std::unique_ptr<ProcessFunctionLibraryRuntime> pflr_; NameAttrList func_; int64 buffer_size_; string container_; string name_; int64 thread_pool_size_; }; REGISTER_KERNEL_BUILDER(Name("FunctionBufferingResource") .Device(DEVICE_CPU) .HostMemory("resource") .HostMemory("string_arg") .HostMemory("target_device"), FunctionBufferResourceHandleOp); REGISTER_KERNEL_BUILDER(Name("FunctionBufferingResource") .Device(DEVICE_GPU) .HostMemory("resource") .HostMemory("string_arg") .HostMemory("target_device"), FunctionBufferResourceHandleOp); #if TENSORFLOW_USE_SYCL REGISTER_KERNEL_BUILDER(Name("FunctionBufferingResource") .Device(DEVICE_SYCL) .HostMemory("resource") .HostMemory("string_arg") .HostMemory("target_device"), FunctionBufferResourceHandleOp); #endif // TENSORFLOW_USE_SYCL // Prefetches and fills up a buffer by calling a function that provides the // elements to buffer. class FunctionBufferingResourceGetNextOp : public AsyncOpKernel { public: explicit FunctionBufferingResourceGetNextOp(OpKernelConstruction* ctx) : AsyncOpKernel(ctx) {} ~FunctionBufferingResourceGetNextOp() override {} void ComputeAsync(OpKernelContext* ctx, DoneCallback done) override { ResourceHandle handle; OP_REQUIRES_OK_ASYNC( ctx, HandleFromInput(ctx, "function_buffer_resource", &handle), done); FunctionBufferingResource* buffer = nullptr; OP_REQUIRES_OK_ASYNC( ctx, LookupResource<FunctionBufferingResource>(ctx, handle, &buffer), done); core::ScopedUnref s(buffer); if (buffer->Finished()) { ctx->SetStatus(errors::OutOfRange("end_of_sequence")); done(); return; } FunctionBufferCallback callback = [ctx, done](const BufferElement& buffer_element) { Status s = buffer_element.status; if (!s.ok()) { ctx->SetStatus(s); done(); return; } for (size_t i = 0; i < buffer_element.value.size(); ++i) { ctx->set_output(i, buffer_element.value[i]); } done(); }; buffer->MaybeGet(std::move(callback)); } }; REGISTER_KERNEL_BUILDER(Name("FunctionBufferingResourceGetNext") .Device(DEVICE_CPU) .HostMemory("function_buffer_resource"), FunctionBufferingResourceGetNextOp); REGISTER_KERNEL_BUILDER(Name("FunctionBufferingResourceGetNext") .Device(DEVICE_GPU) .HostMemory("function_buffer_resource"), FunctionBufferingResourceGetNextOp); #if TENSORFLOW_USE_SYCL REGISTER_KERNEL_BUILDER(Name("FunctionBufferingResourceGetNext") .Device(DEVICE_SYCL) .HostMemory("function_buffer_resource"), FunctionBufferingResourceGetNextOp); #endif // TENSORFLOW_USE_SYCL } // namespace tensorflow <commit_msg>Making sure that the proc FLR doesn't get deleted before lib_ (in FunctionBufferingResource).<commit_after>/* Copyright 2017 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 <deque> #include "tensorflow/core/common_runtime/process_function_library_runtime.h" #include "tensorflow/core/framework/function.h" #include "tensorflow/core/framework/op_kernel.h" #include "tensorflow/core/framework/resource_op_kernel.h" #include "tensorflow/core/lib/core/threadpool.h" #include "tensorflow/core/lib/random/random.h" #include "tensorflow/core/util/device_name_utils.h" namespace tensorflow { struct BufferElement { // The producer sets `status` if getting the input element fails. Status status; // The buffered data element. std::vector<Tensor> value; }; using FunctionBufferCallback = std::function<void(const BufferElement&)>; class FunctionBufferingResource : public ResourceBase { public: FunctionBufferingResource(FunctionLibraryRuntime* lib, std::unique_ptr<ProcessFunctionLibraryRuntime> pflr, const NameAttrList& func, int64 buffer_size, const string& source_device, const string& target_device, const std::vector<Tensor>& func_args, int64 thread_pool_size) : lib_(lib), pflr_(std::move(pflr)), func_(func), buffer_size_(buffer_size), source_device_(source_device), target_device_(target_device), func_args_(func_args), thread_pool_(new thread::ThreadPool(Env::Default(), ThreadOptions(), "buffer_resource", thread_pool_size, false /* low_latency_hint */)), handle_(kInvalidHandle), is_buffering_(false), end_of_sequence_(false), cancelled_(false) { runner_ = [this](std::function<void()> c) { thread_pool_->Schedule(std::move(c)); }; } ~FunctionBufferingResource() override { Cancel(); { mutex_lock l(mu_); while (is_buffering_) { cond_var_.wait(l); } } delete thread_pool_; } string DebugString() override { return strings::StrCat("FunctionBufferingResource. Size: ", buffer_size_, "; target_device: ", target_device_); } // Instantiates the function the first time it's called. After that it caches // the handle. Status Instantiate() LOCKS_EXCLUDED(mu_) { mutex_lock l(mu_); // Re-use existing handle if it's been set, effectively caching it. if (handle_ != kInvalidHandle) { return Status::OK(); } AttrValueMap attr_values = func_.attr(); FunctionLibraryRuntime::InstantiateOptions opts; opts.target = target_device_; return lib_->Instantiate(func_.name(), AttrSlice(&attr_values), opts, &handle_); } // Returns true if we've got to the end of the sequence and exhausted the // buffer. bool Finished() LOCKS_EXCLUDED(mu_) { mutex_lock l(mu_); return end_of_sequence_ && buffer_.empty(); } // Cancels any buffering / prefetching going on. void Cancel() LOCKS_EXCLUDED(mu_) { mutex_lock l(mu_); cancelled_ = true; } // If the buffer has anything, runs `callback` on the first element in the // buffer, else schedules the `callback` to be called. Requires `args` and // `lib` in case more function calls need to be scheduled. void MaybeGet(FunctionBufferCallback callback) LOCKS_EXCLUDED(mu_) { bool start_buffering = false; bool produced_output = false; BufferElement buffer_element; { mutex_lock l(mu_); if (!is_buffering_ && !end_of_sequence_) { start_buffering = true; } if (!buffer_.empty()) { produced_output = true; std::swap(buffer_element, buffer_.front()); buffer_.pop_front(); } else { produced_output = false; requests_.push_back(std::move(callback)); } } if (produced_output) { callback(buffer_element); } if (start_buffering) { FillBuffer(); } } private: void FillBuffer() LOCKS_EXCLUDED(mu_) { FunctionLibraryRuntime::Handle handle; std::vector<FunctionBufferCallback> cancellation_callbacks; std::vector<BufferElement> cancellation_buffer_elements; bool cancelled = false; { mutex_lock l(mu_); handle = handle_; if (cancelled_) { cancelled = true; // Run through and fulfill all pending requests, if possible. while (!requests_.empty()) { if (!buffer_.empty()) { cancellation_buffer_elements.push_back(std::move(buffer_.front())); buffer_.pop_front(); cancellation_callbacks.push_back(std::move(requests_.front())); requests_.pop_front(); } else { LOG(ERROR) << "Buffer ran out of elements and we couldn't satisfy: " << requests_.size() << " requests"; break; } } is_buffering_ = false; } else { is_buffering_ = true; } } if (cancelled) { for (int i = 0; i < cancellation_callbacks.size(); ++i) { cancellation_callbacks[i](cancellation_buffer_elements[i]); } // We only wait on cond_var_ in the destructor, so there would atmost be // one waiter to notify. cond_var_.notify_one(); return; } FunctionLibraryRuntime::Options opts; // Copied from CapturedFunction::generate_step_id(); opts.step_id = -std::abs(static_cast<int64>(random::New64())); opts.runner = &runner_; opts.source_device = source_device_; AllocatorAttributes arg_alloc_attr; arg_alloc_attr.set_on_host(true); opts.args_alloc_attrs.push_back(arg_alloc_attr); if (opts.source_device != target_device_) { opts.remote_execution = true; } opts.create_rendezvous = true; auto* rets = new std::vector<Tensor>; lib_->Run(opts, handle, func_args_, rets, [this, rets](const Status& status) { FunctionBufferCallback callback = nullptr; BufferElement buffer_front; bool restart_buffering = false; { mutex_lock l(mu_); BufferElement buffer_element; buffer_element.status = status; if (!status.ok()) { end_of_sequence_ = true; is_buffering_ = false; buffer_.push_back(std::move(buffer_element)); return; } buffer_element.value.swap(*rets); buffer_.push_back(std::move(buffer_element)); if (!requests_.empty()) { buffer_front = std::move(buffer_.front()); buffer_.pop_front(); callback = std::move(requests_.front()); requests_.pop_front(); } if (buffer_.size() < buffer_size_) { restart_buffering = true; } else { is_buffering_ = false; } } if (callback != nullptr) { callback(buffer_front); } if (restart_buffering) { FillBuffer(); } }); } mutex mu_; FunctionLibraryRuntime* lib_; std::unique_ptr<ProcessFunctionLibraryRuntime> pflr_; NameAttrList func_; const int64 buffer_size_; const string source_device_; const string target_device_; const std::vector<Tensor> func_args_; thread::ThreadPool* thread_pool_; FunctionLibraryRuntime::Handle handle_ GUARDED_BY(mu_); std::deque<BufferElement> buffer_ GUARDED_BY(mu_); std::deque<FunctionBufferCallback> requests_ GUARDED_BY(mu_); std::function<void(std::function<void()>)> runner_ = nullptr; bool is_buffering_ GUARDED_BY(mu_); bool end_of_sequence_ GUARDED_BY(mu_); bool cancelled_ GUARDED_BY(mu_); condition_variable cond_var_; }; class FunctionBufferResourceHandleOp : public OpKernel { public: explicit FunctionBufferResourceHandleOp(OpKernelConstruction* ctx) : OpKernel(ctx), flib_def_(nullptr) { OP_REQUIRES_OK(ctx, ctx->GetAttr("f", &func_)); OP_REQUIRES_OK(ctx, ctx->GetAttr("buffer_size", &buffer_size_)); OP_REQUIRES_OK(ctx, ctx->GetAttr("container", &container_)); OP_REQUIRES_OK(ctx, ctx->GetAttr("shared_name", &name_)); OP_REQUIRES_OK(ctx, ctx->GetAttr("thread_pool_size", &thread_pool_size_)); } ~FunctionBufferResourceHandleOp() override { if (cinfo_.resource_is_private_to_kernel()) { if (!cinfo_.resource_manager() ->Delete<FunctionBufferingResource>(cinfo_.container(), cinfo_.name()) .ok()) { // Do nothing; the resource can have been deleted by session resets. } } } void Compute(OpKernelContext* ctx) override { const Tensor* string_arg; OP_REQUIRES_OK(ctx, ctx->input("string_arg", &string_arg)); std::vector<Tensor> func_args; func_args.push_back(*string_arg); // Obtain and canonicalize target_device. const Tensor* target_arg; OP_REQUIRES_OK(ctx, ctx->input("target_device", &target_arg)); const string& target_device = DeviceNameUtils::CanonicalizeDeviceName(target_arg->scalar<string>()()); FunctionLibraryRuntime* lib = ctx->function_library(); OP_REQUIRES(ctx, lib != nullptr, errors::Internal("No function library is provided.")); const string& source_device = ctx->device()->name(); mutex_lock l(mu_); if (!initialized_) { OP_REQUIRES_OK(ctx, cinfo_.Init(ctx->resource_manager(), def())); FunctionLibraryRuntime* clone_lib; std::unique_ptr<ProcessFunctionLibraryRuntime> pflr; OP_REQUIRES_OK(ctx, lib->Clone(&flib_def_, &pflr, &clone_lib)); // Create the resource. FunctionBufferingResource* buffer; OP_REQUIRES_OK( ctx, ctx->resource_manager()->LookupOrCreate<FunctionBufferingResource>( cinfo_.container(), cinfo_.name(), &buffer, [clone_lib, &pflr, &source_device, &target_device, func_args, this](FunctionBufferingResource** ptr) { *ptr = new FunctionBufferingResource( clone_lib, std::move(pflr), func_, buffer_size_, source_device, target_device, func_args, thread_pool_size_); return Status::OK(); })); OP_REQUIRES_OK(ctx, buffer->Instantiate()); initialized_ = true; } OP_REQUIRES_OK(ctx, MakeResourceHandleToOutput( ctx, 0, cinfo_.container(), cinfo_.name(), MakeTypeIndex<FunctionBufferingResource>())); } private: mutex mu_; ContainerInfo cinfo_ GUARDED_BY(mu_); bool initialized_ GUARDED_BY(mu_) = false; std::unique_ptr<FunctionLibraryDefinition> flib_def_; NameAttrList func_; int64 buffer_size_; string container_; string name_; int64 thread_pool_size_; }; REGISTER_KERNEL_BUILDER(Name("FunctionBufferingResource") .Device(DEVICE_CPU) .HostMemory("resource") .HostMemory("string_arg") .HostMemory("target_device"), FunctionBufferResourceHandleOp); REGISTER_KERNEL_BUILDER(Name("FunctionBufferingResource") .Device(DEVICE_GPU) .HostMemory("resource") .HostMemory("string_arg") .HostMemory("target_device"), FunctionBufferResourceHandleOp); #if TENSORFLOW_USE_SYCL REGISTER_KERNEL_BUILDER(Name("FunctionBufferingResource") .Device(DEVICE_SYCL) .HostMemory("resource") .HostMemory("string_arg") .HostMemory("target_device"), FunctionBufferResourceHandleOp); #endif // TENSORFLOW_USE_SYCL // Prefetches and fills up a buffer by calling a function that provides the // elements to buffer. class FunctionBufferingResourceGetNextOp : public AsyncOpKernel { public: explicit FunctionBufferingResourceGetNextOp(OpKernelConstruction* ctx) : AsyncOpKernel(ctx) {} ~FunctionBufferingResourceGetNextOp() override {} void ComputeAsync(OpKernelContext* ctx, DoneCallback done) override { ResourceHandle handle; OP_REQUIRES_OK_ASYNC( ctx, HandleFromInput(ctx, "function_buffer_resource", &handle), done); FunctionBufferingResource* buffer = nullptr; OP_REQUIRES_OK_ASYNC( ctx, LookupResource<FunctionBufferingResource>(ctx, handle, &buffer), done); core::ScopedUnref s(buffer); if (buffer->Finished()) { ctx->SetStatus(errors::OutOfRange("end_of_sequence")); done(); return; } FunctionBufferCallback callback = [ctx, done](const BufferElement& buffer_element) { Status s = buffer_element.status; if (!s.ok()) { ctx->SetStatus(s); done(); return; } for (size_t i = 0; i < buffer_element.value.size(); ++i) { ctx->set_output(i, buffer_element.value[i]); } done(); }; buffer->MaybeGet(std::move(callback)); } }; REGISTER_KERNEL_BUILDER(Name("FunctionBufferingResourceGetNext") .Device(DEVICE_CPU) .HostMemory("function_buffer_resource"), FunctionBufferingResourceGetNextOp); REGISTER_KERNEL_BUILDER(Name("FunctionBufferingResourceGetNext") .Device(DEVICE_GPU) .HostMemory("function_buffer_resource"), FunctionBufferingResourceGetNextOp); #if TENSORFLOW_USE_SYCL REGISTER_KERNEL_BUILDER(Name("FunctionBufferingResourceGetNext") .Device(DEVICE_SYCL) .HostMemory("function_buffer_resource"), FunctionBufferingResourceGetNextOp); #endif // TENSORFLOW_USE_SYCL } // namespace tensorflow <|endoftext|>
<commit_before>// Copyright 2018 Open Source Robotics Foundation, 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 <gtest/gtest.h> #include <sstream> #include "rcl/rcl.h" #include "rcl/arguments.h" #include "rcl/error_handling.h" #ifdef RMW_IMPLEMENTATION # define CLASSNAME_(NAME, SUFFIX) NAME ## __ ## SUFFIX # define CLASSNAME(NAME, SUFFIX) CLASSNAME_(NAME, SUFFIX) #else # define CLASSNAME(NAME, SUFFIX) NAME #endif class CLASSNAME (TestArgumentsFixture, RMW_IMPLEMENTATION) : public ::testing::Test { public: void SetUp() { } void TearDown() { } }; #define EXPECT_UNPARSED(parsed_args, ...) \ do { \ int expect_unparsed[] = {__VA_ARGS__}; \ int expect_num_unparsed = sizeof(expect_unparsed) / sizeof(int); \ rcl_allocator_t alloc = rcl_get_default_allocator(); \ int actual_num_unparsed = rcl_arguments_get_count_unparsed(&parsed_args); \ int * actual_unparsed = NULL; \ if (actual_num_unparsed > 0) { \ rcl_ret_t ret = rcl_arguments_get_unparsed(&parsed_args, alloc, &actual_unparsed); \ ASSERT_EQ(RCL_RET_OK, ret); \ } \ std::stringstream expected; \ expected << "["; \ for (int e = 0; e < expect_num_unparsed; ++e) { \ expected << expect_unparsed[e] << ", "; \ } \ expected << "]"; \ std::stringstream actual; \ actual << "["; \ for (int a = 0; a < actual_num_unparsed; ++a) { \ actual << actual_unparsed[a] << ", "; \ } \ actual << "]"; \ if (NULL != actual_unparsed) { \ alloc.deallocate(actual_unparsed, alloc.state); \ } \ EXPECT_STREQ(expected.str().c_str(), actual.str().c_str()); \ } while (0) bool is_valid_arg(const char * arg) { const char * argv[] = {arg}; rcl_arguments_t parsed_args = rcl_get_zero_initialized_arguments(); rcl_ret_t ret = rcl_parse_arguments(1, argv, rcl_get_default_allocator(), &parsed_args); EXPECT_EQ(RCL_RET_OK, ret) << rcl_get_error_string_safe(); bool is_valid = 0 == rcl_arguments_get_count_unparsed(&parsed_args); EXPECT_EQ(RCL_RET_OK, rcl_arguments_fini(&parsed_args)); return is_valid; } TEST_F(CLASSNAME(TestArgumentsFixture, RMW_IMPLEMENTATION), check_valid_vs_invalid_args) { EXPECT_TRUE(is_valid_arg("__node:=node_name")); EXPECT_TRUE(is_valid_arg("old_name:__node:=node_name")); EXPECT_TRUE(is_valid_arg("old_name:__node:=nodename123")); EXPECT_TRUE(is_valid_arg("__node:=nodename123")); EXPECT_TRUE(is_valid_arg("__ns:=/foo/bar")); EXPECT_TRUE(is_valid_arg("__ns:=/")); EXPECT_TRUE(is_valid_arg("_:=kq")); EXPECT_TRUE(is_valid_arg("nodename:__ns:=/foobar")); EXPECT_TRUE(is_valid_arg("foo:=bar")); EXPECT_TRUE(is_valid_arg("~/foo:=~/bar")); EXPECT_TRUE(is_valid_arg("/foo/bar:=bar")); EXPECT_TRUE(is_valid_arg("foo:=/bar")); EXPECT_TRUE(is_valid_arg("/foo123:=/bar123")); EXPECT_TRUE(is_valid_arg("node:/foo123:=/bar123")); EXPECT_TRUE(is_valid_arg("rostopic:=/foo/bar")); EXPECT_TRUE(is_valid_arg("rosservice:=baz")); EXPECT_TRUE(is_valid_arg("rostopic://rostopic:=rosservice")); EXPECT_TRUE(is_valid_arg("rostopic:///rosservice:=rostopic")); EXPECT_TRUE(is_valid_arg("rostopic:///foo/bar:=baz")); EXPECT_FALSE(is_valid_arg(":=")); EXPECT_FALSE(is_valid_arg("foo:=")); EXPECT_FALSE(is_valid_arg(":=bar")); EXPECT_FALSE(is_valid_arg("__ns:=")); EXPECT_FALSE(is_valid_arg("__node:=")); EXPECT_FALSE(is_valid_arg("__node:=/foo/bar")); EXPECT_FALSE(is_valid_arg("__ns:=foo")); EXPECT_FALSE(is_valid_arg(":__node:=nodename")); EXPECT_FALSE(is_valid_arg("~:__node:=nodename")); EXPECT_FALSE(is_valid_arg("}foo:=/bar")); EXPECT_FALSE(is_valid_arg("f oo:=/bar")); EXPECT_FALSE(is_valid_arg("foo:=/b ar")); EXPECT_FALSE(is_valid_arg("f{oo:=/bar")); EXPECT_FALSE(is_valid_arg("foo:=/b}ar")); EXPECT_FALSE(is_valid_arg("rostopic://:=rosservice")); EXPECT_FALSE(is_valid_arg("rostopic::=rosservice")); } TEST_F(CLASSNAME(TestArgumentsFixture, RMW_IMPLEMENTATION), test_no_args) { rcl_arguments_t parsed_args = rcl_get_zero_initialized_arguments(); rcl_ret_t ret = rcl_parse_arguments(0, NULL, rcl_get_default_allocator(), &parsed_args); EXPECT_EQ(RCL_RET_OK, ret) << rcl_get_error_string_safe(); EXPECT_EQ(0, rcl_arguments_get_count_unparsed(&parsed_args)); EXPECT_EQ(RCL_RET_OK, rcl_arguments_fini(&parsed_args)); } TEST_F(CLASSNAME(TestArgumentsFixture, RMW_IMPLEMENTATION), test_null_args) { int argc = 1; rcl_arguments_t parsed_args = rcl_get_zero_initialized_arguments(); rcl_ret_t ret = rcl_parse_arguments(argc, NULL, rcl_get_default_allocator(), &parsed_args); EXPECT_EQ(RCL_RET_INVALID_ARGUMENT, ret) << rcl_get_error_string_safe(); rcl_reset_error(); } TEST_F(CLASSNAME(TestArgumentsFixture, RMW_IMPLEMENTATION), test_null_args_output) { const char * argv[] = {"process_name"}; int argc = sizeof(argv) / sizeof(const char *); rcl_ret_t ret = rcl_parse_arguments(argc, argv, rcl_get_default_allocator(), NULL); EXPECT_EQ(RCL_RET_INVALID_ARGUMENT, ret) << rcl_get_error_string_safe(); rcl_reset_error(); } TEST_F(CLASSNAME(TestArgumentsFixture, RMW_IMPLEMENTATION), test_one_remap) { const char * argv[] = {"process_name", "/foo/bar:=/fiz/buz"}; int argc = sizeof(argv) / sizeof(const char *); rcl_arguments_t parsed_args = rcl_get_zero_initialized_arguments(); rcl_ret_t ret; ret = rcl_parse_arguments(argc, argv, rcl_get_default_allocator(), &parsed_args); EXPECT_EQ(RCL_RET_OK, ret) << rcl_get_error_string_safe(); EXPECT_UNPARSED(parsed_args, 0); EXPECT_EQ(RCL_RET_OK, rcl_arguments_fini(&parsed_args)); } TEST_F(CLASSNAME(TestArgumentsFixture, RMW_IMPLEMENTATION), test_mix_valid_invalid_rules) { const char * argv[] = {"process_name", "/foo/bar:=", "bar:=/fiz/buz", "}bar:=fiz"}; int argc = sizeof(argv) / sizeof(const char *); rcl_arguments_t parsed_args = rcl_get_zero_initialized_arguments(); rcl_ret_t ret; ret = rcl_parse_arguments(argc, argv, rcl_get_default_allocator(), &parsed_args); EXPECT_EQ(RCL_RET_OK, ret) << rcl_get_error_string_safe(); EXPECT_UNPARSED(parsed_args, 0, 1, 3); EXPECT_EQ(RCL_RET_OK, rcl_arguments_fini(&parsed_args)); } TEST_F(CLASSNAME(TestArgumentsFixture, RMW_IMPLEMENTATION), test_two_namespace) { const char * argv[] = {"process_name", "__ns:=/foo/bar", "__ns:=/fiz/buz"}; int argc = sizeof(argv) / sizeof(const char *); rcl_arguments_t parsed_args = rcl_get_zero_initialized_arguments(); rcl_ret_t ret; ret = rcl_parse_arguments(argc, argv, rcl_get_default_allocator(), &parsed_args); EXPECT_EQ(RCL_RET_OK, ret) << rcl_get_error_string_safe(); EXPECT_UNPARSED(parsed_args, 0); EXPECT_EQ(RCL_RET_OK, rcl_arguments_fini(&parsed_args)); } TEST_F(CLASSNAME(TestArgumentsFixture, RMW_IMPLEMENTATION), test_uninitialized_parsed_args) { const char * argv[] = {"process_name"}; int argc = sizeof(argv) / sizeof(const char *); rcl_arguments_t parsed_args; int not_null = 1; parsed_args.impl = reinterpret_cast<rcl_arguments_impl_t *>(&not_null); ASSERT_EQ(RCL_RET_INVALID_ARGUMENT, rcl_parse_arguments(argc, argv, rcl_get_default_allocator(), &parsed_args)); rcl_reset_error(); } TEST_F(CLASSNAME(TestArgumentsFixture, RMW_IMPLEMENTATION), test_double_parse) { const char * argv[] = {"process_name", "__ns:=/foo/bar", "__ns:=/fiz/buz"}; int argc = sizeof(argv) / sizeof(const char *); rcl_arguments_t parsed_args = rcl_get_zero_initialized_arguments(); ASSERT_EQ(RCL_RET_OK, rcl_parse_arguments(argc, argv, rcl_get_default_allocator(), &parsed_args)); ASSERT_EQ(RCL_RET_INVALID_ARGUMENT, rcl_parse_arguments(argc, argv, rcl_get_default_allocator(), &parsed_args)); rcl_reset_error(); } TEST_F(CLASSNAME(TestArgumentsFixture, RMW_IMPLEMENTATION), test_fini_null) { EXPECT_EQ(RCL_RET_INVALID_ARGUMENT, rcl_arguments_fini(NULL)); rcl_reset_error(); } TEST_F(CLASSNAME(TestArgumentsFixture, RMW_IMPLEMENTATION), test_fini_impl_null) { rcl_arguments_t parsed_args = rcl_get_zero_initialized_arguments(); parsed_args.impl = NULL; EXPECT_EQ(RCL_RET_ERROR, rcl_arguments_fini(&parsed_args)); rcl_reset_error(); } TEST_F(CLASSNAME(TestArgumentsFixture, RMW_IMPLEMENTATION), test_fini_twice) { const char * argv[] = {"process_name"}; int argc = sizeof(argv) / sizeof(const char *); rcl_arguments_t parsed_args = rcl_get_zero_initialized_arguments(); ASSERT_EQ(RCL_RET_OK, rcl_parse_arguments(argc, argv, rcl_get_default_allocator(), &parsed_args)); EXPECT_EQ(RCL_RET_OK, rcl_arguments_fini(&parsed_args)); EXPECT_EQ(RCL_RET_ERROR, rcl_arguments_fini(&parsed_args)); rcl_reset_error(); } TEST_F(CLASSNAME(TestArgumentsFixture, RMW_IMPLEMENTATION), test_remove_ros_args) { const char * argv[] = {"process_name", "-d", "__ns:=/foo/bar", "__ns:=/fiz/buz", "--foo=bar", "--baz"}; int argc = sizeof(argv) / sizeof(const char *); rcl_allocator_t alloc = rcl_get_default_allocator(); rcl_arguments_t parsed_args = rcl_get_zero_initialized_arguments(); rcl_ret_t ret; ret = rcl_parse_arguments(argc, argv, alloc, &parsed_args); ASSERT_EQ(RCL_RET_OK, ret) << rcl_get_error_string_safe(); int nonros_argc = 0; const char ** nonros_argv = NULL; ret = rcl_remove_ros_arguments( argv, &parsed_args, alloc, &nonros_argc, &nonros_argv); EXPECT_EQ(RCL_RET_OK, ret) << rcl_get_error_string_safe(); ASSERT_EQ(nonros_argc, 4); EXPECT_STREQ(nonros_argv[0], "process_name"); EXPECT_STREQ(nonros_argv[1], "-d"); EXPECT_STREQ(nonros_argv[2], "--foo=bar"); EXPECT_STREQ(nonros_argv[3], "--baz"); EXPECT_EQ(RCL_RET_OK, rcl_arguments_fini(&parsed_args)); if (NULL != nonros_argv) { alloc.deallocate(nonros_argv, alloc.state); } } TEST_F(CLASSNAME(TestArgumentsFixture, RMW_IMPLEMENTATION), test_remove_ros_args_zero) { const char * argv[] = {""}; rcl_ret_t ret; rcl_allocator_t alloc = rcl_get_default_allocator(); rcl_arguments_t parsed_args = rcl_get_zero_initialized_arguments(); int nonros_argc = 0; const char ** nonros_argv = NULL; ret = rcl_remove_ros_arguments( argv, &parsed_args, alloc, &nonros_argc, &nonros_argv); EXPECT_EQ(RCL_RET_INVALID_ARGUMENT, ret) << rcl_get_error_string_safe(); if (NULL != nonros_argv) { alloc.deallocate(nonros_argv, alloc.state); } } <commit_msg>Fix memory leak in test_arguments (#230)<commit_after>// Copyright 2018 Open Source Robotics Foundation, 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 <gtest/gtest.h> #include <sstream> #include "rcl/rcl.h" #include "rcl/arguments.h" #include "rcl/error_handling.h" #ifdef RMW_IMPLEMENTATION # define CLASSNAME_(NAME, SUFFIX) NAME ## __ ## SUFFIX # define CLASSNAME(NAME, SUFFIX) CLASSNAME_(NAME, SUFFIX) #else # define CLASSNAME(NAME, SUFFIX) NAME #endif class CLASSNAME (TestArgumentsFixture, RMW_IMPLEMENTATION) : public ::testing::Test { public: void SetUp() { } void TearDown() { } }; #define EXPECT_UNPARSED(parsed_args, ...) \ do { \ int expect_unparsed[] = {__VA_ARGS__}; \ int expect_num_unparsed = sizeof(expect_unparsed) / sizeof(int); \ rcl_allocator_t alloc = rcl_get_default_allocator(); \ int actual_num_unparsed = rcl_arguments_get_count_unparsed(&parsed_args); \ int * actual_unparsed = NULL; \ if (actual_num_unparsed > 0) { \ rcl_ret_t ret = rcl_arguments_get_unparsed(&parsed_args, alloc, &actual_unparsed); \ ASSERT_EQ(RCL_RET_OK, ret); \ } \ std::stringstream expected; \ expected << "["; \ for (int e = 0; e < expect_num_unparsed; ++e) { \ expected << expect_unparsed[e] << ", "; \ } \ expected << "]"; \ std::stringstream actual; \ actual << "["; \ for (int a = 0; a < actual_num_unparsed; ++a) { \ actual << actual_unparsed[a] << ", "; \ } \ actual << "]"; \ if (NULL != actual_unparsed) { \ alloc.deallocate(actual_unparsed, alloc.state); \ } \ EXPECT_STREQ(expected.str().c_str(), actual.str().c_str()); \ } while (0) bool is_valid_arg(const char * arg) { const char * argv[] = {arg}; rcl_arguments_t parsed_args = rcl_get_zero_initialized_arguments(); rcl_ret_t ret = rcl_parse_arguments(1, argv, rcl_get_default_allocator(), &parsed_args); EXPECT_EQ(RCL_RET_OK, ret) << rcl_get_error_string_safe(); bool is_valid = 0 == rcl_arguments_get_count_unparsed(&parsed_args); EXPECT_EQ(RCL_RET_OK, rcl_arguments_fini(&parsed_args)); return is_valid; } TEST_F(CLASSNAME(TestArgumentsFixture, RMW_IMPLEMENTATION), check_valid_vs_invalid_args) { EXPECT_TRUE(is_valid_arg("__node:=node_name")); EXPECT_TRUE(is_valid_arg("old_name:__node:=node_name")); EXPECT_TRUE(is_valid_arg("old_name:__node:=nodename123")); EXPECT_TRUE(is_valid_arg("__node:=nodename123")); EXPECT_TRUE(is_valid_arg("__ns:=/foo/bar")); EXPECT_TRUE(is_valid_arg("__ns:=/")); EXPECT_TRUE(is_valid_arg("_:=kq")); EXPECT_TRUE(is_valid_arg("nodename:__ns:=/foobar")); EXPECT_TRUE(is_valid_arg("foo:=bar")); EXPECT_TRUE(is_valid_arg("~/foo:=~/bar")); EXPECT_TRUE(is_valid_arg("/foo/bar:=bar")); EXPECT_TRUE(is_valid_arg("foo:=/bar")); EXPECT_TRUE(is_valid_arg("/foo123:=/bar123")); EXPECT_TRUE(is_valid_arg("node:/foo123:=/bar123")); EXPECT_TRUE(is_valid_arg("rostopic:=/foo/bar")); EXPECT_TRUE(is_valid_arg("rosservice:=baz")); EXPECT_TRUE(is_valid_arg("rostopic://rostopic:=rosservice")); EXPECT_TRUE(is_valid_arg("rostopic:///rosservice:=rostopic")); EXPECT_TRUE(is_valid_arg("rostopic:///foo/bar:=baz")); EXPECT_FALSE(is_valid_arg(":=")); EXPECT_FALSE(is_valid_arg("foo:=")); EXPECT_FALSE(is_valid_arg(":=bar")); EXPECT_FALSE(is_valid_arg("__ns:=")); EXPECT_FALSE(is_valid_arg("__node:=")); EXPECT_FALSE(is_valid_arg("__node:=/foo/bar")); EXPECT_FALSE(is_valid_arg("__ns:=foo")); EXPECT_FALSE(is_valid_arg(":__node:=nodename")); EXPECT_FALSE(is_valid_arg("~:__node:=nodename")); EXPECT_FALSE(is_valid_arg("}foo:=/bar")); EXPECT_FALSE(is_valid_arg("f oo:=/bar")); EXPECT_FALSE(is_valid_arg("foo:=/b ar")); EXPECT_FALSE(is_valid_arg("f{oo:=/bar")); EXPECT_FALSE(is_valid_arg("foo:=/b}ar")); EXPECT_FALSE(is_valid_arg("rostopic://:=rosservice")); EXPECT_FALSE(is_valid_arg("rostopic::=rosservice")); } TEST_F(CLASSNAME(TestArgumentsFixture, RMW_IMPLEMENTATION), test_no_args) { rcl_arguments_t parsed_args = rcl_get_zero_initialized_arguments(); rcl_ret_t ret = rcl_parse_arguments(0, NULL, rcl_get_default_allocator(), &parsed_args); EXPECT_EQ(RCL_RET_OK, ret) << rcl_get_error_string_safe(); EXPECT_EQ(0, rcl_arguments_get_count_unparsed(&parsed_args)); EXPECT_EQ(RCL_RET_OK, rcl_arguments_fini(&parsed_args)); } TEST_F(CLASSNAME(TestArgumentsFixture, RMW_IMPLEMENTATION), test_null_args) { int argc = 1; rcl_arguments_t parsed_args = rcl_get_zero_initialized_arguments(); rcl_ret_t ret = rcl_parse_arguments(argc, NULL, rcl_get_default_allocator(), &parsed_args); EXPECT_EQ(RCL_RET_INVALID_ARGUMENT, ret) << rcl_get_error_string_safe(); rcl_reset_error(); } TEST_F(CLASSNAME(TestArgumentsFixture, RMW_IMPLEMENTATION), test_null_args_output) { const char * argv[] = {"process_name"}; int argc = sizeof(argv) / sizeof(const char *); rcl_ret_t ret = rcl_parse_arguments(argc, argv, rcl_get_default_allocator(), NULL); EXPECT_EQ(RCL_RET_INVALID_ARGUMENT, ret) << rcl_get_error_string_safe(); rcl_reset_error(); } TEST_F(CLASSNAME(TestArgumentsFixture, RMW_IMPLEMENTATION), test_one_remap) { const char * argv[] = {"process_name", "/foo/bar:=/fiz/buz"}; int argc = sizeof(argv) / sizeof(const char *); rcl_arguments_t parsed_args = rcl_get_zero_initialized_arguments(); rcl_ret_t ret; ret = rcl_parse_arguments(argc, argv, rcl_get_default_allocator(), &parsed_args); EXPECT_EQ(RCL_RET_OK, ret) << rcl_get_error_string_safe(); EXPECT_UNPARSED(parsed_args, 0); EXPECT_EQ(RCL_RET_OK, rcl_arguments_fini(&parsed_args)); } TEST_F(CLASSNAME(TestArgumentsFixture, RMW_IMPLEMENTATION), test_mix_valid_invalid_rules) { const char * argv[] = {"process_name", "/foo/bar:=", "bar:=/fiz/buz", "}bar:=fiz"}; int argc = sizeof(argv) / sizeof(const char *); rcl_arguments_t parsed_args = rcl_get_zero_initialized_arguments(); rcl_ret_t ret; ret = rcl_parse_arguments(argc, argv, rcl_get_default_allocator(), &parsed_args); EXPECT_EQ(RCL_RET_OK, ret) << rcl_get_error_string_safe(); EXPECT_UNPARSED(parsed_args, 0, 1, 3); EXPECT_EQ(RCL_RET_OK, rcl_arguments_fini(&parsed_args)); } TEST_F(CLASSNAME(TestArgumentsFixture, RMW_IMPLEMENTATION), test_two_namespace) { const char * argv[] = {"process_name", "__ns:=/foo/bar", "__ns:=/fiz/buz"}; int argc = sizeof(argv) / sizeof(const char *); rcl_arguments_t parsed_args = rcl_get_zero_initialized_arguments(); rcl_ret_t ret; ret = rcl_parse_arguments(argc, argv, rcl_get_default_allocator(), &parsed_args); EXPECT_EQ(RCL_RET_OK, ret) << rcl_get_error_string_safe(); EXPECT_UNPARSED(parsed_args, 0); EXPECT_EQ(RCL_RET_OK, rcl_arguments_fini(&parsed_args)); } TEST_F(CLASSNAME(TestArgumentsFixture, RMW_IMPLEMENTATION), test_uninitialized_parsed_args) { const char * argv[] = {"process_name"}; int argc = sizeof(argv) / sizeof(const char *); rcl_arguments_t parsed_args; int not_null = 1; parsed_args.impl = reinterpret_cast<rcl_arguments_impl_t *>(&not_null); ASSERT_EQ(RCL_RET_INVALID_ARGUMENT, rcl_parse_arguments(argc, argv, rcl_get_default_allocator(), &parsed_args)); rcl_reset_error(); } TEST_F(CLASSNAME(TestArgumentsFixture, RMW_IMPLEMENTATION), test_double_parse) { const char * argv[] = {"process_name", "__ns:=/foo/bar", "__ns:=/fiz/buz"}; int argc = sizeof(argv) / sizeof(const char *); rcl_arguments_t parsed_args = rcl_get_zero_initialized_arguments(); ASSERT_EQ(RCL_RET_OK, rcl_parse_arguments(argc, argv, rcl_get_default_allocator(), &parsed_args)); ASSERT_EQ(RCL_RET_INVALID_ARGUMENT, rcl_parse_arguments(argc, argv, rcl_get_default_allocator(), &parsed_args)); rcl_reset_error(); EXPECT_EQ(RCL_RET_OK, rcl_arguments_fini(&parsed_args)); } TEST_F(CLASSNAME(TestArgumentsFixture, RMW_IMPLEMENTATION), test_fini_null) { EXPECT_EQ(RCL_RET_INVALID_ARGUMENT, rcl_arguments_fini(NULL)); rcl_reset_error(); } TEST_F(CLASSNAME(TestArgumentsFixture, RMW_IMPLEMENTATION), test_fini_impl_null) { rcl_arguments_t parsed_args = rcl_get_zero_initialized_arguments(); parsed_args.impl = NULL; EXPECT_EQ(RCL_RET_ERROR, rcl_arguments_fini(&parsed_args)); rcl_reset_error(); } TEST_F(CLASSNAME(TestArgumentsFixture, RMW_IMPLEMENTATION), test_fini_twice) { const char * argv[] = {"process_name"}; int argc = sizeof(argv) / sizeof(const char *); rcl_arguments_t parsed_args = rcl_get_zero_initialized_arguments(); ASSERT_EQ(RCL_RET_OK, rcl_parse_arguments(argc, argv, rcl_get_default_allocator(), &parsed_args)); EXPECT_EQ(RCL_RET_OK, rcl_arguments_fini(&parsed_args)); EXPECT_EQ(RCL_RET_ERROR, rcl_arguments_fini(&parsed_args)); rcl_reset_error(); } TEST_F(CLASSNAME(TestArgumentsFixture, RMW_IMPLEMENTATION), test_remove_ros_args) { const char * argv[] = {"process_name", "-d", "__ns:=/foo/bar", "__ns:=/fiz/buz", "--foo=bar", "--baz"}; int argc = sizeof(argv) / sizeof(const char *); rcl_allocator_t alloc = rcl_get_default_allocator(); rcl_arguments_t parsed_args = rcl_get_zero_initialized_arguments(); rcl_ret_t ret; ret = rcl_parse_arguments(argc, argv, alloc, &parsed_args); ASSERT_EQ(RCL_RET_OK, ret) << rcl_get_error_string_safe(); int nonros_argc = 0; const char ** nonros_argv = NULL; ret = rcl_remove_ros_arguments( argv, &parsed_args, alloc, &nonros_argc, &nonros_argv); EXPECT_EQ(RCL_RET_OK, ret) << rcl_get_error_string_safe(); ASSERT_EQ(nonros_argc, 4); EXPECT_STREQ(nonros_argv[0], "process_name"); EXPECT_STREQ(nonros_argv[1], "-d"); EXPECT_STREQ(nonros_argv[2], "--foo=bar"); EXPECT_STREQ(nonros_argv[3], "--baz"); EXPECT_EQ(RCL_RET_OK, rcl_arguments_fini(&parsed_args)); if (NULL != nonros_argv) { alloc.deallocate(nonros_argv, alloc.state); } } TEST_F(CLASSNAME(TestArgumentsFixture, RMW_IMPLEMENTATION), test_remove_ros_args_zero) { const char * argv[] = {""}; rcl_ret_t ret; rcl_allocator_t alloc = rcl_get_default_allocator(); rcl_arguments_t parsed_args = rcl_get_zero_initialized_arguments(); int nonros_argc = 0; const char ** nonros_argv = NULL; ret = rcl_remove_ros_arguments( argv, &parsed_args, alloc, &nonros_argc, &nonros_argv); EXPECT_EQ(RCL_RET_INVALID_ARGUMENT, ret) << rcl_get_error_string_safe(); if (NULL != nonros_argv) { alloc.deallocate(nonros_argv, alloc.state); } } <|endoftext|>
<commit_before>/* This file is part of kdepim. Copyright (c) 2004 Bo Thorsen <bo@sonofthor.dk> Copyright (c) 2004 Cornelius Schumacher <schumacher@kde.org> 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; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "kmailchanges.h" #include <kapplication.h> #include <klocale.h> #include <kstandarddirs.h> #include <kemailsettings.h> #include <identitymanager.h> #include <identity.h> #include <kdebug.h> #include <kstringhandler.h> #include <kwallet.h> using namespace KWallet; static const char* s_folderContentsType[] = { I18N_NOOP( "Calendar" ), I18N_NOOP( "Contacts" ), I18N_NOOP( "Notes" ), I18N_NOOP( "Tasks" ), I18N_NOOP( "Journal" ) }; Wallet* CreateImapAccount::mWallet = 0; CreateImapAccount::CreateImapAccount( const QString &accountName, const QString &title ) : KConfigPropagator::Change( title ), mAccountName( accountName ), mPort( 993 ), mEnableSieve( false ), mEnableSavePassword( true ), mEncryption( None ), mAuthentication( NONE ), mAuthenticationSend( PLAIN ), mSmtpPort( 25 ), mExistingAccountId( -1 ), mExistingTransportId( -1 ), mCustomWriter( 0 ) { } CreateImapAccount::~CreateImapAccount() { delete mCustomWriter; } void CreateImapAccount::setServer( const QString &s ) { mServer = s; } void CreateImapAccount::setUser( const QString &s ) { mUser = s; } void CreateImapAccount::setPassword( const QString &s ) { mPassword = s; } void CreateImapAccount::setRealName( const QString &s ) { mRealName = s; } void CreateImapAccount::setPort( int port ) { mPort = port; } void CreateImapAccount::setEmail( const QString &s ) { mEmail = s; } void CreateImapAccount::enableSieve( bool b ) { mEnableSieve = b; } void CreateImapAccount::setSieveVacationFileName( const QString& f ) { mSieveVacationFileName = f; } void CreateImapAccount::enableSavePassword( bool b ) { mEnableSavePassword = b; } void CreateImapAccount::setEncryption( CreateImapAccount::Encryption e ) { mEncryption = e; } void CreateImapAccount::setAuthentication( CreateImapAccount::Authentication a ) { mAuthentication = a; } void CreateImapAccount::setDefaultDomain(const QString &d) { mDefaultDomain = d; } void CreateImapAccount::setAuthenticationSend( CreateImapAccount::Authentication a ) { mAuthenticationSend = a; } void CreateImapAccount::setSmtpPort( int port ) { mSmtpPort = port; } void CreateImapAccount::setExistingAccountId( int id ) { mExistingAccountId = id; } void CreateImapAccount::setExistingTransportId( int id ) { mExistingTransportId = id; } void CreateImapAccount::setCustomWriter( CreateImapAccount::CustomWriter *writer ) { mCustomWriter = writer; } CreateDisconnectedImapAccount::CreateDisconnectedImapAccount(const QString & accountName) : CreateImapAccount( accountName, i18n("Create Disconnected IMAP Account for KMail") ), mLocalSubscription( false ), mGroupwareType( GroupwareKolab ) { } void CreateDisconnectedImapAccount::apply() { if ( mEmail.isEmpty() ) mEmail = mUser + "@" + mServer; KConfig c( "kmailrc" ); c.setGroup( "General" ); c.writeEntry( "Default domain", mDefaultDomain ); int accountId; if ( mExistingAccountId < 0 ) { uint accCnt = c.readNumEntry( "accounts", 0 ); accountId = accCnt + 1; c.writeEntry( "accounts", accountId ); } else { accountId = mExistingAccountId; } int transportId; if ( mExistingTransportId < 0 ) { uint transCnt = c.readNumEntry( "transports", 0 ); transportId = transCnt + 1; c.writeEntry( "transports", transportId ); } else { transportId = mExistingTransportId; } c.setGroup( QString("Account %1").arg( accountId ) ); int uid; if ( mExistingAccountId < 0 ) { uid = kapp->random(); c.writeEntry( "Folder", uid ); } else { uid = c.readNumEntry( "Folder" ); } c.writeEntry( "Id", uid ); c.writeEntry( "Type", "cachedimap"); switch ( mAuthentication ) { case NONE: c.writeEntry( "auth", "*" ); break; case PLAIN: c.writeEntry( "auth", "PLAIN" ); break; case LOGIN: c.writeEntry( "auth", "LOGIN" ); break; case NTLM_SPA: c.writeEntry( "auth", "NTLM" ); break; case GSSAPI: c.writeEntry( "auth", "GSSAPI" ); break; case DIGEST_MD5: c.writeEntry( "auth", "DIGEST-MD5" ); break; case CRAM_MD5: c.writeEntry( "auth", "CRAM-MD5" ); break; } c.writeEntry( "Name", mAccountName ); c.writeEntry( "host", mServer ); c.writeEntry( "port", mPort ); c.writeEntry( "groupwareType", mGroupwareType ); // in case the user wants to get rid of some groupware folders c.writeEntry( "locally-subscribed-folders", mLocalSubscription ); c.writeEntry( "login", mUser ); c.writeEntry( "sieve-support", mEnableSieve ? "true" : "false" ); if ( !mSieveVacationFileName.isEmpty() ) c.writeEntry( "sieve-vacation-filename", mSieveVacationFileName ); if ( mEncryption == SSL ) { c.writeEntry( "use-ssl", true ); } else if ( mEncryption == TLS ) { c.writeEntry( "use-tls", true ); } if ( mEnableSavePassword ) { if ( !writeToWallet( "account", accountId ) ) { c.writeEntry( "pass", KStringHandler::obscure( mPassword ) ); c.writeEntry( "store-passwd", true ); } } c.setGroup( QString("Folder-%1").arg( uid ) ); c.writeEntry( "isOpen", true ); c.setGroup( QString("Transport %1").arg( transportId ) ); c.writeEntry( "name", mAccountName ); c.writeEntry( "host", mServer ); c.writeEntry( "type", "smtp" ); c.writeEntry( "port", mSmtpPort ); if ( mEncryption == SSL ) { c.writeEntry( "encryption", "SSL" ); } else if ( mEncryption == TLS ) { c.writeEntry( "encryption", "TLS" ); } c.writeEntry( "auth", true ); if ( mAuthenticationSend == PLAIN ) { c.writeEntry( "authtype", "PLAIN" ); } else if ( mAuthenticationSend == LOGIN ) { c.writeEntry( "authtype", "LOGIN" ); } c.writeEntry( "user", mUser ); if ( mEnableSavePassword ) { if ( !writeToWallet( "transport", transportId ) ) { c.writeEntry( "pass", KStringHandler::obscure( mPassword ) ); c.writeEntry( "storepass", true ); } } // Write email in "default kcontrol settings", used by IdentityManager // if it has to create a default identity. KEMailSettings es; es.setSetting( KEMailSettings::RealName, mRealName ); es.setSetting( KEMailSettings::EmailAddress, mEmail ); KPIM::IdentityManager identityManager; if ( !identityManager.allEmails().contains( mEmail ) ) { // Not sure how to name the identity. First one is "Default", next one mAccountName, but then... // let's use the server name after that. QString accountName = mAccountName; const QStringList identities = identityManager.identities(); if ( identities.find( accountName ) != identities.end() ) { accountName = mServer; int i = 2; // And if there's already one, number them while ( identities.find( accountName ) != identities.end() ) { accountName = mServer + " " + QString::number( i++ ); } } KPIM::Identity& identity = identityManager.newFromScratch( accountName ); identity.setFullName( mRealName ); identity.setEmailAddr( mEmail ); identityManager.commit(); } if ( mCustomWriter ) { mCustomWriter->writeFolder( c, uid ); mCustomWriter->writeIds( accountId, transportId ); } } CreateOnlineImapAccount::CreateOnlineImapAccount(const QString & accountName) : CreateImapAccount( accountName, i18n("Create Online IMAP Account for KMail") ) { } void CreateOnlineImapAccount::apply() { KConfig c( "kmailrc" ); c.setGroup( "General" ); uint accCnt = c.readNumEntry( "accounts", 0 ); c.writeEntry( "accounts", accCnt+1 ); c.setGroup( QString("Account %1").arg(accCnt+1) ); int uid = kapp->random(); c.writeEntry( "Folder", uid ); c.writeEntry( "Id", uid ); c.writeEntry( "Type", "imap" ); c.writeEntry( "auth", "*" ); c.writeEntry( "Name", mAccountName ); c.writeEntry( "host", mServer ); c.writeEntry( "login", mUser ); if ( mEnableSavePassword ) { if ( !writeToWallet( "account", accCnt+1 ) ) { c.writeEntry( "pass", KStringHandler::obscure( mPassword ) ); c.writeEntry( "store-passwd", true ); } } c.writeEntry( "port", "993" ); if ( mEncryption == SSL ) { c.writeEntry( "use-ssl", true ); } else if ( mEncryption == TLS ) { c.writeEntry( "use-tls", true ); } if ( mAuthenticationSend == PLAIN ) { c.writeEntry( "authtype", "PLAIN" ); } else if ( mAuthenticationSend == LOGIN ) { c.writeEntry( "authtype", "LOGIN" ); } c.writeEntry( "sieve-support", mEnableSieve ); // locally unsubscribe the default folders c.writeEntry( "locally-subscribed-folders", true ); QString groupwareFolders = QString("/INBOX/%1/,/INBOX/%2/,/INBOX/%3/,/INBOX/%4/,/INBOX/%5/") .arg( i18n(s_folderContentsType[0]) ).arg( i18n(s_folderContentsType[1]) ) .arg( i18n(s_folderContentsType[2]) ).arg( i18n(s_folderContentsType[3]) ) .arg( i18n(s_folderContentsType[4]) ); c.writeEntry( "locallyUnsubscribedFolders", groupwareFolders ); c.setGroup( QString("Folder-%1").arg( uid ) ); c.writeEntry( "isOpen", true ); } bool CreateImapAccount::writeToWallet(const QString & type, int id) { if ( !Wallet::isEnabled() ) return false; if ( !mWallet || !mWallet->isOpen() ) { delete mWallet; WId window = 0; if ( qApp->activeWindow() ) window = qApp->activeWindow()->winId(); mWallet = Wallet::openWallet( Wallet::NetworkWallet(), window ); if ( !mWallet ) return false; if ( !mWallet->hasFolder( "kmail" ) ) mWallet->createFolder( "kmail" ); mWallet->setFolder( "kmail" ); } return mWallet->writePassword( type + "-" + QString::number( id ), mPassword ); } <commit_msg>code from kde4.x avoid to call wizard when we already config it<commit_after>/* This file is part of kdepim. Copyright (c) 2004 Bo Thorsen <bo@sonofthor.dk> Copyright (c) 2004 Cornelius Schumacher <schumacher@kde.org> 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; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "kmailchanges.h" #include <kapplication.h> #include <klocale.h> #include <kstandarddirs.h> #include <kemailsettings.h> #include <identitymanager.h> #include <identity.h> #include <kdebug.h> #include <kstringhandler.h> #include <kwallet.h> using namespace KWallet; static const char* s_folderContentsType[] = { I18N_NOOP( "Calendar" ), I18N_NOOP( "Contacts" ), I18N_NOOP( "Notes" ), I18N_NOOP( "Tasks" ), I18N_NOOP( "Journal" ) }; Wallet* CreateImapAccount::mWallet = 0; CreateImapAccount::CreateImapAccount( const QString &accountName, const QString &title ) : KConfigPropagator::Change( title ), mAccountName( accountName ), mPort( 993 ), mEnableSieve( false ), mEnableSavePassword( true ), mEncryption( None ), mAuthentication( NONE ), mAuthenticationSend( PLAIN ), mSmtpPort( 25 ), mExistingAccountId( -1 ), mExistingTransportId( -1 ), mCustomWriter( 0 ) { } CreateImapAccount::~CreateImapAccount() { delete mCustomWriter; } void CreateImapAccount::setServer( const QString &s ) { mServer = s; } void CreateImapAccount::setUser( const QString &s ) { mUser = s; } void CreateImapAccount::setPassword( const QString &s ) { mPassword = s; } void CreateImapAccount::setRealName( const QString &s ) { mRealName = s; } void CreateImapAccount::setPort( int port ) { mPort = port; } void CreateImapAccount::setEmail( const QString &s ) { mEmail = s; } void CreateImapAccount::enableSieve( bool b ) { mEnableSieve = b; } void CreateImapAccount::setSieveVacationFileName( const QString& f ) { mSieveVacationFileName = f; } void CreateImapAccount::enableSavePassword( bool b ) { mEnableSavePassword = b; } void CreateImapAccount::setEncryption( CreateImapAccount::Encryption e ) { mEncryption = e; } void CreateImapAccount::setAuthentication( CreateImapAccount::Authentication a ) { mAuthentication = a; } void CreateImapAccount::setDefaultDomain(const QString &d) { mDefaultDomain = d; } void CreateImapAccount::setAuthenticationSend( CreateImapAccount::Authentication a ) { mAuthenticationSend = a; } void CreateImapAccount::setSmtpPort( int port ) { mSmtpPort = port; } void CreateImapAccount::setExistingAccountId( int id ) { mExistingAccountId = id; } void CreateImapAccount::setExistingTransportId( int id ) { mExistingTransportId = id; } void CreateImapAccount::setCustomWriter( CreateImapAccount::CustomWriter *writer ) { mCustomWriter = writer; } CreateDisconnectedImapAccount::CreateDisconnectedImapAccount(const QString & accountName) : CreateImapAccount( accountName, i18n("Create Disconnected IMAP Account for KMail") ), mLocalSubscription( false ), mGroupwareType( GroupwareKolab ) { } void CreateDisconnectedImapAccount::apply() { if ( mEmail.isEmpty() ) mEmail = mUser + "@" + mServer; KConfig c( "kmailrc" ); c.setGroup( "General" ); c.writeEntry( "Default domain", mDefaultDomain ); int accountId; if ( mExistingAccountId < 0 ) { uint accCnt = c.readNumEntry( "accounts", 0 ); accountId = accCnt + 1; c.writeEntry( "accounts", accountId ); } else { accountId = mExistingAccountId; } int transportId; if ( mExistingTransportId < 0 ) { uint transCnt = c.readNumEntry( "transports", 0 ); transportId = transCnt + 1; c.writeEntry( "transports", transportId ); } else { transportId = mExistingTransportId; } c.setGroup( QString("Account %1").arg( accountId ) ); int uid; if ( mExistingAccountId < 0 ) { uid = kapp->random(); c.writeEntry( "Folder", uid ); } else { uid = c.readNumEntry( "Folder" ); } c.writeEntry( "Id", uid ); c.writeEntry( "Type", "cachedimap"); switch ( mAuthentication ) { case NONE: c.writeEntry( "auth", "*" ); break; case PLAIN: c.writeEntry( "auth", "PLAIN" ); break; case LOGIN: c.writeEntry( "auth", "LOGIN" ); break; case NTLM_SPA: c.writeEntry( "auth", "NTLM" ); break; case GSSAPI: c.writeEntry( "auth", "GSSAPI" ); break; case DIGEST_MD5: c.writeEntry( "auth", "DIGEST-MD5" ); break; case CRAM_MD5: c.writeEntry( "auth", "CRAM-MD5" ); break; } c.writeEntry( "Name", mAccountName ); c.writeEntry( "host", mServer ); c.writeEntry( "port", mPort ); c.writeEntry( "groupwareType", mGroupwareType ); // in case the user wants to get rid of some groupware folders c.writeEntry( "locally-subscribed-folders", mLocalSubscription ); c.writeEntry( "login", mUser ); c.writeEntry( "sieve-support", mEnableSieve ? "true" : "false" ); if ( !mSieveVacationFileName.isEmpty() ) c.writeEntry( "sieve-vacation-filename", mSieveVacationFileName ); if ( mEncryption == SSL ) { c.writeEntry( "use-ssl", true ); } else if ( mEncryption == TLS ) { c.writeEntry( "use-tls", true ); } if ( mEnableSavePassword ) { if ( !writeToWallet( "account", accountId ) ) { c.writeEntry( "pass", KStringHandler::obscure( mPassword ) ); c.writeEntry( "store-passwd", true ); } } c.setGroup( QString("Folder-%1").arg( uid ) ); c.writeEntry( "isOpen", true ); c.setGroup( "AccountWizard" ); c.writeEntry( "ShowOnStartup" , false ); c.setGroup( QString("Transport %1").arg( transportId ) ); c.writeEntry( "name", mAccountName ); c.writeEntry( "host", mServer ); c.writeEntry( "type", "smtp" ); c.writeEntry( "port", mSmtpPort ); if ( mEncryption == SSL ) { c.writeEntry( "encryption", "SSL" ); } else if ( mEncryption == TLS ) { c.writeEntry( "encryption", "TLS" ); } c.writeEntry( "auth", true ); if ( mAuthenticationSend == PLAIN ) { c.writeEntry( "authtype", "PLAIN" ); } else if ( mAuthenticationSend == LOGIN ) { c.writeEntry( "authtype", "LOGIN" ); } c.writeEntry( "user", mUser ); if ( mEnableSavePassword ) { if ( !writeToWallet( "transport", transportId ) ) { c.writeEntry( "pass", KStringHandler::obscure( mPassword ) ); c.writeEntry( "storepass", true ); } } // Write email in "default kcontrol settings", used by IdentityManager // if it has to create a default identity. KEMailSettings es; es.setSetting( KEMailSettings::RealName, mRealName ); es.setSetting( KEMailSettings::EmailAddress, mEmail ); KPIM::IdentityManager identityManager; if ( !identityManager.allEmails().contains( mEmail ) ) { // Not sure how to name the identity. First one is "Default", next one mAccountName, but then... // let's use the server name after that. QString accountName = mAccountName; const QStringList identities = identityManager.identities(); if ( identities.find( accountName ) != identities.end() ) { accountName = mServer; int i = 2; // And if there's already one, number them while ( identities.find( accountName ) != identities.end() ) { accountName = mServer + " " + QString::number( i++ ); } } KPIM::Identity& identity = identityManager.newFromScratch( accountName ); identity.setFullName( mRealName ); identity.setEmailAddr( mEmail ); identityManager.commit(); } if ( mCustomWriter ) { mCustomWriter->writeFolder( c, uid ); mCustomWriter->writeIds( accountId, transportId ); } } CreateOnlineImapAccount::CreateOnlineImapAccount(const QString & accountName) : CreateImapAccount( accountName, i18n("Create Online IMAP Account for KMail") ) { } void CreateOnlineImapAccount::apply() { KConfig c( "kmailrc" ); c.setGroup( "General" ); uint accCnt = c.readNumEntry( "accounts", 0 ); c.writeEntry( "accounts", accCnt+1 ); c.setGroup( QString("Account %1").arg(accCnt+1) ); int uid = kapp->random(); c.writeEntry( "Folder", uid ); c.writeEntry( "Id", uid ); c.writeEntry( "Type", "imap" ); c.writeEntry( "auth", "*" ); c.writeEntry( "Name", mAccountName ); c.writeEntry( "host", mServer ); c.writeEntry( "login", mUser ); if ( mEnableSavePassword ) { if ( !writeToWallet( "account", accCnt+1 ) ) { c.writeEntry( "pass", KStringHandler::obscure( mPassword ) ); c.writeEntry( "store-passwd", true ); } } c.writeEntry( "port", "993" ); if ( mEncryption == SSL ) { c.writeEntry( "use-ssl", true ); } else if ( mEncryption == TLS ) { c.writeEntry( "use-tls", true ); } if ( mAuthenticationSend == PLAIN ) { c.writeEntry( "authtype", "PLAIN" ); } else if ( mAuthenticationSend == LOGIN ) { c.writeEntry( "authtype", "LOGIN" ); } c.writeEntry( "sieve-support", mEnableSieve ); // locally unsubscribe the default folders c.writeEntry( "locally-subscribed-folders", true ); QString groupwareFolders = QString("/INBOX/%1/,/INBOX/%2/,/INBOX/%3/,/INBOX/%4/,/INBOX/%5/") .arg( i18n(s_folderContentsType[0]) ).arg( i18n(s_folderContentsType[1]) ) .arg( i18n(s_folderContentsType[2]) ).arg( i18n(s_folderContentsType[3]) ) .arg( i18n(s_folderContentsType[4]) ); c.writeEntry( "locallyUnsubscribedFolders", groupwareFolders ); c.setGroup( QString("Folder-%1").arg( uid ) ); c.writeEntry( "isOpen", true ); c.setGroup( "AccountWizard" ); c.writeEntry( "ShowOnStartup" , false ); } bool CreateImapAccount::writeToWallet(const QString & type, int id) { if ( !Wallet::isEnabled() ) return false; if ( !mWallet || !mWallet->isOpen() ) { delete mWallet; WId window = 0; if ( qApp->activeWindow() ) window = qApp->activeWindow()->winId(); mWallet = Wallet::openWallet( Wallet::NetworkWallet(), window ); if ( !mWallet ) return false; if ( !mWallet->hasFolder( "kmail" ) ) mWallet->createFolder( "kmail" ); mWallet->setFolder( "kmail" ); } return mWallet->writePassword( type + "-" + QString::number( id ), mPassword ); } <|endoftext|>
<commit_before>#include "WMSGridDataLayer.h" #include <boost/move/make_unique.hpp> #include <grid-files/common/GeneralFunctions.h> #include <grid-files/identification/GridDef.h> #include <macgyver/Exception.h> namespace SmartMet { namespace Plugin { namespace WMS { std::vector<boost::posix_time::ptime> get_ptime_vector(std::set<std::string>& contentTimeList) { std::vector<boost::posix_time::ptime> ret; for (auto it = contentTimeList.begin(); it != contentTimeList.end(); ++it) ret.push_back(boost::posix_time::from_time_t(utcTimeToTimeT(*it))); return ret; } time_t even_timesteps(std::set<std::string>& contentTimeList) { try { if (contentTimeList.size() < 2) return 0; time_t prevTime = 0; time_t step = 0; for (auto it = contentTimeList.begin(); it != contentTimeList.end(); ++it) { time_t tt = utcTimeToTimeT(*it); if (prevTime != 0) { time_t s = tt - prevTime; if (step != 0 && s != step) return 0; step = s; } prevTime = tt; } return step; } catch (...) { throw Fmi::Exception::Trace(BCP, "Failed to update querydata layer metadata!"); } } WMSGridDataLayer::WMSGridDataLayer(const WMSConfig& config, const std::string& producer, const std::string& parameter, uint geometryId) : WMSLayer(config), itsGridEngine(config.gridEngine()), itsProducer(producer), itsParameter(parameter), itsGeometryId(geometryId) { } void WMSGridDataLayer::updateLayerMetaData() { try { if (!itsGridEngine || !itsGridEngine->isEnabled()) { Fmi::Exception exception(BCP, "The grid-engine is disabled!"); exception.disableLogging(); throw exception; } auto contentServer = itsGridEngine->getContentServer_sptr(); T::ProducerInfo producerInfo; if (contentServer->getProducerInfoByName(0, itsProducer, producerInfo) != 0) return; T::GenerationInfoList generationInfoList; if (contentServer->getGenerationInfoListByProducerId( 0, producerInfo.mProducerId, generationInfoList) != 0 || generationInfoList.getLength() == 0) return; std::map<boost::posix_time::ptime, boost::shared_ptr<WMSTimeDimension>> newTimeDimensions; for (unsigned int i = 0; i < generationInfoList.getLength(); i++) { T::GenerationInfo* generationInfo = generationInfoList.getGenerationInfoByIndex(i); if (generationInfo == nullptr) continue; if (itsGeometryId <= 0) { std::set<T::GeometryId> geometryIdList; if (contentServer->getContentGeometryIdListByGenerationId( 0, generationInfo->mGenerationId, geometryIdList) != 0 || geometryIdList.size() == 0) return; itsGeometryId = *geometryIdList.begin(); } if (itsGeometryId > 0) { GRIB2::GridDef_ptr def = Identification::gridDef.getGrib2DefinitionByGeometryId(itsGeometryId); if (def != nullptr) { T::Coordinate topLeft, topRight, bottomLeft, bottomRight; if (def->getGridLatLonArea(topLeft, topRight, bottomLeft, bottomRight)) { geographicBoundingBox.xMin = std::min(topLeft.x(), bottomLeft.x()); geographicBoundingBox.xMax = std::max(topRight.x(), bottomRight.x()); geographicBoundingBox.yMin = std::min(bottomLeft.y(), bottomRight.y()); geographicBoundingBox.yMax = std::max(topLeft.y(), topRight.y()); } } } std::set<std::string> contentTimeList; if (itsParameter > "") { std::string param = itsGridEngine->getParameterString(itsProducer, itsParameter); std::vector<std::string> p; splitString(param, ':', p); T::ParamKeyType parameterKeyType = T::ParamKeyTypeValue::FMI_NAME; std::string parameterKey = p[0]; T::ParamLevelId parameterLevelId = 0; T::ParamLevel minLevel = 0; T::ParamLevel maxLevel = 1000000000; T::ForecastType forecastType = 1; T::ForecastNumber forecastNumber = -1; std::string startTime = "19000101T000000"; std::string endTime = "23000101T000000"; if (p.size() >= 3 && p[2] > "") { itsGeometryId = toInt32(p[2]); } if (p.size() >= 4 && p[3] > "") parameterLevelId = toInt32(p[3]); if (p.size() >= 5 && p[4] > "") { minLevel = toInt32(p[4]); maxLevel = minLevel; } if (p.size() >= 6 && p[5] > "") forecastType = toInt32(p[5]); if (p.size() >= 7 && p[6] > "") forecastNumber = toInt32(p[6]); T::ContentInfoList contentInfoList; if (contentServer->getContentListByParameterAndGenerationId(0, generationInfo->mGenerationId, parameterKeyType, parameterKey, parameterLevelId, minLevel, maxLevel, forecastType, forecastNumber, itsGeometryId, startTime, endTime, 0, contentInfoList) != 0) return; uint len = contentInfoList.getLength(); for (uint t = 0; t < len; t++) { T::ContentInfo* info = contentInfoList.getContentInfoByIndex(t); if (contentTimeList.find(info->getForecastTime()) == contentTimeList.end()) contentTimeList.insert(std::string(info->getForecastTime())); } } else { if (contentServer->getContentTimeListByGenerationAndGeometryId( 0, generationInfo->mGenerationId, itsGeometryId, contentTimeList) != 0) return; } boost::shared_ptr<WMSTimeDimension> timeDimension; // timesteps std::list<boost::posix_time::ptime> timesteps; for (const auto& stime : contentTimeList) timesteps.push_back(toTimeStamp(stime)); time_intervals intervals = get_intervals(timesteps); if (!intervals.empty()) { timeDimension = boost::make_shared<IntervalTimeDimension>(intervals); } else { timeDimension = boost::make_shared<StepTimeDimension>(timesteps); } /* time_t step = even_timesteps(contentTimeList); if (step > 0) { // time interval boost::posix_time::time_duration timestep = boost::posix_time::seconds(step); timeDimension = boost::make_shared<IntervalTimeDimension>(toTimeStamp(*(contentTimeList.begin())), toTimeStamp(*(--contentTimeList.end())), timestep); } else { // timesteps std::list<boost::posix_time::ptime> times; for (const auto& stime : contentTimeList) times.push_back(toTimeStamp(stime)); timeDimension = boost::make_shared<StepTimeDimension>(times); } */ if (timeDimension) newTimeDimensions.insert( std::make_pair(toTimeStamp(generationInfo->mAnalysisTime), timeDimension)); } if (!newTimeDimensions.empty()) timeDimensions = boost::make_shared<WMSTimeDimensions>(newTimeDimensions); else timeDimensions = nullptr; metadataTimestamp = boost::posix_time::second_clock::universal_time(); } catch (...) { throw Fmi::Exception::Trace(BCP, "Failed to update querydata layer metadata!"); } } } // namespace WMS } // namespace Plugin } // namespace SmartMet <commit_msg>Minor updates<commit_after>#include "WMSGridDataLayer.h" #include <boost/move/make_unique.hpp> #include <grid-files/common/GeneralFunctions.h> #include <grid-files/identification/GridDef.h> #include <macgyver/Exception.h> namespace SmartMet { namespace Plugin { namespace WMS { std::vector<boost::posix_time::ptime> get_ptime_vector(std::set<std::string>& contentTimeList) { std::vector<boost::posix_time::ptime> ret; for (auto it = contentTimeList.begin(); it != contentTimeList.end(); ++it) ret.push_back(boost::posix_time::from_time_t(utcTimeToTimeT(*it))); return ret; } time_t even_timesteps(std::set<std::string>& contentTimeList) { try { if (contentTimeList.size() < 2) return 0; time_t prevTime = 0; time_t step = 0; for (auto it = contentTimeList.begin(); it != contentTimeList.end(); ++it) { time_t tt = utcTimeToTimeT(*it); if (prevTime != 0) { time_t s = tt - prevTime; if (step != 0 && s != step) return 0; step = s; } prevTime = tt; } return step; } catch (...) { throw Fmi::Exception::Trace(BCP, "Failed to update querydata layer metadata!"); } } WMSGridDataLayer::WMSGridDataLayer(const WMSConfig& config, const std::string& producer, const std::string& parameter, uint geometryId) : WMSLayer(config), itsGridEngine(config.gridEngine()), itsProducer(producer), itsParameter(parameter), itsGeometryId(geometryId) { } void WMSGridDataLayer::updateLayerMetaData() { try { if (!itsGridEngine || !itsGridEngine->isEnabled()) { Fmi::Exception exception(BCP, "The grid-engine is disabled!"); exception.disableLogging(); throw exception; } auto contentServer = itsGridEngine->getContentServer_sptr(); T::ProducerInfo producerInfo; if (contentServer->getProducerInfoByName(0, itsProducer, producerInfo) != 0) return; T::GenerationInfoList generationInfoList; if (contentServer->getGenerationInfoListByProducerId( 0, producerInfo.mProducerId, generationInfoList) != 0 || generationInfoList.getLength() == 0) return; std::map<boost::posix_time::ptime, boost::shared_ptr<WMSTimeDimension>> newTimeDimensions; for (unsigned int i = 0; i < generationInfoList.getLength(); i++) { T::GenerationInfo* generationInfo = generationInfoList.getGenerationInfoByIndex(i); if (generationInfo == nullptr) continue; if (itsGeometryId <= 0) { std::set<T::GeometryId> geometryIdList; if (contentServer->getContentGeometryIdListByGenerationId( 0, generationInfo->mGenerationId, geometryIdList) != 0 || geometryIdList.size() == 0) return; itsGeometryId = *geometryIdList.begin(); } if (itsGeometryId > 0) { auto def = Identification::gridDef.getGrib2DefinitionByGeometryId(itsGeometryId); if (def) { T::Coordinate topLeft, topRight, bottomLeft, bottomRight; if (def->getGridLatLonArea(topLeft, topRight, bottomLeft, bottomRight)) { geographicBoundingBox.xMin = std::min(topLeft.x(), bottomLeft.x()); geographicBoundingBox.xMax = std::max(topRight.x(), bottomRight.x()); geographicBoundingBox.yMin = std::min(bottomLeft.y(), bottomRight.y()); geographicBoundingBox.yMax = std::max(topLeft.y(), topRight.y()); } } } std::set<std::string> contentTimeList; if (itsParameter > "") { std::string param = itsGridEngine->getParameterString(itsProducer, itsParameter); std::vector<std::string> p; splitString(param, ':', p); T::ParamKeyType parameterKeyType = T::ParamKeyTypeValue::FMI_NAME; std::string parameterKey = p[0]; T::ParamLevelId parameterLevelId = 0; T::ParamLevel minLevel = 0; T::ParamLevel maxLevel = 1000000000; T::ForecastType forecastType = 1; T::ForecastNumber forecastNumber = -1; std::string startTime = "19000101T000000"; std::string endTime = "23000101T000000"; if (p.size() >= 3 && p[2] > "") { itsGeometryId = toInt32(p[2]); } if (p.size() >= 4 && p[3] > "") parameterLevelId = toInt32(p[3]); if (p.size() >= 5 && p[4] > "") { minLevel = toInt32(p[4]); maxLevel = minLevel; } if (p.size() >= 6 && p[5] > "") forecastType = toInt32(p[5]); if (p.size() >= 7 && p[6] > "") forecastNumber = toInt32(p[6]); T::ContentInfoList contentInfoList; if (contentServer->getContentListByParameterAndGenerationId(0, generationInfo->mGenerationId, parameterKeyType, parameterKey, parameterLevelId, minLevel, maxLevel, forecastType, forecastNumber, itsGeometryId, startTime, endTime, 0, contentInfoList) != 0) return; uint len = contentInfoList.getLength(); for (uint t = 0; t < len; t++) { T::ContentInfo* info = contentInfoList.getContentInfoByIndex(t); if (contentTimeList.find(info->getForecastTime()) == contentTimeList.end()) contentTimeList.insert(std::string(info->getForecastTime())); } } else { if (contentServer->getContentTimeListByGenerationAndGeometryId( 0, generationInfo->mGenerationId, itsGeometryId, contentTimeList) != 0) return; } boost::shared_ptr<WMSTimeDimension> timeDimension; // timesteps std::list<boost::posix_time::ptime> timesteps; for (const auto& stime : contentTimeList) timesteps.push_back(toTimeStamp(stime)); time_intervals intervals = get_intervals(timesteps); if (!intervals.empty()) { timeDimension = boost::make_shared<IntervalTimeDimension>(intervals); } else { timeDimension = boost::make_shared<StepTimeDimension>(timesteps); } /* time_t step = even_timesteps(contentTimeList); if (step > 0) { // time interval boost::posix_time::time_duration timestep = boost::posix_time::seconds(step); timeDimension = boost::make_shared<IntervalTimeDimension>(toTimeStamp(*(contentTimeList.begin())), toTimeStamp(*(--contentTimeList.end())), timestep); } else { // timesteps std::list<boost::posix_time::ptime> times; for (const auto& stime : contentTimeList) times.push_back(toTimeStamp(stime)); timeDimension = boost::make_shared<StepTimeDimension>(times); } */ if (timeDimension) newTimeDimensions.insert( std::make_pair(toTimeStamp(generationInfo->mAnalysisTime), timeDimension)); } if (!newTimeDimensions.empty()) timeDimensions = boost::make_shared<WMSTimeDimensions>(newTimeDimensions); else timeDimensions = nullptr; metadataTimestamp = boost::posix_time::second_clock::universal_time(); } catch (...) { throw Fmi::Exception::Trace(BCP, "Failed to update querydata layer metadata!"); } } } // namespace WMS } // namespace Plugin } // namespace SmartMet <|endoftext|>
<commit_before>/* writerperfect: * * Copyright (C) 2002 Jon K Hellan (hellan@acm.org) * Copyright (C) 2002-2004 William Lachance (wrlach@gmail.com) * Copyright (C) 2003-2004 Net Integration Technologies (http://www.net-itech.com) * Copyright (C) 2004-2006 Fridrich Strba (fridrich.strba@bluewin.ch) * * This program is free software; you can redistribute it and/or * modify it under the terms of 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 */ #include <stdio.h> #include <string.h> #include <libwpd/libwpd.h> #include "OutputFileHelper.hxx" #include "WordPerfectCollector.hxx" const char mimetypeStr[] = "application/vnd.oasis.opendocument.text"; const char manifestStr[] = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" "<manifest:manifest xmlns:manifest=\"urn:oasis:names:tc:opendocument:xmlns:manifest:1.0\">" " <manifest:file-entry manifest:media-type=\"application/vnd.oasis.opendocument.text\" manifest:full-path=\"/\"/>" " <manifest:file-entry manifest:media-type=\"text/xml\" manifest:full-path=\"content.xml\"/>" " <manifest:file-entry manifest:media-type=\"text/xml\" manifest:full-path=\"styles.xml\"/>" "</manifest:manifest>"; const char stylesStr[] = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" "<office:document-styles xmlns:office=\"urn:oasis:names:tc:opendocument:xmlns:office:1.0\" " "xmlns:style=\"urn:oasis:names:tc:opendocument:xmlns:style:1.0\" xmlns:text=\"urn:oasis:names:tc:opendocument:xmlns:text:1.0\" " "xmlns:table=\"urn:oasis:names:tc:opendocument:xmlns:table:1.0\" xmlns:draw=\"urn:oasis:names:tc:opendocument:xmlns:drawing:1.0\" " "xmlns:fo=\"urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" " "xmlns:number=\"urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0\" " "xmlns:svg=\"urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0\" " "xmlns:chart=\"urn:oasis:names:tc:opendocument:xmlns:chart:1.0\" xmlns:dr3d=\"urn:oasis:names:tc:opendocument:xmlns:dr3d:1.0\" " "xmlns:form=\"urn:oasis:names:tc:opendocument:xmlns:form:1.0\" xmlns:script=\"urn:oasis:names:tc:opendocument:xmlns:script:1.0\">" "<office:styles>" "<style:default-style style:family=\"paragraph\">" "<style:paragraph-properties style:use-window-font-color=\"true\" style:text-autospace=\"ideograph-alpha\" " "style:punctuation-wrap=\"hanging\" style:line-break=\"strict\" style:writing-mode=\"page\"/>" "</style:default-style>" "<style:default-style style:family=\"table\"/>" "<style:default-style style:family=\"table-row\">" "<style:table-row-properties fo:keep-together=\"auto\"/>" "</style:default-style>" "<style:default-style style:family=\"table-column\"/>" "<style:style style:name=\"Standard\" style:family=\"paragraph\" style:class=\"text\"/>" "<style:style style:name=\"Text_body\" style:display-name=\"Text body\" style:family=\"paragraph\" " "style:parent-style-name=\"Standard\" style:class=\"text\"/>" "<style:style style:name=\"List\" style:family=\"paragraph\" style:parent-style-name=\"Text_body\" style:class=\"list\"/>" "<style:style style:name=\"Header\" style:family=\"paragraph\" style:parent-style-name=\"Standard\" style:class=\"extra\"/>" "<style:style style:name=\"Footer\" style:family=\"paragraph\" style:parent-style-name=\"Standard\" style:class=\"extra\"/>" "<style:style style:name=\"Caption\" style:family=\"paragraph\" style:parent-style-name=\"Standard\" style:class=\"extra\"/>" "<style:style style:name=\"Footnote\" style:family=\"paragraph\" style:parent-style-name=\"Standard\" style:class=\"extra\"/>" "<style:style style:name=\"Endnote\" style:family=\"paragraph\" style:parent-style-name=\"Standard\" style:class=\"extra\"/>" "<style:style style:name=\"Index\" style:family=\"paragraph\" style:parent-style-name=\"Standard\" style:class=\"index\"/>" "<style:style style:name=\"Footnote_Symbol\" style:display-name=\"Footnote Symbol\" style:family=\"text\">" "<style:text-properties style:text-position=\"super 58%\"/>" "</style:style>" "<style:style style:name=\"Endnote_Symbol\" style:display-name=\"Endnote Symbol\" style:family=\"text\">" "<style:text-properties style:text-position=\"super 58%\"/>" "</style:style>" "<style:style style:name=\"Footnote_anchor\" style:display-name=\"Footnote anchor\" style:family=\"text\">" "<style:text-properties style:text-position=\"super 58%\"/>" "</style:style>" "<style:style style:name=\"Endnote_anchor\" style:display-name=\"Endnote anchor\" style:family=\"text\">" "<style:text-properties style:text-position=\"super 58%\"/>" "</style:style>" "<text:notes-configuration text:note-class=\"footnote\" text:citation-style-name=\"Footnote_Symbol\" " "text:citation-body-style-name=\"Footnote_anchor\" style:num-format=\"1\" text:start-value=\"0\" " "text:footnotes-position=\"page\" text:start-numbering-at=\"document\"/>" "<text:notes-configuration text:note-class=\"endnote\" text:citation-style-name=\"Endnote_Symbol\" " "text:citation-body-style-name=\"Endnote_anchor\" text:master-page-name=\"Endnote\" " "style:num-format=\"i\" text:start-value=\"0\"/>" "<text:linenumbering-configuration text:number-lines=\"false\" text:offset=\"0.1965in\" " "style:num-format=\"1\" text:number-position=\"left\" text:increment=\"5\"/>" "</office:styles>" "<office:automatic-styles>" "<style:page-layout style:name=\"PM0\">" "<style:page-layout-properties fo:margin-bottom=\"1.0000in\" fo:margin-left=\"1.0000in\" " "fo:margin-right=\"1.0000in\" fo:margin-top=\"1.0000in\" fo:page-height=\"11.0000in\" " "fo:page-width=\"8.5000in\" style:print-orientation=\"portrait\">" "<style:footnote-sep style:adjustment=\"left\" style:color=\"#000000\" style:distance-after-sep=\"0.0398in\" " "style:distance-before-sep=\"0.0398in\" style:rel-width=\"25%\" style:width=\"0.0071in\"/>" "</style:page-layout-properties>" "</style:page-layout>" "<style:page-layout style:name=\"PM1\">" "<style:page-layout-properties fo:margin-bottom=\"1.0000in\" fo:margin-left=\"1.0000in\" " "fo:margin-right=\"1.0000in\" fo:margin-top=\"1.0000in\" fo:page-height=\"11.0000in\" " "fo:page-width=\"8.5000in\" style:print-orientation=\"portrait\">" "<style:footnote-sep style:adjustment=\"left\" style:color=\"#000000\" style:rel-width=\"25%\"/>" "</style:page-layout-properties>" "</style:page-layout>" "</office:automatic-styles>" "<office:master-styles>" "<style:master-page style:name=\"Standard\" style:page-layout-name=\"PM0\"/>" "<style:master-page style:name=\"Endnote\" style:page-layout-name=\"PM1\"/>" "</office:master-styles>" "</office:document-styles>"; class OdtOutputFileHelper : public OutputFileHelper { public: OdtOutputFileHelper(const char *outFileName,const char *password) : OutputFileHelper(outFileName, password) {}; ~OdtOutputFileHelper() {}; private: bool _isSupportedFormat(WPXInputStream *input, const char * password) { bool retVal = (WPD_CONFIDENCE_EXCELLENT == WPDocument::isFileFormatSupported(input, password)); if (!retVal) fprintf(stderr, "ERROR: We have no confidence that you are giving us a valid WordPerfect document.\n"); return retVal; } bool _convertDocument(WPXInputStream *input, const char *password, DocumentHandler *handler, bool isFlatXML) { WordPerfectCollector collector(input, password, handler, isFlatXML); return collector.filter(); } }; int printUsage(char * name) { fprintf(stderr, "USAGE : %s [--stdout] --password <password> <infile> [outfile]\n", name); fprintf(stderr, "USAGE : Where <infile> is the WordPerfect source document\n"); fprintf(stderr, "USAGE : and [outfile] is the odt target document. Alternately,\n"); fprintf(stderr, "USAGE : pass '--stdout' or simply omit the [outfile] to pipe the\n"); fprintf(stderr, "USAGE : resultant document as flat XML to standard output\n"); fprintf(stderr, "USAGE : pass '--password <password>' to try to decrypt password\n"); fprintf(stderr, "USAGE : protected documents.\n"); fprintf(stderr, "USAGE : \n"); return 1; } int main (int argc, char *argv[]) { if (argc < 2) return printUsage(argv[0]); char *szInputFile = 0; char *szOutFile = 0; bool stdOutput = false; char *password = 0; for (int i = 1; i < argc; i++) { if (!strcmp(argv[i], "--password")) { if (i < argc - 1) password = argv[++i]; } else if (!strcmp(argv[i], "--stdout")) stdOutput = true; else if (!szInputFile && strncmp(argv[i], "--", 2)) szInputFile = argv[i]; else if (szInputFile && !szOutFile && strncmp(argv[i], "--", 2)) szOutFile = argv[i]; else return printUsage(argv[0]); } if (!szInputFile) return printUsage(argv[0]); if (szOutFile && stdOutput) szOutFile = 0; OdtOutputFileHelper helper(szOutFile, password); if (!helper.writeChildFile("mimetype", mimetypeStr, (char)0)) { fprintf(stderr, "ERROR : Couldn't write mimetype\n"); return 1; } if (!helper.writeChildFile("META-INF/manifest.xml", manifestStr)) { fprintf(stderr, "ERROR : Couldn't write manifest\n"); return 1; } if (!helper.writeChildFile("styles.xml", stylesStr)) { fprintf(stderr, "ERROR : Couldn't write styles\n"); return 1; } if (!helper.writeConvertedContent("content.xml", szInputFile)) { fprintf(stderr, "ERROR : Couldn't write document content\n"); return 1; } return 0; } <commit_msg>allow passing of password using --password=something<commit_after>/* writerperfect: * * Copyright (C) 2002 Jon K Hellan (hellan@acm.org) * Copyright (C) 2002-2004 William Lachance (wrlach@gmail.com) * Copyright (C) 2003-2004 Net Integration Technologies (http://www.net-itech.com) * Copyright (C) 2004-2006 Fridrich Strba (fridrich.strba@bluewin.ch) * * This program is free software; you can redistribute it and/or * modify it under the terms of 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 */ #include <stdio.h> #include <string.h> #include <libwpd/libwpd.h> #include "OutputFileHelper.hxx" #include "WordPerfectCollector.hxx" const char mimetypeStr[] = "application/vnd.oasis.opendocument.text"; const char manifestStr[] = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" "<manifest:manifest xmlns:manifest=\"urn:oasis:names:tc:opendocument:xmlns:manifest:1.0\">" " <manifest:file-entry manifest:media-type=\"application/vnd.oasis.opendocument.text\" manifest:full-path=\"/\"/>" " <manifest:file-entry manifest:media-type=\"text/xml\" manifest:full-path=\"content.xml\"/>" " <manifest:file-entry manifest:media-type=\"text/xml\" manifest:full-path=\"styles.xml\"/>" "</manifest:manifest>"; const char stylesStr[] = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" "<office:document-styles xmlns:office=\"urn:oasis:names:tc:opendocument:xmlns:office:1.0\" " "xmlns:style=\"urn:oasis:names:tc:opendocument:xmlns:style:1.0\" xmlns:text=\"urn:oasis:names:tc:opendocument:xmlns:text:1.0\" " "xmlns:table=\"urn:oasis:names:tc:opendocument:xmlns:table:1.0\" xmlns:draw=\"urn:oasis:names:tc:opendocument:xmlns:drawing:1.0\" " "xmlns:fo=\"urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" " "xmlns:number=\"urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0\" " "xmlns:svg=\"urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0\" " "xmlns:chart=\"urn:oasis:names:tc:opendocument:xmlns:chart:1.0\" xmlns:dr3d=\"urn:oasis:names:tc:opendocument:xmlns:dr3d:1.0\" " "xmlns:form=\"urn:oasis:names:tc:opendocument:xmlns:form:1.0\" xmlns:script=\"urn:oasis:names:tc:opendocument:xmlns:script:1.0\">" "<office:styles>" "<style:default-style style:family=\"paragraph\">" "<style:paragraph-properties style:use-window-font-color=\"true\" style:text-autospace=\"ideograph-alpha\" " "style:punctuation-wrap=\"hanging\" style:line-break=\"strict\" style:writing-mode=\"page\"/>" "</style:default-style>" "<style:default-style style:family=\"table\"/>" "<style:default-style style:family=\"table-row\">" "<style:table-row-properties fo:keep-together=\"auto\"/>" "</style:default-style>" "<style:default-style style:family=\"table-column\"/>" "<style:style style:name=\"Standard\" style:family=\"paragraph\" style:class=\"text\"/>" "<style:style style:name=\"Text_body\" style:display-name=\"Text body\" style:family=\"paragraph\" " "style:parent-style-name=\"Standard\" style:class=\"text\"/>" "<style:style style:name=\"List\" style:family=\"paragraph\" style:parent-style-name=\"Text_body\" style:class=\"list\"/>" "<style:style style:name=\"Header\" style:family=\"paragraph\" style:parent-style-name=\"Standard\" style:class=\"extra\"/>" "<style:style style:name=\"Footer\" style:family=\"paragraph\" style:parent-style-name=\"Standard\" style:class=\"extra\"/>" "<style:style style:name=\"Caption\" style:family=\"paragraph\" style:parent-style-name=\"Standard\" style:class=\"extra\"/>" "<style:style style:name=\"Footnote\" style:family=\"paragraph\" style:parent-style-name=\"Standard\" style:class=\"extra\"/>" "<style:style style:name=\"Endnote\" style:family=\"paragraph\" style:parent-style-name=\"Standard\" style:class=\"extra\"/>" "<style:style style:name=\"Index\" style:family=\"paragraph\" style:parent-style-name=\"Standard\" style:class=\"index\"/>" "<style:style style:name=\"Footnote_Symbol\" style:display-name=\"Footnote Symbol\" style:family=\"text\">" "<style:text-properties style:text-position=\"super 58%\"/>" "</style:style>" "<style:style style:name=\"Endnote_Symbol\" style:display-name=\"Endnote Symbol\" style:family=\"text\">" "<style:text-properties style:text-position=\"super 58%\"/>" "</style:style>" "<style:style style:name=\"Footnote_anchor\" style:display-name=\"Footnote anchor\" style:family=\"text\">" "<style:text-properties style:text-position=\"super 58%\"/>" "</style:style>" "<style:style style:name=\"Endnote_anchor\" style:display-name=\"Endnote anchor\" style:family=\"text\">" "<style:text-properties style:text-position=\"super 58%\"/>" "</style:style>" "<text:notes-configuration text:note-class=\"footnote\" text:citation-style-name=\"Footnote_Symbol\" " "text:citation-body-style-name=\"Footnote_anchor\" style:num-format=\"1\" text:start-value=\"0\" " "text:footnotes-position=\"page\" text:start-numbering-at=\"document\"/>" "<text:notes-configuration text:note-class=\"endnote\" text:citation-style-name=\"Endnote_Symbol\" " "text:citation-body-style-name=\"Endnote_anchor\" text:master-page-name=\"Endnote\" " "style:num-format=\"i\" text:start-value=\"0\"/>" "<text:linenumbering-configuration text:number-lines=\"false\" text:offset=\"0.1965in\" " "style:num-format=\"1\" text:number-position=\"left\" text:increment=\"5\"/>" "</office:styles>" "<office:automatic-styles>" "<style:page-layout style:name=\"PM0\">" "<style:page-layout-properties fo:margin-bottom=\"1.0000in\" fo:margin-left=\"1.0000in\" " "fo:margin-right=\"1.0000in\" fo:margin-top=\"1.0000in\" fo:page-height=\"11.0000in\" " "fo:page-width=\"8.5000in\" style:print-orientation=\"portrait\">" "<style:footnote-sep style:adjustment=\"left\" style:color=\"#000000\" style:distance-after-sep=\"0.0398in\" " "style:distance-before-sep=\"0.0398in\" style:rel-width=\"25%\" style:width=\"0.0071in\"/>" "</style:page-layout-properties>" "</style:page-layout>" "<style:page-layout style:name=\"PM1\">" "<style:page-layout-properties fo:margin-bottom=\"1.0000in\" fo:margin-left=\"1.0000in\" " "fo:margin-right=\"1.0000in\" fo:margin-top=\"1.0000in\" fo:page-height=\"11.0000in\" " "fo:page-width=\"8.5000in\" style:print-orientation=\"portrait\">" "<style:footnote-sep style:adjustment=\"left\" style:color=\"#000000\" style:rel-width=\"25%\"/>" "</style:page-layout-properties>" "</style:page-layout>" "</office:automatic-styles>" "<office:master-styles>" "<style:master-page style:name=\"Standard\" style:page-layout-name=\"PM0\"/>" "<style:master-page style:name=\"Endnote\" style:page-layout-name=\"PM1\"/>" "</office:master-styles>" "</office:document-styles>"; class OdtOutputFileHelper : public OutputFileHelper { public: OdtOutputFileHelper(const char *outFileName,const char *password) : OutputFileHelper(outFileName, password) {}; ~OdtOutputFileHelper() {}; private: bool _isSupportedFormat(WPXInputStream *input, const char * password) { bool retVal = (WPD_CONFIDENCE_EXCELLENT == WPDocument::isFileFormatSupported(input, password)); if (!retVal) fprintf(stderr, "ERROR: We have no confidence that you are giving us a valid WordPerfect document.\n"); return retVal; } bool _convertDocument(WPXInputStream *input, const char *password, DocumentHandler *handler, bool isFlatXML) { WordPerfectCollector collector(input, password, handler, isFlatXML); return collector.filter(); } }; int printUsage(char * name) { fprintf(stderr, "USAGE : %s [--stdout] --password <password> <infile> [outfile]\n", name); fprintf(stderr, "USAGE : Where <infile> is the WordPerfect source document\n"); fprintf(stderr, "USAGE : and [outfile] is the odt target document. Alternately,\n"); fprintf(stderr, "USAGE : pass '--stdout' or simply omit the [outfile] to pipe the\n"); fprintf(stderr, "USAGE : resultant document as flat XML to standard output\n"); fprintf(stderr, "USAGE : pass '--password <password>' to try to decrypt password\n"); fprintf(stderr, "USAGE : protected documents.\n"); fprintf(stderr, "USAGE : \n"); return 1; } int main (int argc, char *argv[]) { if (argc < 2) return printUsage(argv[0]); char *szInputFile = 0; char *szOutFile = 0; bool stdOutput = false; char *password = 0; for (int i = 1; i < argc; i++) { if (!strcmp(argv[i], "--password")) { if (i < argc - 1) password = argv[++i]; } else if (!strncmp(argv[i], "--password=", 11)) password = &argv[i][11]; else if (!strcmp(argv[i], "--stdout")) stdOutput = true; else if (!szInputFile && strncmp(argv[i], "--", 2)) szInputFile = argv[i]; else if (szInputFile && !szOutFile && strncmp(argv[i], "--", 2)) szOutFile = argv[i]; else return printUsage(argv[0]); } if (!szInputFile) return printUsage(argv[0]); if (szOutFile && stdOutput) szOutFile = 0; OdtOutputFileHelper helper(szOutFile, password); if (!helper.writeChildFile("mimetype", mimetypeStr, (char)0)) { fprintf(stderr, "ERROR : Couldn't write mimetype\n"); return 1; } if (!helper.writeChildFile("META-INF/manifest.xml", manifestStr)) { fprintf(stderr, "ERROR : Couldn't write manifest\n"); return 1; } if (!helper.writeChildFile("styles.xml", stylesStr)) { fprintf(stderr, "ERROR : Couldn't write styles\n"); return 1; } if (!helper.writeConvertedContent("content.xml", szInputFile)) { fprintf(stderr, "ERROR : Couldn't write document content\n"); return 1; } return 0; } <|endoftext|>
<commit_before>/** * @file posixHelperProxy.cc * @author Bartek Kryza * @copyright (C) 2017 ACK CYFRONET AGH * @copyright This software is released under the MIT license cited in * 'LICENSE.txt' */ #include "posixHelper.h" #include <boost/make_shared.hpp> #include <boost/python.hpp> #include <boost/python/extract.hpp> #include <boost/python/raw_function.hpp> #include <boost/python/suite/indexing/vector_indexing_suite.hpp> #include <folly/executors/IOThreadPoolExecutor.h> #include <chrono> #include <future> #include <string> #include <thread> #include <iostream> using ReadDirResult = std::vector<std::string>; using namespace boost::python; using namespace one::helpers; /* * Minimum 4 threads are required to run this helper proxy. */ constexpr int POSIX_HELPER_WORKER_THREADS = 1; class ReleaseGIL { public: ReleaseGIL() : threadState{PyEval_SaveThread(), PyEval_RestoreThread} { } private: std::unique_ptr<PyThreadState, decltype(&PyEval_RestoreThread)> threadState; }; class PosixHelperProxy { public: PosixHelperProxy(std::string mountPoint, uid_t uid, gid_t gid) : m_executor{std::make_shared<folly::IOThreadPoolExecutor>( POSIX_HELPER_WORKER_THREADS, std::make_shared<StorageWorkerFactory>("posix_t"))} { std::unordered_map<folly::fbstring, folly::fbstring> params; params["type"] = "posix"; params["mountPoint"] = mountPoint; params["uid"] = std::to_string(uid); params["gid"] = std::to_string(gid); m_helper = std::make_shared<one::helpers::PosixHelper>( PosixHelperParams::create(params), m_executor, ExecutionContext::ONECLIENT); } ~PosixHelperProxy() {} void open(std::string fileId, int flags) { ReleaseGIL guard; m_helper->open(fileId, flags, {}) .thenValue([&](one::helpers::FileHandlePtr &&handle) { handle->release(); }); } std::string read(std::string fileId, int offset, int size) { ReleaseGIL guard; return m_helper->open(fileId, O_RDONLY, {}) .thenValue([&](one::helpers::FileHandlePtr &&handle) { return handle->read(offset, size) .thenValue([handle](folly::IOBufQueue &&buf) { std::string data; buf.appendToString(data); return data; }); }) .get(); } int write(std::string fileId, std::string data, int offset) { ReleaseGIL guard; // PosixHelper does not support creating file with approriate mode, // so in case it doesn't exist we have to create it first to be // compatible with other helpers' test cases. auto mknodLambda = [&](auto && /*unit*/) { return m_helper->mknod(fileId, S_IFREG | 0666, {}, 0); }; auto writeLambda = [&](auto && /*unit*/) { return m_helper->open(fileId, O_WRONLY, {}) .thenValue([&](one::helpers::FileHandlePtr &&handle) { folly::IOBufQueue buf{ folly::IOBufQueue::cacheChainLength()}; buf.append(data); return handle->write(offset, std::move(buf), {}) .thenValue([handle](auto &&size) { return size; }); }); }; return m_helper->access(fileId, 0) .thenValue(writeLambda) .thenError(folly::tag_t<std::exception>{}, [mknodLambda = std::move(mknodLambda), writeLambda = std::move(writeLambda), executor = m_executor](auto &&e) { return folly::makeFuture() .via(executor.get()) .thenValue(mknodLambda) .thenValue(writeLambda); }) .get(); } struct stat getattr(std::string fileId) { ReleaseGIL guard; return m_helper->getattr(fileId).get(); } void access(std::string fileId, int mask) { ReleaseGIL guard; m_helper->access(fileId, mask).get(); } ReadDirResult readdir(std::string fileId, int offset, int count) { ReleaseGIL guard; std::vector<std::string> res; for (auto &direntry : m_helper->readdir(fileId, offset, count).get()) { res.emplace_back(direntry.toStdString()); } return res; } std::string readlink(std::string fileId) { ReleaseGIL guard; return m_helper->readlink(fileId).get().toStdString(); } void mknod(std::string fileId, mode_t mode, std::vector<Flag> flags) { ReleaseGIL guard; m_helper->mknod(fileId, mode, FlagsSet(flags.begin(), flags.end()), 0) .get(); } void mkdir(std::string fileId, mode_t mode) { ReleaseGIL guard; m_helper->mkdir(fileId, mode).get(); } void unlink(std::string fileId, int size) { ReleaseGIL guard; m_helper->unlink(fileId, size).get(); } void rmdir(std::string fileId) { ReleaseGIL guard; m_helper->rmdir(fileId).get(); } void symlink(std::string from, std::string to) { ReleaseGIL guard; m_helper->symlink(from, to).get(); } void rename(std::string from, std::string to) { ReleaseGIL guard; m_helper->rename(from, to).get(); } void link(std::string from, std::string to) { ReleaseGIL guard; m_helper->link(from, to).get(); } void chmod(std::string fileId, mode_t mode) { ReleaseGIL guard; m_helper->chmod(fileId, mode).get(); } void chown(std::string fileId, uid_t uid, gid_t gid) { ReleaseGIL guard; m_helper->chown(fileId, uid, gid).get(); } void truncate(std::string fileId, int offset, int size) { ReleaseGIL guard; m_helper->truncate(fileId, offset, size).get(); } std::string getxattr(std::string fileId, std::string name) { ReleaseGIL guard; return m_helper->getxattr(fileId, name).get().toStdString(); } void setxattr(std::string fileId, std::string name, std::string value, bool create, bool replace) { ReleaseGIL guard; m_helper->setxattr(fileId, name, value, create, replace).get(); } void removexattr(std::string fileId, std::string name) { ReleaseGIL guard; m_helper->removexattr(fileId, name).get(); } std::vector<std::string> listxattr(std::string fileId) { ReleaseGIL guard; std::vector<std::string> res; for (auto &xattr : m_helper->listxattr(fileId).get()) { res.emplace_back(xattr.toStdString()); } return res; } void refreshParams(std::string mountPoint, int uid, int gid) { std::unordered_map<folly::fbstring, folly::fbstring> params; params["type"] = "posix"; params["mountPoint"] = mountPoint; params["uid"] = std::to_string(uid); params["gid"] = std::to_string(gid); auto p = PosixHelperParams::create(params); m_helper->refreshParams(std::move(p)).get(); } std::string mountpoint() { return m_helper->mountPoint().c_str(); } private: std::shared_ptr<folly::IOExecutor> m_executor; std::shared_ptr<one::helpers::PosixHelper> m_helper; }; namespace { boost::shared_ptr<PosixHelperProxy> create( std::string mountPoint, uid_t uid, gid_t gid) { return boost::make_shared<PosixHelperProxy>( std::move(mountPoint), uid, gid); } } // namespace BOOST_PYTHON_MODULE(posix_helper) { class_<PosixHelperProxy, boost::noncopyable>("PosixHelperProxy", no_init) .def("__init__", make_constructor(create)) .def("open", &PosixHelperProxy::open) .def("read", &PosixHelperProxy::read) .def("write", &PosixHelperProxy::write) .def("getattr", &PosixHelperProxy::getattr) .def("readdir", &PosixHelperProxy::readdir) .def("readlink", &PosixHelperProxy::readlink) .def("mknod", &PosixHelperProxy::mknod) .def("mkdir", &PosixHelperProxy::mkdir) .def("unlink", &PosixHelperProxy::unlink) .def("rmdir", &PosixHelperProxy::rmdir) .def("symlink", &PosixHelperProxy::symlink) .def("rename", &PosixHelperProxy::rename) .def("link", &PosixHelperProxy::link) .def("chmod", &PosixHelperProxy::chmod) .def("chown", &PosixHelperProxy::chown) .def("truncate", &PosixHelperProxy::truncate) .def("getxattr", &PosixHelperProxy::getxattr) .def("setxattr", &PosixHelperProxy::setxattr) .def("removexattr", &PosixHelperProxy::removexattr) .def("listxattr", &PosixHelperProxy::listxattr) .def("refresh_params", &PosixHelperProxy::refreshParams) .def("mountpoint", &PosixHelperProxy::mountpoint); } <commit_msg>VFS-8073 Fixed posix helper test<commit_after>/** * @file posixHelperProxy.cc * @author Bartek Kryza * @copyright (C) 2017 ACK CYFRONET AGH * @copyright This software is released under the MIT license cited in * 'LICENSE.txt' */ #include "posixHelper.h" #include <boost/make_shared.hpp> #include <boost/python.hpp> #include <boost/python/extract.hpp> #include <boost/python/raw_function.hpp> #include <boost/python/suite/indexing/vector_indexing_suite.hpp> #include <folly/executors/IOThreadPoolExecutor.h> #include <chrono> #include <future> #include <string> #include <thread> #include <iostream> using ReadDirResult = std::vector<std::string>; using namespace boost::python; using namespace one::helpers; /* * Minimum 4 threads are required to run this helper proxy. */ constexpr int POSIX_HELPER_WORKER_THREADS = 1; class ReleaseGIL { public: ReleaseGIL() : threadState{PyEval_SaveThread(), PyEval_RestoreThread} { } private: std::unique_ptr<PyThreadState, decltype(&PyEval_RestoreThread)> threadState; }; class PosixHelperProxy { public: PosixHelperProxy(std::string mountPoint, uid_t uid, gid_t gid) : m_executor{std::make_shared<folly::IOThreadPoolExecutor>( POSIX_HELPER_WORKER_THREADS, std::make_shared<StorageWorkerFactory>("posix_t"))} { std::unordered_map<folly::fbstring, folly::fbstring> params; params["type"] = "posix"; params["mountPoint"] = mountPoint; params["uid"] = std::to_string(uid); params["gid"] = std::to_string(gid); m_helper = std::make_shared<one::helpers::PosixHelper>( PosixHelperParams::create(params), m_executor, ExecutionContext::ONECLIENT); } ~PosixHelperProxy() { m_executor->join(); } void open(std::string fileId, int flags) { ReleaseGIL guard; m_helper->open(fileId, flags, {}) .thenValue([&](one::helpers::FileHandlePtr &&handle) { handle->release(); }); } std::string read(std::string fileId, int offset, int size) { ReleaseGIL guard; return m_helper->open(fileId, O_RDONLY, {}) .thenValue([&](one::helpers::FileHandlePtr &&handle) { return handle->read(offset, size) .thenValue([handle](folly::IOBufQueue &&buf) { std::string data; buf.appendToString(data); return data; }); }) .get(); } int write(std::string fileId, std::string data, int offset) { ReleaseGIL guard; // PosixHelper does not support creating file with approriate mode, // so in case it doesn't exist we have to create it first to be // compatible with other helpers' test cases. auto mknodLambda = [&](auto && /*unit*/) { return m_helper->mknod(fileId, S_IFREG | 0666, {}, 0); }; auto writeLambda = [&](auto && /*unit*/) { return m_helper->open(fileId, O_WRONLY, {}) .thenValue([&](one::helpers::FileHandlePtr &&handle) { folly::IOBufQueue buf{ folly::IOBufQueue::cacheChainLength()}; buf.append(data); return handle->write(offset, std::move(buf), {}) .thenValue([handle](auto &&size) { return size; }); }); }; return m_helper->access(fileId, 0) .thenValue(writeLambda) .thenError(folly::tag_t<std::exception>{}, [mknodLambda = std::move(mknodLambda), writeLambda = std::move(writeLambda), executor = m_executor](auto &&e) { return folly::makeFuture() .via(executor.get()) .thenValue(mknodLambda) .thenValue(writeLambda); }) .get(); } struct stat getattr(std::string fileId) { ReleaseGIL guard; return m_helper->getattr(fileId).get(); } void access(std::string fileId, int mask) { ReleaseGIL guard; m_helper->access(fileId, mask).get(); } ReadDirResult readdir(std::string fileId, int offset, int count) { ReleaseGIL guard; std::vector<std::string> res; for (auto &direntry : m_helper->readdir(fileId, offset, count).get()) { res.emplace_back(direntry.toStdString()); } return res; } std::string readlink(std::string fileId) { ReleaseGIL guard; return m_helper->readlink(fileId).get().toStdString(); } void mknod(std::string fileId, mode_t mode, std::vector<Flag> flags) { ReleaseGIL guard; m_helper->mknod(fileId, mode, FlagsSet(flags.begin(), flags.end()), 0) .get(); } void mkdir(std::string fileId, mode_t mode) { ReleaseGIL guard; m_helper->mkdir(fileId, mode).get(); } void unlink(std::string fileId, int size) { ReleaseGIL guard; m_helper->unlink(fileId, size).get(); } void rmdir(std::string fileId) { ReleaseGIL guard; m_helper->rmdir(fileId).get(); } void symlink(std::string from, std::string to) { ReleaseGIL guard; m_helper->symlink(from, to).get(); } void rename(std::string from, std::string to) { ReleaseGIL guard; m_helper->rename(from, to).get(); } void link(std::string from, std::string to) { ReleaseGIL guard; m_helper->link(from, to).get(); } void chmod(std::string fileId, mode_t mode) { ReleaseGIL guard; m_helper->chmod(fileId, mode).get(); } void chown(std::string fileId, uid_t uid, gid_t gid) { ReleaseGIL guard; m_helper->chown(fileId, uid, gid).get(); } void truncate(std::string fileId, int offset, int size) { ReleaseGIL guard; m_helper->truncate(fileId, offset, size).get(); } std::string getxattr(std::string fileId, std::string name) { ReleaseGIL guard; return m_helper->getxattr(fileId, name).get().toStdString(); } void setxattr(std::string fileId, std::string name, std::string value, bool create, bool replace) { ReleaseGIL guard; m_helper->setxattr(fileId, name, value, create, replace).get(); } void removexattr(std::string fileId, std::string name) { ReleaseGIL guard; m_helper->removexattr(fileId, name).get(); } std::vector<std::string> listxattr(std::string fileId) { ReleaseGIL guard; std::vector<std::string> res; for (auto &xattr : m_helper->listxattr(fileId).get()) { res.emplace_back(xattr.toStdString()); } return res; } void refreshParams(std::string mountPoint, int uid, int gid) { std::unordered_map<folly::fbstring, folly::fbstring> params; params["type"] = "posix"; params["mountPoint"] = mountPoint; params["uid"] = std::to_string(uid); params["gid"] = std::to_string(gid); auto p = PosixHelperParams::create(params); m_helper->refreshParams(std::move(p)).get(); } std::string mountpoint() { return m_helper->mountPoint().c_str(); } private: std::shared_ptr<folly::IOThreadPoolExecutor> m_executor; std::shared_ptr<one::helpers::PosixHelper> m_helper; }; namespace { boost::shared_ptr<PosixHelperProxy> create( std::string mountPoint, uid_t uid, gid_t gid) { return boost::make_shared<PosixHelperProxy>( std::move(mountPoint), uid, gid); } } // namespace BOOST_PYTHON_MODULE(posix_helper) { class_<PosixHelperProxy, boost::noncopyable>("PosixHelperProxy", no_init) .def("__init__", make_constructor(create)) .def("open", &PosixHelperProxy::open) .def("read", &PosixHelperProxy::read) .def("write", &PosixHelperProxy::write) .def("getattr", &PosixHelperProxy::getattr) .def("readdir", &PosixHelperProxy::readdir) .def("readlink", &PosixHelperProxy::readlink) .def("mknod", &PosixHelperProxy::mknod) .def("mkdir", &PosixHelperProxy::mkdir) .def("unlink", &PosixHelperProxy::unlink) .def("rmdir", &PosixHelperProxy::rmdir) .def("symlink", &PosixHelperProxy::symlink) .def("rename", &PosixHelperProxy::rename) .def("link", &PosixHelperProxy::link) .def("chmod", &PosixHelperProxy::chmod) .def("chown", &PosixHelperProxy::chown) .def("truncate", &PosixHelperProxy::truncate) .def("getxattr", &PosixHelperProxy::getxattr) .def("setxattr", &PosixHelperProxy::setxattr) .def("removexattr", &PosixHelperProxy::removexattr) .def("listxattr", &PosixHelperProxy::listxattr) .def("refresh_params", &PosixHelperProxy::refreshParams) .def("mountpoint", &PosixHelperProxy::mountpoint); } <|endoftext|>
<commit_before><commit_msg>Make it so that clicking the "Get Themes" link in the options dialog box activates the browser window that the themes gallery is opened in.<commit_after><|endoftext|>
<commit_before> #include <QFile> #include <QTextStream> #include <QDebug> #include "qltgplogger.h" QltGpLogger::QltGpLogger(Mode mode): mode_(mode), lenColumn_(0) { } bool QltGpLogger::addColumn(QStringList column, QString label) { if (column.size() == 0) { errorString_ = "Error! #1"; return false; } if (lenColumn_ == 0) { container_.append(column); lenColumn_ = column.size(); labels_.append(label); return true; } else { if (column.size() != lenColumn_) { errorString_ = "Error! #2"; return false; } container_.append(column); labels_.append(label); } return true; } bool QltGpLogger::addPolygon(QStringList lat, QStringList lon, QString label) { if (lat.size() != lon.size()) { errorString_ = "Error! #5"; return false; } polygonsLat_.append(lat); polygonsLon_.append(lon); polygonsLabels_.append(label); return true; } bool QltGpLogger::addTrack(QStringList lat, QStringList lon, QString label) { if (lat.size() != lon.size()) { errorString_ = "Error! #5"; return false; } tracksLat_.append(lat); tracksLon_.append(lon); tracksLabels_.append(label); return true; } bool QltGpLogger::toFile(QString fileName, bool genIndex) { fileName_ = fileName; QFile fileData(fileName + ".txt"); if (!fileData.open(QIODevice::WriteOnly | QIODevice::Text)) { errorString_ = "Error! #3"; return false; } QFile fileCmd(fileName + ".gpl"); if (!fileCmd.open(QIODevice::WriteOnly | QIODevice::Text)) { errorString_ = "Error! #4"; return false; } switch(mode_) { case GeneralMode : writeGenData(fileData, genIndex); writeGenCmd(fileCmd, genIndex); break; case GisMode : writeGisData(fileData); writeGisCmd(fileCmd); break; default : break; } return true; } void QltGpLogger::writeGenData(QFile &file, bool genIndex) { QTextStream out(&file); for (int index = 0; index < lenColumn_; ++index) { if (genIndex) out << index <<"\t"; for (int i = 0; i < container_.size(); ++i) out <<container_.at(i).at(index) <<"\t"; out << "\n"; } } void QltGpLogger::writeGenCmd (QFile &file, bool genIndex) { QTextStream commands(&file); commands << "datafile = \"" << fileName_ << ".txt\" \n" << "titlename = \"" << titleName_ << "\"\n" << "xlabelname = \"" << xLabelName_ << "\"\n" << "ylabelname = \"" << yLabelName_ << "\"\n" << "set grid; \n" << "plot "; if (genIndex) for (int i=0; i < container_.size(); ++i) { commands << " datafile u 1:" << QString::number(i+2) <<" w lines title \""; commands << labels_.at(i) << "\", "; } else for (int i=1; i < container_.size(); ++i) { commands << " datafile u 1:" << QString::number(i+1) <<" w lines title \""; commands << labels_.at(i) << "\", "; } commands << "\nset title titlename;\n" << "set xlabel xlabelname;\n" << "set ylabel ylabelname;\n" << "pause -1;\n"; } void QltGpLogger::writeGisData(QFile &file) { QTextStream out(&file); for (int index = 0; index < polygonsLat_.size(); ++index) { QStringList latitude = polygonsLat_.at(index); QStringList longitude = polygonsLon_.at(index); for (int i = 0; i < latitude.size(); ++i) out << longitude.at(i) << "\t" << latitude.at(i) << "\n"; // Замыкание полигона. if (latitude.size() > 0) out << longitude.at(0).at(index) << "\t" << latitude.at(0).at(index) << "\n"; out << "\n"; out << "\n"; } for (int index = 0; index < tracksLat_.size(); ++index) { QStringList latitude = tracksLat_.at(index); QStringList longitude = tracksLon_.at(index); for (int i = 0; i < latitude.size(); ++i) out << longitude.at(i) << "\t" << latitude.at(i) << "\n"; out << "\n"; out << "\n"; } } void QltGpLogger::writeGisCmd(QFile &file) { QTextStream commands(&file); commands << "datafile = \"" << fileName_ << ".txt\" \n" << "titlename = \"" << titleName_ << "\"\n" << "xlabelname = \"" << xLabelName_ << "\"\n" << "ylabelname = \"" << yLabelName_ << "\"\n" << "set grid; \n" << "plot "; for (int i=0; i < polygonsLat_.size(); ++i) { commands << " datafile index " << i << " u 1:2 w lines title \""; commands << polygonsLabels_.at(i) << "\", "; } for (int i=0; i < tracksLat_.size(); ++i) { commands << " datafile index " << polygonsLat_.size() + i << " u 1:2 w lines title \""; commands << tracksLabels_.at(i) << "\", "; } commands << "\nset title titlename;\n" << "set xlabel xlabelname;\n" << "set ylabel ylabelname;\n" << "pause -1;\n"; } void QltGpLogger::setTitleName(QString name) { titleName_ = name; } void QltGpLogger::setXLabelName(QString name) { xLabelName_ = name; } void QltGpLogger::setYLabelName(QString name) { yLabelName_ = name; } <commit_msg>minor fix<commit_after> #include <QFile> #include <QTextStream> #include <QDebug> #include "qltgplogger.h" QltGpLogger::QltGpLogger(Mode mode): mode_(mode), lenColumn_(0) { } bool QltGpLogger::addColumn(QStringList column, QString label) { if (column.size() == 0) { errorString_ = "Error! #1"; return false; } if (lenColumn_ == 0) { container_.append(column); lenColumn_ = column.size(); labels_.append(label); return true; } else { if (column.size() != lenColumn_) { errorString_ = "Error! #2"; return false; } container_.append(column); labels_.append(label); } return true; } bool QltGpLogger::addPolygon(QStringList lat, QStringList lon, QString label) { if (lat.size() != lon.size()) { errorString_ = "Error! #5"; return false; } polygonsLat_.append(lat); polygonsLon_.append(lon); polygonsLabels_.append(label); return true; } bool QltGpLogger::addTrack(QStringList lat, QStringList lon, QString label) { if (lat.size() != lon.size()) { errorString_ = "Error! #5"; return false; } tracksLat_.append(lat); tracksLon_.append(lon); tracksLabels_.append(label); return true; } bool QltGpLogger::toFile(QString fileName, bool genIndex) { fileName_ = fileName; QFile fileData(fileName + ".txt"); if (!fileData.open(QIODevice::WriteOnly | QIODevice::Text)) { errorString_ = "Error! #3"; return false; } QFile fileCmd(fileName + ".gpl"); if (!fileCmd.open(QIODevice::WriteOnly | QIODevice::Text)) { errorString_ = "Error! #4"; return false; } switch(mode_) { case GeneralMode : writeGenData(fileData, genIndex); writeGenCmd(fileCmd, genIndex); break; case GisMode : writeGisData(fileData); writeGisCmd(fileCmd); break; default : break; } return true; } void QltGpLogger::writeGenData(QFile &file, bool genIndex) { QTextStream out(&file); for (int index = 0; index < lenColumn_; ++index) { if (genIndex) out << index <<"\t"; for (int i = 0; i < container_.size(); ++i) out <<container_.at(i).at(index) <<"\t"; out << "\n"; } } void QltGpLogger::writeGenCmd (QFile &file, bool genIndex) { QTextStream commands(&file); commands << "datafile = \"" << fileName_ << ".txt\" \n" << "titlename = \"" << titleName_ << "\"\n" << "xlabelname = \"" << xLabelName_ << "\"\n" << "ylabelname = \"" << yLabelName_ << "\"\n" << "set grid; \n" << "plot "; if (genIndex) for (int i=0; i < container_.size(); ++i) { commands << " datafile u 1:" << QString::number(i+2) <<" w lines title \""; commands << labels_.at(i) << "\", "; } else for (int i=1; i < container_.size(); ++i) { commands << " datafile u 1:" << QString::number(i+1) <<" w lines title \""; commands << labels_.at(i) << "\", "; } commands << "\nset title titlename;\n" << "set xlabel xlabelname;\n" << "set ylabel ylabelname;\n" << "pause -1;\n"; } void QltGpLogger::writeGisData(QFile &file) { QTextStream out(&file); for (int index = 0; index < polygonsLat_.size(); ++index) { QStringList latitude = polygonsLat_.at(index); QStringList longitude = polygonsLon_.at(index); for (int i = 0; i < latitude.size(); ++i) out << longitude.at(i) << "\t" << latitude.at(i) << "\n"; // Замыкание полигона. if (latitude.size() > 0) out << longitude.at(0) << "\t" << latitude.at(0) << "\n"; out << "\n"; out << "\n"; } for (int index = 0; index < tracksLat_.size(); ++index) { QStringList latitude = tracksLat_.at(index); QStringList longitude = tracksLon_.at(index); for (int i = 0; i < latitude.size(); ++i) out << longitude.at(i) << "\t" << latitude.at(i) << "\n"; out << "\n"; out << "\n"; } } void QltGpLogger::writeGisCmd(QFile &file) { QTextStream commands(&file); commands << "datafile = \"" << fileName_ << ".txt\" \n" << "titlename = \"" << titleName_ << "\"\n" << "xlabelname = \"" << xLabelName_ << "\"\n" << "ylabelname = \"" << yLabelName_ << "\"\n" << "set grid; \n" << "plot "; for (int i=0; i < polygonsLat_.size(); ++i) { commands << " datafile index " << i << " u 1:2 w lines title \""; commands << polygonsLabels_.at(i) << "\", "; } for (int i=0; i < tracksLat_.size(); ++i) { commands << " datafile index " << polygonsLat_.size() + i << " u 1:2 w lines title \""; commands << tracksLabels_.at(i) << "\", "; } commands << "\nset title titlename;\n" << "set xlabel xlabelname;\n" << "set ylabel ylabelname;\n" << "pause -1;\n"; } void QltGpLogger::setTitleName(QString name) { titleName_ = name; } void QltGpLogger::setXLabelName(QString name) { xLabelName_ = name; } void QltGpLogger::setYLabelName(QString name) { yLabelName_ = name; } <|endoftext|>
<commit_before><commit_msg>Use current dir as working directory if %TEMP% directory doesnt work.<commit_after><|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/service/net/service_url_request_context.h" #include "chrome/service/service_process.h" #include "net/base/cookie_monster.h" #include "net/base/cookie_policy.h" #include "net/base/host_resolver.h" #include "net/base/ssl_config_service_defaults.h" #include "net/ftp/ftp_network_layer.h" #include "net/http/http_auth_handler_factory.h" #include "net/http/http_cache.h" #include "net/http/http_network_layer.h" #include "net/proxy/proxy_service.h" ServiceURLRequestContextGetter::ServiceURLRequestContextGetter() : io_message_loop_proxy_( g_service_process->io_thread()->message_loop_proxy()) { } ServiceURLRequestContext::ServiceURLRequestContext() { host_resolver_ = net::CreateSystemHostResolver(NULL); DCHECK(g_service_process); // TODO(sanjeevr): Change CreateSystemProxyConfigService to accept a // MessageLoopProxy* instead of MessageLoop*. // Also this needs to be created on the UI thread on Linux. Fix this. net::ProxyConfigService * proxy_config_service = net::ProxyService::CreateSystemProxyConfigService( g_service_process->io_thread()->message_loop(), g_service_process->file_thread()->message_loop()); proxy_service_ = net::ProxyService::Create(proxy_config_service, false, this, NULL, NULL, NULL); ftp_transaction_factory_ = new net::FtpNetworkLayer(host_resolver_); ssl_config_service_ = new net::SSLConfigServiceDefaults; http_auth_handler_factory_ = net::HttpAuthHandlerFactory::CreateDefault(); http_transaction_factory_ = new net::HttpCache( net::HttpNetworkLayer::CreateFactory(NULL, host_resolver_, proxy_service_, ssl_config_service_, http_auth_handler_factory_), disk_cache::CreateInMemoryCacheBackend(0)); // In-memory cookie store. cookie_store_ = new net::CookieMonster(NULL, NULL); accept_language_ = "en-us,fr"; accept_charset_ = "iso-8859-1,*,utf-8"; } ServiceURLRequestContext::~ServiceURLRequestContext() { delete ftp_transaction_factory_; delete http_transaction_factory_; delete http_auth_handler_factory_; } <commit_msg>Fixed build break caused by using the new BackendFactory method of constructing an in-memory cache. BUG=None TEST=Buildbots should pass.<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/service/net/service_url_request_context.h" #include "chrome/service/service_process.h" #include "net/base/cookie_monster.h" #include "net/base/cookie_policy.h" #include "net/base/host_resolver.h" #include "net/base/ssl_config_service_defaults.h" #include "net/ftp/ftp_network_layer.h" #include "net/http/http_auth_handler_factory.h" #include "net/http/http_cache.h" #include "net/http/http_network_layer.h" #include "net/proxy/proxy_service.h" ServiceURLRequestContextGetter::ServiceURLRequestContextGetter() : io_message_loop_proxy_( g_service_process->io_thread()->message_loop_proxy()) { } ServiceURLRequestContext::ServiceURLRequestContext() { host_resolver_ = net::CreateSystemHostResolver(NULL); DCHECK(g_service_process); // TODO(sanjeevr): Change CreateSystemProxyConfigService to accept a // MessageLoopProxy* instead of MessageLoop*. // Also this needs to be created on the UI thread on Linux. Fix this. net::ProxyConfigService * proxy_config_service = net::ProxyService::CreateSystemProxyConfigService( g_service_process->io_thread()->message_loop(), g_service_process->file_thread()->message_loop()); proxy_service_ = net::ProxyService::Create(proxy_config_service, false, this, NULL, NULL, NULL); ftp_transaction_factory_ = new net::FtpNetworkLayer(host_resolver_); ssl_config_service_ = new net::SSLConfigServiceDefaults; http_auth_handler_factory_ = net::HttpAuthHandlerFactory::CreateDefault(); http_transaction_factory_ = new net::HttpCache( net::HttpNetworkLayer::CreateFactory(NULL, host_resolver_, proxy_service_, ssl_config_service_, http_auth_handler_factory_), net::HttpCache::DefaultBackend::InMemory(0)); // In-memory cookie store. cookie_store_ = new net::CookieMonster(NULL, NULL); accept_language_ = "en-us,fr"; accept_charset_ = "iso-8859-1,*,utf-8"; } ServiceURLRequestContext::~ServiceURLRequestContext() { delete ftp_transaction_factory_; delete http_transaction_factory_; delete http_auth_handler_factory_; } <|endoftext|>
<commit_before>/* Copyright 2017 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. ==============================================================================*/ // XLA-specific Concat Ops. #include <limits> #include <vector> #include "tensorflow/compiler/tf2xla/type_util.h" #include "tensorflow/compiler/tf2xla/xla_helpers.h" #include "tensorflow/compiler/tf2xla/xla_op_kernel.h" #include "tensorflow/compiler/tf2xla/xla_op_registry.h" #include "tensorflow/compiler/xla/client/xla_builder.h" #include "tensorflow/compiler/xla/literal_util.h" #include "tensorflow/core/framework/op_kernel.h" #include "tensorflow/core/framework/register_types.h" #include "tensorflow/core/framework/tensor.h" #include "tensorflow/core/framework/tensor_types.h" #include "tensorflow/core/framework/types.h" #include "tensorflow/core/kernels/bounds_check.h" #include "tensorflow/core/kernels/concat_lib.h" #include "tensorflow/core/lib/core/status.h" #include "tensorflow/core/platform/types.h" namespace tensorflow { namespace { // Used to determine the number of Tensors allowed in a Concat op to prevent // going over the max gpu parameter memory size. This is an issue because concat // is variadic and can have an unlimited number of arguments when called. // Concat ops with more Tensors than this will be split into multiple concat // ops. // // TODO(b/112613927): Remove the logic here and put it properly in an HLO pass // along with boxing large numbers of parameters. constexpr int64 kMaxConcatArgsPerOp = 500; // -------------------------------------------------------------------------- class ConcatBaseOp : public XlaOpKernel { public: ConcatBaseOp(OpKernelConstruction* c, int axis_index) : XlaOpKernel(c), axis_index_(axis_index) {} void Compile(XlaOpKernelContext* ctx) override { const TensorShape concat_dim_tensor_shape = ctx->InputShape(axis_index_); OP_REQUIRES( ctx, IsLegacyScalar(concat_dim_tensor_shape), errors::InvalidArgument( "Concat dim tensor should be a scalar integer, but got shape ", concat_dim_tensor_shape.DebugString())); xla::Literal literal; OP_REQUIRES_OK(ctx, ctx->ConstantInput(axis_index_, &literal)); // TODO(annarev): add a helper to support int64 input. const int32 concat_dim = literal.Get<int>({}); std::vector<xla::XlaOp> values; std::vector<TensorShape> shapes; OP_REQUIRES_OK(ctx, ctx->InputList("values", &values, &shapes)); const int N = values.size(); const int input_dims = shapes[0].dims(); const TensorShape& input_shape = shapes[0]; int32 axis = concat_dim < 0 ? concat_dim + input_dims : concat_dim; OP_REQUIRES(ctx, (0 <= axis && axis < input_dims) || (allow_legacy_scalars() && concat_dim == 0), errors::InvalidArgument( "ConcatOp : Expected concatenating dimensions in the range " "[", -input_dims, ", ", input_dims, "), but got ", concat_dim)); // Make a vector holding the XlaOp for each of the inputs that has non-zero // elements. std::vector<xla::XlaOp> input_data; std::vector<xla::XlaOp> partial_concats; int output_concat_dim = 0; const bool input_is_scalar = IsLegacyScalar(input_shape); for (int i = 0; i < N; ++i) { xla::XlaOp handle = values[i]; const TensorShape& in_shape = shapes[i]; const bool in_is_scalar = IsLegacyScalar(in_shape); OP_REQUIRES( ctx, in_shape.dims() == input_dims || (input_is_scalar && in_is_scalar), errors::InvalidArgument( "ConcatOp : Ranks of all input tensors should match: shape[0] = ", input_shape.DebugString(), " vs. shape[", i, "] = ", in_shape.DebugString())); if (in_shape.dims() == 0) { // Inputs that come in as scalars must be reshaped to 1-vectors. input_data.push_back(xla::Reshape(handle, {1})); } else { input_data.push_back(handle); } output_concat_dim += in_shape.dims() > 0 ? in_shape.dim_size(axis) : 1; // Concat is associative, so it can be split into many operations when too // many arguments are in a single op. This is a temporary workaround for // b/112613927 where too many parameters in an XlaLaunchOp later result in // too many parameters to a single GPU kernel. if (i && i % kMaxConcatArgsPerOp == 0) { partial_concats.push_back( xla::ConcatInDim(ctx->builder(), input_data, axis)); input_data.clear(); } } // Add any inputs that have not been put into another concat yet. partial_concats.insert(partial_concats.end(), input_data.begin(), input_data.end()); VLOG(1) << "Concat dim " << concat_dim << " equivalent to " << axis; // Don't add an additional "identity" concatenate for better readibility of // IR. if (partial_concats.size() == 1) { ctx->SetOutput(0, partial_concats.front()); } else { ctx->SetOutput(0, xla::ConcatInDim(ctx->builder(), partial_concats, axis)); } } private: int axis_index_; }; class ConcatOp : public ConcatBaseOp { public: explicit ConcatOp(OpKernelConstruction* c) : ConcatBaseOp(c, /* axis_index */ 0) {} }; // ConcatV2 operation is the same as Concat except 'concat_dim' // is the last input instead of the first and renamed to 'axis'. class ConcatV2Op : public ConcatBaseOp { public: explicit ConcatV2Op(OpKernelConstruction* c) : ConcatBaseOp(c, /* axis_index */ c->num_inputs() - 1) {} }; REGISTER_XLA_OP(Name("Concat").CompileTimeConstantInput("concat_dim"), ConcatOp); REGISTER_XLA_OP(Name("ConcatV2") .TypeConstraint("Tidx", DT_INT32) .CompileTimeConstantInput("axis"), ConcatV2Op); class ConcatOffsetOp : public XlaOpKernel { public: explicit ConcatOffsetOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {} void Compile(XlaOpKernelContext* ctx) override { const TensorShape concat_dim_shape = ctx->InputShape(0); OP_REQUIRES( ctx, IsLegacyScalar(concat_dim_shape), errors::InvalidArgument( "Concat dim tensor should be a scalar integer, but got shape ", concat_dim_shape.DebugString())); for (int i = 1; i < ctx->num_inputs(); ++i) { OP_REQUIRES(ctx, TensorShapeUtils::IsVector(ctx->InputShape(i)), errors::InvalidArgument("input ", i, " should be a vector, but got shape ", ctx->InputShape(i).DebugString())); } // Suppose a Concat() op needs to Concatenate N tensors, each of // which has the same number of dimensions. Their shapes match // except the concat dimension. // // E.g., say, we want to concatenate 3 tensors in the 2nd // dimension, and their shapes are: // // [2, 2, 5, 7] // [2, 3, 5, 7] // [2, 4, 5, 7] // // Here, N=3, cdim=1, dims=4. The concatenated tensor has shape // [2,9,5,7]. We will compute the cumulative sum along the 2nd // dimension to figure out each input's offset in the concatenated // output: // [0, 0, 0, 0] // [0, 2, 0, 0] // [0, 5, 0, 0] const int32 N = ctx->num_inputs() - 1; const TensorShape inp0_shape = ctx->InputShape(1); xla::Literal inp0_literal; OP_REQUIRES_OK(ctx, ctx->ConstantInput(1, &inp0_literal)); const int64 dims = inp0_shape.num_elements(); xla::Literal concat_dim_literal; OP_REQUIRES_OK(ctx, ctx->ConstantInput(0, &concat_dim_literal)); const int64 cdim = concat_dim_literal.Get<int>({}); VLOG(1) << "ConcatOffset " << cdim << "," << dims; int32 axis = cdim < 0 ? cdim + dims : cdim; OP_REQUIRES(ctx, FastBoundsCheck(axis, dims), errors::InvalidArgument("Concat dim is out of range: ", axis, " vs. ", dims)); int32 offset = 0; for (int i = 0; i < N; ++i) { const TensorShape inp_shape = ctx->InputShape(1 + i); OP_REQUIRES(ctx, dims == inp_shape.num_elements(), errors::InvalidArgument("input ", i, " should contain ", dims, " elements, but got ", inp_shape.num_elements())); xla::Literal inp_literal; OP_REQUIRES_OK(ctx, ctx->ConstantInput(1 + i, &inp_literal)); Tensor out_constant(DT_INT32, TensorShape({dims})); auto out_vec = out_constant.vec<int32>(); for (int64 j = 0; j < dims; ++j) { if (j == axis) { out_vec(j) = offset; offset += inp_literal.Get<int>({j}); } else { const int32 inp0_element = inp0_literal.Get<int>({j}); const int32 inp_element = inp_literal.Get<int>({j}); OP_REQUIRES(ctx, (inp0_element == inp_element), errors::InvalidArgument("input[", i, ",", j, "] mismatch: ", inp0_element, " vs. ", inp_element)); out_vec(j) = 0; } } ctx->SetConstantOutput(i, out_constant); } } }; REGISTER_XLA_OP(Name("ConcatOffset") .CompileTimeConstantInput("concat_dim") .CompileTimeConstantInput("shape"), ConcatOffsetOp); } // namespace } // namespace tensorflow <commit_msg>Automated rollback of commit 54cbee5d034af8693aa39cc5877c3dfcd62d3740<commit_after>/* Copyright 2017 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. ==============================================================================*/ // XLA-specific Concat Ops. #include <limits> #include <vector> #include "tensorflow/compiler/tf2xla/type_util.h" #include "tensorflow/compiler/tf2xla/xla_helpers.h" #include "tensorflow/compiler/tf2xla/xla_op_kernel.h" #include "tensorflow/compiler/tf2xla/xla_op_registry.h" #include "tensorflow/compiler/xla/client/xla_builder.h" #include "tensorflow/compiler/xla/literal_util.h" #include "tensorflow/core/framework/op_kernel.h" #include "tensorflow/core/framework/register_types.h" #include "tensorflow/core/framework/tensor.h" #include "tensorflow/core/framework/tensor_types.h" #include "tensorflow/core/framework/types.h" #include "tensorflow/core/kernels/bounds_check.h" #include "tensorflow/core/kernels/concat_lib.h" #include "tensorflow/core/lib/core/status.h" #include "tensorflow/core/platform/types.h" namespace tensorflow { namespace { // -------------------------------------------------------------------------- class ConcatBaseOp : public XlaOpKernel { public: ConcatBaseOp(OpKernelConstruction* c, int axis_index) : XlaOpKernel(c), axis_index_(axis_index) {} void Compile(XlaOpKernelContext* ctx) override { const TensorShape concat_dim_tensor_shape = ctx->InputShape(axis_index_); OP_REQUIRES( ctx, IsLegacyScalar(concat_dim_tensor_shape), errors::InvalidArgument( "Concat dim tensor should be a scalar integer, but got shape ", concat_dim_tensor_shape.DebugString())); xla::Literal literal; OP_REQUIRES_OK(ctx, ctx->ConstantInput(axis_index_, &literal)); // TODO(annarev): add a helper to support int64 input. const int32 concat_dim = literal.Get<int>({}); std::vector<xla::XlaOp> values; std::vector<TensorShape> shapes; OP_REQUIRES_OK(ctx, ctx->InputList("values", &values, &shapes)); const int N = values.size(); const int input_dims = shapes[0].dims(); const TensorShape& input_shape = shapes[0]; int32 axis = concat_dim < 0 ? concat_dim + input_dims : concat_dim; OP_REQUIRES(ctx, (0 <= axis && axis < input_dims) || (allow_legacy_scalars() && concat_dim == 0), errors::InvalidArgument( "ConcatOp : Expected concatenating dimensions in the range " "[", -input_dims, ", ", input_dims, "), but got ", concat_dim)); // Make a vector holding the XlaOp for each of the inputs that has non-zero // elements. std::vector<xla::XlaOp> input_data; int output_concat_dim = 0; const bool input_is_scalar = IsLegacyScalar(input_shape); for (int i = 0; i < N; ++i) { xla::XlaOp handle = values[i]; const TensorShape& in_shape = shapes[i]; const bool in_is_scalar = IsLegacyScalar(in_shape); OP_REQUIRES( ctx, in_shape.dims() == input_dims || (input_is_scalar && in_is_scalar), errors::InvalidArgument( "ConcatOp : Ranks of all input tensors should match: shape[0] = ", input_shape.DebugString(), " vs. shape[", i, "] = ", in_shape.DebugString())); if (in_shape.dims() == 0) { // Inputs that come in as scalars must be reshaped to 1-vectors. input_data.push_back(xla::Reshape(handle, {1})); } else { input_data.push_back(handle); } output_concat_dim += in_shape.dims() > 0 ? in_shape.dim_size(axis) : 1; } VLOG(1) << "Concat dim " << concat_dim << " equivalent to " << axis; ctx->SetOutput(0, xla::ConcatInDim(ctx->builder(), input_data, axis)); } private: int axis_index_; }; class ConcatOp : public ConcatBaseOp { public: explicit ConcatOp(OpKernelConstruction* c) : ConcatBaseOp(c, /* axis_index */ 0) {} }; // ConcatV2 operation is the same as Concat except 'concat_dim' // is the last input instead of the first and renamed to 'axis'. class ConcatV2Op : public ConcatBaseOp { public: explicit ConcatV2Op(OpKernelConstruction* c) : ConcatBaseOp(c, /* axis_index */ c->num_inputs() - 1) {} }; REGISTER_XLA_OP(Name("Concat").CompileTimeConstantInput("concat_dim"), ConcatOp); REGISTER_XLA_OP(Name("ConcatV2") .TypeConstraint("Tidx", DT_INT32) .CompileTimeConstantInput("axis"), ConcatV2Op); class ConcatOffsetOp : public XlaOpKernel { public: explicit ConcatOffsetOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {} void Compile(XlaOpKernelContext* ctx) override { const TensorShape concat_dim_shape = ctx->InputShape(0); OP_REQUIRES( ctx, IsLegacyScalar(concat_dim_shape), errors::InvalidArgument( "Concat dim tensor should be a scalar integer, but got shape ", concat_dim_shape.DebugString())); for (int i = 1; i < ctx->num_inputs(); ++i) { OP_REQUIRES(ctx, TensorShapeUtils::IsVector(ctx->InputShape(i)), errors::InvalidArgument("input ", i, " should be a vector, but got shape ", ctx->InputShape(i).DebugString())); } // Suppose a Concat() op needs to Concatenate N tensors, each of // which has the same number of dimensions. Their shapes match // except the concat dimension. // // E.g., say, we want to concatenate 3 tensors in the 2nd // dimension, and their shapes are: // // [2, 2, 5, 7] // [2, 3, 5, 7] // [2, 4, 5, 7] // // Here, N=3, cdim=1, dims=4. The concatenated tensor has shape // [2,9,5,7]. We will compute the cumulative sum along the 2nd // dimension to figure out each input's offset in the concatenated // output: // [0, 0, 0, 0] // [0, 2, 0, 0] // [0, 5, 0, 0] const int32 N = ctx->num_inputs() - 1; const TensorShape inp0_shape = ctx->InputShape(1); xla::Literal inp0_literal; OP_REQUIRES_OK(ctx, ctx->ConstantInput(1, &inp0_literal)); const int64 dims = inp0_shape.num_elements(); xla::Literal concat_dim_literal; OP_REQUIRES_OK(ctx, ctx->ConstantInput(0, &concat_dim_literal)); const int64 cdim = concat_dim_literal.Get<int>({}); VLOG(1) << "ConcatOffset " << cdim << "," << dims; int32 axis = cdim < 0 ? cdim + dims : cdim; OP_REQUIRES(ctx, FastBoundsCheck(axis, dims), errors::InvalidArgument("Concat dim is out of range: ", axis, " vs. ", dims)); int32 offset = 0; for (int i = 0; i < N; ++i) { const TensorShape inp_shape = ctx->InputShape(1 + i); OP_REQUIRES(ctx, dims == inp_shape.num_elements(), errors::InvalidArgument("input ", i, " should contain ", dims, " elements, but got ", inp_shape.num_elements())); xla::Literal inp_literal; OP_REQUIRES_OK(ctx, ctx->ConstantInput(1 + i, &inp_literal)); Tensor out_constant(DT_INT32, TensorShape({dims})); auto out_vec = out_constant.vec<int32>(); for (int64 j = 0; j < dims; ++j) { if (j == axis) { out_vec(j) = offset; offset += inp_literal.Get<int>({j}); } else { const int32 inp0_element = inp0_literal.Get<int>({j}); const int32 inp_element = inp_literal.Get<int>({j}); OP_REQUIRES(ctx, (inp0_element == inp_element), errors::InvalidArgument("input[", i, ",", j, "] mismatch: ", inp0_element, " vs. ", inp_element)); out_vec(j) = 0; } } ctx->SetConstantOutput(i, out_constant); } } }; REGISTER_XLA_OP(Name("ConcatOffset") .CompileTimeConstantInput("concat_dim") .CompileTimeConstantInput("shape"), ConcatOffsetOp); } // namespace } // namespace tensorflow <|endoftext|>
<commit_before>/* * SeeedRFID.cpp * A library for RFID moudle. * * Copyright (c) 2008-2014 seeed technology inc. * Author : Ye Xiaobo(yexiaobo@seeedstudio.com) * Create Time: 2014/2/20 * * The MIT License (MIT) * * 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. */ /************************************************************************** * Pins * ==== * * 1. VCC support 3.3 ~ 5V * 2. TX, RX connect to Arduino or Seeeduino * 3. T1, T2 is the Signal port for RFID antenna * 4. W0, W1 is for wiegand protocol, but this library not support yet. * * ``` * +-----------+ * ----|VCC T1|---- * ----|GND T2|---- * ----|TX SER|---- * ----|RX LED|---- * ----|W0 BEEP|---- * ----|W1 GND|---- * +-----------+ * ``` ***************************************************************************/ #if (PLATFORM_ID == 0) || (PLATFORM_ID == 6) || (PLATFORM_ID == 8) || (PLATFORM_ID == 10) // Core or Photon or P1 or Electron #include "SeeedRFID.h" #else #include <SoftwareSerial.h> #include "SeeedRFID.h" #include "Arduino.h" #endif SeeedRFID::SeeedRFID(int rxPin, int txPin) { #if (PLATFORM_ID == 0) || (PLATFORM_ID == 6) || (PLATFORM_ID == 8) || (PLATFORM_ID == 10) // Core or Photon or P1 or Electron _rfidIO = &Serial1; // Select Serial1 or Serial2 #else _rfidIO = new SoftwareSerial(rxPin, txPin); _rfidIO->begin(9600); #endif // init RFID data _data.dataLen = 0; _data.chk = 0; _data.valid = false; _isAvailable = false; _type = RFID_UART; } SeeedRFID::~SeeedRFID() { } boolean SeeedRFID::checkBitValidationUART() { if( (5 == _data.dataLen) && (_data.raw[4] == _data.raw[0]^_data.raw[1]^_data.raw[2]^_data.raw[3])) { _data.valid = _isAvailable = true; return true; } else { _data.valid = _isAvailable = false; return false; } } boolean SeeedRFID::read() { _isAvailable = false; if (_data.dataLen != 0) { _data.dataLen = 0; } while (_rfidIO->available()) { _data.raw[_data.dataLen++] = _rfidIO->read(); #ifdef DEBUGRFID Serial.println("SeeedRFID:read() function, and the RFID raw data: "); for (int i = 0; i < _data.dataLen; ++i) { Serial.println(); Serial.print(_data.raw[i], HEX); Serial.print('\t'); } Serial.println(); #endif delay(10); } return SeeedRFID::checkBitValidationUART(); } boolean SeeedRFID::isAvailable() { switch(_type){ case RFID_UART: return SeeedRFID::read(); break; case RFID_WIEGAND: return false; break; default: return false; break; } } RFIDdata SeeedRFID::data() { if (_data.valid) { return _data; }else{ // empty data RFIDdata _tag; return _tag; } } unsigned long SeeedRFID::cardNumber() { // unsigned long myZero = 255; unsigned long sum = 0; if(0 != _data.raw[0]){ // _data.raw[0] = _data.raw[0] & myZero; sum = sum + _data.raw[0]; sum = sum<<24; } // _data.raw[1] = _data.raw[1] & myZero; sum = sum + _data.raw[1]; sum = sum<<16; unsigned long sum2 = 0; // _data.raw[2] = _data.raw[2] & myZero; sum2 = sum2 + _data.raw[2]; sum2 = sum2 <<8; // _data.raw[3] = _data.raw[3] & myZero; sum2 = sum2 + _data.raw[3]; sum = sum + sum2; #ifdef DEBUGRFID Serial.print("cardNumber(HEX): "); Serial.println(sum, HEX); Serial.print("cardNumber: "); Serial.println(sum); #endif return sum; } <commit_msg>Change to include Redbear Duo<commit_after>/* * SeeedRFID.cpp * A library for RFID moudle. * * Copyright (c) 2008-2014 seeed technology inc. * Author : Ye Xiaobo(yexiaobo@seeedstudio.com) * Create Time: 2014/2/20 * * The MIT License (MIT) * * 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. */ /************************************************************************** * Pins * ==== * * 1. VCC support 3.3 ~ 5V * 2. TX, RX connect to Arduino or Seeeduino * 3. T1, T2 is the Signal port for RFID antenna * 4. W0, W1 is for wiegand protocol, but this library not support yet. * * ``` * +-----------+ * ----|VCC T1|---- * ----|GND T2|---- * ----|TX SER|---- * ----|RX LED|---- * ----|W0 BEEP|---- * ----|W1 GND|---- * +-----------+ * ``` ***************************************************************************/ // Core, Photon, P1, Electron, Readbear Duo #if (PLATFORM_ID == 0) || (PLATFORM_ID == 6) || (PLATFORM_ID == 8) || (PLATFORM_ID == 10) || (PLATFORM_ID == 88) #include "SeeedRFID.h" #else #include <SoftwareSerial.h> #include "SeeedRFID.h" #include "Arduino.h" #endif SeeedRFID::SeeedRFID(int rxPin, int txPin) { // Core, Photon, P1, Electron, Readbear Duo #if (PLATFORM_ID == 0) || (PLATFORM_ID == 6) || (PLATFORM_ID == 8) || (PLATFORM_ID == 10) || (PLATFORM_ID == 88) _rfidIO = &Serial1; // Select Serial1 or Serial2 #else _rfidIO = new SoftwareSerial(rxPin, txPin); _rfidIO->begin(9600); #endif // init RFID data _data.dataLen = 0; _data.chk = 0; _data.valid = false; _isAvailable = false; _type = RFID_UART; } SeeedRFID::~SeeedRFID() { } boolean SeeedRFID::checkBitValidationUART() { if( (5 == _data.dataLen) && (_data.raw[4] == _data.raw[0]^_data.raw[1]^_data.raw[2]^_data.raw[3])) { _data.valid = _isAvailable = true; return true; } else { _data.valid = _isAvailable = false; return false; } } boolean SeeedRFID::read() { _isAvailable = false; if (_data.dataLen != 0) { _data.dataLen = 0; } while (_rfidIO->available()) { _data.raw[_data.dataLen++] = _rfidIO->read(); #ifdef DEBUGRFID Serial.println("SeeedRFID:read() function, and the RFID raw data: "); for (int i = 0; i < _data.dataLen; ++i) { Serial.println(); Serial.print(_data.raw[i], HEX); Serial.print('\t'); } Serial.println(); #endif delay(10); } return SeeedRFID::checkBitValidationUART(); } boolean SeeedRFID::isAvailable() { switch(_type){ case RFID_UART: return SeeedRFID::read(); break; case RFID_WIEGAND: return false; break; default: return false; break; } } RFIDdata SeeedRFID::data() { if (_data.valid) { return _data; }else{ // empty data RFIDdata _tag; return _tag; } } unsigned long SeeedRFID::cardNumber() { // unsigned long myZero = 255; unsigned long sum = 0; if(0 != _data.raw[0]){ // _data.raw[0] = _data.raw[0] & myZero; sum = sum + _data.raw[0]; sum = sum<<24; } // _data.raw[1] = _data.raw[1] & myZero; sum = sum + _data.raw[1]; sum = sum<<16; unsigned long sum2 = 0; // _data.raw[2] = _data.raw[2] & myZero; sum2 = sum2 + _data.raw[2]; sum2 = sum2 <<8; // _data.raw[3] = _data.raw[3] & myZero; sum2 = sum2 + _data.raw[3]; sum = sum + sum2; #ifdef DEBUGRFID Serial.print("cardNumber(HEX): "); Serial.println(sum, HEX); Serial.print("cardNumber: "); Serial.println(sum); #endif return sum; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: NetChartTypeTemplate.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: obo $ $Date: 2006-09-17 13:19:40 $ * * 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 * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_chart2.hxx" #include "NetChartTypeTemplate.hxx" #include "NetChartType.hxx" #include "macros.hxx" #include "algohelper.hxx" #include "DataSeriesTreeHelper.hxx" #include "PolarCoordinateSystem.hxx" #include "BoundedCoordinateSystem.hxx" #include "Scaling.hxx" #include "Scale.hxx" #ifndef _COM_SUN_STAR_CHART2_SYMBOLSTYLE_HPP_ #include <com/sun/star/chart2/SymbolStyle.hpp> #endif #ifndef _COM_SUN_STAR_CHART2_SYMBOL_HPP_ #include <com/sun/star/chart2/Symbol.hpp> #endif #ifndef _COM_SUN_STAR_DRAWING_LINESTYLE_HPP_ #include <com/sun/star/drawing/LineStyle.hpp> #endif using namespace ::com::sun::star; using ::com::sun::star::uno::Reference; using ::com::sun::star::uno::Sequence; using ::rtl::OUString; using ::com::sun::star::uno::Reference; using ::com::sun::star::uno::Any; using ::osl::MutexGuard; namespace { static const ::rtl::OUString lcl_aServiceName( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.chart2.NetChartTypeTemplate" )); } // anonymous namespace namespace chart { NetChartTypeTemplate::NetChartTypeTemplate( Reference< uno::XComponentContext > const & xContext, const ::rtl::OUString & rServiceName, chart2::StackMode eStackMode, bool bSymbols ) : ChartTypeTemplate( xContext, rServiceName ), m_eStackMode( eStackMode ), m_bHasSymbols( bSymbols ) {} NetChartTypeTemplate::~NetChartTypeTemplate() {} chart2::StackMode NetChartTypeTemplate::getYStackMode() const { return m_eStackMode; } Reference< chart2::XBoundedCoordinateSystem > NetChartTypeTemplate::createCoordinateSystem( const Reference< chart2::XBoundedCoordinateSystemContainer > & xCoordSysCnt ) { Reference< chart2::XCoordinateSystem > xCoordSys( new PolarCoordinateSystem( getDimension() )); Reference< chart2::XBoundedCoordinateSystem > xResult( new BoundedCoordinateSystem( xCoordSys )); chart2::ScaleData aScale; aScale.Scaling = new LinearScaling( 1.0, 0.0 ); aScale.Orientation = chart2::AxisOrientation_REVERSE; xResult->setScaleByDimension( 0, Reference< chart2::XScale >( new Scale( GetComponentContext(), aScale ) )); aScale.Orientation = chart2::AxisOrientation_MATHEMATICAL; xResult->setScaleByDimension( 1, Reference< chart2::XScale >( new Scale( GetComponentContext(), aScale ) )); try { if( xCoordSys.is()) xCoordSysCnt->addCoordinateSystem( xResult ); } catch( lang::IllegalArgumentException ex ) { ASSERT_EXCEPTION( ex ); } return xResult; } Reference< chart2::XChartType > NetChartTypeTemplate::getDefaultChartType() throw (uno::RuntimeException) { return new NetChartType(); } // ____ XChartTypeTemplate ____ Reference< chart2::XDiagram > SAL_CALL NetChartTypeTemplate::createDiagram( const uno::Sequence< Reference< chart2::XDataSeries > >& aSeriesSeq ) throw (uno::RuntimeException) { // set symbol type at data series chart2::SymbolStyle eStyle = m_bHasSymbols ? chart2::SymbolStyle_STANDARD : chart2::SymbolStyle_NONE; for( sal_Int32 i = 0; i < aSeriesSeq.getLength(); ++i ) { try { chart2::Symbol aSymbProp; Reference< beans::XPropertySet > xProp( aSeriesSeq[i], uno::UNO_QUERY_THROW ); if( (xProp->getPropertyValue( C2U( "Symbol" )) >>= aSymbProp ) ) { aSymbProp.aStyle = eStyle; if( m_bHasSymbols ) aSymbProp.nStandardSymbol = i; xProp->setPropertyValue( C2U( "Symbol" ), uno::makeAny( aSymbProp )); } } catch( uno::Exception & ex ) { ASSERT_EXCEPTION( ex ); } } // todo: set symbol type at data points return ChartTypeTemplate::createDiagram( aSeriesSeq ); } sal_Bool SAL_CALL NetChartTypeTemplate::matchesTemplate( const Reference< chart2::XDiagram >& xDiagram ) throw (uno::RuntimeException) { sal_Bool bResult = ChartTypeTemplate::matchesTemplate( xDiagram ); // check symbol-style if( bResult ) { uno::Sequence< Reference< chart2::XDataSeries > > aSeriesSeq( helper::DataSeriesTreeHelper::getDataSeriesFromDiagram( xDiagram )); chart2::SymbolStyle eStyle = m_bHasSymbols ? chart2::SymbolStyle_STANDARD : chart2::SymbolStyle_NONE; for( sal_Int32 i = 0; i < aSeriesSeq.getLength(); ++i ) { try { chart2::Symbol aSymbProp; Reference< beans::XPropertySet > xProp( aSeriesSeq[i], uno::UNO_QUERY_THROW ); if( (xProp->getPropertyValue( C2U( "Symbol" )) >>= aSymbProp ) ) { if( aSymbProp.aStyle != eStyle ) { bResult = false; break; } } } catch( uno::Exception & ex ) { ASSERT_EXCEPTION( ex ); } } } return bResult; } // ---------------------------------------- Sequence< OUString > NetChartTypeTemplate::getSupportedServiceNames_Static() { Sequence< OUString > aServices( 2 ); aServices[ 0 ] = lcl_aServiceName; aServices[ 1 ] = C2U( "com.sun.star.chart2.ChartTypeTemplate" ); return aServices; } // implement XServiceInfo methods basing upon getSupportedServiceNames_Static APPHELPER_XSERVICEINFO_IMPL( NetChartTypeTemplate, lcl_aServiceName ); } // namespace chart <commit_msg>INTEGRATION: CWS chart2mst3 (1.3.4); FILE MERGED 2007/03/26 14:17:52 iha 1.3.4.28: #i75590# copy some aspects from old charttype during creation of new 2007/02/23 18:09:51 iha 1.3.4.27: #i74655# symbols lost when switching smooth lines 2006/10/18 17:14:29 bm 1.3.4.26: RESYNC: (1.4-1.5); FILE MERGED 2006/05/18 14:17:35 bm 1.3.4.25: #i65525# template detection corrected 2006/04/10 12:25:13 iha 1.3.4.24: api restructure axis, grids, scales and increments 2005/12/20 14:13:26 dr 1.3.4.23: API struct member names without prefixes 2005/10/07 12:04:23 bm 1.3.4.22: RESYNC: (1.3-1.4); FILE MERGED 2005/08/05 14:19:58 bm 1.3.4.21: getStackMode: per chart type (open: percent stacking works per coordinate system, how can this be synched) 2005/08/04 11:53:42 bm 1.3.4.20: set stack mode at new series. Percent stacking is now set in adaptScales 2005/08/03 16:36:24 bm 1.3.4.19: algohelper.hxx split up into CommonFunctors.hxx ContainerHelper.hxx CloneHelper.hxx 2005/04/14 16:30:09 iha 1.3.4.18: removed wrong previous changes 2005/04/14 16:28:17 iha 1.3.4.17: defines for servicenames for charttypes (fixed apply to 2nd axis again) 2005/04/11 09:40:09 iha 1.3.4.16: defines for servicenames for charttypes (fixed apply to 2nd axis again) 2004/09/16 15:24:26 bm 1.3.4.15: API simplification 2004/09/16 13:24:50 bm 1.3.4.14: API simplification 2004/09/16 12:27:28 bm 1.3.4.13: API simplification 2004/09/15 17:32:06 bm 1.3.4.12: API simplification 2004/06/29 12:26:34 bm 1.3.4.11: XChartTypeTemplate changes 2004/05/27 17:27:12 bm 1.3.4.10: +getChartTypeForNewSeries at XChartTypeTemplate 2004/05/07 15:34:35 bm 1.3.4.9: applyStyle works for single series now 2004/04/21 20:45:54 iha 1.3.4.8: #i20344# net subtypes changed 2004/04/01 10:53:11 bm 1.3.4.7: XChartType: may return a coordinate system now 2004/03/24 19:05:25 bm 1.3.4.6: XChartTypeTemplate changed: matchesTemplate may modify the template s properties if bAdaptProperties is true 2004/03/22 15:23:50 iha 1.3.4.5: added parameter SwapXAndYAxis for horizontal bar chart to method createCoordinateSystems 2004/03/19 14:32:58 bm 1.3.4.4: XDataSource now contains XLabeledDataSources 2004/03/02 16:40:43 bm 1.3.4.3: allow creating more than one coordinate system 2004/02/20 17:43:56 iha 1.3.4.2: integrate categories at ScaleData 2004/02/13 16:51:43 bm 1.3.4.1: join from changes on branch bm_post_chart01<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: NetChartTypeTemplate.cxx,v $ * * $Revision: 1.6 $ * * last change: $Author: vg $ $Date: 2007-05-22 18:50:23 $ * * 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 * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_chart2.hxx" #include "NetChartTypeTemplate.hxx" #include "macros.hxx" #include "PolarCoordinateSystem.hxx" #include "Scaling.hxx" #include "DiagramHelper.hxx" #include "servicenames_charttypes.hxx" #include "DataSeriesHelper.hxx" #ifndef _COM_SUN_STAR_CHART2_SYMBOLSTYLE_HPP_ #include <com/sun/star/chart2/SymbolStyle.hpp> #endif #ifndef _COM_SUN_STAR_CHART2_SYMBOL_HPP_ #include <com/sun/star/chart2/Symbol.hpp> #endif #ifndef _COM_SUN_STAR_DRAWING_LINESTYLE_HPP_ #include <com/sun/star/drawing/LineStyle.hpp> #endif using namespace ::com::sun::star; using ::com::sun::star::uno::Reference; using ::com::sun::star::uno::Sequence; using ::rtl::OUString; using ::com::sun::star::uno::Reference; using ::com::sun::star::uno::Any; using ::osl::MutexGuard; namespace { static const ::rtl::OUString lcl_aServiceName( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.chart2.NetChartTypeTemplate" )); } // anonymous namespace namespace chart { NetChartTypeTemplate::NetChartTypeTemplate( Reference< uno::XComponentContext > const & xContext, const ::rtl::OUString & rServiceName, StackMode eStackMode, bool bSymbols, bool bHasLines ) : ChartTypeTemplate( xContext, rServiceName ), m_eStackMode( eStackMode ), m_bHasSymbols( bSymbols ), m_bHasLines( bHasLines ) {} NetChartTypeTemplate::~NetChartTypeTemplate() {} StackMode NetChartTypeTemplate::getStackMode( sal_Int32 nChartTypeIndex ) const { return m_eStackMode; } void SAL_CALL NetChartTypeTemplate::applyStyle( const Reference< chart2::XDataSeries >& xSeries, ::sal_Int32 nChartTypeIndex, ::sal_Int32 nSeriesIndex, ::sal_Int32 nSeriesCount ) throw (uno::RuntimeException) { ChartTypeTemplate::applyStyle( xSeries, nChartTypeIndex, nSeriesIndex, nSeriesCount ); try { Reference< beans::XPropertySet > xProp( xSeries, uno::UNO_QUERY_THROW ); DataSeriesHelper::switchSymbolsOnOrOff( xProp, m_bHasSymbols, nSeriesIndex ); DataSeriesHelper::switchLinesOnOrOff( xProp, m_bHasLines ); } catch( uno::Exception & ex ) { ASSERT_EXCEPTION( ex ); } } // ____ XChartTypeTemplate ____ sal_Bool SAL_CALL NetChartTypeTemplate::matchesTemplate( const Reference< chart2::XDiagram >& xDiagram, sal_Bool bAdaptProperties ) throw (uno::RuntimeException) { sal_Bool bResult = ChartTypeTemplate::matchesTemplate( xDiagram, bAdaptProperties ); // check symbol-style // for a template with symbols it is ok, if there is at least one series // with symbols, otherwise an unknown template is too easy to achieve bool bSymbolsFound = false; if( bResult ) { ::std::vector< Reference< chart2::XDataSeries > > aSeriesVec( DiagramHelper::getDataSeriesFromDiagram( xDiagram )); chart2::SymbolStyle eStyle = m_bHasSymbols ? chart2::SymbolStyle_STANDARD : chart2::SymbolStyle_NONE; for( ::std::vector< Reference< chart2::XDataSeries > >::const_iterator aIt = aSeriesVec.begin(); aIt != aSeriesVec.end(); ++aIt ) { try { chart2::Symbol aSymbProp; drawing::LineStyle eLineStyle; Reference< beans::XPropertySet > xProp( *aIt, uno::UNO_QUERY_THROW ); if( (xProp->getPropertyValue( C2U( "Symbol" )) >>= aSymbProp) && (aSymbProp.Style != chart2::SymbolStyle_NONE ) && (! m_bHasSymbols) ) { bResult = false; break; } if( m_bHasSymbols ) bSymbolsFound = bSymbolsFound || (aSymbProp.Style != chart2::SymbolStyle_NONE); if( (xProp->getPropertyValue( C2U( "LineStyle" )) >>= eLineStyle) && (m_bHasLines != ( eLineStyle != drawing::LineStyle_NONE )) ) { bResult = false; break; } } catch( uno::Exception & ex ) { ASSERT_EXCEPTION( ex ); } } if( m_bHasSymbols ) bResult = bResult && bSymbolsFound; } return bResult; } Reference< chart2::XChartType > SAL_CALL NetChartTypeTemplate::getChartTypeForNewSeries( const uno::Sequence< Reference< chart2::XChartType > >& aFormerlyUsedChartTypes ) throw (uno::RuntimeException) { Reference< chart2::XChartType > xResult; try { Reference< lang::XMultiServiceFactory > xFact( GetComponentContext()->getServiceManager(), uno::UNO_QUERY_THROW ); xResult.set( xFact->createInstance( CHART2_SERVICE_NAME_CHARTTYPE_NET ), uno::UNO_QUERY_THROW ); ChartTypeTemplate::copyPropertiesFromOldToNewCoordianteSystem( aFormerlyUsedChartTypes, xResult ); } catch( uno::Exception & ex ) { ASSERT_EXCEPTION( ex ); } return xResult; } // ---------------------------------------- Sequence< OUString > NetChartTypeTemplate::getSupportedServiceNames_Static() { Sequence< OUString > aServices( 2 ); aServices[ 0 ] = lcl_aServiceName; aServices[ 1 ] = C2U( "com.sun.star.chart2.ChartTypeTemplate" ); return aServices; } // implement XServiceInfo methods basing upon getSupportedServiceNames_Static APPHELPER_XSERVICEINFO_IMPL( NetChartTypeTemplate, lcl_aServiceName ); } // namespace chart <|endoftext|>
<commit_before>// Copyright (c) 2012 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/chrome_browser_main_extra_parts_ash.h" #include "ash/accelerators/accelerator_controller.h" #include "ash/ash_switches.h" #include "ash/shell.h" #include "base/command_line.h" #include "chrome/common/chrome_switches.h" #include "chrome/browser/ui/views/ash/caps_lock_handler.h" #include "chrome/browser/ui/views/ash/chrome_shell_delegate.h" #include "chrome/browser/ui/views/ash/screen_orientation_listener.h" #include "chrome/browser/ui/views/ash/screenshot_taker.h" #include "chrome/browser/ui/views/ash/status_area_host_aura.h" #include "ui/aura/env.h" #include "ui/aura/aura_switches.h" #include "ui/aura/monitor_manager.h" #include "ui/aura/root_window.h" #include "ui/gfx/compositor/compositor_setup.h" #if defined(OS_CHROMEOS) #include "base/chromeos/chromeos_version.h" #include "chrome/browser/ui/views/ash/brightness_controller_chromeos.h" #include "chrome/browser/ui/views/ash/ime_controller_chromeos.h" #include "chrome/browser/ui/views/ash/volume_controller_chromeos.h" #include "chrome/browser/chromeos/input_method/input_method_manager.h" #include "chrome/browser/chromeos/login/user_manager.h" #endif ChromeBrowserMainExtraPartsAsh::ChromeBrowserMainExtraPartsAsh() : ChromeBrowserMainExtraParts() { } void ChromeBrowserMainExtraPartsAsh::PreProfileInit() { #if defined(OS_CHROMEOS) aura::MonitorManager::set_use_fullscreen_host_window(true); if (base::chromeos::IsRunningOnChromeOS() || CommandLine::ForCurrentProcess()->HasSwitch( switches::kAuraHostWindowUseFullscreen)) { aura::MonitorManager::set_use_fullscreen_host_window(true); aura::RootWindow::set_hide_host_cursor(true); // Hide the mouse cursor completely at boot. if (!chromeos::UserManager::Get()->IsUserLoggedIn()) ash::Shell::set_initially_hide_cursor(true); } #endif // Shell takes ownership of ChromeShellDelegate. ash::Shell* shell = ash::Shell::CreateInstance(new ChromeShellDelegate); shell->accelerator_controller()->SetScreenshotDelegate( scoped_ptr<ash::ScreenshotDelegate>(new ScreenshotTaker).Pass()); #if defined(OS_CHROMEOS) shell->accelerator_controller()->SetBrightnessControlDelegate( scoped_ptr<ash::BrightnessControlDelegate>( new BrightnessController).Pass()); chromeos::input_method::XKeyboard* xkeyboard = chromeos::input_method::InputMethodManager::GetInstance()->GetXKeyboard(); shell->accelerator_controller()->SetCapsLockDelegate( scoped_ptr<ash::CapsLockDelegate>(new CapsLockHandler(xkeyboard)).Pass()); shell->accelerator_controller()->SetImeControlDelegate( scoped_ptr<ash::ImeControlDelegate>(new ImeController).Pass()); shell->accelerator_controller()->SetVolumeControlDelegate( scoped_ptr<ash::VolumeControlDelegate>(new VolumeController).Pass()); #endif // Make sure the singleton ScreenOrientationListener object is created. ScreenOrientationListener::GetInstance(); } void ChromeBrowserMainExtraPartsAsh::PostProfileInit() { // Add the status area buttons after Profile has been initialized. if (CommandLine::ForCurrentProcess()->HasSwitch( ash::switches::kDisableAshUberTray)) { ChromeShellDelegate::instance()->status_area_host()->AddButtons(); } } void ChromeBrowserMainExtraPartsAsh::PostMainMessageLoopRun() { ash::Shell::DeleteInstance(); } <commit_msg>Remove test code that was checked in by accident<commit_after>// Copyright (c) 2012 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/chrome_browser_main_extra_parts_ash.h" #include "ash/accelerators/accelerator_controller.h" #include "ash/ash_switches.h" #include "ash/shell.h" #include "base/command_line.h" #include "chrome/common/chrome_switches.h" #include "chrome/browser/ui/views/ash/caps_lock_handler.h" #include "chrome/browser/ui/views/ash/chrome_shell_delegate.h" #include "chrome/browser/ui/views/ash/screen_orientation_listener.h" #include "chrome/browser/ui/views/ash/screenshot_taker.h" #include "chrome/browser/ui/views/ash/status_area_host_aura.h" #include "ui/aura/env.h" #include "ui/aura/aura_switches.h" #include "ui/aura/monitor_manager.h" #include "ui/aura/root_window.h" #include "ui/gfx/compositor/compositor_setup.h" #if defined(OS_CHROMEOS) #include "base/chromeos/chromeos_version.h" #include "chrome/browser/ui/views/ash/brightness_controller_chromeos.h" #include "chrome/browser/ui/views/ash/ime_controller_chromeos.h" #include "chrome/browser/ui/views/ash/volume_controller_chromeos.h" #include "chrome/browser/chromeos/input_method/input_method_manager.h" #include "chrome/browser/chromeos/login/user_manager.h" #endif ChromeBrowserMainExtraPartsAsh::ChromeBrowserMainExtraPartsAsh() : ChromeBrowserMainExtraParts() { } void ChromeBrowserMainExtraPartsAsh::PreProfileInit() { #if defined(OS_CHROMEOS) if (base::chromeos::IsRunningOnChromeOS() || CommandLine::ForCurrentProcess()->HasSwitch( switches::kAuraHostWindowUseFullscreen)) { aura::MonitorManager::set_use_fullscreen_host_window(true); aura::RootWindow::set_hide_host_cursor(true); // Hide the mouse cursor completely at boot. if (!chromeos::UserManager::Get()->IsUserLoggedIn()) ash::Shell::set_initially_hide_cursor(true); } #endif // Shell takes ownership of ChromeShellDelegate. ash::Shell* shell = ash::Shell::CreateInstance(new ChromeShellDelegate); shell->accelerator_controller()->SetScreenshotDelegate( scoped_ptr<ash::ScreenshotDelegate>(new ScreenshotTaker).Pass()); #if defined(OS_CHROMEOS) shell->accelerator_controller()->SetBrightnessControlDelegate( scoped_ptr<ash::BrightnessControlDelegate>( new BrightnessController).Pass()); chromeos::input_method::XKeyboard* xkeyboard = chromeos::input_method::InputMethodManager::GetInstance()->GetXKeyboard(); shell->accelerator_controller()->SetCapsLockDelegate( scoped_ptr<ash::CapsLockDelegate>(new CapsLockHandler(xkeyboard)).Pass()); shell->accelerator_controller()->SetImeControlDelegate( scoped_ptr<ash::ImeControlDelegate>(new ImeController).Pass()); shell->accelerator_controller()->SetVolumeControlDelegate( scoped_ptr<ash::VolumeControlDelegate>(new VolumeController).Pass()); #endif // Make sure the singleton ScreenOrientationListener object is created. ScreenOrientationListener::GetInstance(); } void ChromeBrowserMainExtraPartsAsh::PostProfileInit() { // Add the status area buttons after Profile has been initialized. if (CommandLine::ForCurrentProcess()->HasSwitch( ash::switches::kDisableAshUberTray)) { ChromeShellDelegate::instance()->status_area_host()->AddButtons(); } } void ChromeBrowserMainExtraPartsAsh::PostMainMessageLoopRun() { ash::Shell::DeleteInstance(); } <|endoftext|>
<commit_before>// Copyright (c) 2012 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/importer/in_process_importer_bridge.h" #include "base/bind.h" #include "base/utf_string_conversions.h" #include "chrome/browser/importer/importer_host.h" #include "chrome/browser/search_engines/template_url.h" #include "content/public/browser/browser_thread.h" #include "ui/base/l10n/l10n_util.h" #include "webkit/forms/password_form.h" #if defined(OS_WIN) #include "chrome/browser/password_manager/ie7_password.h" #endif using content::BrowserThread; InProcessImporterBridge::InProcessImporterBridge(ProfileWriter* writer, ImporterHost* host) : writer_(writer), host_(host) { } void InProcessImporterBridge::AddBookmarks( const std::vector<ProfileWriter::BookmarkEntry>& bookmarks, const string16& first_folder_name) { BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind(&ProfileWriter::AddBookmarks, writer_, bookmarks, first_folder_name)); } void InProcessImporterBridge::AddHomePage(const GURL& home_page) { BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind(&ProfileWriter::AddHomepage, writer_, home_page)); } #if defined(OS_WIN) void InProcessImporterBridge::AddIE7PasswordInfo( const IE7PasswordInfo& password_info) { BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind(&ProfileWriter::AddIE7PasswordInfo, writer_, password_info)); } #endif // OS_WIN void InProcessImporterBridge::SetFavicons( const std::vector<history::ImportedFaviconUsage>& favicons) { BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind(&ProfileWriter::AddFavicons, writer_, favicons)); } void InProcessImporterBridge::SetHistoryItems( const history::URLRows &rows, history::VisitSource visit_source) { BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind(&ProfileWriter::AddHistoryPage, writer_, rows, visit_source)); } void InProcessImporterBridge::SetKeywords( const std::vector<TemplateURL*>& template_urls, bool unique_on_host_and_path) { ScopedVector<TemplateURL> owned_template_urls; std::copy(template_urls.begin(), template_urls.end(), std::back_inserter(owned_template_urls)); BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, base::Bind(&ProfileWriter::AddKeywords, writer_, base::Passed(&owned_template_urls), unique_on_host_and_path)); } void InProcessImporterBridge::SetPasswordForm( const webkit::forms::PasswordForm& form) { BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind(&ProfileWriter::AddPasswordForm, writer_, form)); } void InProcessImporterBridge::NotifyStarted() { BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind(&ImporterHost::NotifyImportStarted, host_)); } void InProcessImporterBridge::NotifyItemStarted(importer::ImportItem item) { BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind(&ImporterHost::NotifyImportItemStarted, host_, item)); } void InProcessImporterBridge::NotifyItemEnded(importer::ImportItem item) { BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind(&ImporterHost::NotifyImportItemEnded, host_, item)); } void InProcessImporterBridge::NotifyEnded() { BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind(&ImporterHost::NotifyImportEnded, host_)); } string16 InProcessImporterBridge::GetLocalizedString(int message_id) { return l10n_util::GetStringUTF16(message_id); } InProcessImporterBridge::~InProcessImporterBridge() {} <commit_msg>include <iterator>, fixes build for non-pch on vs2010<commit_after>// Copyright (c) 2012 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/importer/in_process_importer_bridge.h" #include "base/bind.h" #include "base/utf_string_conversions.h" #include "chrome/browser/importer/importer_host.h" #include "chrome/browser/search_engines/template_url.h" #include "content/public/browser/browser_thread.h" #include "ui/base/l10n/l10n_util.h" #include "webkit/forms/password_form.h" #if defined(OS_WIN) #include "chrome/browser/password_manager/ie7_password.h" #endif #include <iterator> using content::BrowserThread; InProcessImporterBridge::InProcessImporterBridge(ProfileWriter* writer, ImporterHost* host) : writer_(writer), host_(host) { } void InProcessImporterBridge::AddBookmarks( const std::vector<ProfileWriter::BookmarkEntry>& bookmarks, const string16& first_folder_name) { BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind(&ProfileWriter::AddBookmarks, writer_, bookmarks, first_folder_name)); } void InProcessImporterBridge::AddHomePage(const GURL& home_page) { BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind(&ProfileWriter::AddHomepage, writer_, home_page)); } #if defined(OS_WIN) void InProcessImporterBridge::AddIE7PasswordInfo( const IE7PasswordInfo& password_info) { BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind(&ProfileWriter::AddIE7PasswordInfo, writer_, password_info)); } #endif // OS_WIN void InProcessImporterBridge::SetFavicons( const std::vector<history::ImportedFaviconUsage>& favicons) { BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind(&ProfileWriter::AddFavicons, writer_, favicons)); } void InProcessImporterBridge::SetHistoryItems( const history::URLRows &rows, history::VisitSource visit_source) { BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind(&ProfileWriter::AddHistoryPage, writer_, rows, visit_source)); } void InProcessImporterBridge::SetKeywords( const std::vector<TemplateURL*>& template_urls, bool unique_on_host_and_path) { ScopedVector<TemplateURL> owned_template_urls; std::copy(template_urls.begin(), template_urls.end(), std::back_inserter(owned_template_urls)); BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, base::Bind(&ProfileWriter::AddKeywords, writer_, base::Passed(&owned_template_urls), unique_on_host_and_path)); } void InProcessImporterBridge::SetPasswordForm( const webkit::forms::PasswordForm& form) { BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind(&ProfileWriter::AddPasswordForm, writer_, form)); } void InProcessImporterBridge::NotifyStarted() { BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind(&ImporterHost::NotifyImportStarted, host_)); } void InProcessImporterBridge::NotifyItemStarted(importer::ImportItem item) { BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind(&ImporterHost::NotifyImportItemStarted, host_, item)); } void InProcessImporterBridge::NotifyItemEnded(importer::ImportItem item) { BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind(&ImporterHost::NotifyImportItemEnded, host_, item)); } void InProcessImporterBridge::NotifyEnded() { BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind(&ImporterHost::NotifyImportEnded, host_)); } string16 InProcessImporterBridge::GetLocalizedString(int message_id) { return l10n_util::GetStringUTF16(message_id); } InProcessImporterBridge::~InProcessImporterBridge() {} <|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. // // To know more about the algorithm used and the original code which this is // based of, see // https://wiki.corp.google.com/twiki/bin/view/Main/ChromeGoogleCodeXRef #include "chrome/browser/speech/endpointer/energy_endpointer.h" #include "base/logging.h" #include <math.h> #include <vector> namespace { // Returns the RMS (quadratic mean) of the input signal. float RMS(const int16* samples, int num_samples) { int64 ssq_int64 = 0; int64 sum_int64 = 0; for (int i = 0; i < num_samples; ++i) { sum_int64 += samples[i]; ssq_int64 += samples[i] * samples[i]; } // now convert to floats. double sum = static_cast<double>(sum_int64); sum /= num_samples; double ssq = static_cast<double>(ssq_int64); return static_cast<float>(sqrt((ssq / num_samples) - (sum * sum))); } int64 Secs2Usecs(float seconds) { return static_cast<int64>(0.5 + (1.0e6 * seconds)); } } // namespace namespace speech_input { // Stores threshold-crossing histories for making decisions about the speech // state. class EnergyEndpointer::HistoryRing { public: HistoryRing() {} // Resets the ring to |size| elements each with state |initial_state| void SetRing(int size, bool initial_state); // Inserts a new entry into the ring and drops the oldest entry. void Insert(int64 time_us, bool decision); // Returns the time in microseconds of the most recently added entry. int64 EndTime() const; // Returns the sum of all intervals during which 'decision' is true within // the time in seconds specified by 'duration'. The returned interval is // in seconds. float RingSum(float duration_sec); private: struct DecisionPoint { int64 time_us; bool decision; }; std::vector<DecisionPoint> decision_points_; int insertion_index_; // Index at which the next item gets added/inserted. DISALLOW_COPY_AND_ASSIGN(HistoryRing); }; void EnergyEndpointer::HistoryRing::SetRing(int size, bool initial_state) { insertion_index_ = 0; decision_points_.clear(); DecisionPoint init = { -1, initial_state }; decision_points_.resize(size, init); } void EnergyEndpointer::HistoryRing::Insert(int64 time_us, bool decision) { decision_points_[insertion_index_].time_us = time_us; decision_points_[insertion_index_].decision = decision; insertion_index_ = (insertion_index_ + 1) % decision_points_.size(); } int64 EnergyEndpointer::HistoryRing::EndTime() const { int ind = insertion_index_ - 1; if (ind < 0) ind = decision_points_.size() - 1; return decision_points_[ind].time_us; } float EnergyEndpointer::HistoryRing::RingSum(float duration_sec) { if (!decision_points_.size()) return 0.0; int64 sum_us = 0; int ind = insertion_index_ - 1; if (ind < 0) ind = decision_points_.size() - 1; int64 end_us = decision_points_[ind].time_us; bool is_on = decision_points_[ind].decision; int64 start_us = end_us - static_cast<int64>(0.5 + (1.0e6 * duration_sec)); if (start_us < 0) start_us = 0; size_t n_summed = 1; // n points ==> (n-1) intervals while ((decision_points_[ind].time_us > start_us) && (n_summed < decision_points_.size())) { --ind; if (ind < 0) ind = decision_points_.size() - 1; if (is_on) sum_us += end_us - decision_points_[ind].time_us; is_on = decision_points_[ind].decision; end_us = decision_points_[ind].time_us; n_summed++; } return 1.0e-6f * sum_us; // Returns total time that was super threshold. } EnergyEndpointer::EnergyEndpointer() : endpointer_time_us_(0), max_window_dur_(4.0), history_(new HistoryRing()) { } EnergyEndpointer::~EnergyEndpointer() { } int EnergyEndpointer::TimeToFrame(float time) const { return static_cast<int32>(0.5 + (time / params_.frame_period())); } void EnergyEndpointer::Restart(bool reset_threshold) { status_ = EP_PRE_SPEECH; user_input_start_time_us_ = 0; if (reset_threshold) { decision_threshold_ = params_.decision_threshold(); rms_adapt_ = decision_threshold_; noise_level_ = params_.decision_threshold() / 2.0f; frame_counter_ = 0; // Used for rapid initial update of levels. } // Set up the memories to hold the history windows. history_->SetRing(TimeToFrame(max_window_dur_), false); // Flag that indicates that current input should be used for // estimating the environment. The user has not yet started input // by e.g. pressed the push-to-talk button. By default, this is // false for backward compatibility. estimating_environment_ = false; } void EnergyEndpointer::Init(const EnergyEndpointerParams& params) { params_ = params; // Find the longest history interval to be used, and make the ring // large enough to accommodate that number of frames. NOTE: This // depends upon ep_frame_period being set correctly in the factory // that did this instantiation. max_window_dur_ = params_.onset_window(); if (params_.speech_on_window() > max_window_dur_) max_window_dur_ = params_.speech_on_window(); if (params_.offset_window() > max_window_dur_) max_window_dur_ = params_.offset_window(); Restart(true); offset_confirm_dur_sec_ = params_.offset_window() - params_.offset_confirm_dur(); if (offset_confirm_dur_sec_ < 0.0) offset_confirm_dur_sec_ = 0.0; user_input_start_time_us_ = 0; // Flag that indicates that current input should be used for // estimating the environment. The user has not yet started input // by e.g. pressed the push-to-talk button. By default, this is // false for backward compatibility. estimating_environment_ = false; // The initial value of the noise and speech levels is inconsequential. // The level of the first frame will overwrite these values. noise_level_ = params_.decision_threshold() / 2.0f; fast_update_frames_ = static_cast<int64>(params_.fast_update_dur() / params_.frame_period()); frame_counter_ = 0; // Used for rapid initial update of levels. sample_rate_ = params_.sample_rate(); start_lag_ = static_cast<int>(sample_rate_ / params_.max_fundamental_frequency()); end_lag_ = static_cast<int>(sample_rate_ / params_.min_fundamental_frequency()); } void EnergyEndpointer::StartSession() { Restart(true); } void EnergyEndpointer::EndSession() { status_ = EP_POST_SPEECH; } void EnergyEndpointer::SetEnvironmentEstimationMode() { Restart(true); estimating_environment_ = true; } void EnergyEndpointer::SetUserInputMode() { estimating_environment_ = false; user_input_start_time_us_ = endpointer_time_us_; } void EnergyEndpointer::ProcessAudioFrame(int64 time_us, const int16* samples, int num_samples, float* rms_out) { endpointer_time_us_ = time_us; float rms = RMS(samples, num_samples); // Check that this is user input audio vs. pre-input adaptation audio. // Input audio starts when the user indicates start of input, by e.g. // pressing push-to-talk. Audio recieved prior to that is used to update // noise and speech level estimates. if (!estimating_environment_) { bool decision = false; if ((endpointer_time_us_ - user_input_start_time_us_) < Secs2Usecs(params_.contamination_rejection_period())) { decision = false; DLOG(INFO) << "decision: forced to false, time: " << endpointer_time_us_; } else { decision = (rms > decision_threshold_); } DLOG(INFO) << "endpointer_time: " << endpointer_time_us_ << " user_input_start_time: " << user_input_start_time_us_ << " FA reject period " << Secs2Usecs(params_.contamination_rejection_period()) << " decision: " << (decision ? "SPEECH +++" : "SIL ------"); history_->Insert(endpointer_time_us_, decision); switch (status_) { case EP_PRE_SPEECH: if (history_->RingSum(params_.onset_window()) > params_.onset_detect_dur()) { status_ = EP_POSSIBLE_ONSET; } break; case EP_POSSIBLE_ONSET: { float tsum = history_->RingSum(params_.onset_window()); if (tsum > params_.onset_confirm_dur()) { status_ = EP_SPEECH_PRESENT; } else { // If signal is not maintained, drop back to pre-speech. if (tsum <= params_.onset_detect_dur()) status_ = EP_PRE_SPEECH; } break; } case EP_SPEECH_PRESENT: { // To induce hysteresis in the state residency, we allow a // smaller residency time in the on_ring, than was required to // enter the SPEECH_PERSENT state. float on_time = history_->RingSum(params_.speech_on_window()); if (on_time < params_.on_maintain_dur()) status_ = EP_POSSIBLE_OFFSET; break; } case EP_POSSIBLE_OFFSET: if (history_->RingSum(params_.offset_window()) <= offset_confirm_dur_sec_) { // Note that this offset time may be beyond the end // of the input buffer in a real-time system. It will be up // to the RecognizerSession to decide what to do. status_ = EP_PRE_SPEECH; // Automatically reset for next utterance. } else { // If speech picks up again we allow return to SPEECH_PRESENT. if (history_->RingSum(params_.speech_on_window()) >= params_.on_maintain_dur()) status_ = EP_SPEECH_PRESENT; } break; default: LOG(WARNING) << "Invalid case in switch: " << status_; break; } // If this is a quiet, non-speech region, slowly adapt the detection // threshold to be about 6dB above the average RMS. if ((!decision) && (status_ == EP_PRE_SPEECH)) { decision_threshold_ = (0.98f * decision_threshold_) + (0.02f * 2 * rms); rms_adapt_ = decision_threshold_; } else { // If this is in a speech region, adapt the decision threshold to // be about 10dB below the average RMS. If the noise level is high, // the threshold is pushed up. // Adaptation up to a higher level is 5 times faster than decay to // a lower level. if ((status_ == EP_SPEECH_PRESENT) && decision) { if (rms_adapt_ > rms) { rms_adapt_ = (0.99f * rms_adapt_) + (0.01f * rms); } else { rms_adapt_ = (0.95f * rms_adapt_) + (0.05f * rms); } float target_threshold = 0.3f * rms_adapt_ + noise_level_; decision_threshold_ = (.90f * decision_threshold_) + (0.10f * target_threshold); } } // Set a floor if (decision_threshold_ < params_.min_decision_threshold()) decision_threshold_ = params_.min_decision_threshold(); } // Update speech and noise levels. UpdateLevels(rms); ++frame_counter_; if (rms_out) { *rms_out = -120.0; if ((noise_level_ > 0.0) && ((rms / noise_level_ ) > 0.000001)) *rms_out = static_cast<float>(20.0 * log10(rms / noise_level_)); } } void EnergyEndpointer::UpdateLevels(float rms) { // Update quickly initially. We assume this is noise and that // speech is 6dB above the noise. if (frame_counter_ < fast_update_frames_) { // Alpha increases from 0 to (k-1)/k where k is the number of time // steps in the initial adaptation period. float alpha = static_cast<float>(frame_counter_) / static_cast<float>(fast_update_frames_); noise_level_ = (alpha * noise_level_) + ((1 - alpha) * rms); DLOG(INFO) << "FAST UPDATE, frame_counter_ " << frame_counter_ << "fast_update_frames_ " << fast_update_frames_; } else { // Update Noise level. The noise level adapts quickly downward, but // slowly upward. The noise_level_ parameter is not currently used // for threshold adaptation. It is used for UI feedback. if (noise_level_ < rms) noise_level_ = (0.999f * noise_level_) + (0.001f * rms); else noise_level_ = (0.95f * noise_level_) + (0.05f * rms); } if (estimating_environment_ || (frame_counter_ < fast_update_frames_)) { decision_threshold_ = noise_level_ * 2; // 6dB above noise level. // Set a floor if (decision_threshold_ < params_.min_decision_threshold()) decision_threshold_ = params_.min_decision_threshold(); } } EpStatus EnergyEndpointer::Status(int64* status_time) const { *status_time = history_->EndTime(); return status_; } } // namespace speech <commit_msg>Remove console LOG(INFO) spam from EnergyEndpointer.<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. // // To know more about the algorithm used and the original code which this is // based of, see // https://wiki.corp.google.com/twiki/bin/view/Main/ChromeGoogleCodeXRef #include "chrome/browser/speech/endpointer/energy_endpointer.h" #include "base/logging.h" #include <math.h> #include <vector> namespace { // Returns the RMS (quadratic mean) of the input signal. float RMS(const int16* samples, int num_samples) { int64 ssq_int64 = 0; int64 sum_int64 = 0; for (int i = 0; i < num_samples; ++i) { sum_int64 += samples[i]; ssq_int64 += samples[i] * samples[i]; } // now convert to floats. double sum = static_cast<double>(sum_int64); sum /= num_samples; double ssq = static_cast<double>(ssq_int64); return static_cast<float>(sqrt((ssq / num_samples) - (sum * sum))); } int64 Secs2Usecs(float seconds) { return static_cast<int64>(0.5 + (1.0e6 * seconds)); } } // namespace namespace speech_input { // Stores threshold-crossing histories for making decisions about the speech // state. class EnergyEndpointer::HistoryRing { public: HistoryRing() {} // Resets the ring to |size| elements each with state |initial_state| void SetRing(int size, bool initial_state); // Inserts a new entry into the ring and drops the oldest entry. void Insert(int64 time_us, bool decision); // Returns the time in microseconds of the most recently added entry. int64 EndTime() const; // Returns the sum of all intervals during which 'decision' is true within // the time in seconds specified by 'duration'. The returned interval is // in seconds. float RingSum(float duration_sec); private: struct DecisionPoint { int64 time_us; bool decision; }; std::vector<DecisionPoint> decision_points_; int insertion_index_; // Index at which the next item gets added/inserted. DISALLOW_COPY_AND_ASSIGN(HistoryRing); }; void EnergyEndpointer::HistoryRing::SetRing(int size, bool initial_state) { insertion_index_ = 0; decision_points_.clear(); DecisionPoint init = { -1, initial_state }; decision_points_.resize(size, init); } void EnergyEndpointer::HistoryRing::Insert(int64 time_us, bool decision) { decision_points_[insertion_index_].time_us = time_us; decision_points_[insertion_index_].decision = decision; insertion_index_ = (insertion_index_ + 1) % decision_points_.size(); } int64 EnergyEndpointer::HistoryRing::EndTime() const { int ind = insertion_index_ - 1; if (ind < 0) ind = decision_points_.size() - 1; return decision_points_[ind].time_us; } float EnergyEndpointer::HistoryRing::RingSum(float duration_sec) { if (!decision_points_.size()) return 0.0; int64 sum_us = 0; int ind = insertion_index_ - 1; if (ind < 0) ind = decision_points_.size() - 1; int64 end_us = decision_points_[ind].time_us; bool is_on = decision_points_[ind].decision; int64 start_us = end_us - static_cast<int64>(0.5 + (1.0e6 * duration_sec)); if (start_us < 0) start_us = 0; size_t n_summed = 1; // n points ==> (n-1) intervals while ((decision_points_[ind].time_us > start_us) && (n_summed < decision_points_.size())) { --ind; if (ind < 0) ind = decision_points_.size() - 1; if (is_on) sum_us += end_us - decision_points_[ind].time_us; is_on = decision_points_[ind].decision; end_us = decision_points_[ind].time_us; n_summed++; } return 1.0e-6f * sum_us; // Returns total time that was super threshold. } EnergyEndpointer::EnergyEndpointer() : endpointer_time_us_(0), max_window_dur_(4.0), history_(new HistoryRing()) { } EnergyEndpointer::~EnergyEndpointer() { } int EnergyEndpointer::TimeToFrame(float time) const { return static_cast<int32>(0.5 + (time / params_.frame_period())); } void EnergyEndpointer::Restart(bool reset_threshold) { status_ = EP_PRE_SPEECH; user_input_start_time_us_ = 0; if (reset_threshold) { decision_threshold_ = params_.decision_threshold(); rms_adapt_ = decision_threshold_; noise_level_ = params_.decision_threshold() / 2.0f; frame_counter_ = 0; // Used for rapid initial update of levels. } // Set up the memories to hold the history windows. history_->SetRing(TimeToFrame(max_window_dur_), false); // Flag that indicates that current input should be used for // estimating the environment. The user has not yet started input // by e.g. pressed the push-to-talk button. By default, this is // false for backward compatibility. estimating_environment_ = false; } void EnergyEndpointer::Init(const EnergyEndpointerParams& params) { params_ = params; // Find the longest history interval to be used, and make the ring // large enough to accommodate that number of frames. NOTE: This // depends upon ep_frame_period being set correctly in the factory // that did this instantiation. max_window_dur_ = params_.onset_window(); if (params_.speech_on_window() > max_window_dur_) max_window_dur_ = params_.speech_on_window(); if (params_.offset_window() > max_window_dur_) max_window_dur_ = params_.offset_window(); Restart(true); offset_confirm_dur_sec_ = params_.offset_window() - params_.offset_confirm_dur(); if (offset_confirm_dur_sec_ < 0.0) offset_confirm_dur_sec_ = 0.0; user_input_start_time_us_ = 0; // Flag that indicates that current input should be used for // estimating the environment. The user has not yet started input // by e.g. pressed the push-to-talk button. By default, this is // false for backward compatibility. estimating_environment_ = false; // The initial value of the noise and speech levels is inconsequential. // The level of the first frame will overwrite these values. noise_level_ = params_.decision_threshold() / 2.0f; fast_update_frames_ = static_cast<int64>(params_.fast_update_dur() / params_.frame_period()); frame_counter_ = 0; // Used for rapid initial update of levels. sample_rate_ = params_.sample_rate(); start_lag_ = static_cast<int>(sample_rate_ / params_.max_fundamental_frequency()); end_lag_ = static_cast<int>(sample_rate_ / params_.min_fundamental_frequency()); } void EnergyEndpointer::StartSession() { Restart(true); } void EnergyEndpointer::EndSession() { status_ = EP_POST_SPEECH; } void EnergyEndpointer::SetEnvironmentEstimationMode() { Restart(true); estimating_environment_ = true; } void EnergyEndpointer::SetUserInputMode() { estimating_environment_ = false; user_input_start_time_us_ = endpointer_time_us_; } void EnergyEndpointer::ProcessAudioFrame(int64 time_us, const int16* samples, int num_samples, float* rms_out) { endpointer_time_us_ = time_us; float rms = RMS(samples, num_samples); // Check that this is user input audio vs. pre-input adaptation audio. // Input audio starts when the user indicates start of input, by e.g. // pressing push-to-talk. Audio recieved prior to that is used to update // noise and speech level estimates. if (!estimating_environment_) { bool decision = false; if ((endpointer_time_us_ - user_input_start_time_us_) < Secs2Usecs(params_.contamination_rejection_period())) { decision = false; DLOG(INFO) << "decision: forced to false, time: " << endpointer_time_us_; } else { decision = (rms > decision_threshold_); } history_->Insert(endpointer_time_us_, decision); switch (status_) { case EP_PRE_SPEECH: if (history_->RingSum(params_.onset_window()) > params_.onset_detect_dur()) { status_ = EP_POSSIBLE_ONSET; } break; case EP_POSSIBLE_ONSET: { float tsum = history_->RingSum(params_.onset_window()); if (tsum > params_.onset_confirm_dur()) { status_ = EP_SPEECH_PRESENT; } else { // If signal is not maintained, drop back to pre-speech. if (tsum <= params_.onset_detect_dur()) status_ = EP_PRE_SPEECH; } break; } case EP_SPEECH_PRESENT: { // To induce hysteresis in the state residency, we allow a // smaller residency time in the on_ring, than was required to // enter the SPEECH_PERSENT state. float on_time = history_->RingSum(params_.speech_on_window()); if (on_time < params_.on_maintain_dur()) status_ = EP_POSSIBLE_OFFSET; break; } case EP_POSSIBLE_OFFSET: if (history_->RingSum(params_.offset_window()) <= offset_confirm_dur_sec_) { // Note that this offset time may be beyond the end // of the input buffer in a real-time system. It will be up // to the RecognizerSession to decide what to do. status_ = EP_PRE_SPEECH; // Automatically reset for next utterance. } else { // If speech picks up again we allow return to SPEECH_PRESENT. if (history_->RingSum(params_.speech_on_window()) >= params_.on_maintain_dur()) status_ = EP_SPEECH_PRESENT; } break; default: LOG(WARNING) << "Invalid case in switch: " << status_; break; } // If this is a quiet, non-speech region, slowly adapt the detection // threshold to be about 6dB above the average RMS. if ((!decision) && (status_ == EP_PRE_SPEECH)) { decision_threshold_ = (0.98f * decision_threshold_) + (0.02f * 2 * rms); rms_adapt_ = decision_threshold_; } else { // If this is in a speech region, adapt the decision threshold to // be about 10dB below the average RMS. If the noise level is high, // the threshold is pushed up. // Adaptation up to a higher level is 5 times faster than decay to // a lower level. if ((status_ == EP_SPEECH_PRESENT) && decision) { if (rms_adapt_ > rms) { rms_adapt_ = (0.99f * rms_adapt_) + (0.01f * rms); } else { rms_adapt_ = (0.95f * rms_adapt_) + (0.05f * rms); } float target_threshold = 0.3f * rms_adapt_ + noise_level_; decision_threshold_ = (.90f * decision_threshold_) + (0.10f * target_threshold); } } // Set a floor if (decision_threshold_ < params_.min_decision_threshold()) decision_threshold_ = params_.min_decision_threshold(); } // Update speech and noise levels. UpdateLevels(rms); ++frame_counter_; if (rms_out) { *rms_out = -120.0; if ((noise_level_ > 0.0) && ((rms / noise_level_ ) > 0.000001)) *rms_out = static_cast<float>(20.0 * log10(rms / noise_level_)); } } void EnergyEndpointer::UpdateLevels(float rms) { // Update quickly initially. We assume this is noise and that // speech is 6dB above the noise. if (frame_counter_ < fast_update_frames_) { // Alpha increases from 0 to (k-1)/k where k is the number of time // steps in the initial adaptation period. float alpha = static_cast<float>(frame_counter_) / static_cast<float>(fast_update_frames_); noise_level_ = (alpha * noise_level_) + ((1 - alpha) * rms); DLOG(INFO) << "FAST UPDATE, frame_counter_ " << frame_counter_ << "fast_update_frames_ " << fast_update_frames_; } else { // Update Noise level. The noise level adapts quickly downward, but // slowly upward. The noise_level_ parameter is not currently used // for threshold adaptation. It is used for UI feedback. if (noise_level_ < rms) noise_level_ = (0.999f * noise_level_) + (0.001f * rms); else noise_level_ = (0.95f * noise_level_) + (0.05f * rms); } if (estimating_environment_ || (frame_counter_ < fast_update_frames_)) { decision_threshold_ = noise_level_ * 2; // 6dB above noise level. // Set a floor if (decision_threshold_ < params_.min_decision_threshold()) decision_threshold_ = params_.min_decision_threshold(); } } EpStatus EnergyEndpointer::Status(int64* status_time) const { *status_time = history_->EndTime(); return status_; } } // namespace speech <|endoftext|>
<commit_before>// Copyright (c) 2011 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/sync/engine/process_updates_command.h" #include <vector> #include "base/basictypes.h" #include "base/location.h" #include "chrome/browser/sync/engine/syncer.h" #include "chrome/browser/sync/engine/syncer_proto_util.h" #include "chrome/browser/sync/engine/syncer_util.h" #include "chrome/browser/sync/engine/syncproto.h" #include "chrome/browser/sync/sessions/sync_session.h" #include "chrome/browser/sync/syncable/directory_manager.h" #include "chrome/browser/sync/syncable/syncable.h" using std::vector; namespace browser_sync { using sessions::SyncSession; using sessions::StatusController; using sessions::UpdateProgress; ProcessUpdatesCommand::ProcessUpdatesCommand() {} ProcessUpdatesCommand::~ProcessUpdatesCommand() {} bool ProcessUpdatesCommand::HasCustomGroupsToChange() const { return true; } std::set<ModelSafeGroup> ProcessUpdatesCommand::GetGroupsToChange( const sessions::SyncSession& session) const { return session.GetEnabledGroupsWithVerifiedUpdates(); } bool ProcessUpdatesCommand::ModelNeutralExecuteImpl(SyncSession* session) { const GetUpdatesResponse& updates = session->status_controller().updates_response().get_updates(); const int update_count = updates.entries_size(); // Don't bother processing updates if there were none. return update_count != 0; } void ProcessUpdatesCommand::ModelChangingExecuteImpl(SyncSession* session) { syncable::ScopedDirLookup dir(session->context()->directory_manager(), session->context()->account_name()); if (!dir.good()) { LOG(ERROR) << "Scoped dir lookup failed!"; return; } const sessions::UpdateProgress* progress = session->status_controller().update_progress(); if (!progress) return; // Nothing to do. syncable::WriteTransaction trans(FROM_HERE, syncable::SYNCER, dir); vector<sessions::VerifiedUpdate>::const_iterator it; for (it = progress->VerifiedUpdatesBegin(); it != progress->VerifiedUpdatesEnd(); ++it) { const sync_pb::SyncEntity& update = it->second; if (it->first != VERIFY_SUCCESS && it->first != VERIFY_UNDELETE) continue; switch (ProcessUpdate(dir, update, &trans)) { case SUCCESS_PROCESSED: case SUCCESS_STORED: break; default: NOTREACHED(); break; } } StatusController* status = session->mutable_status_controller(); status->set_num_consecutive_errors(0); status->mutable_update_progress()->ClearVerifiedUpdates(); } namespace { // Returns true if the entry is still ok to process. bool ReverifyEntry(syncable::WriteTransaction* trans, const SyncEntity& entry, syncable::MutableEntry* same_id) { const bool deleted = entry.has_deleted() && entry.deleted(); const bool is_directory = entry.IsFolder(); const syncable::ModelType model_type = entry.GetModelType(); return VERIFY_SUCCESS == SyncerUtil::VerifyUpdateConsistency(trans, entry, same_id, deleted, is_directory, model_type); } } // namespace // Process a single update. Will avoid touching global state. ServerUpdateProcessingResult ProcessUpdatesCommand::ProcessUpdate( const syncable::ScopedDirLookup& dir, const sync_pb::SyncEntity& proto_update, syncable::WriteTransaction* const trans) { const SyncEntity& update = *static_cast<const SyncEntity*>(&proto_update); syncable::Id server_id = update.id(); const std::string name = SyncerProtoUtil::NameFromSyncEntity(update); // Look to see if there's a local item that should recieve this update, // maybe due to a duplicate client tag or a lost commit response. syncable::Id local_id = SyncerUtil::FindLocalIdToUpdate(trans, update); // FindLocalEntryToUpdate has veto power. if (local_id.IsNull()) { return SUCCESS_PROCESSED; // The entry has become irrelevant. } SyncerUtil::CreateNewEntry(trans, local_id); // We take a two step approach. First we store the entries data in the // server fields of a local entry and then move the data to the local fields syncable::MutableEntry target_entry(trans, syncable::GET_BY_ID, local_id); // We need to run the Verify checks again; the world could have changed // since VerifyUpdatesCommand. if (!ReverifyEntry(trans, update, &target_entry)) { return SUCCESS_PROCESSED; // The entry has become irrelevant. } // If we're repurposing an existing local entry with a new server ID, // change the ID now, after we're sure that the update can succeed. if (local_id != server_id) { DCHECK(!update.deleted()); SyncerUtil::ChangeEntryIDAndUpdateChildren(trans, &target_entry, server_id); // When IDs change, versions become irrelevant. Forcing BASE_VERSION // to zero would ensure that this update gets applied, but would indicate // creation or undeletion if it were committed that way. Instead, prefer // forcing BASE_VERSION to entry.version() while also forcing // IS_UNAPPLIED_UPDATE to true. If the item is UNSYNCED, it's committable // from the new state; it may commit before the conflict resolver gets // a crack at it. if (target_entry.Get(syncable::IS_UNSYNCED) || target_entry.Get(syncable::BASE_VERSION) > 0) { // If either of these conditions are met, then we can expect valid client // fields for this entry. When BASE_VERSION is positive, consistency is // enforced on the client fields at update-application time. Otherwise, // we leave the BASE_VERSION field alone; it'll get updated the first time // we successfully apply this update. target_entry.Put(syncable::BASE_VERSION, update.version()); } // Force application of this update, no matter what. target_entry.Put(syncable::IS_UNAPPLIED_UPDATE, true); } SyncerUtil::UpdateServerFieldsFromUpdate(&target_entry, update, name); return SUCCESS_PROCESSED; } } // namespace browser_sync <commit_msg>Revert 114090 - [Sync] Set HasCustomGroupsToChange() to true for ProcessUpdatesCommand<commit_after>// Copyright (c) 2011 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/sync/engine/process_updates_command.h" #include <vector> #include "base/basictypes.h" #include "base/location.h" #include "chrome/browser/sync/engine/syncer.h" #include "chrome/browser/sync/engine/syncer_proto_util.h" #include "chrome/browser/sync/engine/syncer_util.h" #include "chrome/browser/sync/engine/syncproto.h" #include "chrome/browser/sync/sessions/sync_session.h" #include "chrome/browser/sync/syncable/directory_manager.h" #include "chrome/browser/sync/syncable/syncable.h" using std::vector; namespace browser_sync { using sessions::SyncSession; using sessions::StatusController; using sessions::UpdateProgress; ProcessUpdatesCommand::ProcessUpdatesCommand() {} ProcessUpdatesCommand::~ProcessUpdatesCommand() {} bool ProcessUpdatesCommand::HasCustomGroupsToChange() const { // TODO(akalin): Set to true. return false; } std::set<ModelSafeGroup> ProcessUpdatesCommand::GetGroupsToChange( const sessions::SyncSession& session) const { return session.GetEnabledGroupsWithVerifiedUpdates(); } bool ProcessUpdatesCommand::ModelNeutralExecuteImpl(SyncSession* session) { const GetUpdatesResponse& updates = session->status_controller().updates_response().get_updates(); const int update_count = updates.entries_size(); // Don't bother processing updates if there were none. return update_count != 0; } void ProcessUpdatesCommand::ModelChangingExecuteImpl(SyncSession* session) { syncable::ScopedDirLookup dir(session->context()->directory_manager(), session->context()->account_name()); if (!dir.good()) { LOG(ERROR) << "Scoped dir lookup failed!"; return; } const sessions::UpdateProgress* progress = session->status_controller().update_progress(); if (!progress) return; // Nothing to do. syncable::WriteTransaction trans(FROM_HERE, syncable::SYNCER, dir); vector<sessions::VerifiedUpdate>::const_iterator it; for (it = progress->VerifiedUpdatesBegin(); it != progress->VerifiedUpdatesEnd(); ++it) { const sync_pb::SyncEntity& update = it->second; if (it->first != VERIFY_SUCCESS && it->first != VERIFY_UNDELETE) continue; switch (ProcessUpdate(dir, update, &trans)) { case SUCCESS_PROCESSED: case SUCCESS_STORED: break; default: NOTREACHED(); break; } } StatusController* status = session->mutable_status_controller(); status->set_num_consecutive_errors(0); status->mutable_update_progress()->ClearVerifiedUpdates(); } namespace { // Returns true if the entry is still ok to process. bool ReverifyEntry(syncable::WriteTransaction* trans, const SyncEntity& entry, syncable::MutableEntry* same_id) { const bool deleted = entry.has_deleted() && entry.deleted(); const bool is_directory = entry.IsFolder(); const syncable::ModelType model_type = entry.GetModelType(); return VERIFY_SUCCESS == SyncerUtil::VerifyUpdateConsistency(trans, entry, same_id, deleted, is_directory, model_type); } } // namespace // Process a single update. Will avoid touching global state. ServerUpdateProcessingResult ProcessUpdatesCommand::ProcessUpdate( const syncable::ScopedDirLookup& dir, const sync_pb::SyncEntity& proto_update, syncable::WriteTransaction* const trans) { const SyncEntity& update = *static_cast<const SyncEntity*>(&proto_update); syncable::Id server_id = update.id(); const std::string name = SyncerProtoUtil::NameFromSyncEntity(update); // Look to see if there's a local item that should recieve this update, // maybe due to a duplicate client tag or a lost commit response. syncable::Id local_id = SyncerUtil::FindLocalIdToUpdate(trans, update); // FindLocalEntryToUpdate has veto power. if (local_id.IsNull()) { return SUCCESS_PROCESSED; // The entry has become irrelevant. } SyncerUtil::CreateNewEntry(trans, local_id); // We take a two step approach. First we store the entries data in the // server fields of a local entry and then move the data to the local fields syncable::MutableEntry target_entry(trans, syncable::GET_BY_ID, local_id); // We need to run the Verify checks again; the world could have changed // since VerifyUpdatesCommand. if (!ReverifyEntry(trans, update, &target_entry)) { return SUCCESS_PROCESSED; // The entry has become irrelevant. } // If we're repurposing an existing local entry with a new server ID, // change the ID now, after we're sure that the update can succeed. if (local_id != server_id) { DCHECK(!update.deleted()); SyncerUtil::ChangeEntryIDAndUpdateChildren(trans, &target_entry, server_id); // When IDs change, versions become irrelevant. Forcing BASE_VERSION // to zero would ensure that this update gets applied, but would indicate // creation or undeletion if it were committed that way. Instead, prefer // forcing BASE_VERSION to entry.version() while also forcing // IS_UNAPPLIED_UPDATE to true. If the item is UNSYNCED, it's committable // from the new state; it may commit before the conflict resolver gets // a crack at it. if (target_entry.Get(syncable::IS_UNSYNCED) || target_entry.Get(syncable::BASE_VERSION) > 0) { // If either of these conditions are met, then we can expect valid client // fields for this entry. When BASE_VERSION is positive, consistency is // enforced on the client fields at update-application time. Otherwise, // we leave the BASE_VERSION field alone; it'll get updated the first time // we successfully apply this update. target_entry.Put(syncable::BASE_VERSION, update.version()); } // Force application of this update, no matter what. target_entry.Put(syncable::IS_UNAPPLIED_UPDATE, true); } SyncerUtil::UpdateServerFieldsFromUpdate(&target_entry, update, name); return SUCCESS_PROCESSED; } } // namespace browser_sync <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: fudraw.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: rt $ $Date: 2005-09-08 21:28: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 SC_FUDRAW_HXX #define SC_FUDRAW_HXX #ifndef _SC_FUPOOR_HXX #include "fupoor.hxx" #endif #ifndef _SV_POINTR_HXX //autogen #include <vcl/pointr.hxx> #endif /************************************************************************* |* |* Basisklasse fuer alle Drawmodul-spezifischen Funktionen |* \************************************************************************/ class FuDraw : public FuPoor { protected: Pointer aNewPointer; Pointer aOldPointer; public: FuDraw(ScTabViewShell* pViewSh, Window* pWin, SdrView* pView, SdrModel* pDoc, SfxRequest& rReq); virtual ~FuDraw(); virtual BOOL KeyInput(const KeyEvent& rKEvt); virtual void ScrollStart(); virtual void ScrollEnd(); virtual void Activate(); virtual void Deactivate(); virtual void ForcePointer(const MouseEvent* pMEvt); virtual BOOL MouseMove(const MouseEvent& rMEvt); virtual BOOL MouseButtonUp(const MouseEvent& rMEvt); virtual BOOL MouseButtonDown(const MouseEvent& rMEvt); // #97016# II virtual void SelectionHasChanged(); BOOL IsReSizingNote(const MouseEvent& rMEvt) const; void CheckVisibleNote() const; private: void DoModifiers(const MouseEvent& rMEvt); void ResetModifiers(); }; #endif // _SD_FUDRAW_HXX <commit_msg>INTEGRATION: CWS dr37 (1.3.36); FILE MERGED 2005/05/12 15:20:07 dr 1.3.36.1: #i42981# do not close new note object when clicked on its border<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: fudraw.hxx,v $ * * $Revision: 1.5 $ * * last change: $Author: hr $ $Date: 2005-09-28 12:12:10 $ * * 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 SC_FUDRAW_HXX #define SC_FUDRAW_HXX #ifndef _SC_FUPOOR_HXX #include "fupoor.hxx" #endif #ifndef _SV_POINTR_HXX //autogen #include <vcl/pointr.hxx> #endif /************************************************************************* |* |* Basisklasse fuer alle Drawmodul-spezifischen Funktionen |* \************************************************************************/ class FuDraw : public FuPoor { protected: Pointer aNewPointer; Pointer aOldPointer; public: FuDraw(ScTabViewShell* pViewSh, Window* pWin, SdrView* pView, SdrModel* pDoc, SfxRequest& rReq); virtual ~FuDraw(); virtual BOOL KeyInput(const KeyEvent& rKEvt); virtual void ScrollStart(); virtual void ScrollEnd(); virtual void Activate(); virtual void Deactivate(); virtual void ForcePointer(const MouseEvent* pMEvt); virtual BOOL MouseMove(const MouseEvent& rMEvt); virtual BOOL MouseButtonUp(const MouseEvent& rMEvt); virtual BOOL MouseButtonDown(const MouseEvent& rMEvt); // #97016# II virtual void SelectionHasChanged(); BOOL IsSizingOrMovingNote( const MouseEvent& rMEvt ) const; void CheckVisibleNote() const; private: void DoModifiers(const MouseEvent& rMEvt); void ResetModifiers(); }; #endif // _SD_FUDRAW_HXX <|endoftext|>
<commit_before>// Copyright 2014 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 "content/browser/renderer_host/render_view_host_impl.h" #include "content/browser/renderer_host/render_widget_host_impl.h" #include "content/port/browser/render_widget_host_view_port.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/render_widget_host.h" #include "content/public/browser/render_widget_host_view.h" #include "content/public/browser/web_contents.h" #include "content/public/common/url_constants.h" #include "content/shell/browser/shell.h" #include "content/test/accessibility_browser_test_utils.h" #include "content/test/content_browser_test.h" #include "content/test/content_browser_test_utils.h" #include "testing/gtest/include/gtest/gtest.h" namespace content { const char kMinimalPageDataURL[] = "data:text/html,<html><head></head><body>Hello, world</body></html>"; class AccessibilityModeTest : public ContentBrowserTest { protected: content::WebContents* web_contents() { return shell()->web_contents(); } content::RenderWidgetHostImpl* rwhi() { content::RenderWidgetHost* rwh = web_contents()->GetRenderWidgetHostView()->GetRenderWidgetHost(); return content::RenderWidgetHostImpl::From(rwh); } content::RenderWidgetHostViewPort* host_view() { return RenderWidgetHostViewPort::FromRWHV( shell()->web_contents()->GetRenderWidgetHostView()); } void ExpectBrowserAccessibilityManager(bool expect_bam, std::string message = "") { if (expect_bam) { EXPECT_NE((BrowserAccessibilityManager*)NULL, host_view()->GetBrowserAccessibilityManager()) << message; } else { EXPECT_EQ((BrowserAccessibilityManager*)NULL, host_view()->GetBrowserAccessibilityManager()) << message; } } }; IN_PROC_BROWSER_TEST_F(AccessibilityModeTest, AccessibilityModeOff) { NavigateToURL(shell(), GURL(kMinimalPageDataURL)); EXPECT_EQ(AccessibilityModeOff, rwhi()->accessibility_mode()); ExpectBrowserAccessibilityManager(false); } IN_PROC_BROWSER_TEST_F(AccessibilityModeTest, AccessibilityModeComplete) { NavigateToURL(shell(), GURL(kMinimalPageDataURL)); ASSERT_EQ(AccessibilityModeOff, rwhi()->accessibility_mode()); AccessibilityNotificationWaiter waiter(shell()); rwhi()->AddAccessibilityMode(AccessibilityModeComplete); EXPECT_EQ(AccessibilityModeComplete, rwhi()->accessibility_mode()); waiter.WaitForNotification(); ExpectBrowserAccessibilityManager(true); } IN_PROC_BROWSER_TEST_F(AccessibilityModeTest, AccessibilityModeTreeOnly) { NavigateToURL(shell(), GURL(kMinimalPageDataURL)); ASSERT_EQ(AccessibilityModeOff, rwhi()->accessibility_mode()); AccessibilityNotificationWaiter waiter(shell()); rwhi()->AddAccessibilityMode(AccessibilityModeTreeOnly); EXPECT_EQ(AccessibilityModeTreeOnly, rwhi()->accessibility_mode()); waiter.WaitForNotification(); // No BrowserAccessibilityManager expected for AccessibilityModeTreeOnly ExpectBrowserAccessibilityManager(false); } IN_PROC_BROWSER_TEST_F(AccessibilityModeTest, AddingModes) { NavigateToURL(shell(), GURL(kMinimalPageDataURL)); AccessibilityNotificationWaiter waiter(shell()); rwhi()->AddAccessibilityMode(AccessibilityModeTreeOnly); EXPECT_EQ(AccessibilityModeTreeOnly, rwhi()->accessibility_mode()); waiter.WaitForNotification(); ExpectBrowserAccessibilityManager(false, "Should be no BrowserAccessibilityManager " "for AccessibilityModeTreeOnly"); AccessibilityNotificationWaiter waiter2(shell()); rwhi()->AddAccessibilityMode(AccessibilityModeComplete); EXPECT_EQ(AccessibilityModeComplete, rwhi()->accessibility_mode()); waiter2.WaitForNotification(); ExpectBrowserAccessibilityManager(true, "Should be a BrowserAccessibilityManager " "for AccessibilityModeComplete"); } } // namespace content <commit_msg>update headers<commit_after>// Copyright 2014 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 "content/browser/renderer_host/render_view_host_impl.h" #include "content/browser/renderer_host/render_widget_host_impl.h" #include "content/port/browser/render_widget_host_view_port.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/render_widget_host.h" #include "content/public/browser/render_widget_host_view.h" #include "content/public/browser/web_contents.h" #include "content/public/common/url_constants.h" #include "content/public/test/content_browser_test.h" #include "content/public/test/content_browser_test_utils.h" #include "content/shell/browser/shell.h" #include "content/test/accessibility_browser_test_utils.h" #include "testing/gtest/include/gtest/gtest.h" namespace content { const char kMinimalPageDataURL[] = "data:text/html,<html><head></head><body>Hello, world</body></html>"; class AccessibilityModeTest : public ContentBrowserTest { protected: content::WebContents* web_contents() { return shell()->web_contents(); } content::RenderWidgetHostImpl* rwhi() { content::RenderWidgetHost* rwh = web_contents()->GetRenderWidgetHostView()->GetRenderWidgetHost(); return content::RenderWidgetHostImpl::From(rwh); } content::RenderWidgetHostViewPort* host_view() { return RenderWidgetHostViewPort::FromRWHV( shell()->web_contents()->GetRenderWidgetHostView()); } void ExpectBrowserAccessibilityManager(bool expect_bam, std::string message = "") { if (expect_bam) { EXPECT_NE((BrowserAccessibilityManager*)NULL, host_view()->GetBrowserAccessibilityManager()) << message; } else { EXPECT_EQ((BrowserAccessibilityManager*)NULL, host_view()->GetBrowserAccessibilityManager()) << message; } } }; IN_PROC_BROWSER_TEST_F(AccessibilityModeTest, AccessibilityModeOff) { NavigateToURL(shell(), GURL(kMinimalPageDataURL)); EXPECT_EQ(AccessibilityModeOff, rwhi()->accessibility_mode()); ExpectBrowserAccessibilityManager(false); } IN_PROC_BROWSER_TEST_F(AccessibilityModeTest, AccessibilityModeComplete) { NavigateToURL(shell(), GURL(kMinimalPageDataURL)); ASSERT_EQ(AccessibilityModeOff, rwhi()->accessibility_mode()); AccessibilityNotificationWaiter waiter(shell()); rwhi()->AddAccessibilityMode(AccessibilityModeComplete); EXPECT_EQ(AccessibilityModeComplete, rwhi()->accessibility_mode()); waiter.WaitForNotification(); ExpectBrowserAccessibilityManager(true); } IN_PROC_BROWSER_TEST_F(AccessibilityModeTest, AccessibilityModeTreeOnly) { NavigateToURL(shell(), GURL(kMinimalPageDataURL)); ASSERT_EQ(AccessibilityModeOff, rwhi()->accessibility_mode()); AccessibilityNotificationWaiter waiter(shell()); rwhi()->AddAccessibilityMode(AccessibilityModeTreeOnly); EXPECT_EQ(AccessibilityModeTreeOnly, rwhi()->accessibility_mode()); waiter.WaitForNotification(); // No BrowserAccessibilityManager expected for AccessibilityModeTreeOnly ExpectBrowserAccessibilityManager(false); } IN_PROC_BROWSER_TEST_F(AccessibilityModeTest, AddingModes) { NavigateToURL(shell(), GURL(kMinimalPageDataURL)); AccessibilityNotificationWaiter waiter(shell()); rwhi()->AddAccessibilityMode(AccessibilityModeTreeOnly); EXPECT_EQ(AccessibilityModeTreeOnly, rwhi()->accessibility_mode()); waiter.WaitForNotification(); ExpectBrowserAccessibilityManager(false, "Should be no BrowserAccessibilityManager " "for AccessibilityModeTreeOnly"); AccessibilityNotificationWaiter waiter2(shell()); rwhi()->AddAccessibilityMode(AccessibilityModeComplete); EXPECT_EQ(AccessibilityModeComplete, rwhi()->accessibility_mode()); waiter2.WaitForNotification(); ExpectBrowserAccessibilityManager(true, "Should be a BrowserAccessibilityManager " "for AccessibilityModeComplete"); } } // namespace content <|endoftext|>
<commit_before>////////////////////////////////////////////////////////////////////////// // // SneezyMUD - All rights reserved, SneezyMUD Coding Team // // $Log: task_smythe.cc,v $ // Revision 5.8 2002/03/14 15:43:13 jesus // *** empty log message *** // // Revision 5.7 2002/03/14 15:30:38 jesus // *** empty log message *** // // Revision 5.6 2002/03/14 15:22:37 jesus // made move drain skill dependant // // Revision 5.5 2002/01/10 00:45:49 peel // more splitting up of obj2.h // // Revision 5.4 2001/09/25 12:44:43 jesus // smythe fix // // Revision 5.3 2001/09/07 07:07:35 peel // changed TThing->stuff to getStuff() and setStuff() // // Revision 5.2 2001/07/23 00:33:30 jesus // added goofers dust // // Revision 5.1.1.4 2000/12/21 20:15:35 jesus // *** empty log message *** // // Revision 5.1.1.3 2000/11/19 22:20:48 jesus // smythe update // // Revision 5.1.1.2 2000/11/19 13:44:19 jesus // smythe fixed // // Revision 5.1.1.1 1999/10/16 04:32:20 batopr // new branch // // Revision 5.1 1999/10/16 04:31:17 batopr // new branch // // Revision 1.1 1999/09/12 17:24:04 sneezy // Initial revision // // ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// // // SneezyMUD 4.0 - All rights reserved, SneezyMUD Coding Team // "task.cc" - All functions related to tasks that keep mobs/PCs busy // ////////////////////////////////////////////////////////////////////////// #include "stdsneezy.h" #include "obj_tool.h" void TTool::findSmytheTools(TTool **forge, TTool **anvil) { if (!*forge && getToolType() == TOOL_FORGE) *forge = this; else if (!*anvil && getToolType() == TOOL_ANVIL) *anvil = this; } int smythe_tools_in_room(int room, TTool **forge, TTool **anvil) { TRoom *rp; TThing *t; if (!(rp = real_roomp(room))) return FALSE; for (t = rp->getStuff(); t; t = t->nextThing) { t->findSmytheTools(forge, anvil); } return (*forge && *anvil); } void smythe_stop(TBeing *ch) { if (ch->getPosition() < POSITION_SITTING) { act("You stop smything, and look about confused. Are you missing something?", FALSE, ch, 0, 0, TO_CHAR); act("$n stops smything, and looks about confused and embarrassed.", FALSE, ch, 0, 0, TO_ROOM); } ch->stopTask(); } void TThing::smythePulse(TBeing *ch, TObj *) { smythe_stop(ch); } void TTool::smythePulse(TBeing *ch, TObj *o) { TTool *forge = NULL, *anvil = NULL; int percent; int movemod = ::number(10,25); int movebonus = ::number(1,((ch->getSkillValue(SKILL_SMYTHE) / 10))); const int HEATING_TIME = 3; // sanity check if ((getToolType() != TOOL_HAMMER) || !smythe_tools_in_room(ch->in_room, &forge, &anvil) || (ch->getPosition() < POSITION_RESTING)) { smythe_stop(ch); return; } if (movebonus > movemod) { movebonus = 5; } if (ch->getRace() == RACE_DWARF) { ch->addToMove(-movemod); ch->addToMove(movebonus); ch->addToMove(4); } else { ch->addToMove(-movemod); ch->addToMove(movebonus); } if (ch->getMove() < 10) { act("You are much too tired to continue repairing $p.", FALSE, ch, o, this, TO_CHAR); act("$n stops repairing, and wipes sweat from $s brow.", FALSE, ch, o, this, TO_ROOM); ch->stopTask(); return; } if (ch->task->status < HEATING_TIME) { if (!ch->task->status) { act("$n allows $p to heat in $P.", FALSE, ch, o, forge, TO_ROOM); act("You allow $p to heat in $P.", FALSE, ch, o, forge, TO_CHAR); } else { act("$n continues to let $p heat in $P.", FALSE, ch, o, forge, TO_ROOM); act("You continue to let $p heat in $P.", FALSE, ch, o, forge, TO_CHAR); } ch->task->status++; } else if (ch->task->status == HEATING_TIME) { act("$n removes $p from $P, as it glows red hot.", FALSE, ch, o, forge, TO_ROOM); act("You remove $p from $P, as it glows red hot.", FALSE, ch, o, forge, TO_CHAR); ch->task->status++; } else { act("$n pounds $p on an anvil with $s hammer.", FALSE, ch, o, 0, TO_ROOM); act("You pound $p on an anvil with your hammer.", FALSE, ch, o, 0, TO_CHAR); addToToolUses(-1); if (getToolUses() <= 0) { ch->sendTo("Your %s breaks due to overuse.\n\r", fname(name).c_str()); act("$n looks startled as $e breaks $P while hammering.", FALSE, ch, o, this, TO_ROOM); makeScraps(); ch->stopTask(); delete this; return; } if (o->getMaxStructPoints() <= o->getStructPoints() - o->getDepreciation()) { act("$n finishes repairing $p and proudly smiles.", FALSE, ch, o, forge, TO_ROOM); act("You finish repairing $p and smile triumphantly.", FALSE, ch, o, forge, TO_CHAR); act("You let $p cool down.", FALSE, ch, o, 0, TO_CHAR); act("$n lets $p cool down.", FALSE, ch, o, 0, TO_ROOM); ch->stopTask(); return; } if ((percent = ::number(1, 101)) != 101) // 101 is complete failure percent -= ch->getDexReaction() * 3; if (percent < ch->getSkillValue(SKILL_SMYTHE)) o->addToStructPoints(1); else o->addToStructPoints(-1); if (o->getStructPoints() <= 1) { act("$n screws up repairing $p and utterly destroys it.", FALSE, ch, o, forge, TO_ROOM); act("You screw up repairing $p and utterly destroy it.", FALSE, ch, o, forge, TO_CHAR); makeScraps(); ch->stopTask(); delete o; return; } // task can continue forever, so don't bother decrementing the timer } } int task_smythe(TBeing *ch, cmdTypeT cmd, const char *, int pulse, TRoom *, TObj *) { TThing *w = NULL; TObj *o = dynamic_cast<TObj *>(ch->heldInSecHand()); int learning; // sanity check if (ch->isLinkdead() || (ch->in_room < 0) || !o || !isname(ch->task->orig_arg, o->name)) { smythe_stop(ch); return FALSE; // returning FALSE lets command be interpreted } if (ch->utilityTaskCommand(cmd)) return FALSE; switch (cmd) { case CMD_TASK_CONTINUE: if (!(w = ch->heldInPrimHand())) { smythe_stop(ch); return FALSE; // returning FALSE lets command be interpreted } if (ch->task->status) { learning = ch->getSkillValue(SKILL_SMYTHE); ch->task->calcNextUpdate(pulse, 2 * PULSE_MOBACT); if (bSuccess(ch, learning, SKILL_SMYTHE)) { w->smythePulse(ch, o); } else if (!(::number(0,1))) act("$n examines $p carefully.", FALSE, ch, o, 0, TO_ROOM); act("You carefully examine $p.", FALSE, ch, o, 0, TO_CHAR); return FALSE; } else { ch->task->calcNextUpdate(pulse, 2 * PULSE_MOBACT); w->smythePulse(ch, o); // w may be invalid here return FALSE; } case CMD_ABORT: case CMD_STOP: act("You stop trying to repair $p.", FALSE, ch, o, 0, TO_CHAR); ch->sendTo("Isn't there a professional around here somewhere?\n\r"); act("$n stops repairing $p.", FALSE, ch, o, 0, TO_ROOM); if (ch->task->status > 0) { act("You let $p cool down.", FALSE, ch, o, 0, TO_CHAR); act("$n lets $p cool down.", FALSE, ch, o, 0, TO_ROOM); } ch->stopTask(); break; case CMD_TASK_FIGHTING: ch->sendTo("You are unable to continue repairing while under attack!\n\r"); ch->stopTask(); break; default: if (cmd < MAX_CMD_LIST) warn_busy(ch); break; // eat the command } return TRUE; } <commit_msg>depreciation code was buggy, so I just removed it probably ok for players to repair to brand new anyway, gies them an advantage over repair shop<commit_after>////////////////////////////////////////////////////////////////////////// // // SneezyMUD - All rights reserved, SneezyMUD Coding Team // // $Log: task_smythe.cc,v $ // Revision 5.9 2002/06/13 04:39:20 peel // depreciation code was buggy, so I just removed it // probably ok for players to repair to brand new anyway, gies them an // advantage over repair shop // // Revision 5.8 2002/03/14 15:43:13 jesus // *** empty log message *** // // Revision 5.7 2002/03/14 15:30:38 jesus // *** empty log message *** // // Revision 5.6 2002/03/14 15:22:37 jesus // made move drain skill dependant // // Revision 5.5 2002/01/10 00:45:49 peel // more splitting up of obj2.h // // Revision 5.4 2001/09/25 12:44:43 jesus // smythe fix // // Revision 5.3 2001/09/07 07:07:35 peel // changed TThing->stuff to getStuff() and setStuff() // // Revision 5.2 2001/07/23 00:33:30 jesus // added goofers dust // // Revision 5.1.1.4 2000/12/21 20:15:35 jesus // *** empty log message *** // // Revision 5.1.1.3 2000/11/19 22:20:48 jesus // smythe update // // Revision 5.1.1.2 2000/11/19 13:44:19 jesus // smythe fixed // // Revision 5.1.1.1 1999/10/16 04:32:20 batopr // new branch // // Revision 5.1 1999/10/16 04:31:17 batopr // new branch // // Revision 1.1 1999/09/12 17:24:04 sneezy // Initial revision // // ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// // // SneezyMUD 4.0 - All rights reserved, SneezyMUD Coding Team // "task.cc" - All functions related to tasks that keep mobs/PCs busy // ////////////////////////////////////////////////////////////////////////// #include "stdsneezy.h" #include "obj_tool.h" void TTool::findSmytheTools(TTool **forge, TTool **anvil) { if (!*forge && getToolType() == TOOL_FORGE) *forge = this; else if (!*anvil && getToolType() == TOOL_ANVIL) *anvil = this; } int smythe_tools_in_room(int room, TTool **forge, TTool **anvil) { TRoom *rp; TThing *t; if (!(rp = real_roomp(room))) return FALSE; for (t = rp->getStuff(); t; t = t->nextThing) { t->findSmytheTools(forge, anvil); } return (*forge && *anvil); } void smythe_stop(TBeing *ch) { if (ch->getPosition() < POSITION_SITTING) { act("You stop smything, and look about confused. Are you missing something?", FALSE, ch, 0, 0, TO_CHAR); act("$n stops smything, and looks about confused and embarrassed.", FALSE, ch, 0, 0, TO_ROOM); } ch->stopTask(); } void TThing::smythePulse(TBeing *ch, TObj *) { smythe_stop(ch); } void TTool::smythePulse(TBeing *ch, TObj *o) { TTool *forge = NULL, *anvil = NULL; int percent; int movemod = ::number(10,25); int movebonus = ::number(1,((ch->getSkillValue(SKILL_SMYTHE) / 10))); const int HEATING_TIME = 3; // sanity check if ((getToolType() != TOOL_HAMMER) || !smythe_tools_in_room(ch->in_room, &forge, &anvil) || (ch->getPosition() < POSITION_RESTING)) { smythe_stop(ch); return; } if (movebonus > movemod) { movebonus = 5; } if (ch->getRace() == RACE_DWARF) { ch->addToMove(-movemod); ch->addToMove(movebonus); ch->addToMove(4); } else { ch->addToMove(-movemod); ch->addToMove(movebonus); } if (ch->getMove() < 10) { act("You are much too tired to continue repairing $p.", FALSE, ch, o, this, TO_CHAR); act("$n stops repairing, and wipes sweat from $s brow.", FALSE, ch, o, this, TO_ROOM); ch->stopTask(); return; } if (ch->task->status < HEATING_TIME) { if (!ch->task->status) { act("$n allows $p to heat in $P.", FALSE, ch, o, forge, TO_ROOM); act("You allow $p to heat in $P.", FALSE, ch, o, forge, TO_CHAR); } else { act("$n continues to let $p heat in $P.", FALSE, ch, o, forge, TO_ROOM); act("You continue to let $p heat in $P.", FALSE, ch, o, forge, TO_CHAR); } ch->task->status++; } else if (ch->task->status == HEATING_TIME) { act("$n removes $p from $P, as it glows red hot.", FALSE, ch, o, forge, TO_ROOM); act("You remove $p from $P, as it glows red hot.", FALSE, ch, o, forge, TO_CHAR); ch->task->status++; } else { act("$n pounds $p on an anvil with $s hammer.", FALSE, ch, o, 0, TO_ROOM); act("You pound $p on an anvil with your hammer.", FALSE, ch, o, 0, TO_CHAR); addToToolUses(-1); if (getToolUses() <= 0) { ch->sendTo("Your %s breaks due to overuse.\n\r", fname(name).c_str()); act("$n looks startled as $e breaks $P while hammering.", FALSE, ch, o, this, TO_ROOM); makeScraps(); ch->stopTask(); delete this; return; } if (o->getMaxStructPoints() <= o->getStructPoints()) { act("$n finishes repairing $p and proudly smiles.", FALSE, ch, o, forge, TO_ROOM); act("You finish repairing $p and smile triumphantly.", FALSE, ch, o, forge, TO_CHAR); act("You let $p cool down.", FALSE, ch, o, 0, TO_CHAR); act("$n lets $p cool down.", FALSE, ch, o, 0, TO_ROOM); ch->stopTask(); return; } if ((percent = ::number(1, 101)) != 101) // 101 is complete failure percent -= ch->getDexReaction() * 3; if (percent < ch->getSkillValue(SKILL_SMYTHE)) o->addToStructPoints(1); else o->addToStructPoints(-1); if (o->getStructPoints() <= 1) { act("$n screws up repairing $p and utterly destroys it.", FALSE, ch, o, forge, TO_ROOM); act("You screw up repairing $p and utterly destroy it.", FALSE, ch, o, forge, TO_CHAR); makeScraps(); ch->stopTask(); delete o; return; } // task can continue forever, so don't bother decrementing the timer } } int task_smythe(TBeing *ch, cmdTypeT cmd, const char *, int pulse, TRoom *, TObj *) { TThing *w = NULL; TObj *o = dynamic_cast<TObj *>(ch->heldInSecHand()); int learning; // sanity check if (ch->isLinkdead() || (ch->in_room < 0) || !o || !isname(ch->task->orig_arg, o->name)) { smythe_stop(ch); return FALSE; // returning FALSE lets command be interpreted } if (ch->utilityTaskCommand(cmd)) return FALSE; switch (cmd) { case CMD_TASK_CONTINUE: if (!(w = ch->heldInPrimHand())) { smythe_stop(ch); return FALSE; // returning FALSE lets command be interpreted } if (ch->task->status) { learning = ch->getSkillValue(SKILL_SMYTHE); ch->task->calcNextUpdate(pulse, 2 * PULSE_MOBACT); if (bSuccess(ch, learning, SKILL_SMYTHE)) { w->smythePulse(ch, o); } else if (!(::number(0,1))) act("$n examines $p carefully.", FALSE, ch, o, 0, TO_ROOM); act("You carefully examine $p.", FALSE, ch, o, 0, TO_CHAR); return FALSE; } else { ch->task->calcNextUpdate(pulse, 2 * PULSE_MOBACT); w->smythePulse(ch, o); // w may be invalid here return FALSE; } case CMD_ABORT: case CMD_STOP: act("You stop trying to repair $p.", FALSE, ch, o, 0, TO_CHAR); ch->sendTo("Isn't there a professional around here somewhere?\n\r"); act("$n stops repairing $p.", FALSE, ch, o, 0, TO_ROOM); if (ch->task->status > 0) { act("You let $p cool down.", FALSE, ch, o, 0, TO_CHAR); act("$n lets $p cool down.", FALSE, ch, o, 0, TO_ROOM); } ch->stopTask(); break; case CMD_TASK_FIGHTING: ch->sendTo("You are unable to continue repairing while under attack!\n\r"); ch->stopTask(); break; default: if (cmd < MAX_CMD_LIST) warn_busy(ch); break; // eat the command } return TRUE; } <|endoftext|>
<commit_before>/********************************************************************** * $Id$ * * GEOS - Geometry Engine Open Source * http://geos.refractions.net * * Copyright (C) 2001-2002 Vivid Solutions Inc. * Copyright (C) 2005 Refractions Research Inc. * * This is free software; you can redistribute and/or modify it under * the terms of the GNU Lesser General Public Licence as published * by the Free Software Foundation. * See the COPYING file for more information. * **********************************************************************/ #include <cassert> #include <vector> #include <geos/opOverlay.h> // FIXME: reduce this include #include <geos/operation/buffer/BufferSubgraph.h> #include <geos/geom/Envelope.h> #include <geos/geomgraph/Node.h> #include <geos/geomgraph/DirectedEdge.h> #ifndef GEOS_DEBUG #define GEOS_DEBUG 0 #endif using namespace std; using namespace geos::geomgraph; using namespace geos::noding; using namespace geos::algorithm; using namespace geos::operation::overlay; using namespace geos::geom; namespace geos { namespace operation { // geos.operation namespace buffer { // geos.operation.buffer // Argument is unused BufferSubgraph::BufferSubgraph(CGAlgorithms *cga): rightMostCoord(NULL), env(NULL) { } BufferSubgraph::~BufferSubgraph() { delete env; } /** * Creates the subgraph consisting of all edges reachable from this node. * Finds the edges in the graph and the rightmost coordinate. * * @param node a node to start the graph traversal from */ void BufferSubgraph::create(Node *node) { addReachable(node); finder.findEdge(&dirEdgeList); rightMostCoord=&(finder.getCoordinate()); } /** * Adds all nodes and edges reachable from this node to the subgraph. * Uses an explicit stack to avoid a large depth of recursion. * * @param node a node known to be in the subgraph */ void BufferSubgraph::addReachable(Node *startNode) { vector<Node*> nodeStack; nodeStack.push_back(startNode); while (!nodeStack.empty()) { Node *node=nodeStack.back(); nodeStack.pop_back(); add(node, &nodeStack); } } /** * Adds the argument node and all its out edges to the subgraph * @param node the node to add * @param nodeStack the current set of nodes being traversed */ void BufferSubgraph::add(Node *node, vector<Node*> *nodeStack) { node->setVisited(true); nodes.push_back(node); EdgeEndStar *ees=node->getEdges(); EdgeEndStar::iterator it=ees->begin(); EdgeEndStar::iterator endIt=ees->end(); for( ; it!=endIt; ++it) { DirectedEdge *de=(DirectedEdge*) (*it); dirEdgeList.push_back(de); DirectedEdge *sym=de->getSym(); Node *symNode=sym->getNode(); /** * NOTE: this is a depth-first traversal of the graph. * This will cause a large depth of recursion. * It might be better to do a breadth-first traversal. */ if (! symNode->isVisited()) nodeStack->push_back(symNode); } } void BufferSubgraph::clearVisitedEdges() { for(unsigned int i=0; i<dirEdgeList.size(); ++i) { DirectedEdge *de=dirEdgeList[i]; de->setVisited(false); } } void BufferSubgraph::computeDepth(int outsideDepth) { clearVisitedEdges(); // find an outside edge to assign depth to DirectedEdge *de=finder.getEdge(); #if GEOS_DEBUG cerr<<"outside depth: "<<outsideDepth<<endl; #endif //Node *n=de->getNode(); //Label *label=de->getLabel(); // right side of line returned by finder is on the outside de->setEdgeDepths(Position::RIGHT, outsideDepth); copySymDepths(de); //computeNodeDepth(n, de); computeDepths(de); } void BufferSubgraph::computeNodeDepth(Node *n) // throw(TopologyException *) { // find a visited dirEdge to start at DirectedEdge *startEdge=NULL; DirectedEdgeStar *ees=(DirectedEdgeStar *)n->getEdges(); EdgeEndStar::iterator endIt=ees->end(); EdgeEndStar::iterator it=ees->begin(); for(; it!=endIt; ++it) { DirectedEdge *de=(DirectedEdge*)*it; if (de->isVisited() || de->getSym()->isVisited()) { startEdge=de; break; } } // MD - testing Result: breaks algorithm //if (startEdge==null) return; assert(startEdge!=NULL); // unable to find edge to compute depths at n->getCoordinate() ees->computeDepths(startEdge); // copy depths to sym edges for(it=ees->begin(); it!=endIt; ++it) { DirectedEdge *de=(DirectedEdge*) (*it); de->setVisited(true); copySymDepths(de); } } void BufferSubgraph::copySymDepths(DirectedEdge *de) { DirectedEdge *sym=de->getSym(); sym->setDepth(Position::LEFT, de->getDepth(Position::RIGHT)); sym->setDepth(Position::RIGHT, de->getDepth(Position::LEFT)); #if GEOS_DEBUG cerr<<"copySymDepths: "<<de->getDepth(Position::LEFT)<<", "<<de->getDepth(Position::RIGHT)<<endl; #endif } /** * Find all edges whose depths indicates that they are in the result area(s). * Since we want polygon shells to be * oriented CW, choose dirEdges with the interior of the result on the RHS. * Mark them as being in the result. * Interior Area edges are the result of dimensional collapses. * They do not form part of the result area boundary. */ void BufferSubgraph::findResultEdges() { #if GEOS_DEBUG cerr<<"BufferSubgraph::findResultEdges got "<<dirEdgeList.size()<<" edges"<<endl; #endif for(unsigned int i=0; i<dirEdgeList.size(); ++i) { DirectedEdge *de=dirEdgeList[i]; /** * Select edges which have an interior depth on the RHS * and an exterior depth on the LHS. * Note that because of weird rounding effects there may be * edges which have negative depths! Negative depths * count as "outside". */ // <FIX> - handle negative depths #if GEOS_DEBUG cerr<<" dirEdge "<<i<<": depth right:"<<de->getDepth(Position::RIGHT)<<endl; #endif if ( de->getDepth(Position::RIGHT)>=1 && de->getDepth(Position::LEFT)<=0 && !de->isInteriorAreaEdge()) { de->setInResult(true); #if GEOS_DEBUG cerr<<" in result"<<endl; #endif } } } /** * BufferSubgraphs are compared on the x-value of their rightmost Coordinate. * This defines a partial ordering on the graphs such that: * * g1 >= g2 <==> Ring(g2) does not contain Ring(g1) * * where Polygon(g) is the buffer polygon that is built from g. * * This relationship is used to sort the BufferSubgraphs so that shells are * guaranteed to be built before holes. */ int BufferSubgraph::compareTo(BufferSubgraph *graph) { if (rightMostCoord->x<graph->rightMostCoord->x) { return -1; } if (rightMostCoord->x>graph->rightMostCoord->x) { return 1; } return 0; } /** * Compute depths for all dirEdges via breadth-first traversal of * nodes in graph. * * @param startEdge edge to start processing with */ // <FIX> MD - use iteration & queue rather than recursion, for speed and robustness void BufferSubgraph::computeDepths(DirectedEdge *startEdge) { //vector<Node*> nodesVisited; //Used to be a HashSet set<Node *>nodesVisited; vector<Node*> nodeQueue; Node *startNode=startEdge->getNode(); nodeQueue.push_back(startNode); //nodesVisited.push_back(startNode); nodesVisited.insert(startNode); startEdge->setVisited(true); while (! nodeQueue.empty()) { //System.out.println(nodes.size() + " queue: " + nodeQueue.size()); Node *n=nodeQueue[0]; nodeQueue.erase(nodeQueue.begin()); nodesVisited.insert(n); // compute depths around node, starting at this edge since it has depths assigned computeNodeDepth(n); // add all adjacent nodes to process queue, // unless the node has been visited already EdgeEndStar *ees=n->getEdges(); EdgeEndStar::iterator endIt=ees->end(); EdgeEndStar::iterator it=ees->begin(); for(; it!=endIt; ++it) { DirectedEdge *de=(DirectedEdge*) (*it); DirectedEdge *sym=de->getSym(); if (sym->isVisited()) continue; Node *adjNode=sym->getNode(); //if (! contains(nodesVisited,adjNode)) if(nodesVisited.insert(adjNode).second) { nodeQueue.push_back(adjNode); //nodesVisited.insert(adjNode); } } } } bool BufferSubgraph::contains(set<Node*>&nodeSet, Node *node) { //bool result=false; if ( nodeSet.find(node) != nodeSet.end() ) return true; return false; } Envelope * BufferSubgraph::getEnvelope() { if (env == NULL) { env = new Envelope(); unsigned int size = dirEdgeList.size(); for(unsigned int i=0; i<size; ++i) { DirectedEdge *dirEdge=dirEdgeList[i]; const CoordinateSequence *pts = dirEdge->getEdge()->getCoordinates(); int n = pts->getSize()-1; for (int j=0; j<n; ++j) { env->expandToInclude(pts->getAt(j)); } } } return env; } std::ostream& operator<< (std::ostream& os, const BufferSubgraph& bs) { os << "BufferSubgraph[" << &bs << "] " << bs.nodes.size() << " nodes, " << bs.dirEdgeList.size() << " directed edges" << std::endl; for (unsigned int i=0, n=bs.nodes.size(); i<n; i++) os << " Node " << i << ": " << bs.nodes[i]->print() << std::endl; for (unsigned int i=0, n=bs.dirEdgeList.size(); i<n; i++) { os << " DirEdge " << i << ": " << std::endl << bs.dirEdgeList[i]->printEdge() << std::endl; } return os; } } // namespace geos.operation.buffer } // namespace geos.operation } // namespace geos /********************************************************************** * $Log$ * Revision 1.27 2006/03/14 17:10:14 strk * cleanups * * Revision 1.26 2006/03/14 14:16:52 strk * operator<< for BufferSubgraph, more debugging calls * * Revision 1.25 2006/03/14 00:19:40 strk * opBuffer.h split, streamlined headers in some (not all) files in operation/buffer/ * * Revision 1.24 2006/03/06 19:40:47 strk * geos::util namespace. New GeometryCollection::iterator interface, many cleanups. * * Revision 1.23 2006/03/03 10:46:21 strk * Removed 'using namespace' from headers, added missing headers in .cpp files, removed useless includes in headers (bug#46) * * Revision 1.22 2006/03/02 12:12:01 strk * Renamed DEBUG macros to GEOS_DEBUG, all wrapped in #ifndef block to allow global override (bug#43) * * Revision 1.21 2006/02/19 19:46:49 strk * Packages <-> namespaces mapping for most GEOS internal code (uncomplete, but working). Dir-level libs for index/ subdirs. * * Revision 1.20 2005/11/29 00:48:35 strk * Removed edgeList cache from EdgeEndRing. edgeMap is enough. * Restructured iterated access by use of standard ::iterator abstraction * with scoped typedefs. * * Revision 1.19 2005/11/08 20:12:44 strk * Memory overhead reductions in buffer operations. * **********************************************************************/ <commit_msg>comments cleanup, changed computeDepths to use a list<> rather then a vector (performance related)<commit_after>/********************************************************************** * $Id$ * * GEOS - Geometry Engine Open Source * http://geos.refractions.net * * Copyright (C) 2001-2002 Vivid Solutions Inc. * Copyright (C) 2005 Refractions Research Inc. * * This is free software; you can redistribute and/or modify it under * the terms of the GNU Lesser General Public Licence as published * by the Free Software Foundation. * See the COPYING file for more information. * ********************************************************************** * * Last port: operation/buffer/BufferSubgraph.java rev. 1.17 * **********************************************************************/ #include <cassert> #include <vector> #include <list> #include <geos/opOverlay.h> // FIXME: reduce this include #include <geos/operation/buffer/BufferSubgraph.h> #include <geos/geom/Envelope.h> #include <geos/geomgraph/Node.h> #include <geos/geomgraph/DirectedEdge.h> #ifndef GEOS_DEBUG #define GEOS_DEBUG 0 #endif using namespace std; using namespace geos::geomgraph; using namespace geos::noding; using namespace geos::algorithm; using namespace geos::operation::overlay; using namespace geos::geom; namespace geos { namespace operation { // geos.operation namespace buffer { // geos.operation.buffer // Argument is unused BufferSubgraph::BufferSubgraph(CGAlgorithms *cga): rightMostCoord(NULL), env(NULL) { } BufferSubgraph::~BufferSubgraph() { delete env; } /*public*/ void BufferSubgraph::create(Node *node) { addReachable(node); finder.findEdge(&dirEdgeList); rightMostCoord=&(finder.getCoordinate()); } /*private*/ void BufferSubgraph::addReachable(Node *startNode) { vector<Node*> nodeStack; nodeStack.push_back(startNode); while (!nodeStack.empty()) { Node *node=nodeStack.back(); nodeStack.pop_back(); add(node, &nodeStack); } } /*private*/ void BufferSubgraph::add(Node *node, vector<Node*> *nodeStack) { node->setVisited(true); nodes.push_back(node); EdgeEndStar *ees=node->getEdges(); EdgeEndStar::iterator it=ees->begin(); EdgeEndStar::iterator endIt=ees->end(); for( ; it!=endIt; ++it) { DirectedEdge *de=(DirectedEdge*) (*it); dirEdgeList.push_back(de); DirectedEdge *sym=de->getSym(); Node *symNode=sym->getNode(); /** * NOTE: this is a depth-first traversal of the graph. * This will cause a large depth of recursion. * It might be better to do a breadth-first traversal. */ if (! symNode->isVisited()) nodeStack->push_back(symNode); } } /*private*/ void BufferSubgraph::clearVisitedEdges() { for(unsigned int i=0; i<dirEdgeList.size(); ++i) { DirectedEdge *de=dirEdgeList[i]; de->setVisited(false); } } /*public*/ void BufferSubgraph::computeDepth(int outsideDepth) { clearVisitedEdges(); // find an outside edge to assign depth to DirectedEdge *de=finder.getEdge(); #if GEOS_DEBUG cerr<<"outside depth: "<<outsideDepth<<endl; #endif //Node *n=de->getNode(); //Label *label=de->getLabel(); // right side of line returned by finder is on the outside de->setEdgeDepths(Position::RIGHT, outsideDepth); copySymDepths(de); //computeNodeDepth(n, de); computeDepths(de); } void BufferSubgraph::computeNodeDepth(Node *n) // throw(TopologyException *) { // find a visited dirEdge to start at DirectedEdge *startEdge=NULL; DirectedEdgeStar *ees=(DirectedEdgeStar *)n->getEdges(); EdgeEndStar::iterator endIt=ees->end(); EdgeEndStar::iterator it=ees->begin(); for(; it!=endIt; ++it) { DirectedEdge *de=(DirectedEdge*)*it; if (de->isVisited() || de->getSym()->isVisited()) { startEdge=de; break; } } // MD - testing Result: breaks algorithm //if (startEdge==null) return; assert(startEdge!=NULL); // unable to find edge to compute depths at n->getCoordinate() ees->computeDepths(startEdge); // copy depths to sym edges for(it=ees->begin(); it!=endIt; ++it) { DirectedEdge *de=(DirectedEdge*) (*it); de->setVisited(true); copySymDepths(de); } } /*private*/ void BufferSubgraph::copySymDepths(DirectedEdge *de) { #if GEOS_DEBUG cerr << "copySymDepths: " << de->getDepth(Position::LEFT) << ", " << de->getDepth(Position::RIGHT) << endl; #endif DirectedEdge *sym=de->getSym(); sym->setDepth(Position::LEFT, de->getDepth(Position::RIGHT)); sym->setDepth(Position::RIGHT, de->getDepth(Position::LEFT)); } /*public*/ void BufferSubgraph::findResultEdges() { #if GEOS_DEBUG cerr<<"BufferSubgraph::findResultEdges got "<<dirEdgeList.size()<<" edges"<<endl; #endif for(unsigned int i=0; i<dirEdgeList.size(); ++i) { DirectedEdge *de=dirEdgeList[i]; /** * Select edges which have an interior depth on the RHS * and an exterior depth on the LHS. * Note that because of weird rounding effects there may be * edges which have negative depths! Negative depths * count as "outside". */ // <FIX> - handle negative depths #if GEOS_DEBUG cerr << " dirEdge "<<i<<": " << de->printEdge() << endl << " depth right: " << de->getDepth(Position::RIGHT) << endl << " depth left: " << de->getDepth(Position::LEFT) << endl << " interiorAreaEdge: " << de->isInteriorAreaEdge()<<endl; #endif if ( de->getDepth(Position::RIGHT)>=1 && de->getDepth(Position::LEFT)<=0 && !de->isInteriorAreaEdge()) { de->setInResult(true); #if GEOS_DEBUG cerr<<" IN RESULT"<<endl; #endif } } } /*public*/ int BufferSubgraph::compareTo(BufferSubgraph *graph) { if (rightMostCoord->x<graph->rightMostCoord->x) { return -1; } if (rightMostCoord->x>graph->rightMostCoord->x) { return 1; } return 0; } /*private*/ void BufferSubgraph::computeDepths(DirectedEdge *startEdge) { set<Node *> nodesVisited; list<Node*> nodeQueue; // Used to be a vector Node *startNode=startEdge->getNode(); nodeQueue.push_back(startNode); //nodesVisited.push_back(startNode); nodesVisited.insert(startNode); startEdge->setVisited(true); while (! nodeQueue.empty()) { //System.out.println(nodes.size() + " queue: " + nodeQueue.size()); Node *n=nodeQueue.front(); // [0]; //nodeQueue.erase(nodeQueue.begin()); nodeQueue.pop_front(); nodesVisited.insert(n); // compute depths around node, starting at this edge since it has depths assigned computeNodeDepth(n); // add all adjacent nodes to process queue, // unless the node has been visited already EdgeEndStar *ees=n->getEdges(); EdgeEndStar::iterator endIt=ees->end(); EdgeEndStar::iterator it=ees->begin(); for(; it!=endIt; ++it) { DirectedEdge *de=(DirectedEdge*) (*it); DirectedEdge *sym=de->getSym(); if (sym->isVisited()) continue; Node *adjNode=sym->getNode(); //if (! contains(nodesVisited,adjNode)) if(nodesVisited.insert(adjNode).second) { nodeQueue.push_back(adjNode); //nodesVisited.insert(adjNode); } } } } /*private*/ bool BufferSubgraph::contains(set<Node*>&nodeSet, Node *node) { //bool result=false; if ( nodeSet.find(node) != nodeSet.end() ) return true; return false; } /*public*/ Envelope * BufferSubgraph::getEnvelope() { if (env == NULL) { env = new Envelope(); unsigned int size = dirEdgeList.size(); for(unsigned int i=0; i<size; ++i) { DirectedEdge *dirEdge=dirEdgeList[i]; const CoordinateSequence *pts = dirEdge->getEdge()->getCoordinates(); int n = pts->getSize()-1; for (int j=0; j<n; ++j) { env->expandToInclude(pts->getAt(j)); } } } return env; } std::ostream& operator<< (std::ostream& os, const BufferSubgraph& bs) { os << "BufferSubgraph[" << &bs << "] " << bs.nodes.size() << " nodes, " << bs.dirEdgeList.size() << " directed edges" << std::endl; for (unsigned int i=0, n=bs.nodes.size(); i<n; i++) os << " Node " << i << ": " << bs.nodes[i]->print() << std::endl; for (unsigned int i=0, n=bs.dirEdgeList.size(); i<n; i++) { os << " DirEdge " << i << ": " << std::endl << bs.dirEdgeList[i]->printEdge() << std::endl; } return os; } } // namespace geos.operation.buffer } // namespace geos.operation } // namespace geos /********************************************************************** * $Log$ * Revision 1.28 2006/03/15 11:39:45 strk * comments cleanup, changed computeDepths to use a list<> rather then a vector (performance related) * * Revision 1.27 2006/03/14 17:10:14 strk * cleanups * * Revision 1.26 2006/03/14 14:16:52 strk * operator<< for BufferSubgraph, more debugging calls * * Revision 1.25 2006/03/14 00:19:40 strk * opBuffer.h split, streamlined headers in some (not all) files in operation/buffer/ * * Revision 1.24 2006/03/06 19:40:47 strk * geos::util namespace. New GeometryCollection::iterator interface, many cleanups. * * Revision 1.23 2006/03/03 10:46:21 strk * Removed 'using namespace' from headers, added missing headers in .cpp files, removed useless includes in headers (bug#46) * * Revision 1.22 2006/03/02 12:12:01 strk * Renamed DEBUG macros to GEOS_DEBUG, all wrapped in #ifndef block to allow global override (bug#43) * * Revision 1.21 2006/02/19 19:46:49 strk * Packages <-> namespaces mapping for most GEOS internal code (uncomplete, but working). Dir-level libs for index/ subdirs. * * Revision 1.20 2005/11/29 00:48:35 strk * Removed edgeList cache from EdgeEndRing. edgeMap is enough. * Restructured iterated access by use of standard ::iterator abstraction * with scoped typedefs. * * Revision 1.19 2005/11/08 20:12:44 strk * Memory overhead reductions in buffer operations. * **********************************************************************/ <|endoftext|>
<commit_before>// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "atomic_entry_ref.h" #include "buffer_type.hpp" #include <cassert> #include <cmath> namespace vespalib::datastore { namespace { constexpr float DEFAULT_ALLOC_GROW_FACTOR = 0.2; } void BufferTypeBase::CleanContext::extraBytesCleaned(size_t value) { assert(_extraUsedBytes >= value); assert(_extraHoldBytes >= value); _extraUsedBytes -= value; _extraHoldBytes -= value; } BufferTypeBase::BufferTypeBase(uint32_t arraySize, uint32_t minArrays, uint32_t maxArrays, uint32_t numArraysForNewBuffer, float allocGrowFactor) noexcept : _arraySize(arraySize), _minArrays(std::min(minArrays, maxArrays)), _maxArrays(maxArrays), _numArraysForNewBuffer(std::min(numArraysForNewBuffer, maxArrays)), _allocGrowFactor(allocGrowFactor), _holdBuffers(0), _holdUsedElems(0), _aggr_counts(), _active_buffers() { } BufferTypeBase::BufferTypeBase(uint32_t arraySize, uint32_t minArrays, uint32_t maxArrays) noexcept : BufferTypeBase(arraySize, minArrays, maxArrays, 0u, DEFAULT_ALLOC_GROW_FACTOR) { } BufferTypeBase::~BufferTypeBase() { assert(_holdBuffers == 0); assert(_holdUsedElems == 0); assert(_aggr_counts.empty()); assert(_active_buffers.empty()); } ElemCount BufferTypeBase::getReservedElements(uint32_t bufferId) const { return bufferId == 0 ? _arraySize : 0u; } void BufferTypeBase::onActive(uint32_t bufferId, ElemCount* usedElems, ElemCount* deadElems, void* buffer) { _aggr_counts.add_buffer(usedElems, deadElems); assert(std::find(_active_buffers.begin(), _active_buffers.end(), bufferId) == _active_buffers.end()); _active_buffers.emplace_back(bufferId); size_t reservedElems = getReservedElements(bufferId); if (reservedElems != 0u) { initializeReservedElements(buffer, reservedElems); *usedElems = reservedElems; *deadElems = reservedElems; } } void BufferTypeBase::onHold(uint32_t buffer_id, const ElemCount* usedElems, const ElemCount* deadElems) { ++_holdBuffers; auto itr = std::find(_active_buffers.begin(), _active_buffers.end(), buffer_id); assert(itr != _active_buffers.end()); _active_buffers.erase(itr); _aggr_counts.remove_buffer(usedElems, deadElems); _holdUsedElems += *usedElems; } void BufferTypeBase::onFree(ElemCount usedElems) { --_holdBuffers; assert(_holdUsedElems >= usedElems); _holdUsedElems -= usedElems; } void BufferTypeBase::resume_primary_buffer(uint32_t buffer_id, ElemCount* used_elems, ElemCount* dead_elems) { auto itr = std::find(_active_buffers.begin(), _active_buffers.end(), buffer_id); assert(itr != _active_buffers.end()); _active_buffers.erase(itr); _active_buffers.emplace_back(buffer_id); _aggr_counts.remove_buffer(used_elems, dead_elems); _aggr_counts.add_buffer(used_elems, dead_elems); } const alloc::MemoryAllocator* BufferTypeBase::get_memory_allocator() const { return nullptr; } void BufferTypeBase::clampMaxArrays(uint32_t maxArrays) { _maxArrays = std::min(_maxArrays, maxArrays); _minArrays = std::min(_minArrays, _maxArrays); _numArraysForNewBuffer = std::min(_numArraysForNewBuffer, _maxArrays); } size_t BufferTypeBase::calcArraysToAlloc(uint32_t bufferId, ElemCount elemsNeeded, bool resizing) const { size_t reservedElems = getReservedElements(bufferId); BufferCounts last_bc; BufferCounts bc; if (resizing) { if (!_aggr_counts.empty()) { last_bc = _aggr_counts.last_buffer(); } } bc = _aggr_counts.all_buffers(); assert((bc.used_elems % _arraySize) == 0); assert((bc.dead_elems % _arraySize) == 0); assert(bc.used_elems >= bc.dead_elems); size_t neededArrays = (elemsNeeded + (resizing ? last_bc.used_elems : reservedElems) + _arraySize - 1) / _arraySize; size_t liveArrays = (bc.used_elems - bc.dead_elems) / _arraySize; size_t growArrays = (liveArrays * _allocGrowFactor); size_t usedArrays = last_bc.used_elems / _arraySize; size_t wantedArrays = std::max((resizing ? usedArrays : 0u) + growArrays, static_cast<size_t>(_minArrays)); size_t result = wantedArrays; if (result < neededArrays) { result = neededArrays; } if (result > _maxArrays) { result = _maxArrays; } assert(result >= neededArrays); return result; } uint32_t BufferTypeBase::get_scaled_num_arrays_for_new_buffer() const { uint32_t active_buffers_count = get_active_buffers_count(); if (active_buffers_count <= 1u || _numArraysForNewBuffer == 0u) { return _numArraysForNewBuffer; } double scale_factor = std::pow(1.0 + _allocGrowFactor, active_buffers_count - 1); double scaled_result = _numArraysForNewBuffer * scale_factor; if (scaled_result >= _maxArrays) { return _maxArrays; } return scaled_result; } BufferTypeBase::AggregatedBufferCounts::AggregatedBufferCounts() : _counts() { } void BufferTypeBase::AggregatedBufferCounts::add_buffer(const ElemCount* used_elems, const ElemCount* dead_elems) { for (const auto& elem : _counts) { assert(elem.used_ptr != used_elems); assert(elem.dead_ptr != dead_elems); } _counts.emplace_back(used_elems, dead_elems); } void BufferTypeBase::AggregatedBufferCounts::remove_buffer(const ElemCount* used_elems, const ElemCount* dead_elems) { auto itr = std::find_if(_counts.begin(), _counts.end(), [=](const auto& elem){ return elem.used_ptr == used_elems; }); assert(itr != _counts.end()); assert(itr->dead_ptr == dead_elems); _counts.erase(itr); } BufferTypeBase::BufferCounts BufferTypeBase::AggregatedBufferCounts::last_buffer() const { BufferCounts result; assert(!_counts.empty()); const auto& last = _counts.back(); result.used_elems += *last.used_ptr; result.dead_elems += *last.dead_ptr; return result; } BufferTypeBase::BufferCounts BufferTypeBase::AggregatedBufferCounts::all_buffers() const { BufferCounts result; for (const auto& elem : _counts) { result.used_elems += *elem.used_ptr; result.dead_elems += *elem.dead_ptr; } return result; } template class BufferType<char>; template class BufferType<uint8_t>; template class BufferType<uint32_t>; template class BufferType<uint64_t>; template class BufferType<int32_t>; template class BufferType<std::string>; template class BufferType<AtomicEntryRef>; } <commit_msg>Add include to get declaration of std::find<commit_after>// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "atomic_entry_ref.h" #include "buffer_type.hpp" #include <algorithm> #include <cassert> #include <cmath> namespace vespalib::datastore { namespace { constexpr float DEFAULT_ALLOC_GROW_FACTOR = 0.2; } void BufferTypeBase::CleanContext::extraBytesCleaned(size_t value) { assert(_extraUsedBytes >= value); assert(_extraHoldBytes >= value); _extraUsedBytes -= value; _extraHoldBytes -= value; } BufferTypeBase::BufferTypeBase(uint32_t arraySize, uint32_t minArrays, uint32_t maxArrays, uint32_t numArraysForNewBuffer, float allocGrowFactor) noexcept : _arraySize(arraySize), _minArrays(std::min(minArrays, maxArrays)), _maxArrays(maxArrays), _numArraysForNewBuffer(std::min(numArraysForNewBuffer, maxArrays)), _allocGrowFactor(allocGrowFactor), _holdBuffers(0), _holdUsedElems(0), _aggr_counts(), _active_buffers() { } BufferTypeBase::BufferTypeBase(uint32_t arraySize, uint32_t minArrays, uint32_t maxArrays) noexcept : BufferTypeBase(arraySize, minArrays, maxArrays, 0u, DEFAULT_ALLOC_GROW_FACTOR) { } BufferTypeBase::~BufferTypeBase() { assert(_holdBuffers == 0); assert(_holdUsedElems == 0); assert(_aggr_counts.empty()); assert(_active_buffers.empty()); } ElemCount BufferTypeBase::getReservedElements(uint32_t bufferId) const { return bufferId == 0 ? _arraySize : 0u; } void BufferTypeBase::onActive(uint32_t bufferId, ElemCount* usedElems, ElemCount* deadElems, void* buffer) { _aggr_counts.add_buffer(usedElems, deadElems); assert(std::find(_active_buffers.begin(), _active_buffers.end(), bufferId) == _active_buffers.end()); _active_buffers.emplace_back(bufferId); size_t reservedElems = getReservedElements(bufferId); if (reservedElems != 0u) { initializeReservedElements(buffer, reservedElems); *usedElems = reservedElems; *deadElems = reservedElems; } } void BufferTypeBase::onHold(uint32_t buffer_id, const ElemCount* usedElems, const ElemCount* deadElems) { ++_holdBuffers; auto itr = std::find(_active_buffers.begin(), _active_buffers.end(), buffer_id); assert(itr != _active_buffers.end()); _active_buffers.erase(itr); _aggr_counts.remove_buffer(usedElems, deadElems); _holdUsedElems += *usedElems; } void BufferTypeBase::onFree(ElemCount usedElems) { --_holdBuffers; assert(_holdUsedElems >= usedElems); _holdUsedElems -= usedElems; } void BufferTypeBase::resume_primary_buffer(uint32_t buffer_id, ElemCount* used_elems, ElemCount* dead_elems) { auto itr = std::find(_active_buffers.begin(), _active_buffers.end(), buffer_id); assert(itr != _active_buffers.end()); _active_buffers.erase(itr); _active_buffers.emplace_back(buffer_id); _aggr_counts.remove_buffer(used_elems, dead_elems); _aggr_counts.add_buffer(used_elems, dead_elems); } const alloc::MemoryAllocator* BufferTypeBase::get_memory_allocator() const { return nullptr; } void BufferTypeBase::clampMaxArrays(uint32_t maxArrays) { _maxArrays = std::min(_maxArrays, maxArrays); _minArrays = std::min(_minArrays, _maxArrays); _numArraysForNewBuffer = std::min(_numArraysForNewBuffer, _maxArrays); } size_t BufferTypeBase::calcArraysToAlloc(uint32_t bufferId, ElemCount elemsNeeded, bool resizing) const { size_t reservedElems = getReservedElements(bufferId); BufferCounts last_bc; BufferCounts bc; if (resizing) { if (!_aggr_counts.empty()) { last_bc = _aggr_counts.last_buffer(); } } bc = _aggr_counts.all_buffers(); assert((bc.used_elems % _arraySize) == 0); assert((bc.dead_elems % _arraySize) == 0); assert(bc.used_elems >= bc.dead_elems); size_t neededArrays = (elemsNeeded + (resizing ? last_bc.used_elems : reservedElems) + _arraySize - 1) / _arraySize; size_t liveArrays = (bc.used_elems - bc.dead_elems) / _arraySize; size_t growArrays = (liveArrays * _allocGrowFactor); size_t usedArrays = last_bc.used_elems / _arraySize; size_t wantedArrays = std::max((resizing ? usedArrays : 0u) + growArrays, static_cast<size_t>(_minArrays)); size_t result = wantedArrays; if (result < neededArrays) { result = neededArrays; } if (result > _maxArrays) { result = _maxArrays; } assert(result >= neededArrays); return result; } uint32_t BufferTypeBase::get_scaled_num_arrays_for_new_buffer() const { uint32_t active_buffers_count = get_active_buffers_count(); if (active_buffers_count <= 1u || _numArraysForNewBuffer == 0u) { return _numArraysForNewBuffer; } double scale_factor = std::pow(1.0 + _allocGrowFactor, active_buffers_count - 1); double scaled_result = _numArraysForNewBuffer * scale_factor; if (scaled_result >= _maxArrays) { return _maxArrays; } return scaled_result; } BufferTypeBase::AggregatedBufferCounts::AggregatedBufferCounts() : _counts() { } void BufferTypeBase::AggregatedBufferCounts::add_buffer(const ElemCount* used_elems, const ElemCount* dead_elems) { for (const auto& elem : _counts) { assert(elem.used_ptr != used_elems); assert(elem.dead_ptr != dead_elems); } _counts.emplace_back(used_elems, dead_elems); } void BufferTypeBase::AggregatedBufferCounts::remove_buffer(const ElemCount* used_elems, const ElemCount* dead_elems) { auto itr = std::find_if(_counts.begin(), _counts.end(), [=](const auto& elem){ return elem.used_ptr == used_elems; }); assert(itr != _counts.end()); assert(itr->dead_ptr == dead_elems); _counts.erase(itr); } BufferTypeBase::BufferCounts BufferTypeBase::AggregatedBufferCounts::last_buffer() const { BufferCounts result; assert(!_counts.empty()); const auto& last = _counts.back(); result.used_elems += *last.used_ptr; result.dead_elems += *last.dead_ptr; return result; } BufferTypeBase::BufferCounts BufferTypeBase::AggregatedBufferCounts::all_buffers() const { BufferCounts result; for (const auto& elem : _counts) { result.used_elems += *elem.used_ptr; result.dead_elems += *elem.dead_ptr; } return result; } template class BufferType<char>; template class BufferType<uint8_t>; template class BufferType<uint32_t>; template class BufferType<uint64_t>; template class BufferType<int32_t>; template class BufferType<std::string>; template class BufferType<AtomicEntryRef>; } <|endoftext|>
<commit_before>/** * This file is part of the "libfnord" project * Copyright (c) 2015 Paul Asmuth * * FnordMetric is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License v3.0. 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 <thread> #include <fnord-eventdb/Table.h> #include <fnord-base/logging.h> #include <fnord-base/io/fileutil.h> #include <fnord-msg/MessageDecoder.h> #include <fnord-msg/MessageEncoder.h> #include <fnord-msg/MessagePrinter.h> #include "fnord-sstable/sstablereader.h" #include "fnord-sstable/sstablewriter.h" #include "fnord-sstable/SSTableColumnSchema.h" #include "fnord-sstable/SSTableColumnReader.h" #include "fnord-sstable/SSTableColumnWriter.h" #include "fnord-cstable/CSTableWriter.h" #include "fnord-cstable/CSTableReader.h" #include "fnord-cstable/CSTableBuilder.h" namespace fnord { namespace eventdb { RefPtr<Table> Table::open( const String& table_name, const String& replica_id, const String& db_path, const msg::MessageSchema& schema) { RefPtr<TableGeneration> head(new TableGeneration); uint64_t seq = 0; return new Table(table_name, replica_id, db_path, schema, seq, head); } Table::Table( const String& table_name, const String& replica_id, const String& db_path, const msg::MessageSchema& schema, uint64_t head_sequence, RefPtr<TableGeneration> snapshot) : name_(table_name), replica_id_(replica_id), db_path_(db_path), schema_(schema), seq_(head_sequence + 1), head_(snapshot) { arenas_.emplace_front(new TableArena(seq_, rnd_.hex128())); } void Table::addRecords(const Buffer& records) { for (size_t offset = 0; offset < records.size(); ) { msg::MessageObject msg; msg::MessageDecoder::decode(records, schema_, &msg, &offset); addRecord(msg); } } void Table::addRecord(const msg::MessageObject& record) { std::unique_lock<std::mutex> lk(mutex_); arenas_.front()->addRecord(record); ++seq_; } size_t Table::commit() { std::unique_lock<std::mutex> lk(mutex_); auto arena = arenas_.front(); const auto& records = arena->records(); if (records.size() == 0) { return 0; } arenas_.emplace_front(new TableArena(seq_, rnd_.hex128())); lk.unlock(); auto t = std::thread(std::bind(&Table::writeTable, this, arena)); t.detach(); return records.size(); } void Table::writeTable(RefPtr<TableArena> arena) { TableChunkRef chunk; chunk.replica_id = replica_id_; chunk.chunk_id = arena->chunkID(); chunk.start_sequence = arena->startSequence(); chunk.num_records = arena->records().size(); auto chunkname = StringUtil::format( "$0.$1.$2", name_, replica_id_, chunk.chunk_id); fnord::logInfo("fnord.evdb", "Writing chunk: $0", chunkname); auto filename = FileUtil::joinPaths(db_path_, chunkname); { cstable::CSTableBuilder cstable(&schema_); auto sstable = sstable::SSTableWriter::create( filename + ".sst~", sstable::IndexProvider{}, nullptr, 0); uint64_t seq = chunk.start_sequence; for (const auto& r : arena->records()) { cstable.addRecord(r); Buffer buf; msg::MessageEncoder::encode(r, schema_, &buf); sstable->appendRow(&seq, sizeof(seq), buf.data(), buf.size()); ++seq; } cstable.write(filename + ".cst~"); sstable->finalize(); } FileUtil::mv(filename + ".sst~", filename + ".sst"); FileUtil::mv(filename + ".cst~", filename + ".cst"); addChunk(chunk); } void Table::addChunk(TableChunkRef chunk) { std::unique_lock<std::mutex> lk(mutex_); auto next = head_->clone(); next->generation++; next->chunks.emplace_back(chunk); head_ = next; writeSnapshot(); } // precondition: mutex_ must be locked void Table::writeSnapshot() { auto snapname = StringUtil::format( "$0.$1.$2", name_, replica_id_, head_->generation); fnord::logInfo("fnord.evdb", "Writing snapshot: $0", snapname); auto filename = FileUtil::joinPaths(db_path_, snapname + ".idx"); auto file = File::openFile(filename + "~", File::O_CREATE | File::O_WRITE); Buffer buf; head_->encode(&buf); file.write(buf); FileUtil::mv(filename + "~", filename); } const String& Table::name() const { return name_; } RefPtr<TableSnapshot> Table::getSnapshot() { std::unique_lock<std::mutex> lk(mutex_); return new TableSnapshot(head_, arenas_); } RefPtr<TableGeneration> TableGeneration::clone() const { RefPtr<TableGeneration> c(new TableGeneration); c->table_name = table_name; c->generation = generation; c->chunks = chunks; return c; } void TableGeneration::encode(Buffer* buf) { } TableSnapshot::TableSnapshot( RefPtr<TableGeneration> _head, List<RefPtr<TableArena>> _arenas) : head(_head), arenas(_arenas) {} } // namespace eventdb } // namespace fnord <commit_msg>TableGeneration::encode<commit_after>/** * This file is part of the "libfnord" project * Copyright (c) 2015 Paul Asmuth * * FnordMetric is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License v3.0. 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 <thread> #include <fnord-eventdb/Table.h> #include <fnord-base/logging.h> #include <fnord-base/io/fileutil.h> #include <fnord-base/util/binarymessagewriter.h> #include <fnord-msg/MessageDecoder.h> #include <fnord-msg/MessageEncoder.h> #include <fnord-msg/MessagePrinter.h> #include "fnord-sstable/sstablereader.h" #include "fnord-sstable/sstablewriter.h" #include "fnord-sstable/SSTableColumnSchema.h" #include "fnord-sstable/SSTableColumnReader.h" #include "fnord-sstable/SSTableColumnWriter.h" #include "fnord-cstable/CSTableWriter.h" #include "fnord-cstable/CSTableReader.h" #include "fnord-cstable/CSTableBuilder.h" namespace fnord { namespace eventdb { RefPtr<Table> Table::open( const String& table_name, const String& replica_id, const String& db_path, const msg::MessageSchema& schema) { RefPtr<TableGeneration> head(new TableGeneration); head->generation = 0; head->table_name = table_name; uint64_t last_seq = 0; return new Table(table_name, replica_id, db_path, schema, last_seq, head); } Table::Table( const String& table_name, const String& replica_id, const String& db_path, const msg::MessageSchema& schema, uint64_t head_sequence, RefPtr<TableGeneration> snapshot) : name_(table_name), replica_id_(replica_id), db_path_(db_path), schema_(schema), seq_(head_sequence + 1), head_(snapshot) { arenas_.emplace_front(new TableArena(seq_, rnd_.hex128())); } void Table::addRecords(const Buffer& records) { for (size_t offset = 0; offset < records.size(); ) { msg::MessageObject msg; msg::MessageDecoder::decode(records, schema_, &msg, &offset); addRecord(msg); } } void Table::addRecord(const msg::MessageObject& record) { std::unique_lock<std::mutex> lk(mutex_); arenas_.front()->addRecord(record); ++seq_; } size_t Table::commit() { std::unique_lock<std::mutex> lk(mutex_); auto arena = arenas_.front(); const auto& records = arena->records(); if (records.size() == 0) { return 0; } arenas_.emplace_front(new TableArena(seq_, rnd_.hex128())); lk.unlock(); auto t = std::thread(std::bind(&Table::writeTable, this, arena)); t.detach(); return records.size(); } void Table::writeTable(RefPtr<TableArena> arena) { TableChunkRef chunk; chunk.replica_id = replica_id_; chunk.chunk_id = arena->chunkID(); chunk.start_sequence = arena->startSequence(); chunk.num_records = arena->records().size(); auto chunkname = StringUtil::format( "$0.$1.$2", name_, replica_id_, chunk.chunk_id); fnord::logInfo("fnord.evdb", "Writing chunk: $0", chunkname); auto filename = FileUtil::joinPaths(db_path_, chunkname); { cstable::CSTableBuilder cstable(&schema_); auto sstable = sstable::SSTableWriter::create( filename + ".sst~", sstable::IndexProvider{}, nullptr, 0); uint64_t seq = chunk.start_sequence; for (const auto& r : arena->records()) { cstable.addRecord(r); Buffer buf; msg::MessageEncoder::encode(r, schema_, &buf); sstable->appendRow(&seq, sizeof(seq), buf.data(), buf.size()); ++seq; } cstable.write(filename + ".cst~"); sstable->finalize(); } FileUtil::mv(filename + ".sst~", filename + ".sst"); FileUtil::mv(filename + ".cst~", filename + ".cst"); addChunk(chunk); } void Table::addChunk(TableChunkRef chunk) { std::unique_lock<std::mutex> lk(mutex_); auto next = head_->clone(); next->generation++; next->chunks.emplace_back(chunk); head_ = next; writeSnapshot(); } // precondition: mutex_ must be locked void Table::writeSnapshot() { auto snapname = StringUtil::format( "$0.$1.$2", name_, replica_id_, head_->generation); fnord::logInfo("fnord.evdb", "Writing snapshot: $0", snapname); auto filename = FileUtil::joinPaths(db_path_, snapname + ".idx"); auto file = File::openFile(filename + "~", File::O_CREATE | File::O_WRITE); Buffer buf; head_->encode(&buf); file.write(buf); FileUtil::mv(filename + "~", filename); } const String& Table::name() const { return name_; } RefPtr<TableSnapshot> Table::getSnapshot() { std::unique_lock<std::mutex> lk(mutex_); return new TableSnapshot(head_, arenas_); } RefPtr<TableGeneration> TableGeneration::clone() const { RefPtr<TableGeneration> c(new TableGeneration); c->table_name = table_name; c->generation = generation; c->chunks = chunks; return c; } void TableGeneration::encode(Buffer* buf) { util::BinaryMessageWriter writer; writer.appendUInt8(0x01); writer.appendUInt64(generation); writer.appendUInt32(table_name.size()); writer.append(table_name.data(), table_name.size()); writer.appendUInt32(chunks.size()); for (const auto& c : chunks) { writer.appendUInt16(c.replica_id.size()); writer.append(c.replica_id.data(), c.replica_id.size()); writer.appendUInt16(c.chunk_id.size()); writer.append(c.chunk_id.data(), c.chunk_id.size()); writer.appendUInt64(c.start_sequence); writer.appendUInt64(c.num_records); } buf->append(writer.data(), writer.size()); } TableSnapshot::TableSnapshot( RefPtr<TableGeneration> _head, List<RefPtr<TableArena>> _arenas) : head(_head), arenas(_arenas) {} } // namespace eventdb } // namespace fnord <|endoftext|>
<commit_before>#include "BatteryProfile.hpp" #include <algorithm> using namespace std; // 2008,2011 battery: http://www.thunderpowerrc.com/Products/1350ProlitePlusPower/TP1350-4SP25_2 // 2015 battery: http://www.hobbyking.com/%E2%80%A6/__9942__ZIPPY_Flightmax_2200mAh_3S1P_40C.html // // based on the li-po discharge curve from SparkFun // https://learn.sparkfun.com/tutorials/battery-technologies/lithium-polymer const BatteryProfile RJ2008BatteryProfile( 10, 12.67, 0.00, 13.17, 0.07, 13.40, 0.19, 13.48, 0.30, 13.56, 0.42, 13.67, 0.53, 13.79, 0.65, 13.86, 0.77, 14.13, 0.88, 14.90, 1.00 ); #warning Battery profile for 2015 robot isnt calibrated yet - it always reports 0% charged const BatteryProfile RJ2015BatteryProfile( 2, 0, 0.00, 100, 0.00 ); BatteryProfile::BatteryProfile(int count, double v1, double l1, ...) { // first data point _voltages.push_back(v1); _chargeLevels.push_back(l1); // get the rest of the data points from the variadic list va_list vals; va_start(vals, l1); for (int i = 0; i < 2*(count - 1); i++) { _voltages.push_back(va_arg(vals, double)); _chargeLevels.push_back(va_arg(vals, double)); } va_end(vals); } BatteryProfile::BatteryProfile(const std::vector<double> &voltages, const std::vector<double> &chargeLevels) : _voltages(voltages), _chargeLevels(chargeLevels) {} double BatteryProfile::getChargeLevel(double voltage) const { // lower_bound does a binary search and returns an iterator pointing to the first element // that is not less than @voltage, or end() if no element exists auto nextBiggest = lower_bound(_voltages.begin(), _voltages.end(), voltage); if (nextBiggest == _voltages.end()) { return 1; // this voltage is off the charts! } else if (nextBiggest == _voltages.begin()) { return 0; // this voltage is super low } else { int i = nextBiggest - _voltages.begin(); double after = *nextBiggest; double before = *(nextBiggest-1); // slope of this line segment double m = (_chargeLevels[i] - _chargeLevels[i-1]) / (after - before); // y1-y2 = m(x1-x2) // m(x1-x2) + y2 = y1 return m*(voltage - before) + _chargeLevels[i-1]; } } <commit_msg>Adjusts 2008 battery profile to be closer to accurate.<commit_after>#include "BatteryProfile.hpp" #include <algorithm> using namespace std; // 2008,2011 battery: http://www.thunderpowerrc.com/Products/1350ProlitePlusPower/TP1350-4SP25_2 // 2015 battery: http://www.hobbyking.com/%E2%80%A6/__9942__ZIPPY_Flightmax_2200mAh_3S1P_40C.html // // based on the li-po discharge curve from SparkFun // https://learn.sparkfun.com/tutorials/battery-technologies/lithium-polymer const BatteryProfile RJ2008BatteryProfile( 3, 14.20, 0.20, 15.10, 0.50, 16.00, 1.00 ); #warning Battery profile for 2015 robot isnt calibrated yet - it always reports 0% charged const BatteryProfile RJ2015BatteryProfile( 2, 0, 0.00, 100, 0.00 ); BatteryProfile::BatteryProfile(int count, double v1, double l1, ...) { // first data point _voltages.push_back(v1); _chargeLevels.push_back(l1); // get the rest of the data points from the variadic list va_list vals; va_start(vals, l1); for (int i = 0; i < 2*(count - 1); i++) { _voltages.push_back(va_arg(vals, double)); _chargeLevels.push_back(va_arg(vals, double)); } va_end(vals); } BatteryProfile::BatteryProfile(const std::vector<double> &voltages, const std::vector<double> &chargeLevels) : _voltages(voltages), _chargeLevels(chargeLevels) {} double BatteryProfile::getChargeLevel(double voltage) const { // lower_bound does a binary search and returns an iterator pointing to the first element // that is not less than @voltage, or end() if no element exists auto nextBiggest = lower_bound(_voltages.begin(), _voltages.end(), voltage); if (nextBiggest == _voltages.end()) { return 1; // this voltage is off the charts! } else if (nextBiggest == _voltages.begin()) { return 0; // this voltage is super low } else { int i = nextBiggest - _voltages.begin(); double after = *nextBiggest; double before = *(nextBiggest-1); // slope of this line segment double m = (_chargeLevels[i] - _chargeLevels[i-1]) / (after - before); // y1-y2 = m(x1-x2) // m(x1-x2) + y2 = y1 return m*(voltage - before) + _chargeLevels[i-1]; } } <|endoftext|>
<commit_before>// Include GLEW #ifndef __GL_GLEW_H_INCLUDED #define __GL_GLEW_H_INCLUDED #include <GL/glew.h> #endif // Include GLFW #ifndef __GLFW3_H_INCLUDED #define __GLFW3_H_INCLUDED #include <glfw3.h> #endif // Include GLM #ifndef __GLM_GLM_HPP_INCLUDED #define __GLM_GLM_HPP_INCLUDED #include <glm/glm.hpp> #endif #include "globals.hpp" extern GLFWwindow* window; // The "extern" keyword here is to access the variable "window" declared in tutorialXXX.cpp. This is a hack to keep the tutorials simple. Please avoid this. #include <glm/gtc/matrix_transform.hpp> using namespace glm; #ifndef __COMMON_GLOBALS_HPP_INCLUDED #define __COMMON_GLOBALS_HPP_INCLUDED #include "common/globals.hpp" #endif #include "controls.hpp" #define WINDOW_WIDTH 1600 #define WINDOW_HEIGHT 900 #define PI 3.14159265359f glm::mat4 ViewMatrix; glm::mat4 ProjectionMatrix; namespace controls { glm::mat4 getViewMatrix() { return ViewMatrix; } glm::mat4 getProjectionMatrix() { return ProjectionMatrix; } GLfloat speed = 5.0f; // 5 units / second GLfloat turbo_factor = 3.0f; // 5 units / second GLfloat mouseSpeed = 0.005f; void computeMatricesFromInputs() { // glfwGetTime is called only once, the first time this function is called static double lastTime = glfwGetTime(); // Compute time difference between current and last frame double currentTime = glfwGetTime(); float deltaTime = float(currentTime - lastTime); // Get mouse position double xpos, ypos; glfwGetCursorPos(window, &xpos, &ypos); // Reset mouse position for next frame glfwSetCursorPos(window, WINDOW_WIDTH/2, WINDOW_HEIGHT/2); if (hasMouseEverMoved || (abs(xpos) > 0.0001) || (abs(ypos) > 0.0001)) { hasMouseEverMoved = true; // Compute new orientation horizontalAngle += mouseSpeed * GLfloat(WINDOW_WIDTH/2 - xpos); if (is_invert_mouse_in_use) { // invert mouse. verticalAngle -= mouseSpeed * GLfloat(WINDOW_HEIGHT/2 - ypos); } else { // don't invert mouse. verticalAngle += mouseSpeed * GLfloat(WINDOW_HEIGHT/2 - ypos); } } // Direction : Spherical coordinates to Cartesian coordinates conversion glm::vec3 direction( cos(verticalAngle) * sin(horizontalAngle), sin(verticalAngle), cos(verticalAngle) * cos(horizontalAngle) ); // Right vector glm::vec3 right = glm::vec3( sin(horizontalAngle - PI/2.0f), 0, cos(horizontalAngle - PI/2.0f) ); // Up vector glm::vec3 up = glm::cross(right, direction); GLfloat temp_speed; // Turbo. if ((glfwGetKey(window, GLFW_KEY_LEFT_CONTROL) == GLFW_PRESS) || (glfwGetKey(window, GLFW_KEY_RIGHT_CONTROL) == GLFW_PRESS)) { temp_speed = turbo_factor * speed; } else { temp_speed = speed; } // Move forward if (glfwGetKey(window, GLFW_KEY_UP) == GLFW_PRESS) { position += direction * deltaTime * temp_speed; } // Move backward if (glfwGetKey(window, GLFW_KEY_DOWN) == GLFW_PRESS) { position -= direction * deltaTime * temp_speed; } // Strafe right if (glfwGetKey(window, GLFW_KEY_RIGHT) == GLFW_PRESS) { position += right * deltaTime * temp_speed; } // Strafe left if (glfwGetKey(window, GLFW_KEY_LEFT) == GLFW_PRESS) { position -= right * deltaTime * temp_speed; } // Move up. if (glfwGetKey(window, GLFW_KEY_SPACE) == GLFW_PRESS) { position.y += deltaTime * temp_speed; } // Move down. if (glfwGetKey(window, GLFW_KEY_ENTER) == GLFW_PRESS) { position.y -= deltaTime * temp_speed; } // Move west. if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS) { position.x -= deltaTime * temp_speed; } // Move east. if (glfwGetKey(window, GLFW_KEY_E) == GLFW_PRESS) { position.x += deltaTime * temp_speed; } // Move north. if (glfwGetKey(window, GLFW_KEY_N) == GLFW_PRESS) { position.z += deltaTime * temp_speed; } // Move south. if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS) { position.z -= deltaTime * temp_speed; } GLfloat FoV = initialFoV;// - 5 * glfwGetMouseWheel(); // Now GLFW 3 requires setting up a callback for this. It's a bit too complicated for this beginner's tutorial, so it's disabled instead. if (glfwGetKey(window, GLFW_KEY_I) == GLFW_PRESS) { if (is_key_I_released) { if (is_invert_mouse_in_use) { is_invert_mouse_in_use = false; } else { is_invert_mouse_in_use = true; } } } else { is_key_I_released = true; } // Projection matrix : 45° Field of View, 4:3 ratio, display range : 0.1 unit <-> 100 units ProjectionMatrix = glm::perspective(FoV, 4.0f / 3.0f, 0.1f, 500.0f); // Camera matrix ViewMatrix = glm::lookAt( position, // Camera is here position+direction, // and looks here : at the same position, plus "direction" up // Head is up (set to 0,-1,0 to look upside-down) ); // For the next frame, the "last time" will be "now" lastTime = currentTime; } } <commit_msg>Näkyvyyttä nostettu 500m -> 5000m.<commit_after>// Include GLEW #ifndef __GL_GLEW_H_INCLUDED #define __GL_GLEW_H_INCLUDED #include <GL/glew.h> #endif // Include GLFW #ifndef __GLFW3_H_INCLUDED #define __GLFW3_H_INCLUDED #include <glfw3.h> #endif // Include GLM #ifndef __GLM_GLM_HPP_INCLUDED #define __GLM_GLM_HPP_INCLUDED #include <glm/glm.hpp> #endif #include "globals.hpp" extern GLFWwindow* window; // The "extern" keyword here is to access the variable "window" declared in tutorialXXX.cpp. This is a hack to keep the tutorials simple. Please avoid this. #include <glm/gtc/matrix_transform.hpp> using namespace glm; #ifndef __COMMON_GLOBALS_HPP_INCLUDED #define __COMMON_GLOBALS_HPP_INCLUDED #include "common/globals.hpp" #endif #include "controls.hpp" #define WINDOW_WIDTH 1600 #define WINDOW_HEIGHT 900 #define PI 3.14159265359f glm::mat4 ViewMatrix; glm::mat4 ProjectionMatrix; namespace controls { glm::mat4 getViewMatrix() { return ViewMatrix; } glm::mat4 getProjectionMatrix() { return ProjectionMatrix; } GLfloat speed = 5.0f; // 5 units / second GLfloat turbo_factor = 3.0f; // 5 units / second GLfloat mouseSpeed = 0.005f; void computeMatricesFromInputs() { // glfwGetTime is called only once, the first time this function is called static double lastTime = glfwGetTime(); // Compute time difference between current and last frame double currentTime = glfwGetTime(); float deltaTime = float(currentTime - lastTime); // Get mouse position double xpos, ypos; glfwGetCursorPos(window, &xpos, &ypos); // Reset mouse position for next frame glfwSetCursorPos(window, WINDOW_WIDTH/2, WINDOW_HEIGHT/2); if (hasMouseEverMoved || (abs(xpos) > 0.0001) || (abs(ypos) > 0.0001)) { hasMouseEverMoved = true; // Compute new orientation horizontalAngle += mouseSpeed * GLfloat(WINDOW_WIDTH/2 - xpos); if (is_invert_mouse_in_use) { // invert mouse. verticalAngle -= mouseSpeed * GLfloat(WINDOW_HEIGHT/2 - ypos); } else { // don't invert mouse. verticalAngle += mouseSpeed * GLfloat(WINDOW_HEIGHT/2 - ypos); } } // Direction : Spherical coordinates to Cartesian coordinates conversion glm::vec3 direction( cos(verticalAngle) * sin(horizontalAngle), sin(verticalAngle), cos(verticalAngle) * cos(horizontalAngle) ); // Right vector glm::vec3 right = glm::vec3( sin(horizontalAngle - PI/2.0f), 0, cos(horizontalAngle - PI/2.0f) ); // Up vector glm::vec3 up = glm::cross(right, direction); GLfloat temp_speed; // Turbo. if ((glfwGetKey(window, GLFW_KEY_LEFT_CONTROL) == GLFW_PRESS) || (glfwGetKey(window, GLFW_KEY_RIGHT_CONTROL) == GLFW_PRESS)) { temp_speed = turbo_factor * speed; } else { temp_speed = speed; } // Move forward if (glfwGetKey(window, GLFW_KEY_UP) == GLFW_PRESS) { position += direction * deltaTime * temp_speed; } // Move backward if (glfwGetKey(window, GLFW_KEY_DOWN) == GLFW_PRESS) { position -= direction * deltaTime * temp_speed; } // Strafe right if (glfwGetKey(window, GLFW_KEY_RIGHT) == GLFW_PRESS) { position += right * deltaTime * temp_speed; } // Strafe left if (glfwGetKey(window, GLFW_KEY_LEFT) == GLFW_PRESS) { position -= right * deltaTime * temp_speed; } // Move up. if (glfwGetKey(window, GLFW_KEY_SPACE) == GLFW_PRESS) { position.y += deltaTime * temp_speed; } // Move down. if (glfwGetKey(window, GLFW_KEY_ENTER) == GLFW_PRESS) { position.y -= deltaTime * temp_speed; } // Move west. if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS) { position.x -= deltaTime * temp_speed; } // Move east. if (glfwGetKey(window, GLFW_KEY_E) == GLFW_PRESS) { position.x += deltaTime * temp_speed; } // Move north. if (glfwGetKey(window, GLFW_KEY_N) == GLFW_PRESS) { position.z += deltaTime * temp_speed; } // Move south. if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS) { position.z -= deltaTime * temp_speed; } GLfloat FoV = initialFoV;// - 5 * glfwGetMouseWheel(); // Now GLFW 3 requires setting up a callback for this. It's a bit too complicated for this beginner's tutorial, so it's disabled instead. if (glfwGetKey(window, GLFW_KEY_I) == GLFW_PRESS) { if (is_key_I_released) { if (is_invert_mouse_in_use) { is_invert_mouse_in_use = false; } else { is_invert_mouse_in_use = true; } } } else { is_key_I_released = true; } // Projection matrix : 45° Field of View, 4:3 ratio, display range : 0.1 unit <-> 100 units ProjectionMatrix = glm::perspective(FoV, 4.0f / 3.0f, 0.1f, 5000.0f); // Camera matrix ViewMatrix = glm::lookAt( position, // Camera is here position+direction, // and looks here : at the same position, plus "direction" up // Head is up (set to 0,-1,0 to look upside-down) ); // For the next frame, the "last time" will be "now" lastTime = currentTime; } } <|endoftext|>
<commit_before>#include "ctc.h" #include "logger.h" PrefixTree::Node::Node() : inTok (0), parent (NULL), nStates (0), outLen (0) { } PrefixTree::Node::Node (const PrefixTree& tree, const Node* parent, InputToken inTok) : inTok (inTok), parent (parent), nStates (tree.nStates), outLen (tree.outLen) { } void PrefixTree::Node::fill (const PrefixTree& tree) { cellStorage = vector<double> (nCells(), -numeric_limits<double>::infinity()); logPrefixProb = -numeric_limits<double>::infinity(); if (!parent) seqCell (0, 0) = 0; for (OutputIndex outPos = 0; outPos <= outLen; ++outPos) { const OutputToken outTok = outPos ? tree.output[outPos-1] : OutputTokenizer::emptyToken(); for (StateIndex d = 0; d < nStates; ++d) { LogThisAt(9,"d="<<d<<": "); const EvaluatedMachineState& state = tree.machine.state[d]; double& ll = seqCell (outPos, d); if (parent && state.incoming.count (inTok)) { const auto& incoming = state.incoming.at (inTok); if (outPos) accumulateSeqCell (ll, incoming, *parent, outTok, outPos - 1); accumulateSeqCell (ll, incoming, *parent, OutputTokenizer::emptyToken(), outPos); } if (state.incoming.count (InputTokenizer::emptyToken())) { const auto& incoming = state.incoming.at (InputTokenizer::emptyToken()); if (outPos) accumulateSeqCell (ll, incoming, *this, outTok, outPos - 1); accumulateSeqCell (ll, incoming, *this, OutputTokenizer::emptyToken(), outPos); } LogThisAt(8,"seqCell("<<outPos<<","<<d<<")="<<ll<<endl); } // looping over d AND prevState seems inefficient! Could precompute sumInTrans*outTrans for each outTok for (StateIndex d = 0; d < nStates; ++d) { double& ll = prefixCell (outPos, d); ll = seqCell (outPos, d); if (outPos) { const EvaluatedMachineState& state = tree.machine.state[d]; for (const auto& i_ostm: state.incoming) { const EvaluatedMachineState::OutStateTransMap& outStateTransMap = i_ostm.second; if (outStateTransMap.count (outTok)) for (const auto& st: outStateTransMap.at (outTok)) { const EvaluatedMachineState::Trans& trans = st.second; for (StateIndex prevState = 0; prevState < nStates; ++prevState) { const double prevCell = prefixCell (outPos - 1, prevState); const double logEmitWeight = prevCell + tree.sumInTrans[prevState][st.first] + trans.logWeight; log_accum_exp (ll, logEmitWeight); LogThisAt(9,"prefixCell("<<outPos<<","<<d<<") logsum+= "<<prevCell<<" + "<<tree.sumInTrans[prevState][st.first]<<" + "<<trans.logWeight<<" ("<<prevState<<"->"<<st.first<<"->"<<d<<")"<<endl); } } } } LogThisAt(8,"prefixCell("<<outPos<<","<<d<<")="<<ll<<endl); } } for (StateIndex d = 0; d < nStates; ++d) { log_accum_exp (logPrefixProb, prefixCell(outLen,d) + tree.sumInTrans[d][tree.nStates - 1]); LogThisAt(9,"logPrefixProb logsum+= "<<prefixCell(outLen,d)<<" + "<<tree.sumInTrans[d][tree.nStates - 1]<<" ("<<d<<"->end)"<<endl); } if (parent && logPrefixProb > parent->logPrefixProb) Warn ("LogP(%s*)=%g rose from LogP(%s*)=%g", to_string_join(tree.seqTraceback(this),"").c_str(), logPrefixProb, to_string_join(tree.seqTraceback(parent),"").c_str(), parent->logPrefixProb); } double PrefixTree::Node::logSeqProb() const { return seqCell (outLen, nStates - 1); } PrefixTree::PrefixTree (const EvaluatedMachine& machine, const vguard<OutputSymbol>& outSym) : machine (machine), sumInTrans (machine.sumInTrans()), output (machine.outputTokenizer.tokenize (outSym)), outLen (output.size()), nStates (machine.nStates()), bestSeqNode (NULL), bestLogSeqProb (-numeric_limits<double>::infinity()) { addNode (NULL, machine.inputTokenizer.emptyToken()); const InputToken inToks = machine.inputTokenizer.tok2sym.size() - 1; while (!nodeQueue.empty()) { Node* parent = bestPrefixNode(); LogThisAt (5, "Nodes: " << nodeStore.size() << " Extending " << to_string_join(bestPrefix(),"") << "* (" << parent->logPrefixProb << ")" << endl); if (parent->logPrefixProb > bestLogSeqProb) { nodeQueue.pop(); double norm = -numeric_limits<double>::infinity(); for (InputToken inTok = 1; inTok <= inToks; ++inTok) log_accum_exp (norm, addNode(parent,inTok)->logPrefixProb); LogThisAt (6, "log(Sum_x(P(Sx*)) / P(S*)) = " << (norm - exp(parent->logPrefixProb)) << endl); } else break; } } PrefixTree::Node* PrefixTree::addNode (const Node* parent, InputToken inTok) { nodeStore.push_back (Node (*this, parent, inTok)); Node* nodePtr = &nodeStore.back(); LogThisAt (6, "Adding node " << (parent ? to_string_join (seqTraceback (nodePtr), "") : string("<root>")) << endl); nodePtr->fill (*this); if (nodePtr->logPrefixProb > bestLogSeqProb) nodeQueue.push (nodePtr); const double logNodeSeqProb = nodePtr->logSeqProb(); if (logNodeSeqProb > bestLogSeqProb) { bestSeqNode = nodePtr; bestLogSeqProb = logNodeSeqProb; LogThisAt (4, "Nodes: " << nodeStore.size() << " Best sequence so far: " << to_string_join (bestSeq(), "") << " (" << bestLogSeqProb << ")" << endl); } LogThisAt (7, "logP(seq)=" << logNodeSeqProb << " logP(seq*)=" << nodePtr->logPrefixProb << " seq: " << to_string_join (seqTraceback (nodePtr), "") << endl); return nodePtr; } vguard<InputSymbol> PrefixTree::seqTraceback (const Node* node) const { list<InputToken> inSeq; while (node && node->inTok) { inSeq.push_back (node->inTok); node = node->parent; } return machine.inputTokenizer.detokenize (vguard<InputToken> (inSeq.rbegin(), inSeq.rend())); } <commit_msg>added a debugging message further exposing prefix prob calculation bug (fixed)<commit_after>#include "ctc.h" #include "logger.h" PrefixTree::Node::Node() : inTok (0), parent (NULL), nStates (0), outLen (0) { } PrefixTree::Node::Node (const PrefixTree& tree, const Node* parent, InputToken inTok) : inTok (inTok), parent (parent), nStates (tree.nStates), outLen (tree.outLen) { } void PrefixTree::Node::fill (const PrefixTree& tree) { cellStorage = vector<double> (nCells(), -numeric_limits<double>::infinity()); logPrefixProb = -numeric_limits<double>::infinity(); if (!parent) seqCell (0, 0) = 0; for (OutputIndex outPos = 0; outPos <= outLen; ++outPos) { const OutputToken outTok = outPos ? tree.output[outPos-1] : OutputTokenizer::emptyToken(); for (StateIndex d = 0; d < nStates; ++d) { LogThisAt(9,"d="<<d<<": "); const EvaluatedMachineState& state = tree.machine.state[d]; double& ll = seqCell (outPos, d); if (parent && state.incoming.count (inTok)) { const auto& incoming = state.incoming.at (inTok); if (outPos) accumulateSeqCell (ll, incoming, *parent, outTok, outPos - 1); accumulateSeqCell (ll, incoming, *parent, OutputTokenizer::emptyToken(), outPos); } if (state.incoming.count (InputTokenizer::emptyToken())) { const auto& incoming = state.incoming.at (InputTokenizer::emptyToken()); if (outPos) accumulateSeqCell (ll, incoming, *this, outTok, outPos - 1); accumulateSeqCell (ll, incoming, *this, OutputTokenizer::emptyToken(), outPos); } LogThisAt(8,"seqCell("<<outPos<<","<<d<<")="<<ll<<endl); } // looping over d AND prevState seems inefficient! Could precompute sumInTrans*outTrans for each outTok for (StateIndex d = 0; d < nStates; ++d) { double& ll = prefixCell (outPos, d); ll = seqCell (outPos, d); if (outPos) { const EvaluatedMachineState& state = tree.machine.state[d]; for (const auto& i_ostm: state.incoming) { const EvaluatedMachineState::OutStateTransMap& outStateTransMap = i_ostm.second; if (outStateTransMap.count (outTok)) for (const auto& st: outStateTransMap.at (outTok)) { const EvaluatedMachineState::Trans& trans = st.second; for (StateIndex prevState = 0; prevState < nStates; ++prevState) { const double prevCell = prefixCell (outPos - 1, prevState); const double logEmitWeight = prevCell + tree.sumInTrans[prevState][st.first] + trans.logWeight; log_accum_exp (ll, logEmitWeight); LogThisAt(9,"prefixCell("<<outPos<<","<<d<<") logsum+= "<<prevCell<<" + "<<tree.sumInTrans[prevState][st.first]<<" + "<<trans.logWeight<<" ("<<prevState<<"->"<<st.first<<"->"<<d<<")"<<endl); } } } } LogThisAt(8,"prefixCell("<<outPos<<","<<d<<")="<<ll<<endl); } } for (StateIndex d = 0; d < nStates; ++d) { log_accum_exp (logPrefixProb, prefixCell(outLen,d) + tree.sumInTrans[d][tree.nStates - 1]); LogThisAt(9,"logPrefixProb logsum+= "<<prefixCell(outLen,d)<<" + "<<tree.sumInTrans[d][tree.nStates - 1]<<" ("<<d<<"->end)"<<endl); } if (parent && logPrefixProb > parent->logPrefixProb) Warn ("LogP(%s*)=%g rose from LogP(%s*)=%g", to_string_join(tree.seqTraceback(this),"").c_str(), logPrefixProb, to_string_join(tree.seqTraceback(parent),"").c_str(), parent->logPrefixProb); } double PrefixTree::Node::logSeqProb() const { return seqCell (outLen, nStates - 1); } PrefixTree::PrefixTree (const EvaluatedMachine& machine, const vguard<OutputSymbol>& outSym) : machine (machine), sumInTrans (machine.sumInTrans()), output (machine.outputTokenizer.tokenize (outSym)), outLen (output.size()), nStates (machine.nStates()), bestSeqNode (NULL), bestLogSeqProb (-numeric_limits<double>::infinity()) { addNode (NULL, machine.inputTokenizer.emptyToken()); const InputToken inToks = machine.inputTokenizer.tok2sym.size() - 1; while (!nodeQueue.empty()) { Node* parent = bestPrefixNode(); LogThisAt (5, "Nodes: " << nodeStore.size() << " Extending " << to_string_join(bestPrefix(),"") << "* (" << parent->logPrefixProb << ")" << endl); if (parent->logPrefixProb > bestLogSeqProb) { nodeQueue.pop(); double norm = parent->logSeqProb(); for (InputToken inTok = 1; inTok <= inToks; ++inTok) log_accum_exp (norm, addNode(parent,inTok)->logPrefixProb); LogThisAt (6, "log(Sum_x(P(S|Sx*)) / P(S*)) = " << (norm - exp(parent->logPrefixProb)) << endl); } else break; } } PrefixTree::Node* PrefixTree::addNode (const Node* parent, InputToken inTok) { nodeStore.push_back (Node (*this, parent, inTok)); Node* nodePtr = &nodeStore.back(); LogThisAt (6, "Adding node " << (parent ? to_string_join (seqTraceback (nodePtr), "") : string("<root>")) << endl); nodePtr->fill (*this); if (nodePtr->logPrefixProb > bestLogSeqProb) nodeQueue.push (nodePtr); const double logNodeSeqProb = nodePtr->logSeqProb(); if (logNodeSeqProb > bestLogSeqProb) { bestSeqNode = nodePtr; bestLogSeqProb = logNodeSeqProb; LogThisAt (4, "Nodes: " << nodeStore.size() << " Best sequence so far: " << to_string_join (bestSeq(), "") << " (" << bestLogSeqProb << ")" << endl); } LogThisAt (7, "logP(seq)=" << logNodeSeqProb << " logP(seq*)=" << nodePtr->logPrefixProb << " seq: " << to_string_join (seqTraceback (nodePtr), "") << endl); return nodePtr; } vguard<InputSymbol> PrefixTree::seqTraceback (const Node* node) const { list<InputToken> inSeq; while (node && node->inTok) { inSeq.push_back (node->inTok); node = node->parent; } return machine.inputTokenizer.detokenize (vguard<InputToken> (inSeq.rbegin(), inSeq.rend())); } <|endoftext|>
<commit_before>#include "xchainer/context.h" #include <cstdlib> #include <future> #include <gtest/gtest.h> #include <nonstd/optional.hpp> #include "xchainer/backend.h" #include "xchainer/device.h" namespace xchainer { namespace { TEST(ContextTest, Ctor) { EXPECT_NO_THROW(Context()); } TEST(Context, GetBackend) { Context ctx; Backend& backend = ctx.GetBackend("native"); EXPECT_EQ(&backend, &ctx.GetBackend("native")); } TEST(Context, BackendNotFound) { Context ctx; EXPECT_THROW(ctx.GetBackend("something_that_does_not_exist"), BackendError); } TEST(Context, GetDevice) { Context ctx; Device& device = ctx.GetDevice({"native", 0}); EXPECT_EQ(&device, &ctx.GetDevice({"native:0"})); } TEST(ContextTest, DefaultContext) { SetGlobalDefaultContext(nullptr); SetDefaultContext(nullptr); ASSERT_THROW(GetDefaultContext(), XchainerError); Context ctx; SetGlobalDefaultContext(nullptr); SetDefaultContext(&ctx); ASSERT_EQ(&ctx, &GetDefaultContext()); Context global_ctx; SetGlobalDefaultContext(&global_ctx); SetDefaultContext(nullptr); ASSERT_EQ(&global_ctx, &GetDefaultContext()); SetGlobalDefaultContext(&global_ctx); SetDefaultContext(&ctx); ASSERT_EQ(&ctx, &GetDefaultContext()); } TEST(ContextTest, GlobalDefaultContext) { SetGlobalDefaultContext(nullptr); ASSERT_THROW(GetGlobalDefaultContext(), XchainerError); Context ctx; SetGlobalDefaultContext(&ctx); ASSERT_EQ(&ctx, &GetGlobalDefaultContext()); } TEST(ContextTest, ThreadLocal) { Context ctx; SetDefaultContext(&ctx); Context ctx2; auto future = std::async(std::launch::async, [&ctx2] { SetDefaultContext(&ctx2); return &GetDefaultContext(); }); ASSERT_NE(&GetDefaultContext(), future.get()); } TEST(ContextTest, ContextScopeCtor) { SetGlobalDefaultContext(nullptr); SetDefaultContext(nullptr); Context ctx1; { // ContextScope should work even if default context is not set ContextScope scope(ctx1); EXPECT_EQ(&ctx1, &GetDefaultContext()); } ASSERT_THROW(GetDefaultContext(), XchainerError); SetDefaultContext(&ctx1); { Context ctx2; ContextScope scope(ctx2); EXPECT_EQ(&ctx2, &GetDefaultContext()); } ASSERT_EQ(&ctx1, &GetDefaultContext()); { ContextScope scope; EXPECT_EQ(&ctx1, &GetDefaultContext()); Context ctx2; SetDefaultContext(&ctx2); } ASSERT_EQ(&ctx1, &GetDefaultContext()); Context ctx2; { ContextScope scope(ctx2); scope.Exit(); EXPECT_EQ(&ctx1, &GetDefaultContext()); SetDefaultContext(&ctx2); // not recovered here because the scope has already existed } ASSERT_EQ(&ctx2, &GetDefaultContext()); } TEST(ContextTest, UserDefinedBackend) { ::setenv("XCHAINER_PATH", XCHAINER_TEST_DIR "/context_testdata", 1); Context ctx; Backend& backend0 = ctx.GetBackend("backend0"); EXPECT_EQ("backend0", backend0.GetName()); Backend& backend0_2 = ctx.GetBackend("backend0"); EXPECT_EQ(&backend0, &backend0_2); Backend& backend1 = ctx.GetBackend("backend1"); EXPECT_EQ("backend1", backend1.GetName()); Device& device0 = ctx.GetDevice(std::string("backend0:0")); EXPECT_EQ(&backend0, &device0.backend()); } TEST(ContextTest, GetBackendOnDefaultContext) { Context ctx; SetDefaultContext(&ctx); Backend& backend = GetBackend("native"); // xchainer::GetBackend EXPECT_EQ(&ctx, &backend.context()); EXPECT_EQ("native", backend.GetName()); } TEST(ContextTest, GetDeviceOnDefaultContext0) { Context ctx; SetDefaultContext(&ctx); // xchainer::GetDevice with device_name Device& device = GetDevice({"native:0"}); EXPECT_EQ(&ctx, &device.backend().context()); EXPECT_EQ("native:0", device.name()); } TEST(ContextTest, GetDeviceOnDefaultContext1) { Context ctx; SetDefaultContext(&ctx); // xchainer::GetDevice with backend_name and index Device& device = GetDevice({"native", 0}); EXPECT_EQ(&ctx, &device.backend().context()); EXPECT_EQ("native:0", device.name()); } } // namespace } // namespace xchainer <commit_msg>Remove duplicate test<commit_after>#include "xchainer/context.h" #include <cstdlib> #include <future> #include <gtest/gtest.h> #include <nonstd/optional.hpp> #include "xchainer/backend.h" #include "xchainer/device.h" namespace xchainer { namespace { TEST(ContextTest, Ctor) { EXPECT_NO_THROW(Context()); } TEST(Context, GetBackend) { Context ctx; Backend& backend = ctx.GetBackend("native"); EXPECT_EQ(&backend, &ctx.GetBackend("native")); } TEST(Context, BackendNotFound) { Context ctx; EXPECT_THROW(ctx.GetBackend("something_that_does_not_exist"), BackendError); } TEST(Context, GetDevice) { Context ctx; Device& device = ctx.GetDevice({"native", 0}); EXPECT_EQ(&device, &ctx.GetDevice({"native:0"})); } TEST(ContextTest, DefaultContext) { SetGlobalDefaultContext(nullptr); SetDefaultContext(nullptr); ASSERT_THROW(GetDefaultContext(), XchainerError); Context ctx; SetGlobalDefaultContext(nullptr); SetDefaultContext(&ctx); ASSERT_EQ(&ctx, &GetDefaultContext()); Context global_ctx; SetGlobalDefaultContext(&global_ctx); SetDefaultContext(nullptr); ASSERT_EQ(&global_ctx, &GetDefaultContext()); SetGlobalDefaultContext(&global_ctx); SetDefaultContext(&ctx); ASSERT_EQ(&ctx, &GetDefaultContext()); } TEST(ContextTest, GlobalDefaultContext) { SetGlobalDefaultContext(nullptr); ASSERT_THROW(GetGlobalDefaultContext(), XchainerError); Context ctx; SetGlobalDefaultContext(&ctx); ASSERT_EQ(&ctx, &GetGlobalDefaultContext()); } TEST(ContextTest, ThreadLocal) { Context ctx; SetDefaultContext(&ctx); Context ctx2; auto future = std::async(std::launch::async, [&ctx2] { SetDefaultContext(&ctx2); return &GetDefaultContext(); }); ASSERT_NE(&GetDefaultContext(), future.get()); } TEST(ContextTest, ContextScopeCtor) { SetGlobalDefaultContext(nullptr); SetDefaultContext(nullptr); Context ctx1; { // ContextScope should work even if default context is not set ContextScope scope(ctx1); EXPECT_EQ(&ctx1, &GetDefaultContext()); } ASSERT_THROW(GetDefaultContext(), XchainerError); SetDefaultContext(&ctx1); { Context ctx2; ContextScope scope(ctx2); EXPECT_EQ(&ctx2, &GetDefaultContext()); } ASSERT_EQ(&ctx1, &GetDefaultContext()); { ContextScope scope; EXPECT_EQ(&ctx1, &GetDefaultContext()); Context ctx2; SetDefaultContext(&ctx2); } ASSERT_EQ(&ctx1, &GetDefaultContext()); Context ctx2; { ContextScope scope(ctx2); scope.Exit(); EXPECT_EQ(&ctx1, &GetDefaultContext()); SetDefaultContext(&ctx2); // not recovered here because the scope has already existed } ASSERT_EQ(&ctx2, &GetDefaultContext()); } TEST(ContextTest, UserDefinedBackend) { ::setenv("XCHAINER_PATH", XCHAINER_TEST_DIR "/context_testdata", 1); Context ctx; Backend& backend0 = ctx.GetBackend("backend0"); EXPECT_EQ("backend0", backend0.GetName()); Backend& backend0_2 = ctx.GetBackend("backend0"); EXPECT_EQ(&backend0, &backend0_2); Backend& backend1 = ctx.GetBackend("backend1"); EXPECT_EQ("backend1", backend1.GetName()); Device& device0 = ctx.GetDevice(std::string("backend0:0")); EXPECT_EQ(&backend0, &device0.backend()); } TEST(ContextTest, GetBackendOnDefaultContext) { // xchainer::GetBackend Context ctx; SetDefaultContext(&ctx); Backend& backend = GetBackend("native"); EXPECT_EQ(&ctx, &backend.context()); EXPECT_EQ("native", backend.GetName()); } TEST(ContextTest, GetDeviceOnDefaultContext) { // xchainer::GetDevice Context ctx; SetDefaultContext(&ctx); Device& device = GetDevice({"native:0"}); EXPECT_EQ(&ctx, &device.backend().context()); EXPECT_EQ("native:0", device.name()); } } // namespace } // namespace xchainer <|endoftext|>
<commit_before>#include "xchainer/indexer.h" #include <gtest/gtest.h> namespace xchainer { namespace { TEST(IndexerTest, Ctor) { Indexer<0> indexer({}); EXPECT_EQ(0, indexer.ndim()); EXPECT_EQ(1, indexer.total_size()); EXPECT_NO_THROW(indexer.Set(0)); } TEST(IndexerTest, Rank1) { Indexer<1> indexer({3}); EXPECT_EQ(1, indexer.ndim()); EXPECT_EQ(3, indexer.total_size()); EXPECT_EQ(3, indexer.shape()[0]); for (int64_t i = 0; i < 3; ++i) { indexer.Set(i); EXPECT_EQ(i, indexer.index()[0]); } } TEST(IndexerTest, Rank3) { Indexer<3> indexer({2, 3, 4}); EXPECT_EQ(3, indexer.ndim()); EXPECT_EQ(2 * 3 * 4, indexer.total_size()); EXPECT_EQ(2, indexer.shape()[0]); EXPECT_EQ(3, indexer.shape()[1]); EXPECT_EQ(4, indexer.shape()[2]); int64_t lin = 0; for (int64_t i = 0; i < 2; ++i) { for (int64_t j = 0; j < 3; ++j) { for (int64_t k = 0; k < 4; ++k) { indexer.Set(lin); EXPECT_EQ(i, indexer.index()[0]); EXPECT_EQ(j, indexer.index()[1]); EXPECT_EQ(k, indexer.index()[2]); EXPECT_EQ(lin, indexer.raw_index()); lin++; } } } } TEST(DynamicIndexerTest, Rank0) { Indexer<> indexer({}); EXPECT_EQ(0, indexer.ndim()); EXPECT_EQ(1, indexer.total_size()); EXPECT_NO_THROW(indexer.Set(0)); } TEST(DynamicIndexerTest, Rank1) { Indexer<> indexer({3}); EXPECT_EQ(1, indexer.ndim()); EXPECT_EQ(3, indexer.total_size()); EXPECT_EQ(3, indexer.shape()[0]); for (int64_t i = 0; i < 3; ++i) { indexer.Set(i); EXPECT_EQ(i, indexer.index()[0]); } } TEST(DynamicIndexerTest, Rank3) { Indexer<> indexer({2, 3, 4}); EXPECT_EQ(3, indexer.ndim()); EXPECT_EQ(2 * 3 * 4, indexer.total_size()); EXPECT_EQ(2, indexer.shape()[0]); EXPECT_EQ(3, indexer.shape()[1]); EXPECT_EQ(4, indexer.shape()[2]); int64_t lin = 0; for (int64_t i = 0; i < 2; ++i) { for (int64_t j = 0; j < 3; ++j) { for (int64_t k = 0; k < 4; ++k) { indexer.Set(lin); EXPECT_EQ(i, indexer.index()[0]); EXPECT_EQ(j, indexer.index()[1]); EXPECT_EQ(k, indexer.index()[2]); EXPECT_EQ(lin, indexer.raw_index()); lin++; } } } } } // namespace } // namespace xchainer <commit_msg>Add raw index check<commit_after>#include "xchainer/indexer.h" #include <gtest/gtest.h> namespace xchainer { namespace { TEST(IndexerTest, Ctor) { Indexer<0> indexer({}); EXPECT_EQ(0, indexer.ndim()); EXPECT_EQ(1, indexer.total_size()); EXPECT_NO_THROW(indexer.Set(0)); } TEST(IndexerTest, Rank1) { Indexer<1> indexer({3}); EXPECT_EQ(1, indexer.ndim()); EXPECT_EQ(3, indexer.total_size()); EXPECT_EQ(3, indexer.shape()[0]); for (int64_t i = 0; i < 3; ++i) { indexer.Set(i); EXPECT_EQ(i, indexer.index()[0]); EXPECT_EQ(i, indexer.raw_index()); } } TEST(IndexerTest, Rank3) { Indexer<3> indexer({2, 3, 4}); EXPECT_EQ(3, indexer.ndim()); EXPECT_EQ(2 * 3 * 4, indexer.total_size()); EXPECT_EQ(2, indexer.shape()[0]); EXPECT_EQ(3, indexer.shape()[1]); EXPECT_EQ(4, indexer.shape()[2]); int64_t lin = 0; for (int64_t i = 0; i < 2; ++i) { for (int64_t j = 0; j < 3; ++j) { for (int64_t k = 0; k < 4; ++k) { indexer.Set(lin); EXPECT_EQ(i, indexer.index()[0]); EXPECT_EQ(j, indexer.index()[1]); EXPECT_EQ(k, indexer.index()[2]); EXPECT_EQ(lin, indexer.raw_index()); lin++; } } } } TEST(DynamicIndexerTest, Rank0) { Indexer<> indexer({}); EXPECT_EQ(0, indexer.ndim()); EXPECT_EQ(1, indexer.total_size()); EXPECT_NO_THROW(indexer.Set(0)); } TEST(DynamicIndexerTest, Rank1) { Indexer<> indexer({3}); EXPECT_EQ(1, indexer.ndim()); EXPECT_EQ(3, indexer.total_size()); EXPECT_EQ(3, indexer.shape()[0]); for (int64_t i = 0; i < 3; ++i) { indexer.Set(i); EXPECT_EQ(i, indexer.index()[0]); EXPECT_EQ(i, indexer.raw_index()); } } TEST(DynamicIndexerTest, Rank3) { Indexer<> indexer({2, 3, 4}); EXPECT_EQ(3, indexer.ndim()); EXPECT_EQ(2 * 3 * 4, indexer.total_size()); EXPECT_EQ(2, indexer.shape()[0]); EXPECT_EQ(3, indexer.shape()[1]); EXPECT_EQ(4, indexer.shape()[2]); int64_t lin = 0; for (int64_t i = 0; i < 2; ++i) { for (int64_t j = 0; j < 3; ++j) { for (int64_t k = 0; k < 4; ++k) { indexer.Set(lin); EXPECT_EQ(i, indexer.index()[0]); EXPECT_EQ(j, indexer.index()[1]); EXPECT_EQ(k, indexer.index()[2]); EXPECT_EQ(lin, indexer.raw_index()); lin++; } } } } } // namespace } // namespace xchainer <|endoftext|>
<commit_before>#include <common/buffer.h> #include <common/endian.h> #if defined(XCODEC_PIPES) #include <io/pipe.h> #endif #include <xcodec/xcodec.h> #include <xcodec/xcodec_cache.h> #include <xcodec/xcodec_encoder.h> #if defined(XCODEC_PIPES) #include <xcodec/xcodec_encoder_pipe.h> #endif #include <xcodec/xcodec_hash.h> typedef std::pair<unsigned, uint64_t> offset_hash_pair_t; XCodecEncoder::XCodecEncoder(XCodec *codec) : log_("/xcodec/encoder"), cache_(codec->cache_), window_(), #if defined(XCODEC_PIPES) pipe_(NULL), #endif queued_() { queued_.append(codec->hello()); #if defined(XCODEC_PIPES) if (pipe_ != NULL) pipe_->output_ready(); #endif } XCodecEncoder::~XCodecEncoder() { ASSERT(pipe_ == NULL); } /* * This takes a view of a data stream and turns it into a series of references * to other data, declarations of data to be referenced, and data that needs * escaped. */ void XCodecEncoder::encode(Buffer *output, Buffer *input) { /* Process any queued HELLOs, ASKs or LEARNs. */ if (!queued_.empty()) { DEBUG(log_) << "Pushing queued data."; output->append(&queued_); queued_.clear(); if (input->empty()) return; } ASSERT(!input->empty()); if (input->length() < XCODEC_SEGMENT_LENGTH) { encode_escape(output, input, input->length()); return; } XCodecHash<XCODEC_SEGMENT_LENGTH> xcodec_hash; offset_hash_pair_t candidate; bool have_candidate; Buffer outq; unsigned o = 0; have_candidate = false; /* * While there is input. */ while (!input->empty()) { /* * Take the first BufferSegment out of the input Buffer. */ BufferSegment *seg; input->moveout(&seg); /* * And add it to a temporary Buffer where input is queued. */ outq.append(seg); /* * And for every byte in this BufferSegment. */ const uint8_t *p; for (p = seg->data(); p < seg->end(); p++) { /* * Add it to the rolling hash. */ xcodec_hash.roll(*p); /* * If the rolling hash does not cover an entire * segment yet, just keep adding to it. */ if (++o < XCODEC_SEGMENT_LENGTH) continue; /* * And then mix the hash's internal state into a * uint64_t that we can use to refer to that data * and to look up possible past occurances of that * data in the XCodecCache. */ unsigned start = o - XCODEC_SEGMENT_LENGTH; uint64_t hash = xcodec_hash.mix(); /* * If there is a pending candidate hash that wouldn't * overlap with the data that the rolling hash presently * covers, declare it now. */ if (have_candidate && candidate.first + XCODEC_SEGMENT_LENGTH <= start) { BufferSegment *nseg; encode_declaration(output, &outq, candidate.first, candidate.second, &nseg); o -= candidate.first + XCODEC_SEGMENT_LENGTH; start = o - XCODEC_SEGMENT_LENGTH; have_candidate = false; /* * If, on top of that, the just-declared hash is * the same as the current hash, consider referencing * it immediately. */ if (hash == candidate.second) { /* * If it's a hash collision, though, nevermind. * Skip trying to use this hash as a reference, * too, and go on to the next one. */ if (!encode_reference(output, &outq, start, hash, nseg)) { nseg->unref(); DEBUG(log_) << "Collision in adjacent-declare pass."; continue; } nseg->unref(); /* * But if there's no collection, then we can move * on to looking for the *next* hash/data to declare * or reference. */ o = 0; DEBUG(log_) << "Hit in adjacent-declare pass."; continue; } nseg->unref(); } /* * Now attempt to encode this hash as a reference if it * has been defined before. */ BufferSegment *oseg = cache_->lookup(hash); if (oseg != NULL) { /* * This segment already exists. If it's * identical to this chunk of data, then that's * positively fantastic. */ if (encode_reference(output, &outq, start, hash, oseg)) { oseg->unref(); o = 0; /* * We have output any data before this hash * in escaped form, so any candidate hash * before it is invalid now. */ have_candidate = false; continue; } /* * This hash isn't usable because it collides * with another, so keep looking for something * viable. */ oseg->unref(); DEBUG(log_) << "Collision in first pass."; continue; } /* * Not defined before, it's a candidate for declaration if * we don't already have one. */ if (have_candidate) { /* * We already have a hash that occurs earlier, * isn't a collision and includes data that's * covered by this hash, so don't remember it * and keep going. */ ASSERT(candidate.first + XCODEC_SEGMENT_LENGTH > start); continue; } /* * The hash at this offset doesn't collide with any * other and is the first viable hash we've seen so far * in the stream, so remember it so that if we don't * find something to reference we can declare this one * for future use. */ candidate.first = start; candidate.second = hash; have_candidate = true; } seg->unref(); } /* * Done processing input. If there's still data in the outq Buffer, * then we need to declare any candidate hashes and escape any data * after them. */ /* * There's a hash we can declare, do it. */ if (have_candidate) { ASSERT(!outq.empty()); encode_declaration(output, &outq, candidate.first, candidate.second, NULL); have_candidate = false; } /* * There's data after that hash or no candidate hash, so * just escape it. */ if (!outq.empty()) { encode_escape(output, &outq, outq.length()); } ASSERT(!have_candidate); ASSERT(outq.empty()); ASSERT(input->empty()); } /* * Encode an ASK of the remote XCodec. */ void XCodecEncoder::encode_ask(uint64_t hash) { uint64_t behash = BigEndian::encode(hash); queued_.append(XCODEC_MAGIC); queued_.append(XCODEC_OP_ASK); queued_.append((const uint8_t *)&behash, sizeof behash); #if defined(XCODEC_PIPES) if (pipe_ != NULL) pipe_->output_ready(); #endif } /* * Encode a LEARN for the remote XCodec. */ void XCodecEncoder::encode_learn(BufferSegment *seg) { queued_.append(XCODEC_MAGIC); queued_.append(XCODEC_OP_LEARN); queued_.append(seg); #if defined(XCODEC_PIPES) if (pipe_ != NULL) pipe_->output_ready(); #endif } #if defined(XCODEC_PIPES) /* * Set or clear the association with an XCodecPipe. */ void XCodecEncoder::set_pipe(XCodecEncoderPipe *pipe) { ASSERT(pipe != NULL || pipe_ != NULL); ASSERT(pipe_ == NULL || pipe == NULL); pipe_ = pipe; if (pipe_ != NULL && !queued_.empty()) pipe_->output_ready(); } #endif void XCodecEncoder::encode_declaration(Buffer *output, Buffer *input, unsigned offset, uint64_t hash, BufferSegment **segp) { if (offset != 0) { encode_escape(output, input, offset); } BufferSegment *nseg; input->copyout(&nseg, XCODEC_SEGMENT_LENGTH); cache_->enter(hash, nseg); output->append(XCODEC_MAGIC); output->append(XCODEC_OP_EXTRACT); output->append(nseg); window_.declare(hash, nseg); if (segp == NULL) nseg->unref(); /* * Skip to the end. */ input->skip(XCODEC_SEGMENT_LENGTH); if (segp != NULL) *segp = nseg; } void XCodecEncoder::encode_escape(Buffer *output, Buffer *input, unsigned length) { do { unsigned offset; if (!input->find(XCODEC_MAGIC, &offset, length)) { output->append(input, length); input->skip(length); return; } if (offset != 0) { output->append(input, offset); length -= offset; input->skip(offset); } output->append(XCODEC_MAGIC); output->append(XCODEC_OP_ESCAPE); length -= sizeof XCODEC_MAGIC; input->skip(sizeof XCODEC_MAGIC); } while (length != 0); } bool XCodecEncoder::encode_reference(Buffer *output, Buffer *input, unsigned offset, uint64_t hash, BufferSegment *oseg) { uint8_t data[XCODEC_SEGMENT_LENGTH]; input->copyout(data, offset, sizeof data); if (!oseg->match(data, sizeof data)) return (false); if (offset != 0) { encode_escape(output, input, offset); } /* * Skip to the end. */ input->skip(XCODEC_SEGMENT_LENGTH); /* * And output a reference. */ uint8_t b; if (window_.present(hash, &b)) { output->append(XCODEC_MAGIC); output->append(XCODEC_OP_BACKREF); output->append(b); } else { output->append(XCODEC_MAGIC); output->append(XCODEC_OP_REF); uint64_t behash = BigEndian::encode(hash); output->append((const uint8_t *)&behash, sizeof behash); window_.declare(hash, oseg); } return (true); } <commit_msg>Fix build with !XCODEC_PIPES.<commit_after>#include <common/buffer.h> #include <common/endian.h> #if defined(XCODEC_PIPES) #include <io/pipe.h> #endif #include <xcodec/xcodec.h> #include <xcodec/xcodec_cache.h> #include <xcodec/xcodec_encoder.h> #if defined(XCODEC_PIPES) #include <xcodec/xcodec_encoder_pipe.h> #endif #include <xcodec/xcodec_hash.h> typedef std::pair<unsigned, uint64_t> offset_hash_pair_t; XCodecEncoder::XCodecEncoder(XCodec *codec) : log_("/xcodec/encoder"), cache_(codec->cache_), window_(), #if defined(XCODEC_PIPES) pipe_(NULL), #endif queued_() { queued_.append(codec->hello()); #if defined(XCODEC_PIPES) if (pipe_ != NULL) pipe_->output_ready(); #endif } XCodecEncoder::~XCodecEncoder() { #if defined(XCODEC_PIPES) ASSERT(pipe_ == NULL); #endif } /* * This takes a view of a data stream and turns it into a series of references * to other data, declarations of data to be referenced, and data that needs * escaped. */ void XCodecEncoder::encode(Buffer *output, Buffer *input) { /* Process any queued HELLOs, ASKs or LEARNs. */ if (!queued_.empty()) { DEBUG(log_) << "Pushing queued data."; output->append(&queued_); queued_.clear(); if (input->empty()) return; } ASSERT(!input->empty()); if (input->length() < XCODEC_SEGMENT_LENGTH) { encode_escape(output, input, input->length()); return; } XCodecHash<XCODEC_SEGMENT_LENGTH> xcodec_hash; offset_hash_pair_t candidate; bool have_candidate; Buffer outq; unsigned o = 0; have_candidate = false; /* * While there is input. */ while (!input->empty()) { /* * Take the first BufferSegment out of the input Buffer. */ BufferSegment *seg; input->moveout(&seg); /* * And add it to a temporary Buffer where input is queued. */ outq.append(seg); /* * And for every byte in this BufferSegment. */ const uint8_t *p; for (p = seg->data(); p < seg->end(); p++) { /* * Add it to the rolling hash. */ xcodec_hash.roll(*p); /* * If the rolling hash does not cover an entire * segment yet, just keep adding to it. */ if (++o < XCODEC_SEGMENT_LENGTH) continue; /* * And then mix the hash's internal state into a * uint64_t that we can use to refer to that data * and to look up possible past occurances of that * data in the XCodecCache. */ unsigned start = o - XCODEC_SEGMENT_LENGTH; uint64_t hash = xcodec_hash.mix(); /* * If there is a pending candidate hash that wouldn't * overlap with the data that the rolling hash presently * covers, declare it now. */ if (have_candidate && candidate.first + XCODEC_SEGMENT_LENGTH <= start) { BufferSegment *nseg; encode_declaration(output, &outq, candidate.first, candidate.second, &nseg); o -= candidate.first + XCODEC_SEGMENT_LENGTH; start = o - XCODEC_SEGMENT_LENGTH; have_candidate = false; /* * If, on top of that, the just-declared hash is * the same as the current hash, consider referencing * it immediately. */ if (hash == candidate.second) { /* * If it's a hash collision, though, nevermind. * Skip trying to use this hash as a reference, * too, and go on to the next one. */ if (!encode_reference(output, &outq, start, hash, nseg)) { nseg->unref(); DEBUG(log_) << "Collision in adjacent-declare pass."; continue; } nseg->unref(); /* * But if there's no collection, then we can move * on to looking for the *next* hash/data to declare * or reference. */ o = 0; DEBUG(log_) << "Hit in adjacent-declare pass."; continue; } nseg->unref(); } /* * Now attempt to encode this hash as a reference if it * has been defined before. */ BufferSegment *oseg = cache_->lookup(hash); if (oseg != NULL) { /* * This segment already exists. If it's * identical to this chunk of data, then that's * positively fantastic. */ if (encode_reference(output, &outq, start, hash, oseg)) { oseg->unref(); o = 0; /* * We have output any data before this hash * in escaped form, so any candidate hash * before it is invalid now. */ have_candidate = false; continue; } /* * This hash isn't usable because it collides * with another, so keep looking for something * viable. */ oseg->unref(); DEBUG(log_) << "Collision in first pass."; continue; } /* * Not defined before, it's a candidate for declaration if * we don't already have one. */ if (have_candidate) { /* * We already have a hash that occurs earlier, * isn't a collision and includes data that's * covered by this hash, so don't remember it * and keep going. */ ASSERT(candidate.first + XCODEC_SEGMENT_LENGTH > start); continue; } /* * The hash at this offset doesn't collide with any * other and is the first viable hash we've seen so far * in the stream, so remember it so that if we don't * find something to reference we can declare this one * for future use. */ candidate.first = start; candidate.second = hash; have_candidate = true; } seg->unref(); } /* * Done processing input. If there's still data in the outq Buffer, * then we need to declare any candidate hashes and escape any data * after them. */ /* * There's a hash we can declare, do it. */ if (have_candidate) { ASSERT(!outq.empty()); encode_declaration(output, &outq, candidate.first, candidate.second, NULL); have_candidate = false; } /* * There's data after that hash or no candidate hash, so * just escape it. */ if (!outq.empty()) { encode_escape(output, &outq, outq.length()); } ASSERT(!have_candidate); ASSERT(outq.empty()); ASSERT(input->empty()); } /* * Encode an ASK of the remote XCodec. */ void XCodecEncoder::encode_ask(uint64_t hash) { uint64_t behash = BigEndian::encode(hash); queued_.append(XCODEC_MAGIC); queued_.append(XCODEC_OP_ASK); queued_.append((const uint8_t *)&behash, sizeof behash); #if defined(XCODEC_PIPES) if (pipe_ != NULL) pipe_->output_ready(); #endif } /* * Encode a LEARN for the remote XCodec. */ void XCodecEncoder::encode_learn(BufferSegment *seg) { queued_.append(XCODEC_MAGIC); queued_.append(XCODEC_OP_LEARN); queued_.append(seg); #if defined(XCODEC_PIPES) if (pipe_ != NULL) pipe_->output_ready(); #endif } #if defined(XCODEC_PIPES) /* * Set or clear the association with an XCodecPipe. */ void XCodecEncoder::set_pipe(XCodecEncoderPipe *pipe) { ASSERT(pipe != NULL || pipe_ != NULL); ASSERT(pipe_ == NULL || pipe == NULL); pipe_ = pipe; if (pipe_ != NULL && !queued_.empty()) pipe_->output_ready(); } #endif void XCodecEncoder::encode_declaration(Buffer *output, Buffer *input, unsigned offset, uint64_t hash, BufferSegment **segp) { if (offset != 0) { encode_escape(output, input, offset); } BufferSegment *nseg; input->copyout(&nseg, XCODEC_SEGMENT_LENGTH); cache_->enter(hash, nseg); output->append(XCODEC_MAGIC); output->append(XCODEC_OP_EXTRACT); output->append(nseg); window_.declare(hash, nseg); if (segp == NULL) nseg->unref(); /* * Skip to the end. */ input->skip(XCODEC_SEGMENT_LENGTH); if (segp != NULL) *segp = nseg; } void XCodecEncoder::encode_escape(Buffer *output, Buffer *input, unsigned length) { do { unsigned offset; if (!input->find(XCODEC_MAGIC, &offset, length)) { output->append(input, length); input->skip(length); return; } if (offset != 0) { output->append(input, offset); length -= offset; input->skip(offset); } output->append(XCODEC_MAGIC); output->append(XCODEC_OP_ESCAPE); length -= sizeof XCODEC_MAGIC; input->skip(sizeof XCODEC_MAGIC); } while (length != 0); } bool XCodecEncoder::encode_reference(Buffer *output, Buffer *input, unsigned offset, uint64_t hash, BufferSegment *oseg) { uint8_t data[XCODEC_SEGMENT_LENGTH]; input->copyout(data, offset, sizeof data); if (!oseg->match(data, sizeof data)) return (false); if (offset != 0) { encode_escape(output, input, offset); } /* * Skip to the end. */ input->skip(XCODEC_SEGMENT_LENGTH); /* * And output a reference. */ uint8_t b; if (window_.present(hash, &b)) { output->append(XCODEC_MAGIC); output->append(XCODEC_OP_BACKREF); output->append(b); } else { output->append(XCODEC_MAGIC); output->append(XCODEC_OP_REF); uint64_t behash = BigEndian::encode(hash); output->append((const uint8_t *)&behash, sizeof behash); window_.declare(hash, oseg); } return (true); } <|endoftext|>
<commit_before>#include "material.hpp" Material::Material() : name_{"defaultmaterial"}, ka_{Color()}, kd_{Color()}, ks_{Color()}, reflection_{0} {} Material::Material(std::string const& n, Color const& a, Color const& d, Color const& s, float const& m) : name_{n}, ka_{a}, kd_{d}, ks_{s}, reflection_{m} {} Material::Material(std::string const& n, Color const& a, float const& m) : name_{n}, ka_{a}, kd_{a}, ks_{a}, reflection_{m} {} Material::~Material() {} std::string const& Material::name() const{ return name_; } Color const& Material::ka() const{ return ka_; } Color const& Material::kd() const{ return kd_; } Color const& Material::ks() const{ return ks_; } float const& Material::m() const{ return reflection_; } std::ostream& operator<<(std::ostream& os, Material const& m) { os << "Material: \n" << "Name: " << m.name_ << "\n" << "Ambiente Reflexion: " << m.ka() << "Diffuse Reflexion: "<< m.kd() << "Spiegelnde Reflexion: " << m.ks() << "Exponent: " << m.m() <<"\n"; return os; } <commit_msg>minor fix ostream operator<commit_after>#include "material.hpp" Material::Material() : name_{"defaultmaterial"}, ka_{Color()}, kd_{Color()}, ks_{Color()}, reflection_{0} {} Material::Material(std::string const& n, Color const& a, Color const& d, Color const& s, float const& m) : name_{n}, ka_{a}, kd_{d}, ks_{s}, reflection_{m} {} Material::Material(std::string const& n, Color const& a, float const& m) : name_{n}, ka_{a}, kd_{a}, ks_{a}, reflection_{m} {} Material::~Material() {} std::string const& Material::name() const{ return name_; } Color const& Material::ka() const{ return ka_; } Color const& Material::kd() const{ return kd_; } Color const& Material::ks() const{ return ks_; } float const& Material::m() const{ return reflection_; } std::ostream& operator<<(std::ostream& os, Material const& m) { os << "Material: \n" << "Name: " << m.name() << "\n" << "Ambiente Reflexion: " << m.ka() << "Diffuse Reflexion: "<< m.kd() << "Spiegelnde Reflexion: " << m.ks() << "Exponent: " << m.m() <<"\n"; return os; } <|endoftext|>
<commit_before>#include <triangle.hpp> #include <math.h> Triangle::Triangle() : Shape(), p1_{ glm::vec3{0.0,0.0,0.0} }, p2_{ glm::vec3{0.0,0.0,0.0} }, p3_{ glm::vec3{0.0,0.0,0.0} }{} Triangle::Triangle(glm::vec3 p1, glm::vec3 p2, glm::vec3 p3) : Shape(), p1_{p1}, p2_{p2}, p3_{p3}{} Triangle::Triangle(Material material, std::string name, glm::vec3 p1, glm::vec3 p2, glm::vec3 p3) : Shape(material, name), p1_{p1}, p2_{p2}, p3_{p3}{} Triangle::~Triangle(){} glm::vec3 Triangle::get_p1() const { return p1_; } glm::vec3 Triangle::get_p2() const { return p2_; } glm::vec3 Triangle::get_p3() const { return p3_; } double Triangle::area() const { double a = sqrt(std::abs((p1_.x - p2_.x)*(p1_.x - p2_.x) + (p1_.y - p2_.y)*(p1_.y - p2_.y) + (p1_.z - p2_.z)*(p1_.z - p2_.z))); double b = sqrt(std::abs((p1_.x - p3_.x)*(p1_.x - p3_.x) + (p1_.y - p3_.y)*(p1_.y - p3_.y) + (p1_.z - p3_.z)*(p1_.z - p3_.z))); double c = sqrt(std::abs((p2_.x - p3_.x)*(p2_.x - p3_.x) + (p2_.y - p3_.y)*(p2_.y - p3_.y) + (p2_.z - p3_.z)*(p2_.z - p3_.z))); double s = ((a + b + c)/2); return sqrt(s*(s-a)*(s-b)*(s-c)); } double Triangle::volume() const { return 0; } <commit_msg>minor changes<commit_after>#include <triangle.hpp> #include <math.h> Triangle::Triangle() : Shape(), p1_{ glm::vec3{0.0,0.0,0.0} }, p2_{ glm::vec3{0.0,0.0,0.0} }, p3_{ glm::vec3{0.0,0.0,0.0} }{} Triangle::Triangle(glm::vec3 p1, glm::vec3 p2, glm::vec3 p3) : Shape(), p1_{p1}, p2_{p2}, p3_{p3}{} Triangle::Triangle(Material material, std::string name, glm::vec3 p1, glm::vec3 p2, glm::vec3 p3) : Shape(material, name), p1_{p1}, p2_{p2}, p3_{p3}{} Triangle::~Triangle(){} glm::vec3 Triangle::get_p1() const { return p1_; } glm::vec3 Triangle::get_p2() const { return p2_; } glm::vec3 Triangle::get_p3() const { return p3_; } double Triangle::area() const { double a = sqrt(((p1_.x - p2_.x)*(p1_.x - p2_.x) + (p1_.y - p2_.y)*(p1_.y - p2_.y) + (p1_.z - p2_.z)*(p1_.z - p2_.z))); double b = sqrt(((p1_.x - p3_.x)*(p1_.x - p3_.x) + (p1_.y - p3_.y)*(p1_.y - p3_.y) + (p1_.z - p3_.z)*(p1_.z - p3_.z))); double c = sqrt(((p2_.x - p3_.x)*(p2_.x - p3_.x) + (p2_.y - p3_.y)*(p2_.y - p3_.y) + (p2_.z - p3_.z)*(p2_.z - p3_.z))); double s = ((a + b + c)/2); return sqrt(s*(s-a)*(s-b)*(s-c)); } double Triangle::volume() const { return 0; } <|endoftext|>
<commit_before>/* logger_metrics_interface.cc François-Michel L'Heureux, 21 May 2013 Copyright (c) 2013 Datacratic. All rights reserved. */ #include "soa/jsoncpp/reader.h" #include "jml/utils/exc_assert.h" #include "soa/logger/logger_metrics_interface.h" #include "soa/logger/logger_metrics_mongo.h" #include "soa/logger/logger_metrics_void.h" #include "soa/logger/logger_metrics_term.h" using namespace std; using namespace Datacratic; namespace { std::mutex m; std::shared_ptr<ILoggerMetrics> logger; // getenv that sanely deals with empty strings string getEnv(const char * variable) { const char * c = getenv(variable); return c ? c : ""; } } // file scope /****************************************************************************/ /* LOGGER METRICS */ /****************************************************************************/ const string ILoggerMetrics::METRICS = "metrics"; const string ILoggerMetrics::PROCESS = "process"; const string ILoggerMetrics::META = "meta"; bool ILoggerMetrics::failSafe(true); string ILoggerMetrics::parentObjectId; shared_ptr<ILoggerMetrics> ILoggerMetrics:: setup(const string & configKey, const string & coll, const string & appName) { std::lock_guard<std::mutex> lock(m); if (logger) { throw ML::Exception("Cannot setup more than once"); } string configFile(getEnv("CONFIG")); if (configFile.empty()) { cerr << ("Logger Metrics setup: CONFIG is not defined," " logging disabled\n"); logger.reset(new LoggerMetricsVoid(coll)); } else if (configKey.empty()) { cerr << ("Logger Metrics setup: configKey is empty," " logging disabled\n"); logger.reset(new LoggerMetricsVoid(coll)); } else { Json::Value config = Json::parseFromFile(getEnv("CONFIG")); config = config[configKey]; setupLogger(config, coll, appName); } return logger; } shared_ptr<ILoggerMetrics> ILoggerMetrics:: setupFromJson(const Json::Value & config, const string & coll, const string & appName) { std::lock_guard<std::mutex> lock(m); if (logger) { throw ML::Exception("Cannot setup more than once"); } setupLogger(config, coll, appName); return logger; } void ILoggerMetrics:: setupLogger(const Json::Value & config, const string & coll, const string & appName) { ExcAssert(!config.isNull()); ILoggerMetrics::parentObjectId = getEnv("METRICS_PARENT_ID"); if (config["type"].isNull()) { throw ML::Exception("Your LoggerMetrics config needs to " "specify a [type] key."); } string loggerType = config["type"].asString(); failSafe = config["failSafe"].asBool(); auto fct = [&] { if (loggerType == "mongo") { logger.reset(new LoggerMetricsMongo(config, coll, appName)); } else if (loggerType == "term" || loggerType == "terminal") { logger.reset(new LoggerMetricsTerm(config, coll, appName)); } else if (loggerType == "void") { logger.reset(new LoggerMetricsVoid(config, coll, appName)); } else { throw ML::Exception("Unknown logger type [%s]", loggerType.c_str()); } }; if (failSafe) { try { fct(); } catch (const exception & exc) { cerr << "Logger fail safe caught: " << exc.what() << endl; logger = shared_ptr<ILoggerMetrics>( new LoggerMetricsTerm(config, coll, appName)); } } else { fct(); } auto getCmdResult = [&] (const char* cmd) { FILE* pipe = popen(cmd, "r"); if (!pipe) { return string("ERROR"); } char buffer[128]; stringstream result; while (!feof(pipe)) { if (fgets(buffer, 128, pipe) != NULL) { result << buffer; } } pclose(pipe); string res = result.str(); return res.substr(0, res.length() - 1);//chop \n }; string now = Date::now().printClassic(); Json::Value v; v["startTime"] = now; v["appName"] = appName; v["parent_id"] = getEnv("METRICS_PARENT_ID"); v["user"] = string(getEnv("LOGNAME")); char hostname[128]; int hostnameOk = !gethostname(hostname, 128); v["hostname"] = string(hostnameOk ? hostname : ""); v["workingDirectory"] = string(getEnv("PWD")); v["gitBranch"] = getCmdResult("git rev-parse --abbrev-ref HEAD"); v["gitHash"] = getCmdResult("git rev-parse HEAD"); // Log environment variable RUNID. Useful to give a name to an // experiment. v["runid"] = getEnv("RUNID"); logger->logProcess(v); setenv("METRICS_PARENT_ID", logger->getProcessId().c_str(), 1); } shared_ptr<ILoggerMetrics> ILoggerMetrics:: getSingleton() { std::lock_guard<std::mutex> lock(m); if (!logger) { cerr << ("Calling getSingleton without calling setup first," " logging implicitly disabled.\n"); logger.reset(new LoggerMetricsVoid("")); } return logger; } void ILoggerMetrics:: logMetrics(const Json::Value & json) { vector<string> stack; std::function<void(const Json::Value &)> doit; doit = [&] (const Json::Value & v) { for (auto it = v.begin(); it != v.end(); ++it) { string memberName = it.memberName(); if (v[memberName].isObject()) { stack.push_back(memberName); doit(v[memberName]); stack.pop_back(); } else { const Json::Value & current = v[memberName]; if (!(current.isInt() || current.isUInt() || current.isDouble() || current.isNumeric())) { stringstream key; for (const string & s: stack) { key << s << "."; } key << memberName; string value = current.toString(); cerr << value << endl; value = value.substr(1, value.length() - 3); throw ML::Exception("logMetrics only accepts numerical" " values. Key [%s] has value [%s].", key.str().c_str(), value.c_str()); } } } }; auto fct = [&] () { doit(json); logInCategory(METRICS, json); }; failSafeHelper(fct); } void ILoggerMetrics:: failSafeHelper(const std::function<void()> & fct) { if (failSafe) { try { fct(); } catch (const exception & exc) { cerr << "Logger fail safe caught: " << exc.what() << endl; } } else { fct(); } } void ILoggerMetrics:: close() { Json::Value v; Date endDate = Date::now(); v["endDate"] = endDate.printClassic(); v["duration"] = endDate - startDate; logInCategory(PROCESS, v); logProcess(v); } <commit_msg>logger_metrics_interface: no longer log git infos<commit_after>/* logger_metrics_interface.cc François-Michel L'Heureux, 21 May 2013 Copyright (c) 2013 Datacratic. All rights reserved. */ #include "soa/jsoncpp/reader.h" #include "jml/utils/exc_assert.h" #include "soa/logger/logger_metrics_interface.h" #include "soa/logger/logger_metrics_mongo.h" #include "soa/logger/logger_metrics_void.h" #include "soa/logger/logger_metrics_term.h" using namespace std; using namespace Datacratic; namespace { std::mutex m; std::shared_ptr<ILoggerMetrics> logger; // getenv that sanely deals with empty strings string getEnv(const char * variable) { const char * c = getenv(variable); return c ? c : ""; } } // file scope /****************************************************************************/ /* LOGGER METRICS */ /****************************************************************************/ const string ILoggerMetrics::METRICS = "metrics"; const string ILoggerMetrics::PROCESS = "process"; const string ILoggerMetrics::META = "meta"; bool ILoggerMetrics::failSafe(true); string ILoggerMetrics::parentObjectId; shared_ptr<ILoggerMetrics> ILoggerMetrics:: setup(const string & configKey, const string & coll, const string & appName) { std::lock_guard<std::mutex> lock(m); if (logger) { throw ML::Exception("Cannot setup more than once"); } string configFile(getEnv("CONFIG")); if (configFile.empty()) { cerr << ("Logger Metrics setup: CONFIG is not defined," " logging disabled\n"); logger.reset(new LoggerMetricsVoid(coll)); } else if (configKey.empty()) { cerr << ("Logger Metrics setup: configKey is empty," " logging disabled\n"); logger.reset(new LoggerMetricsVoid(coll)); } else { Json::Value config = Json::parseFromFile(getEnv("CONFIG")); config = config[configKey]; setupLogger(config, coll, appName); } return logger; } shared_ptr<ILoggerMetrics> ILoggerMetrics:: setupFromJson(const Json::Value & config, const string & coll, const string & appName) { std::lock_guard<std::mutex> lock(m); if (logger) { throw ML::Exception("Cannot setup more than once"); } setupLogger(config, coll, appName); return logger; } void ILoggerMetrics:: setupLogger(const Json::Value & config, const string & coll, const string & appName) { ExcAssert(!config.isNull()); ILoggerMetrics::parentObjectId = getEnv("METRICS_PARENT_ID"); if (config["type"].isNull()) { throw ML::Exception("Your LoggerMetrics config needs to " "specify a [type] key."); } string loggerType = config["type"].asString(); failSafe = config["failSafe"].asBool(); auto fct = [&] { if (loggerType == "mongo") { logger.reset(new LoggerMetricsMongo(config, coll, appName)); } else if (loggerType == "term" || loggerType == "terminal") { logger.reset(new LoggerMetricsTerm(config, coll, appName)); } else if (loggerType == "void") { logger.reset(new LoggerMetricsVoid(config, coll, appName)); } else { throw ML::Exception("Unknown logger type [%s]", loggerType.c_str()); } }; if (failSafe) { try { fct(); } catch (const exception & exc) { cerr << "Logger fail safe caught: " << exc.what() << endl; logger = shared_ptr<ILoggerMetrics>( new LoggerMetricsTerm(config, coll, appName)); } } else { fct(); } string now = Date::now().printClassic(); Json::Value v; v["startTime"] = now; v["appName"] = appName; v["parent_id"] = getEnv("METRICS_PARENT_ID"); v["user"] = string(getEnv("LOGNAME")); char hostname[128]; int hostnameOk = !gethostname(hostname, 128); v["hostname"] = string(hostnameOk ? hostname : ""); v["workingDirectory"] = string(getEnv("PWD")); // Log environment variable RUNID. Useful to give a name to an // experiment. v["runid"] = getEnv("RUNID"); logger->logProcess(v); setenv("METRICS_PARENT_ID", logger->getProcessId().c_str(), 1); } shared_ptr<ILoggerMetrics> ILoggerMetrics:: getSingleton() { std::lock_guard<std::mutex> lock(m); if (!logger) { cerr << ("Calling getSingleton without calling setup first," " logging implicitly disabled.\n"); logger.reset(new LoggerMetricsVoid("")); } return logger; } void ILoggerMetrics:: logMetrics(const Json::Value & json) { vector<string> stack; std::function<void(const Json::Value &)> doit; doit = [&] (const Json::Value & v) { for (auto it = v.begin(); it != v.end(); ++it) { string memberName = it.memberName(); if (v[memberName].isObject()) { stack.push_back(memberName); doit(v[memberName]); stack.pop_back(); } else { const Json::Value & current = v[memberName]; if (!(current.isInt() || current.isUInt() || current.isDouble() || current.isNumeric())) { stringstream key; for (const string & s: stack) { key << s << "."; } key << memberName; string value = current.toString(); cerr << value << endl; value = value.substr(1, value.length() - 3); throw ML::Exception("logMetrics only accepts numerical" " values. Key [%s] has value [%s].", key.str().c_str(), value.c_str()); } } } }; auto fct = [&] () { doit(json); logInCategory(METRICS, json); }; failSafeHelper(fct); } void ILoggerMetrics:: failSafeHelper(const std::function<void()> & fct) { if (failSafe) { try { fct(); } catch (const exception & exc) { cerr << "Logger fail safe caught: " << exc.what() << endl; } } else { fct(); } } void ILoggerMetrics:: close() { Json::Value v; Date endDate = Date::now(); v["endDate"] = endDate.printClassic(); v["duration"] = endDate - startDate; logInCategory(PROCESS, v); logProcess(v); } <|endoftext|>
<commit_before>// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "structuredfieldvalue.hpp" #include "fieldvalues.h" #include <vespa/log/log.h> LOG_SETUP(".document.fieldvalue.structured"); namespace document { IMPLEMENT_IDENTIFIABLE_ABSTRACT(StructuredFieldValue, FieldValue); StructuredFieldValue::Iterator::Iterator() : _owner(0), _iterator(), _field(0) { } StructuredFieldValue::Iterator::Iterator(const StructuredFieldValue& owner, const Field* first) : _owner(&const_cast<StructuredFieldValue&>(owner)), _iterator(owner.getIterator(first).release()), _field(_iterator->getNextField()) { } StructuredFieldValue::Iterator StructuredFieldValue::Iterator::operator++(int) // postfix { StructuredFieldValue::Iterator it(*this); operator++(); return it; } StructuredFieldValue::StructuredFieldValue(const StructuredFieldValue& other) : FieldValue(other), _type(other._type) { } StructuredFieldValue::StructuredFieldValue(const DataType &type) : FieldValue(), _type(&type) { } void StructuredFieldValue::setType(const DataType& type) { _type = &type; } StructuredFieldValue& StructuredFieldValue::operator=(const StructuredFieldValue& other) { if (this == &other) { return *this; } FieldValue::operator=(other); _type = other._type; return *this; } void StructuredFieldValue::setFieldValue(const Field & field, const FieldValue & value) { if (!field.getDataType().isValueType(value) && !value.getDataType()->isA(field.getDataType())) { throw vespalib::IllegalArgumentException( "Cannot assign value of type " + value.getDataType()->toString() + "with value : '" + value.toString() + "' to field " + field.getName().c_str() + " of type " + field.getDataType().toString() + ".", VESPA_STRLOC); } setFieldValue(field, FieldValue::UP(value.clone())); } FieldValue::UP StructuredFieldValue::onGetNestedFieldValue( FieldPath::const_iterator start, FieldPath::const_iterator end_) const { FieldValue::UP fv = getValue(start->getFieldRef()); if (fv.get() != NULL) { if ((start + 1) != end_) { return fv->getNestedFieldValue(start + 1, end_); } } return fv; } FieldValue::IteratorHandler::ModificationStatus StructuredFieldValue::onIterateNested( FieldPath::const_iterator start, FieldPath::const_iterator end_, IteratorHandler & handler) const { IteratorHandler::StructScope autoScope(handler, *this); if (start != end_) { if (start->getType() == FieldPathEntry::STRUCT_FIELD) { bool exists = getValue(start->getFieldRef(), start->getFieldValueToSet()); LOG(spam, "fieldRef = %s", start->getFieldRef().toString().c_str()); LOG(spam, "fieldValueToSet = %s", start->getFieldValueToSet().toString().c_str()); if (exists) { IteratorHandler::ModificationStatus status = start->getFieldValueToSet().iterateNested(start + 1, end_, handler); if (status == IteratorHandler::REMOVED) { LOG(spam, "field exists, status = REMOVED"); const_cast<StructuredFieldValue&>(*this).remove(start->getFieldRef()); return IteratorHandler::MODIFIED; } else if (status == IteratorHandler::MODIFIED) { LOG(spam, "field exists, status = MODIFIED"); const_cast<StructuredFieldValue&>(*this).setFieldValue( start->getFieldRef(), start->getFieldValueToSet()); return IteratorHandler::MODIFIED; } else { LOG(spam, "field exists, status = %u", status); return status; } } else if (handler.createMissingPath()) { LOG(spam, "createMissingPath is true"); IteratorHandler::ModificationStatus status = start->getFieldValueToSet().iterateNested(start + 1, end_, handler); if (status == IteratorHandler::MODIFIED) { LOG(spam, "field did not exist, status = MODIFIED"); const_cast<StructuredFieldValue&>(*this).setFieldValue( start->getFieldRef(), start->getFieldValueToSet()); return status; } } LOG(spam, "field did not exist, returning NOT_MODIFIED"); return IteratorHandler::NOT_MODIFIED; } else { throw vespalib::IllegalArgumentException("Illegal field path for struct value"); } } else { IteratorHandler::ModificationStatus status = handler.modify(const_cast<StructuredFieldValue&>(*this)); if (status == IteratorHandler::REMOVED) { LOG(spam, "field REMOVED"); return status; } if (handler.handleComplex(*this)) { LOG(spam, "handleComplex"); std::vector<const Field*> fieldsToRemove; for (const_iterator it(begin()), mt(end()); it != mt; it++) { IteratorHandler::ModificationStatus currStatus = getValue(it.field())->iterateNested(start, end_, handler); if (currStatus == IteratorHandler::REMOVED) { fieldsToRemove.push_back(&it.field()); status = IteratorHandler::MODIFIED; } else if (currStatus == IteratorHandler::MODIFIED) { status = currStatus; } } for (const Field * toRemove : fieldsToRemove){ const_cast<StructuredFieldValue&>(*this).remove(*toRemove); } } return status; } } using ConstCharP = const char *; template void StructuredFieldValue::set(const vespalib::stringref & field, int32_t value); template void StructuredFieldValue::set(const vespalib::stringref & field, int64_t value); template void StructuredFieldValue::set(const vespalib::stringref & field, double value); template void StructuredFieldValue::set(const vespalib::stringref & field, ConstCharP value); template void StructuredFieldValue::set(const vespalib::stringref & field, vespalib::stringref value); template void StructuredFieldValue::set(const vespalib::stringref & field, vespalib::string value); template std::unique_ptr<MapFieldValue> StructuredFieldValue::getAs<MapFieldValue>(const Field &field) const; template std::unique_ptr<ArrayFieldValue> StructuredFieldValue::getAs<ArrayFieldValue>(const Field &field) const; template std::unique_ptr<WeightedSetFieldValue> StructuredFieldValue::getAs<WeightedSetFieldValue>(const Field &field) const; } // document <commit_msg>Remove use of LinkedPtr<commit_after>// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "structuredfieldvalue.hpp" #include "fieldvalues.h" #include <vespa/log/log.h> LOG_SETUP(".document.fieldvalue.structured"); namespace document { IMPLEMENT_IDENTIFIABLE_ABSTRACT(StructuredFieldValue, FieldValue); StructuredFieldValue::Iterator::Iterator() : _owner(0), _iterator(), _field(0) { } StructuredFieldValue::Iterator::Iterator(const StructuredFieldValue& owner, const Field* first) : _owner(&const_cast<StructuredFieldValue&>(owner)), _iterator(owner.getIterator(first).release()), _field(_iterator->getNextField()) { } StructuredFieldValue::StructuredFieldValue(const StructuredFieldValue& other) : FieldValue(other), _type(other._type) { } StructuredFieldValue::StructuredFieldValue(const DataType &type) : FieldValue(), _type(&type) { } void StructuredFieldValue::setType(const DataType& type) { _type = &type; } StructuredFieldValue& StructuredFieldValue::operator=(const StructuredFieldValue& other) { if (this == &other) { return *this; } FieldValue::operator=(other); _type = other._type; return *this; } void StructuredFieldValue::setFieldValue(const Field & field, const FieldValue & value) { if (!field.getDataType().isValueType(value) && !value.getDataType()->isA(field.getDataType())) { throw vespalib::IllegalArgumentException( "Cannot assign value of type " + value.getDataType()->toString() + "with value : '" + value.toString() + "' to field " + field.getName().c_str() + " of type " + field.getDataType().toString() + ".", VESPA_STRLOC); } setFieldValue(field, FieldValue::UP(value.clone())); } FieldValue::UP StructuredFieldValue::onGetNestedFieldValue( FieldPath::const_iterator start, FieldPath::const_iterator end_) const { FieldValue::UP fv = getValue(start->getFieldRef()); if (fv.get() != NULL) { if ((start + 1) != end_) { return fv->getNestedFieldValue(start + 1, end_); } } return fv; } FieldValue::IteratorHandler::ModificationStatus StructuredFieldValue::onIterateNested( FieldPath::const_iterator start, FieldPath::const_iterator end_, IteratorHandler & handler) const { IteratorHandler::StructScope autoScope(handler, *this); if (start != end_) { if (start->getType() == FieldPathEntry::STRUCT_FIELD) { bool exists = getValue(start->getFieldRef(), start->getFieldValueToSet()); LOG(spam, "fieldRef = %s", start->getFieldRef().toString().c_str()); LOG(spam, "fieldValueToSet = %s", start->getFieldValueToSet().toString().c_str()); if (exists) { IteratorHandler::ModificationStatus status = start->getFieldValueToSet().iterateNested(start + 1, end_, handler); if (status == IteratorHandler::REMOVED) { LOG(spam, "field exists, status = REMOVED"); const_cast<StructuredFieldValue&>(*this).remove(start->getFieldRef()); return IteratorHandler::MODIFIED; } else if (status == IteratorHandler::MODIFIED) { LOG(spam, "field exists, status = MODIFIED"); const_cast<StructuredFieldValue&>(*this).setFieldValue( start->getFieldRef(), start->getFieldValueToSet()); return IteratorHandler::MODIFIED; } else { LOG(spam, "field exists, status = %u", status); return status; } } else if (handler.createMissingPath()) { LOG(spam, "createMissingPath is true"); IteratorHandler::ModificationStatus status = start->getFieldValueToSet().iterateNested(start + 1, end_, handler); if (status == IteratorHandler::MODIFIED) { LOG(spam, "field did not exist, status = MODIFIED"); const_cast<StructuredFieldValue&>(*this).setFieldValue( start->getFieldRef(), start->getFieldValueToSet()); return status; } } LOG(spam, "field did not exist, returning NOT_MODIFIED"); return IteratorHandler::NOT_MODIFIED; } else { throw vespalib::IllegalArgumentException("Illegal field path for struct value"); } } else { IteratorHandler::ModificationStatus status = handler.modify(const_cast<StructuredFieldValue&>(*this)); if (status == IteratorHandler::REMOVED) { LOG(spam, "field REMOVED"); return status; } if (handler.handleComplex(*this)) { LOG(spam, "handleComplex"); std::vector<const Field*> fieldsToRemove; for (const_iterator it(begin()), mt(end()); it != mt; ++it) { IteratorHandler::ModificationStatus currStatus = getValue(it.field())->iterateNested(start, end_, handler); if (currStatus == IteratorHandler::REMOVED) { fieldsToRemove.push_back(&it.field()); status = IteratorHandler::MODIFIED; } else if (currStatus == IteratorHandler::MODIFIED) { status = currStatus; } } for (const Field * toRemove : fieldsToRemove){ const_cast<StructuredFieldValue&>(*this).remove(*toRemove); } } return status; } } using ConstCharP = const char *; template void StructuredFieldValue::set(const vespalib::stringref & field, int32_t value); template void StructuredFieldValue::set(const vespalib::stringref & field, int64_t value); template void StructuredFieldValue::set(const vespalib::stringref & field, double value); template void StructuredFieldValue::set(const vespalib::stringref & field, ConstCharP value); template void StructuredFieldValue::set(const vespalib::stringref & field, vespalib::stringref value); template void StructuredFieldValue::set(const vespalib::stringref & field, vespalib::string value); template std::unique_ptr<MapFieldValue> StructuredFieldValue::getAs<MapFieldValue>(const Field &field) const; template std::unique_ptr<ArrayFieldValue> StructuredFieldValue::getAs<ArrayFieldValue>(const Field &field) const; template std::unique_ptr<WeightedSetFieldValue> StructuredFieldValue::getAs<WeightedSetFieldValue>(const Field &field) const; } // document <|endoftext|>
<commit_before>#ifndef AX_VECTOR_H #define AX_VECTOR_H #include <array> #include <iostream> #include "VectorExp.hpp" namespace ax { template<std::size_t N> class RealVector { public: using value_trait = Vector; constexpr static std::size_t size = N; public: RealVector() { values.fill(0e0); } RealVector(const double d) { values.fill(d); } RealVector(const std::array<double, N>& v) : values(v) {} template<class E, typename std::enable_if<is_VectorExpression< typename E::value_trait>::value>::type*& = enabler> RealVector(const E& exp) { for(auto i(0); i<size; ++i) (*this)[i] = exp[i]; } template<class E, typename std::enable_if<is_VectorExpression< typename E::value_trait>::value>::type*& = enabler> RealVector& operator=(const E& exp) { for(auto i(0); i<size; ++i) (*this)[i] = exp[i]; return *this; } template<class E, typename std::enable_if<is_VectorExpression< typename E::value_trait>::value>::type*& = enabler> RealVector& operator+=(const E& exp) { *this = VectorAdd<RealVector, E>(*this, exp); return *this; } template<class E, typename std::enable_if<is_VectorExpression< typename E::value_trait>::value>::type*& = enabler> RealVector& operator-=(const E& exp) { *this = VectorSub<RealVector, E>(*this, exp); return *this; } template<class E, typename std::enable_if<is_ScalarType<E>::value>::type*& = enabler> RealVector& operator*=(const E& exp) { *this = VectorSclMul<RealVector>(*this, exp); return *this; } template<class E, typename std::enable_if<is_ScalarType<E>::value>::type*& = enabler> RealVector& operator/=(const E& exp) { *this = VectorSclDiv<RealVector>(*this, exp); return *this; } double operator[](const std::size_t i) const { return values[i]; } double& operator[](const std::size_t i) { return values[i]; } private: std::array<double, N> values; }; template<std::size_t N> std::ostream& operator<<(std::ostream& os, const RealVector<N>& vec) { for(auto i(0); i<N; ++i) os << vec[i] << " "; return os; } } #endif//AX_VECTOR_H <commit_msg>fix *= operator of VectorNd<commit_after>#ifndef AX_VECTOR_H #define AX_VECTOR_H #include <array> #include <iostream> #include "VectorExp.hpp" namespace ax { template<std::size_t N> class RealVector { public: using value_trait = Vector; constexpr static std::size_t size = N; public: RealVector() { values.fill(0e0); } RealVector(const double d) { values.fill(d); } RealVector(const std::array<double, N>& v) : values(v) {} template<class E, typename std::enable_if<is_VectorExpression< typename E::value_trait>::value>::type*& = enabler> RealVector(const E& exp) { for(auto i(0); i<size; ++i) (*this)[i] = exp[i]; } template<class E, typename std::enable_if<is_VectorExpression< typename E::value_trait>::value>::type*& = enabler> RealVector& operator=(const E& exp) { for(auto i(0); i<size; ++i) (*this)[i] = exp[i]; return *this; } template<class E, typename std::enable_if<is_VectorExpression< typename E::value_trait>::value>::type*& = enabler> RealVector& operator+=(const E& exp) { *this = VectorAdd<RealVector, E>(*this, exp); return *this; } template<class E, typename std::enable_if<is_VectorExpression< typename E::value_trait>::value>::type*& = enabler> RealVector& operator-=(const E& exp) { *this = VectorSub<RealVector, E>(*this, exp); return *this; } template<class E, typename std::enable_if<is_ScalarType<E>::value>::type*& = enabler> RealVector& operator*=(const E& exp) { *this = VectorSclMul<RealVector>(exp, *this); return *this; } template<class E, typename std::enable_if<is_ScalarType<E>::value>::type*& = enabler> RealVector& operator/=(const E& exp) { *this = VectorSclDiv<RealVector>(*this, exp); return *this; } double operator[](const std::size_t i) const { return values[i]; } double& operator[](const std::size_t i) { return values[i]; } private: std::array<double, N> values; }; template<std::size_t N> std::ostream& operator<<(std::ostream& os, const RealVector<N>& vec) { for(auto i(0); i<N; ++i) os << vec[i] << " "; return os; } } #endif//AX_VECTOR_H <|endoftext|>
<commit_before>#include <windows.h> #include <SDL2/SDL.h> #include <SDL2/SDL_syswm.h> #include "Common.h" #include "PrjHndl.h" #include "WinAPI.h" namespace WinAPI { HWND hWnd; HMENU hMenu; HMENU hSubMenu_File; HMENU hSubMenu_View; COLORREF custom_colours[16]; void SaveHWND(SDL_Window* const window) { SDL_SysWMinfo info; SDL_VERSION(&info.version) SDL_GetWindowWMInfo(window,&info); hWnd = info.info.win.window; } void CreateMenuBar(void) { hMenu = CreateMenu(); hSubMenu_File = CreatePopupMenu(); AppendMenu(hMenu, MF_STRING | MF_POPUP, (UINT)hSubMenu_File, "&File"); AppendMenu(hSubMenu_File, MF_STRING, MENUBAR_FILE_OPENPROJECT, "&Open"); AppendMenu(hSubMenu_File, MF_STRING | MF_GRAYED, MENUBAR_FILE_SAVE, "&Save"); AppendMenu(hSubMenu_File, MF_STRING | MF_GRAYED, MENUBAR_FILE_CLOSE, "&Close"); AppendMenu(hSubMenu_File, MF_SEPARATOR, 0, NULL); AppendMenu(hSubMenu_File, MF_STRING, MENUBAR_FILE_EXIT, "&Exit"); hSubMenu_View = CreatePopupMenu(); AppendMenu(hMenu, MF_STRING | MF_POPUP, (UINT)hSubMenu_View, "&View"); AppendMenu(hSubMenu_View, MF_STRING, MENUBAR_VIEW_BACKGROUNDCOLOUR, "&Background Colour..."); SetMenu(hWnd, hMenu); SDL_EventState(SDL_SYSWMEVENT, SDL_ENABLE); } void HandleWindowsEvent(const SDL_Event* const event) { if (event->syswm.msg->msg.win.msg == WM_COMMAND) { switch (LOWORD(event->syswm.msg->msg.win.wParam)) { case MENUBAR_FILE_OPENPROJECT: { char filename[500] = ""; if (WinAPI::OpenProjectFilePrompt(filename) == true) { if (CurProject != NULL) delete CurProject; CurProject = new Project(filename, MainScreen); EnableMenuItem(hSubMenu_File, MENUBAR_FILE_SAVE, MF_ENABLED); EnableMenuItem(hSubMenu_File, MENUBAR_FILE_CLOSE, MF_ENABLED); //Process initial display MainScreen->Fill(MainScreen->BackgroundColour.red, MainScreen->BackgroundColour.green, MainScreen->BackgroundColour.blue); CurProject->Redraw(); } break; } case MENUBAR_FILE_SAVE: { CurProject->Save(); break; } case MENUBAR_FILE_CLOSE: { delete CurProject; CurProject = NULL; // Deleting an object does not NULL this pointer, so we have to do it ourselves EnableMenuItem(hSubMenu_File, MENUBAR_FILE_SAVE, MF_GRAYED); EnableMenuItem(hSubMenu_File, MENUBAR_FILE_CLOSE, MF_GRAYED); MainScreen->Fill(MainScreen->BackgroundColour.red, MainScreen->BackgroundColour.green, MainScreen->BackgroundColour.blue); break; } case MENUBAR_FILE_EXIT: { exit(1); } case MENUBAR_VIEW_BACKGROUNDCOLOUR: { CHOOSECOLOR user_colour; user_colour.lStructSize = sizeof(user_colour); user_colour.hwndOwner = hWnd; user_colour.rgbResult = RGB(MainScreen->BackgroundColour.red,MainScreen->BackgroundColour.green,MainScreen->BackgroundColour.blue); user_colour.lpCustColors = custom_colours; user_colour.Flags = CC_RGBINIT; if (ChooseColor(&user_colour) == true) { MainScreen->BackgroundColour.red = GetRValue(user_colour.rgbResult); MainScreen->BackgroundColour.green = GetGValue(user_colour.rgbResult); MainScreen->BackgroundColour.blue = GetBValue(user_colour.rgbResult); MainScreen->Fill(MainScreen->BackgroundColour.red, MainScreen->BackgroundColour.green, MainScreen->BackgroundColour.blue); if (CurProject != NULL) CurProject->Redraw(); } break; } } } } bool OpenProjectFilePrompt(char* const filepath) { OPENFILENAME ofn; memset(&ofn, 0, sizeof(ofn)); ofn.lStructSize = sizeof(ofn); ofn.hwndOwner = hWnd; ofn.hInstance = NULL; ofn.lpstrFilter = TEXT("PlaneEd project file (*.txt)\0*.txt\0\0"); ofn.nFilterIndex = 1; ofn.lpstrFile = filepath; ofn.nMaxFile = 500; ofn.Flags = OFN_FILEMUSTEXIST; bool bRes = GetOpenFileName(&ofn); return bRes; } } <commit_msg>Clearing CHOOSECOLOR before using it<commit_after>#include <windows.h> #include <SDL2/SDL.h> #include <SDL2/SDL_syswm.h> #include "Common.h" #include "PrjHndl.h" #include "WinAPI.h" namespace WinAPI { HWND hWnd; HMENU hMenu; HMENU hSubMenu_File; HMENU hSubMenu_View; COLORREF custom_colours[16]; void SaveHWND(SDL_Window* const window) { SDL_SysWMinfo info; SDL_VERSION(&info.version) SDL_GetWindowWMInfo(window,&info); hWnd = info.info.win.window; } void CreateMenuBar(void) { hMenu = CreateMenu(); hSubMenu_File = CreatePopupMenu(); AppendMenu(hMenu, MF_STRING | MF_POPUP, (UINT)hSubMenu_File, "&File"); AppendMenu(hSubMenu_File, MF_STRING, MENUBAR_FILE_OPENPROJECT, "&Open"); AppendMenu(hSubMenu_File, MF_STRING | MF_GRAYED, MENUBAR_FILE_SAVE, "&Save"); AppendMenu(hSubMenu_File, MF_STRING | MF_GRAYED, MENUBAR_FILE_CLOSE, "&Close"); AppendMenu(hSubMenu_File, MF_SEPARATOR, 0, NULL); AppendMenu(hSubMenu_File, MF_STRING, MENUBAR_FILE_EXIT, "&Exit"); hSubMenu_View = CreatePopupMenu(); AppendMenu(hMenu, MF_STRING | MF_POPUP, (UINT)hSubMenu_View, "&View"); AppendMenu(hSubMenu_View, MF_STRING, MENUBAR_VIEW_BACKGROUNDCOLOUR, "&Background Colour..."); SetMenu(hWnd, hMenu); SDL_EventState(SDL_SYSWMEVENT, SDL_ENABLE); } void HandleWindowsEvent(const SDL_Event* const event) { if (event->syswm.msg->msg.win.msg == WM_COMMAND) { switch (LOWORD(event->syswm.msg->msg.win.wParam)) { case MENUBAR_FILE_OPENPROJECT: { char filename[500] = ""; if (WinAPI::OpenProjectFilePrompt(filename) == true) { if (CurProject != NULL) delete CurProject; CurProject = new Project(filename, MainScreen); EnableMenuItem(hSubMenu_File, MENUBAR_FILE_SAVE, MF_ENABLED); EnableMenuItem(hSubMenu_File, MENUBAR_FILE_CLOSE, MF_ENABLED); //Process initial display MainScreen->Fill(MainScreen->BackgroundColour.red, MainScreen->BackgroundColour.green, MainScreen->BackgroundColour.blue); CurProject->Redraw(); } break; } case MENUBAR_FILE_SAVE: { CurProject->Save(); break; } case MENUBAR_FILE_CLOSE: { delete CurProject; CurProject = NULL; // Deleting an object does not NULL this pointer, so we have to do it ourselves EnableMenuItem(hSubMenu_File, MENUBAR_FILE_SAVE, MF_GRAYED); EnableMenuItem(hSubMenu_File, MENUBAR_FILE_CLOSE, MF_GRAYED); MainScreen->Fill(MainScreen->BackgroundColour.red, MainScreen->BackgroundColour.green, MainScreen->BackgroundColour.blue); break; } case MENUBAR_FILE_EXIT: { exit(1); } case MENUBAR_VIEW_BACKGROUNDCOLOUR: { CHOOSECOLOR user_colour; memset(&user_colour, 0, sizeof(user_colour)); user_colour.lStructSize = sizeof(user_colour); user_colour.hwndOwner = hWnd; user_colour.rgbResult = RGB(MainScreen->BackgroundColour.red,MainScreen->BackgroundColour.green,MainScreen->BackgroundColour.blue); user_colour.lpCustColors = custom_colours; user_colour.Flags = CC_RGBINIT; if (ChooseColor(&user_colour) == true) { MainScreen->BackgroundColour.red = GetRValue(user_colour.rgbResult); MainScreen->BackgroundColour.green = GetGValue(user_colour.rgbResult); MainScreen->BackgroundColour.blue = GetBValue(user_colour.rgbResult); MainScreen->Fill(MainScreen->BackgroundColour.red, MainScreen->BackgroundColour.green, MainScreen->BackgroundColour.blue); if (CurProject != NULL) CurProject->Redraw(); } break; } } } } bool OpenProjectFilePrompt(char* const filepath) { OPENFILENAME ofn; memset(&ofn, 0, sizeof(ofn)); ofn.lStructSize = sizeof(ofn); ofn.hwndOwner = hWnd; ofn.hInstance = NULL; ofn.lpstrFilter = TEXT("PlaneEd project file (*.txt)\0*.txt\0\0"); ofn.nFilterIndex = 1; ofn.lpstrFile = filepath; ofn.nMaxFile = 500; ofn.Flags = OFN_FILEMUSTEXIST; bool bRes = GetOpenFileName(&ofn); return bRes; } } <|endoftext|>
<commit_before>/****************************************************************************** * ____ _ _____ * * / ___| / \ | ___| C++ * * | | / _ \ | |_ Actor * * | |___ / ___ \| _| Framework * * \____/_/ \_|_| * * * * Copyright (C) 2011 - 2017 * * Dominik Charousset <dominik.charousset (at) haw-hamburg.de> * * * * Distributed under the terms and conditions of the BSD 3-Clause License or * * (at your option) under the terms and conditions of the Boost Software * * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. * * * * If you did not receive a copy of the license files, see * * http://opensource.org/licenses/BSD-3-Clause and * * http://www.boost.org/LICENSE_1_0.txt. * ******************************************************************************/ #ifndef CAF_STREAMBUF_HPP #define CAF_STREAMBUF_HPP #include <algorithm> #include <cstddef> #include <cstring> #include <limits> #include <streambuf> #include <type_traits> #include <vector> #include "caf/config.hpp" #include "caf/detail/type_traits.hpp" namespace caf { /// The base class for all stream buffer implementations. template <class CharT = char, class Traits = std::char_traits<CharT>> class stream_buffer : public std::basic_streambuf<CharT, Traits> { protected: /// The standard only defines pbump(int), which can overflow on 64-bit /// architectures. All stream buffer implementations should therefore use /// these function instead. For a detailed discussion, see: /// https://gcc.gnu.org/bugzilla/show_bug.cgi?id=47921 template <class T = int> typename std::enable_if<sizeof(T) == 4>::type safe_pbump(std::streamsize n) { while (n > std::numeric_limits<int>::max()) { this->pbump(std::numeric_limits<int>::max()); n -= std::numeric_limits<int>::max(); } this->pbump(static_cast<int>(n)); } template <class T = int> typename std::enable_if<sizeof(T) == 8>::type safe_pbump(std::streamsize n) { this->pbump(static_cast<int>(n)); } // As above, but for the get area. template <class T = int> typename std::enable_if<sizeof(T) == 4>::type safe_gbump(std::streamsize n) { while (n > std::numeric_limits<int>::max()) { this->gbump(std::numeric_limits<int>::max()); n -= std::numeric_limits<int>::max(); } this->gbump(static_cast<int>(n)); } template <class T = int> typename std::enable_if<sizeof(T) == 8>::type safe_gbump(std::streamsize n) { this->gbump(static_cast<int>(n)); } }; /// A streambuffer abstraction over a fixed array of bytes. This streambuffer /// cannot overflow/underflow. Once it has reached its end, attempts to read /// characters will return `trait_type::eof`. template <class CharT = char, class Traits = std::char_traits<CharT>> class arraybuf : public stream_buffer<CharT, Traits> { public: using base = std::basic_streambuf<CharT, Traits>; using char_type = typename base::char_type; using traits_type = typename base::traits_type; using int_type = typename base::int_type; using pos_type = typename base::pos_type; using off_type = typename base::off_type; /// Constructs an array streambuffer from a container. /// @param c A contiguous container. /// @pre `c.data()` must point to a contiguous sequence of characters having /// length `c.size()`. template < class Container, class = typename std::enable_if< detail::has_data_member<Container>::value && detail::has_size_member<Container>::value >::type > arraybuf(Container& c) : arraybuf(const_cast<char_type*>(c.data()), c.size()) { // nop } /// Constructs an array streambuffer from a raw character sequence. /// @param data A pointer to the first character. /// @param size The length of the character sequence. arraybuf(char_type* data, size_t size) { setbuf(data, static_cast<std::streamsize>(size)); } // There exists a bug in libstdc++ version < 5: the implementation does not // provide the necessary move constructors, so we have to roll our own :-/. // See https://gcc.gnu.org/bugzilla/show_bug.cgi?id=54316 for details. // TODO: remove after having raised the minimum GCC version to 5. arraybuf(arraybuf&& other) { this->setg(other.eback(), other.gptr(), other.egptr()); this->setp(other.pptr(), other.epptr()); other.setg(nullptr, nullptr, nullptr); other.setp(nullptr, nullptr); } // TODO: remove after having raised the minimum GCC version to 5. arraybuf& operator=(arraybuf&& other) { this->setg(other.eback(), other.gptr(), other.egptr()); this->setp(other.pptr(), other.epptr()); other.setg(nullptr, nullptr, nullptr); other.setp(nullptr, nullptr); return *this; } protected: // -- positioning ---------------------------------------------------------- std::basic_streambuf<char_type, Traits>* setbuf(char_type* s, std::streamsize n) override { this->setg(s, s, s + n); this->setp(s, s + n); return this; } pos_type seekpos(pos_type pos, std::ios_base::openmode which = std::ios_base::in | std::ios_base::out) override { auto get = (which & std::ios_base::in) == std::ios_base::in; auto put = (which & std::ios_base::out) == std::ios_base::out; if (!(get || put)) return pos_type(off_type(-1)); // nothing to do if (get) this->setg(this->eback(), this->eback() + pos, this->egptr()); if (put) { this->setp(this->pbase(), this->epptr()); this->safe_pbump(pos); } return pos; } pos_type seekoff(off_type off, std::ios_base::seekdir dir, std::ios_base::openmode which) override { auto new_off = pos_type(off_type(-1)); auto get = (which & std::ios_base::in) == std::ios_base::in; auto put = (which & std::ios_base::out) == std::ios_base::out; if (!(get || put)) return new_off; // nothing to do if (get) { switch (dir) { case std::ios_base::beg: new_off = 0; break; case std::ios_base::cur: new_off = this->gptr() - this->eback(); break; case std::ios_base::end: new_off = this->egptr() - this->eback(); break; } new_off += off; this->setg(this->eback(), this->eback() + new_off, this->egptr()); } if (put) { switch (dir) { case std::ios_base::beg: new_off = 0; break; case std::ios_base::cur: new_off = this->pptr() - this->pbase(); break; case std::ios_base::end: new_off = this->egptr() - this->pbase(); break; } new_off += off; this->setp(this->pbase(), this->epptr()); this->safe_pbump(new_off); } return new_off; } // -- put area ------------------------------------------------------------- std::streamsize xsputn(const char_type* s, std::streamsize n) override { auto available = this->epptr() - this->pptr(); auto actual = std::min(n, static_cast<std::streamsize>(available)); std::memcpy(this->pptr(), s, static_cast<size_t>(actual) * sizeof(char_type)); this->safe_pbump(actual); return actual; } // -- get area ------------------------------------------------------------- std::streamsize xsgetn(char_type* s, std::streamsize n) override { auto available = this->egptr() - this->gptr(); auto actual = std::min(n, static_cast<std::streamsize>(available)); std::memcpy(s, this->gptr(), static_cast<size_t>(actual) * sizeof(char_type)); this->safe_gbump(actual); return actual; } }; /// A streambuffer abstraction over a contiguous container. It supports /// reading in the same style as `arraybuf`, but is unbounded for output. template <class Container> class containerbuf : public stream_buffer< typename Container::value_type, std::char_traits<typename Container::value_type> > { public: using base = std::basic_streambuf< typename Container::value_type, std::char_traits<typename Container::value_type> >; using char_type = typename base::char_type; using traits_type = typename base::traits_type; using int_type = typename base::int_type; using pos_type = typename base::pos_type; using off_type = typename base::off_type; /// Constructs a container streambuf. /// @param c A contiguous container. template < class C = Container, class = typename std::enable_if< detail::has_data_member<C>::value && detail::has_size_member<C>::value >::type > containerbuf(Container& c) : container_(c) { this->setg(const_cast<char_type*>(c.data()), const_cast<char_type*>(c.data()), const_cast<char_type*>(c.data()) + c.size()); } // See note in arraybuf(arraybuf&&). // TODO: remove after having raised the minimum GCC version to 5. containerbuf(containerbuf&& other) : container_(other.container_) { this->setg(other.eback(), other.gptr(), other.egptr()); other.setg(nullptr, nullptr, nullptr); } // TODO: remove after having raised the minimum GCC version to 5. containerbuf& operator=(containerbuf&& other) { this->setg(other.eback(), other.gptr(), other.egptr()); other.setg(nullptr, nullptr, nullptr); return *this; } // Hides base-class implementation to simplify single-character lookup. int_type sgetc() { if (this->gptr() == this->egptr()) return traits_type::eof(); return traits_type::to_int_type(*this->gptr()); } // Hides base-class implementation to simplify single-character insert. int_type sputc(char_type c) { container_.push_back(c); return c; } protected: // We can't get obtain more characters on underflow, so we only optimize // multi-character sequential reads. std::streamsize xsgetn(char_type* s, std::streamsize n) override { auto available = this->egptr() - this->gptr(); auto actual = std::min(n, static_cast<std::streamsize>(available)); std::memcpy(s, this->gptr(), static_cast<size_t>(actual) * sizeof(char_type)); this->safe_gbump(actual); return actual; } // Should never get called, because there is always space in the buffer. // (But just in case, it does the same thing as sputc.) int_type overflow(int_type c = traits_type::eof()) final { if (!traits_type::eq_int_type(c, traits_type::eof())) container_.push_back(traits_type::to_char_type(c)); return c; } std::streamsize xsputn(const char_type* s, std::streamsize n) override { // TODO: Do a performance analysis whether the current implementation based // on copy_n is faster than these two statements: // (1) container_.resize(container_.size() + n); // (2) std::memcpy(this->pptr(), s, n * sizeof(char_type)); std::copy_n(s, n, std::back_inserter(container_)); return n; } private: Container& container_; }; using charbuf = arraybuf<char>; using vectorbuf = containerbuf<std::vector<char>>; } // namespace caf #endif // CAF_STREAMBUF_HPP <commit_msg>Remove warnings<commit_after>/****************************************************************************** * ____ _ _____ * * / ___| / \ | ___| C++ * * | | / _ \ | |_ Actor * * | |___ / ___ \| _| Framework * * \____/_/ \_|_| * * * * Copyright (C) 2011 - 2017 * * Dominik Charousset <dominik.charousset (at) haw-hamburg.de> * * * * Distributed under the terms and conditions of the BSD 3-Clause License or * * (at your option) under the terms and conditions of the Boost Software * * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. * * * * If you did not receive a copy of the license files, see * * http://opensource.org/licenses/BSD-3-Clause and * * http://www.boost.org/LICENSE_1_0.txt. * ******************************************************************************/ #ifndef CAF_STREAMBUF_HPP #define CAF_STREAMBUF_HPP #include <algorithm> #include <cstddef> #include <cstring> #include <limits> #include <streambuf> #include <type_traits> #include <vector> #include "caf/config.hpp" #include "caf/detail/type_traits.hpp" namespace caf { /// The base class for all stream buffer implementations. template <class CharT = char, class Traits = std::char_traits<CharT>> class stream_buffer : public std::basic_streambuf<CharT, Traits> { protected: /// The standard only defines pbump(int), which can overflow on 64-bit /// architectures. All stream buffer implementations should therefore use /// these function instead. For a detailed discussion, see: /// https://gcc.gnu.org/bugzilla/show_bug.cgi?id=47921 template <class T = int> typename std::enable_if<sizeof(T) == 4>::type safe_pbump(std::streamsize n) { while (n > std::numeric_limits<int>::max()) { this->pbump(std::numeric_limits<int>::max()); n -= std::numeric_limits<int>::max(); } this->pbump(static_cast<int>(n)); } template <class T = int> typename std::enable_if<sizeof(T) == 8>::type safe_pbump(std::streamsize n) { this->pbump(static_cast<int>(n)); } // As above, but for the get area. template <class T = int> typename std::enable_if<sizeof(T) == 4>::type safe_gbump(std::streamsize n) { while (n > std::numeric_limits<int>::max()) { this->gbump(std::numeric_limits<int>::max()); n -= std::numeric_limits<int>::max(); } this->gbump(static_cast<int>(n)); } template <class T = int> typename std::enable_if<sizeof(T) == 8>::type safe_gbump(std::streamsize n) { this->gbump(static_cast<int>(n)); } }; /// A streambuffer abstraction over a fixed array of bytes. This streambuffer /// cannot overflow/underflow. Once it has reached its end, attempts to read /// characters will return `trait_type::eof`. template <class CharT = char, class Traits = std::char_traits<CharT>> class arraybuf : public stream_buffer<CharT, Traits> { public: using base = std::basic_streambuf<CharT, Traits>; using char_type = typename base::char_type; using traits_type = typename base::traits_type; using int_type = typename base::int_type; using pos_type = typename base::pos_type; using off_type = typename base::off_type; /// Constructs an array streambuffer from a container. /// @param c A contiguous container. /// @pre `c.data()` must point to a contiguous sequence of characters having /// length `c.size()`. template < class Container, class = typename std::enable_if< detail::has_data_member<Container>::value && detail::has_size_member<Container>::value >::type > arraybuf(Container& c) : arraybuf(const_cast<char_type*>(c.data()), c.size()) { // nop } /// Constructs an array streambuffer from a raw character sequence. /// @param data A pointer to the first character. /// @param size The length of the character sequence. arraybuf(char_type* data, size_t size) { setbuf(data, static_cast<std::streamsize>(size)); } // There exists a bug in libstdc++ version < 5: the implementation does not // provide the necessary move constructors, so we have to roll our own :-/. // See https://gcc.gnu.org/bugzilla/show_bug.cgi?id=54316 for details. // TODO: remove after having raised the minimum GCC version to 5. arraybuf(arraybuf&& other) { this->setg(other.eback(), other.gptr(), other.egptr()); this->setp(other.pptr(), other.epptr()); other.setg(nullptr, nullptr, nullptr); other.setp(nullptr, nullptr); } // TODO: remove after having raised the minimum GCC version to 5. arraybuf& operator=(arraybuf&& other) { this->setg(other.eback(), other.gptr(), other.egptr()); this->setp(other.pptr(), other.epptr()); other.setg(nullptr, nullptr, nullptr); other.setp(nullptr, nullptr); return *this; } protected: // -- positioning ---------------------------------------------------------- std::basic_streambuf<char_type, Traits>* setbuf(char_type* s, std::streamsize n) override { this->setg(s, s, s + n); this->setp(s, s + n); return this; } pos_type seekpos(pos_type pos, std::ios_base::openmode which = std::ios_base::in | std::ios_base::out) override { auto get = (which & std::ios_base::in) == std::ios_base::in; auto put = (which & std::ios_base::out) == std::ios_base::out; if (!(get || put)) return pos_type(off_type(-1)); // nothing to do if (get) this->setg(this->eback(), this->eback() + pos, this->egptr()); if (put) { this->setp(this->pbase(), this->epptr()); this->safe_pbump(pos); } return pos; } pos_type seekoff(off_type off, std::ios_base::seekdir dir, std::ios_base::openmode which) override { auto new_off = pos_type(off_type(-1)); auto get = (which & std::ios_base::in) == std::ios_base::in; auto put = (which & std::ios_base::out) == std::ios_base::out; if (!(get || put)) return new_off; // nothing to do if (get) { switch (dir) { default: return pos_type(off_type(-1)); case std::ios_base::beg: new_off = 0; break; case std::ios_base::cur: new_off = this->gptr() - this->eback(); break; case std::ios_base::end: new_off = this->egptr() - this->eback(); break; } new_off += off; this->setg(this->eback(), this->eback() + new_off, this->egptr()); } if (put) { switch (dir) { default: return pos_type(off_type(-1)); case std::ios_base::beg: new_off = 0; break; case std::ios_base::cur: new_off = this->pptr() - this->pbase(); break; case std::ios_base::end: new_off = this->egptr() - this->pbase(); break; } new_off += off; this->setp(this->pbase(), this->epptr()); this->safe_pbump(new_off); } return new_off; } // -- put area ------------------------------------------------------------- std::streamsize xsputn(const char_type* s, std::streamsize n) override { auto available = this->epptr() - this->pptr(); auto actual = std::min(n, static_cast<std::streamsize>(available)); std::memcpy(this->pptr(), s, static_cast<size_t>(actual) * sizeof(char_type)); this->safe_pbump(actual); return actual; } // -- get area ------------------------------------------------------------- std::streamsize xsgetn(char_type* s, std::streamsize n) override { auto available = this->egptr() - this->gptr(); auto actual = std::min(n, static_cast<std::streamsize>(available)); std::memcpy(s, this->gptr(), static_cast<size_t>(actual) * sizeof(char_type)); this->safe_gbump(actual); return actual; } }; /// A streambuffer abstraction over a contiguous container. It supports /// reading in the same style as `arraybuf`, but is unbounded for output. template <class Container> class containerbuf : public stream_buffer< typename Container::value_type, std::char_traits<typename Container::value_type> > { public: using base = std::basic_streambuf< typename Container::value_type, std::char_traits<typename Container::value_type> >; using char_type = typename base::char_type; using traits_type = typename base::traits_type; using int_type = typename base::int_type; using pos_type = typename base::pos_type; using off_type = typename base::off_type; /// Constructs a container streambuf. /// @param c A contiguous container. template < class C = Container, class = typename std::enable_if< detail::has_data_member<C>::value && detail::has_size_member<C>::value >::type > containerbuf(Container& c) : container_(c) { this->setg(const_cast<char_type*>(c.data()), const_cast<char_type*>(c.data()), const_cast<char_type*>(c.data()) + c.size()); } // See note in arraybuf(arraybuf&&). // TODO: remove after having raised the minimum GCC version to 5. containerbuf(containerbuf&& other) : container_(other.container_) { this->setg(other.eback(), other.gptr(), other.egptr()); other.setg(nullptr, nullptr, nullptr); } // TODO: remove after having raised the minimum GCC version to 5. containerbuf& operator=(containerbuf&& other) { this->setg(other.eback(), other.gptr(), other.egptr()); other.setg(nullptr, nullptr, nullptr); return *this; } // Hides base-class implementation to simplify single-character lookup. int_type sgetc() { if (this->gptr() == this->egptr()) return traits_type::eof(); return traits_type::to_int_type(*this->gptr()); } // Hides base-class implementation to simplify single-character insert. int_type sputc(char_type c) { container_.push_back(c); return c; } protected: // We can't get obtain more characters on underflow, so we only optimize // multi-character sequential reads. std::streamsize xsgetn(char_type* s, std::streamsize n) override { auto available = this->egptr() - this->gptr(); auto actual = std::min(n, static_cast<std::streamsize>(available)); std::memcpy(s, this->gptr(), static_cast<size_t>(actual) * sizeof(char_type)); this->safe_gbump(actual); return actual; } // Should never get called, because there is always space in the buffer. // (But just in case, it does the same thing as sputc.) int_type overflow(int_type c = traits_type::eof()) final { if (!traits_type::eq_int_type(c, traits_type::eof())) container_.push_back(traits_type::to_char_type(c)); return c; } std::streamsize xsputn(const char_type* s, std::streamsize n) override { // TODO: Do a performance analysis whether the current implementation based // on copy_n is faster than these two statements: // (1) container_.resize(container_.size() + n); // (2) std::memcpy(this->pptr(), s, n * sizeof(char_type)); std::copy_n(s, n, std::back_inserter(container_)); return n; } private: Container& container_; }; using charbuf = arraybuf<char>; using vectorbuf = containerbuf<std::vector<char>>; } // namespace caf #endif // CAF_STREAMBUF_HPP <|endoftext|>
<commit_before>#include <iostream> #include <fstream> using namespace std; template <class T> struct Node { T element; Node<T> *left, *right, *pparent; }; template <class T> class BST { private: Node<T> *root; int count; public: BST(); ~BST(); void deleteTree(Node<T> *Tree); void show(ostream&cout, const Node<T> *Tree) const; void add(const T&); bool search(const T&, Node<T> *Tree) const; void input(const string& file); void output(const string& file) const; Node<T>* MinElement(Node<T>* min); Node<T>* getroot() const; int getcount() const; Node<T>* del(Node<T>* parent, Node<T>* current, const T& val); bool delVal(const T& val); }; template <typename T> BST<T>::BST() { root = NULL; count = 0; } template <typename T> BST<T>::~BST() { deleteTree(root); } template <typename T>void BST<T>::deleteTree(Node<T> *Tree) { if (!Tree) return; if (Tree->left) { deleteTree(Tree->left); Tree->left = nullptr; } if (Tree->right) { deleteTree(Tree->right); Tree->right = nullptr; } delete Tree; } template <typename T> void BST<T>::show(ostream&cout, const Node<T> *Tree) const{ if (Tree != NULL) { cout << Tree->element << endl;; show(cout, Tree->left); show(cout, Tree->right); } } template <typename T> void BST<T>::add(const T &x) { Node<T>* daughter = new Node<T>; daughter->element = x; daughter->left = daughter->right = nullptr; Node<T>* parent = root; Node<T>* temp = root; while (temp) { parent = temp; if (x < temp->element) temp = temp->left; else temp = temp->right; } if (!parent) root = daughter; else { if (x < parent->element) parent->left = daughter; else parent->right = daughter; } count++; } template <typename T> Node<T>* BST<T>::getroot() const { return root; } template <typename T> int BST<T>::getcount() const { return count; } template <typename T> void BST<T>::input(const string& file) { ifstream fin(file); if (fin) { T temp; fin >> temp; add(temp); } fin.close(); } template <typename T> void BST<T>::output(const string& file) const { ofstream fout(file); show(fout, root); fout.close(); } template <typename T> bool BST<T>::search(const T&x, Node<T>* Tree) const { if (Tree == nullptr) return false; if (x == Tree->element) { return true; } else if (x < Tree->element) { search(x, Tree->left); } else search(x, Tree->right); } template <typename T> Node<T>* BST<T>::MinElement(Node<T>* min) { if (min->left == nullptr) return min; else return MinElement(min->left); } template <typename T> Node<T>* BST<T>::del(Node<T>* parent, Node<T>* current, const T& val) { if (!current) return false; if (current->element == val) { if (current->left == NULL || current->right == NULL) { Node<T>* temp = current->left; if (current->right) temp = current->right; if (parent) { if (parent->left == current) { parent->left = temp; } else { parent->right = temp; } } else { this->root = temp; } } else { Node<T>* validSubs = current->right; while (validSubs->left) { validSubs = validSubs->left; } T temp = current->element; current->element = validSubs->element; validSubs->element = temp; return del(current, current->right, temp); } delete current; count--; return true; } if (current->element > val) return del(current, current->left, val); else return del(current, current->right, val); } template <typename T> bool BST<T>::delVal(const T& val) { return this->del(NULL, root, val); } <commit_msg>Create BST.hpp<commit_after>#include <iostream> #include <fstream> using namespace std; template <class T> struct Node { T element; Node<T> *left, *right, *pparent; }; template <class T> class BST { private: Node<T> *root; int count; public: BST(); ~BST(); void deleteTree(Node<T> *Tree); void show(ostream&cout, const Node<T> *Tree) const; void add(const T&); bool search(const T&, Node<T> *Tree) const; void input(const string& file); void output(const string& file) const; Node<T>* MinElement(Node<T>* min); Node<T>* getroot() const; int getcount() const; Node<T>* del(Node<T>* parent, Node<T>* current, const T& val); bool delVal(const T& val); }; template <typename T> BST<T>::BST() { root = NULL; count = 0; } template <typename T> BST<T>::~BST() { deleteTree(root); } template <typename T>void BST<T>::deleteTree(Node<T> *Tree) { if (!Tree) return; if (Tree->left) { deleteTree(Tree->left); Tree->left = nullptr; } if (Tree->right) { deleteTree(Tree->right); Tree->right = nullptr; } delete Tree; } template <typename T> void BST<T>::show(ostream&cout, const Node<T> *Tree) const{ if (Tree != NULL) { cout << Tree->element << endl;; show(cout, Tree->left); show(cout, Tree->right); } } template <typename T> void BST<T>::add(const T &x) { Node<T>* daughter = new Node<T>; daughter->element = x; daughter->left = daughter->right = nullptr; Node<T>* parent = root; Node<T>* temp = root; while (temp) { parent = temp; if (x < temp->element) temp = temp->left; else temp = temp->right; } if (!parent) root = daughter; else { if (x < parent->element) parent->left = daughter; else parent->right = daughter; } count++; } template <typename T> Node<T>* BST<T>::getroot() const { return root; } template <typename T> int BST<T>::getcount() const { return count; } template <typename T> void BST<T>::input(const string& file) { ifstream fin(file); T temp; if (!fin) { fin >> temp; add(temp); } fin.close(); } template <typename T> void BST<T>::output(const string& file) const { ofstream fout(file); show(fout, root); fout.close(); } template <typename T> bool BST<T>::search(const T&x, Node<T>* Tree) const { if (Tree == nullptr) return false; if (x == Tree->element) { return true; } else if (x < Tree->element) { search(x, Tree->left); } else search(x, Tree->right); } template <typename T> Node<T>* BST<T>::MinElement(Node<T>* min) { if (min->left == nullptr) return min; else return MinElement(min->left); } template <typename T> Node<T>* BST<T>::del(Node<T>* parent, Node<T>* current, const T& val) { if (!current) return false; if (current->element == val) { if (current->left == NULL || current->right == NULL) { Node<T>* temp = current->left; if (current->right) temp = current->right; if (parent) { if (parent->left == current) { parent->left = temp; } else { parent->right = temp; } } else { this->root = temp; } } else { Node<T>* validSubs = current->right; while (validSubs->left) { validSubs = validSubs->left; } T temp = current->element; current->element = validSubs->element; validSubs->element = temp; return del(current, current->right, temp); } delete current; count--; return true; } if (current->element > val) return del(current, current->left, val); else return del(current, current->right, val); } template <typename T> bool BST<T>::delVal(const T& val) { return this->del(NULL, root, val); } <|endoftext|>
<commit_before>/* * 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. * * Written (W) 2012 Heiko Strathmann * Copyright (C) 2012 Berlin Institute of Technology and Max-Planck-Society */ #include <shogun/base/init.h> #include <shogun/features/SimpleFeatures.h> #include <shogun/features/Labels.h> #include <shogun/kernel/LinearKernel.h> #include <shogun/classifier/svm/LibSVM.h> #include <shogun/evaluation/ContingencyTableEvaluation.h> using namespace shogun; void print_message(FILE* target, const char* str) { fprintf(target, "%s", str); } void test() { /* data matrix dimensions */ index_t num_vectors=6; index_t num_features=2; /* data means -1, 1 in all components, std deviation of 3 */ SGVector<float64_t> mean_1(num_features); SGVector<float64_t> mean_2(num_features); CMath::fill_vector(mean_1.vector, mean_1.vlen, -10.0); CMath::fill_vector(mean_2.vector, mean_2.vlen, 10.0); float64_t sigma=0.5; CMath::display_vector(mean_1.vector, mean_1.vlen, "mean 1"); CMath::display_vector(mean_2.vector, mean_2.vlen, "mean 2"); /* fill data matrix around mean */ SGMatrix<float64_t> train_dat(num_features, num_vectors); for (index_t i=0; i<num_vectors; ++i) { for (index_t j=0; j<num_features; ++j) { float64_t mean=i<num_vectors/2 ? mean_1.vector[0] : mean_2.vector[0]; train_dat.matrix[i*num_features+j]=CMath::normal_random(mean, sigma); } } CMath::display_matrix(train_dat.matrix, train_dat.num_rows, train_dat.num_cols, "training data"); /* training features */ CSimpleFeatures<float64_t>* features= new CSimpleFeatures<float64_t>(train_dat); SG_REF(features); /* training labels +/- 1 for each cluster */ SGVector<float64_t> lab(num_vectors); for (index_t i=0; i<num_vectors; ++i) lab.vector[i]=i<num_vectors/2 ? -1.0 : 1.0; CMath::display_vector(lab.vector, lab.vlen, "training labels"); CLabels* labels=new CLabels(lab); /* evaluation instance */ CContingencyTableEvaluation* eval=new CContingencyTableEvaluation(ACCURACY); /* kernel */ CKernel* kernel=new CLinearKernel(); kernel->init(features, features); /* create svm via libsvm */ float64_t svm_C=10; float64_t svm_eps=0.0001; CLibSVM* svm=new CLibSVM(svm_C, kernel, labels); svm->set_epsilon(svm_eps); /* now train a few times on different subsets on data and assert that * results are correc (data linear separable) */ svm->data_lock(); SGVector<index_t> indices(4); indices.vector[0]=1; indices.vector[1]=2; indices.vector[2]=3; indices.vector[3]=4; CMath::display_vector(indices.vector, indices.vlen, "training indices"); svm->train_locked(indices); CLabels* output=svm->apply(); ASSERT(eval->evaluate(output, labels)==1); CMath::display_vector(output->get_labels().vector, output->get_num_labels(), "apply() output"); SG_UNREF(output); SG_SPRINT("\n\n"); indices.destroy_vector(); indices=SGVector<index_t>(3); indices.vector[0]=1; indices.vector[1]=2; indices.vector[2]=3; CMath::display_vector(indices.vector, indices.vlen, "training indices"); output=svm->apply(); ASSERT(eval->evaluate(output, labels)==1); CMath::display_vector(output->get_labels().vector, output->get_num_labels(), "apply() output"); SG_UNREF(output); SG_SPRINT("\n\n"); indices.destroy_vector(); indices=SGVector<index_t>(4); indices.range_fill(); CMath::display_vector(indices.vector, indices.vlen, "training indices"); svm->train_locked(indices); output=svm->apply(); ASSERT(eval->evaluate(output, labels)==1); CMath::display_vector(output->get_labels().vector, output->get_num_labels(), "apply() output"); SG_UNREF(output); SG_SPRINT("normal train\n"); svm->data_unlock(); svm->train(); output=svm->apply(); ASSERT(eval->evaluate(output, labels)==1); CMath::display_vector(output->get_labels().vector, output->get_num_labels(), "output"); SG_UNREF(output); /* clean up */ SG_UNREF(svm); SG_UNREF(features); SG_UNREF(eval); mean_1.destroy_vector(); mean_2.destroy_vector(); indices.destroy_vector(); } int main(int argc, char **argv) { init_shogun(&print_message, &print_message, &print_message); test(); exit_shogun(); return 0; } <commit_msg>update data_lock usage<commit_after>/* * 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. * * Written (W) 2012 Heiko Strathmann * Copyright (C) 2012 Berlin Institute of Technology and Max-Planck-Society */ #include <shogun/base/init.h> #include <shogun/features/SimpleFeatures.h> #include <shogun/features/Labels.h> #include <shogun/kernel/LinearKernel.h> #include <shogun/classifier/svm/LibSVM.h> #include <shogun/evaluation/ContingencyTableEvaluation.h> using namespace shogun; void print_message(FILE* target, const char* str) { fprintf(target, "%s", str); } void test() { /* data matrix dimensions */ index_t num_vectors=6; index_t num_features=2; /* data means -1, 1 in all components, std deviation of 3 */ SGVector<float64_t> mean_1(num_features); SGVector<float64_t> mean_2(num_features); CMath::fill_vector(mean_1.vector, mean_1.vlen, -10.0); CMath::fill_vector(mean_2.vector, mean_2.vlen, 10.0); float64_t sigma=0.5; CMath::display_vector(mean_1.vector, mean_1.vlen, "mean 1"); CMath::display_vector(mean_2.vector, mean_2.vlen, "mean 2"); /* fill data matrix around mean */ SGMatrix<float64_t> train_dat(num_features, num_vectors); for (index_t i=0; i<num_vectors; ++i) { for (index_t j=0; j<num_features; ++j) { float64_t mean=i<num_vectors/2 ? mean_1.vector[0] : mean_2.vector[0]; train_dat.matrix[i*num_features+j]=CMath::normal_random(mean, sigma); } } CMath::display_matrix(train_dat.matrix, train_dat.num_rows, train_dat.num_cols, "training data"); /* training features */ CSimpleFeatures<float64_t>* features= new CSimpleFeatures<float64_t>(train_dat); SG_REF(features); /* training labels +/- 1 for each cluster */ SGVector<float64_t> lab(num_vectors); for (index_t i=0; i<num_vectors; ++i) lab.vector[i]=i<num_vectors/2 ? -1.0 : 1.0; CMath::display_vector(lab.vector, lab.vlen, "training labels"); CLabels* labels=new CLabels(lab); /* evaluation instance */ CContingencyTableEvaluation* eval=new CContingencyTableEvaluation(ACCURACY); /* kernel */ CKernel* kernel=new CLinearKernel(); kernel->init(features, features); /* create svm via libsvm */ float64_t svm_C=10; float64_t svm_eps=0.0001; CLibSVM* svm=new CLibSVM(svm_C, kernel, labels); svm->set_epsilon(svm_eps); /* now train a few times on different subsets on data and assert that * results are correc (data linear separable) */ svm->data_lock(features, labels); SGVector<index_t> indices(4); indices.vector[0]=1; indices.vector[1]=2; indices.vector[2]=3; indices.vector[3]=4; CMath::display_vector(indices.vector, indices.vlen, "training indices"); svm->train_locked(indices); CLabels* output=svm->apply(); ASSERT(eval->evaluate(output, labels)==1); CMath::display_vector(output->get_labels().vector, output->get_num_labels(), "apply() output"); SG_UNREF(output); SG_SPRINT("\n\n"); indices.destroy_vector(); indices=SGVector<index_t>(3); indices.vector[0]=1; indices.vector[1]=2; indices.vector[2]=3; CMath::display_vector(indices.vector, indices.vlen, "training indices"); output=svm->apply(); ASSERT(eval->evaluate(output, labels)==1); CMath::display_vector(output->get_labels().vector, output->get_num_labels(), "apply() output"); SG_UNREF(output); SG_SPRINT("\n\n"); indices.destroy_vector(); indices=SGVector<index_t>(4); indices.range_fill(); CMath::display_vector(indices.vector, indices.vlen, "training indices"); svm->train_locked(indices); output=svm->apply(); ASSERT(eval->evaluate(output, labels)==1); CMath::display_vector(output->get_labels().vector, output->get_num_labels(), "apply() output"); SG_UNREF(output); SG_SPRINT("normal train\n"); svm->data_unlock(); svm->train(); output=svm->apply(); ASSERT(eval->evaluate(output, labels)==1); CMath::display_vector(output->get_labels().vector, output->get_num_labels(), "output"); SG_UNREF(output); /* clean up */ SG_UNREF(svm); SG_UNREF(features); SG_UNREF(eval); mean_1.destroy_vector(); mean_2.destroy_vector(); indices.destroy_vector(); } int main(int argc, char **argv) { init_shogun(&print_message, &print_message, &print_message); test(); exit_shogun(); 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 "mitkTestingMacros.h" #include <mitkTestingConfig.h> #include <mitkTestFixture.h> #include <mitkIOUtil.h> #include <mitkInteractionTestHelper.h> #include <mitkPointSet.h> #include <mitkPointSetDataInteractor.h> class mitkPointSetDataInteractorTestSuite : public mitk::TestFixture { CPPUNIT_TEST_SUITE(mitkPointSetDataInteractorTestSuite); MITK_TEST(AddPointInteraction); CPPUNIT_TEST_SUITE_END(); private: mitk::DataNode::Pointer m_TestPointSetNode; mitk::PointSetDataInteractor::Pointer m_DataInteractor; mitk::PointSet::Pointer m_TestPointSet; public: void setUp() { //Create DataNode as a container for our PointSet to be tested m_TestPointSetNode = mitk::DataNode::New(); // Create PointSetData Interactor m_DataInteractor = mitk::PointSetDataInteractor::New(); // Load the according state machine for regular point set interaction m_DataInteractor->LoadStateMachine("PointSet.xml"); // Set the configuration file that defines the triggers for the transitions m_DataInteractor->SetEventConfig("PointSetConfig.xml"); // set the DataNode (which already is added to the DataStorage) m_DataInteractor->SetDataNode(m_TestPointSetNode); //Create new PointSet which will receive the interaction input m_TestPointSet = mitk::PointSet::New(); m_TestPointSetNode->SetData(m_TestPointSet); } void tearDown() { //destroy all objects m_TestPointSetNode = NULL; m_TestPointSet = NULL; m_DataInteractor = NULL; } void AddPointInteraction() { //Path to the reference PointSet std::string referencePointSetPath = GetTestDataFilePath("InteractionTestData/ReferenceData/PointSetDataInteractor_add_points_in_2D_ref.mps"); //Path to the interaction xml file std::string interactionXmlPath = GetTestDataFilePath("InteractionTestData/Interactions/PointSetDataInteractor_add_points_in_2D.xml"); //Create test helper to initialize all necessary objects for interaction mitk::InteractionTestHelper interactionTestHelper(interactionXmlPath); //Add our test node to the DataStorage of our test helper interactionTestHelper.AddNodeToStorage(m_TestPointSetNode); //Start Interaction interactionTestHelper.PlaybackInteraction(); //Load the reference PointSet mitk::PointSet::Pointer referencePointSet = mitk::IOUtil::LoadPointSet(referencePointSetPath); //Compare reference with the result of the interaction MITK_ASSERT_EQUAL(m_TestPointSet, referencePointSet, ""); } }; MITK_TEST_SUITE_REGISTRATION(mitkPointSetDataInteractor) <commit_msg>COMP: first add point set to datanode, else ps will be created and reference that is checked does not match actual results<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 "mitkTestingMacros.h" #include <mitkTestingConfig.h> #include <mitkTestFixture.h> #include <mitkIOUtil.h> #include <mitkInteractionTestHelper.h> #include <mitkPointSet.h> #include <mitkPointSetDataInteractor.h> class mitkPointSetDataInteractorTestSuite : public mitk::TestFixture { CPPUNIT_TEST_SUITE(mitkPointSetDataInteractorTestSuite); MITK_TEST(AddPointInteraction); CPPUNIT_TEST_SUITE_END(); private: mitk::DataNode::Pointer m_TestPointSetNode; mitk::PointSetDataInteractor::Pointer m_DataInteractor; mitk::PointSet::Pointer m_TestPointSet; public: void setUp() { //Create DataNode as a container for our PointSet to be tested m_TestPointSetNode = mitk::DataNode::New(); // Create PointSetData Interactor m_DataInteractor = mitk::PointSetDataInteractor::New(); // Load the according state machine for regular point set interaction m_DataInteractor->LoadStateMachine("PointSet.xml"); // Set the configuration file that defines the triggers for the transitions m_DataInteractor->SetEventConfig("PointSetConfig.xml"); //Create new PointSet which will receive the interaction input m_TestPointSet = mitk::PointSet::New(); m_TestPointSetNode->SetData(m_TestPointSet); // set the DataNode (which already is added to the DataStorage) m_DataInteractor->SetDataNode(m_TestPointSetNode); } void tearDown() { //destroy all objects m_TestPointSetNode = NULL; m_TestPointSet = NULL; m_DataInteractor = NULL; } void AddPointInteraction() { //Path to the reference PointSet std::string referencePointSetPath = GetTestDataFilePath("InteractionTestData/ReferenceData/PointSetDataInteractor_add_points_in_2D_ref.mps"); //Path to the interaction xml file std::string interactionXmlPath = GetTestDataFilePath("InteractionTestData/Interactions/PointSetDataInteractor_add_points_in_2D.xml"); //Create test helper to initialize all necessary objects for interaction mitk::InteractionTestHelper interactionTestHelper(interactionXmlPath); //Add our test node to the DataStorage of our test helper interactionTestHelper.AddNodeToStorage(m_TestPointSetNode); //Start Interaction interactionTestHelper.PlaybackInteraction(); //Load the reference PointSet mitk::PointSet::Pointer referencePointSet = mitk::IOUtil::LoadPointSet(referencePointSetPath); //Compare reference with the result of the interaction MITK_ASSERT_EQUAL(m_TestPointSet, referencePointSet, ""); } }; MITK_TEST_SUITE_REGISTRATION(mitkPointSetDataInteractor) <|endoftext|>
<commit_before>// Copyright (c) 2013-2018 mogemimi. Distributed under the MIT license. #pragma once #include "Pomdog/Utility/Assert.hpp" #include <type_traits> #include <cstdint> #include <limits> namespace Pomdog { namespace Detail { namespace Skeletal2D { template <typename T, T Denominator> class CompressedFloat { public: static_assert(std::is_integral<T>::value, ""); T data; CompressedFloat() = default; CompressedFloat(float scalar) : data(scalar * Denominator) { POMDOG_ASSERT(scalar < Max()); POMDOG_ASSERT(scalar >= Min()); } CompressedFloat & operator=(float scalar) { POMDOG_ASSERT(scalar < Max()); POMDOG_ASSERT(scalar >= Min()); data = scalar * Denominator; return *this; } float ToFloat() const { static_assert(Denominator != 0, ""); return data * (1.0f / Denominator); } constexpr static float Max() { static_assert(Denominator != 0, ""); return std::numeric_limits<T>::max()/Denominator; } constexpr static float Min() { static_assert(Denominator != 0, ""); return std::numeric_limits<T>::min()/Denominator; } bool operator<(CompressedFloat const& other) const { return data < other.data; } }; } // namespace Skeletal2D } // namespace Detail } // namespace Pomdog <commit_msg>Fix warning C4244 in MSVC and refactor<commit_after>// Copyright (c) 2013-2018 mogemimi. Distributed under the MIT license. #pragma once #include "Pomdog/Utility/Assert.hpp" #include <type_traits> #include <cstdint> #include <limits> namespace Pomdog { namespace Detail { namespace Skeletal2D { template <typename T, T Denominator> class CompressedFloat { public: static_assert(std::is_integral<T>::value, ""); T data; CompressedFloat() = default; CompressedFloat(float scalar) : data(scalar * Denominator) { POMDOG_ASSERT(scalar < Max()); POMDOG_ASSERT(scalar >= Min()); } CompressedFloat & operator=(float scalar) { POMDOG_ASSERT(scalar < Max()); POMDOG_ASSERT(scalar >= Min()); data = scalar * Denominator; return *this; } float ToFloat() const noexcept { static_assert(Denominator != 0); constexpr float scale = 1.0f / Denominator; return data * scale; } constexpr static float Max() noexcept { static_assert(Denominator != 0); return static_cast<float>(std::numeric_limits<T>::max()) / Denominator; } constexpr static float Min() noexcept { static_assert(Denominator != 0); return static_cast<float>(std::numeric_limits<T>::min()) / Denominator; } bool operator<(const CompressedFloat& other) const noexcept { return data < other.data; } }; } // namespace Skeletal2D } // namespace Detail } // namespace Pomdog <|endoftext|>
<commit_before>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** Commercial Usage ** ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** 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. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at http://qt.nokia.com/contact. ** **************************************************************************/ #include "qtoutputformatter.h" #include <texteditor/basetexteditor.h> #include <qt4projectmanager/qt4project.h> #include <QtCore/QFileInfo> #include <QtGui/QPlainTextEdit> using namespace ProjectExplorer; using namespace Qt4ProjectManager; QtOutputFormatter::QtOutputFormatter(Qt4Project *project) : OutputFormatter() , m_qmlError(QLatin1String("(file:///[^:]+:\\d+:\\d+):")) , m_qtError(QLatin1String("Object::.*in (.*:\\d+)")) , m_project(project) { } LinkResult QtOutputFormatter::matchLine(const QString &line) const { LinkResult lr; lr.start = -1; lr.end = -1; if (m_qmlError.indexIn(line) != -1) { lr.href = m_qmlError.cap(1); lr.start = m_qmlError.pos(1); lr.end = lr.start + lr.href.length(); } else if (m_qtError.indexIn(line) != -1) { lr.href = m_qtError.cap(1); lr.start = m_qtError.pos(1); lr.end = lr.start + lr.href.length(); } return lr; } void QtOutputFormatter::appendApplicationOutput(const QString &txt, bool onStdErr) { // Do the initialization lazily, as we don't have a plaintext edit // in the ctor if (!m_linkFormat.isValid()) { m_linkFormat.setForeground(plainTextEdit()->palette().link().color()); m_linkFormat.setUnderlineStyle(QTextCharFormat::SingleUnderline); m_linkFormat.setAnchor(true); } QString text = txt; text.remove(QLatin1Char('\r')); int start = 0; int pos = txt.indexOf(QLatin1Char('\n')); while (pos != -1) { // Line identified if (!m_lastLine.isEmpty()) { // Line continuation const QString newPart = txt.mid(start, pos - start + 1); const QString line = m_lastLine + newPart; LinkResult lr = matchLine(line); if (!lr.href.isEmpty()) { // Found something && line continuation clearLastLine(); appendLine(lr, line, onStdErr); } else { // Found nothing, just emit the new part append(newPart, onStdErr ? StdErrFormat : StdOutFormat); } // Handled line continuation m_lastLine.clear(); } else { const QString line = txt.mid(start, pos - start + 1); LinkResult lr = matchLine(line); if (!lr.href.isEmpty()) { appendLine(lr, line, onStdErr); } else { append(line, onStdErr ? StdErrFormat : StdOutFormat); } } start = pos + 1; pos = txt.indexOf(QLatin1Char('\n'), start); } // Handle left over stuff if (start < txt.length()) { if (!m_lastLine.isEmpty()) { // Line continuation const QString newPart = txt.mid(start); m_lastLine.append(newPart); LinkResult lr = matchLine(m_lastLine); if (!lr.href.isEmpty()) { // Found something && line continuation clearLastLine(); appendLine(lr, m_lastLine, onStdErr); } else { // Found nothing, just emit the new part append(newPart, onStdErr ? StdErrFormat : StdOutFormat); } } else { m_lastLine = txt.mid(start); LinkResult lr = matchLine(m_lastLine); if (!lr.href.isEmpty()) { appendLine(lr, m_lastLine, onStdErr); } else { append(m_lastLine, onStdErr ? StdErrFormat : StdOutFormat); } } } } void QtOutputFormatter::appendLine(LinkResult lr, const QString &line, bool onStdErr) { append(line.left(lr.start), onStdErr ? StdErrFormat : StdOutFormat); m_linkFormat.setAnchorHref(lr.href); append(line.mid(lr.start, lr.end - lr.start), m_linkFormat); append(line.mid(lr.end), onStdErr ? StdErrFormat : StdOutFormat); } void QtOutputFormatter::handleLink(const QString &href) { if (!href.isEmpty()) { QRegExp qmlErrorLink(QLatin1String("^file://(/[^:]+):(\\d+):(\\d+)")); if (qmlErrorLink.indexIn(href) != -1) { const QString fileName = qmlErrorLink.cap(1); const int line = qmlErrorLink.cap(2).toInt(); const int column = qmlErrorLink.cap(3).toInt(); TextEditor::BaseTextEditor::openEditorAt(fileName, line, column - 1); return; } QRegExp qtErrorLink(QLatin1String("^(.*):(\\d+)$")); if (qtErrorLink.indexIn(href) != 1) { QString fileName = qtErrorLink.cap(1); const int line = qtErrorLink.cap(2).toInt(); QFileInfo fi(fileName); if (fi.isRelative()) { // Yeah fileName is relative, no suprise Qt4Project *pro = m_project.data(); if (pro) { QString baseName = fi.fileName(); foreach (const QString &file, pro->files(Project::AllFiles)) { if (file.endsWith(baseName)) { // pick the first one... fileName = file; break; } } } } TextEditor::BaseTextEditor::openEditorAt(fileName, line, 0); return; } } } <commit_msg>Fix qml application output "jump-to-qml-error" for Windows.<commit_after>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** Commercial Usage ** ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** 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. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at http://qt.nokia.com/contact. ** **************************************************************************/ #include "qtoutputformatter.h" #include <texteditor/basetexteditor.h> #include <qt4projectmanager/qt4project.h> #include <QtCore/QFileInfo> #include <QtCore/QUrl> #include <QtGui/QPlainTextEdit> using namespace ProjectExplorer; using namespace Qt4ProjectManager; QtOutputFormatter::QtOutputFormatter(Qt4Project *project) : OutputFormatter() , m_qmlError(QLatin1String("(file:///.+:\\d+:\\d+):")) , m_qtError(QLatin1String("Object::.*in (.*:\\d+)")) , m_project(project) { } LinkResult QtOutputFormatter::matchLine(const QString &line) const { LinkResult lr; lr.start = -1; lr.end = -1; if (m_qmlError.indexIn(line) != -1) { lr.href = m_qmlError.cap(1); lr.start = m_qmlError.pos(1); lr.end = lr.start + lr.href.length(); } else if (m_qtError.indexIn(line) != -1) { lr.href = m_qtError.cap(1); lr.start = m_qtError.pos(1); lr.end = lr.start + lr.href.length(); } return lr; } void QtOutputFormatter::appendApplicationOutput(const QString &txt, bool onStdErr) { // Do the initialization lazily, as we don't have a plaintext edit // in the ctor if (!m_linkFormat.isValid()) { m_linkFormat.setForeground(plainTextEdit()->palette().link().color()); m_linkFormat.setUnderlineStyle(QTextCharFormat::SingleUnderline); m_linkFormat.setAnchor(true); } QString text = txt; text.remove(QLatin1Char('\r')); int start = 0; int pos = txt.indexOf(QLatin1Char('\n')); while (pos != -1) { // Line identified if (!m_lastLine.isEmpty()) { // Line continuation const QString newPart = txt.mid(start, pos - start + 1); const QString line = m_lastLine + newPart; LinkResult lr = matchLine(line); if (!lr.href.isEmpty()) { // Found something && line continuation clearLastLine(); appendLine(lr, line, onStdErr); } else { // Found nothing, just emit the new part append(newPart, onStdErr ? StdErrFormat : StdOutFormat); } // Handled line continuation m_lastLine.clear(); } else { const QString line = txt.mid(start, pos - start + 1); LinkResult lr = matchLine(line); if (!lr.href.isEmpty()) { appendLine(lr, line, onStdErr); } else { append(line, onStdErr ? StdErrFormat : StdOutFormat); } } start = pos + 1; pos = txt.indexOf(QLatin1Char('\n'), start); } // Handle left over stuff if (start < txt.length()) { if (!m_lastLine.isEmpty()) { // Line continuation const QString newPart = txt.mid(start); m_lastLine.append(newPart); LinkResult lr = matchLine(m_lastLine); if (!lr.href.isEmpty()) { // Found something && line continuation clearLastLine(); appendLine(lr, m_lastLine, onStdErr); } else { // Found nothing, just emit the new part append(newPart, onStdErr ? StdErrFormat : StdOutFormat); } } else { m_lastLine = txt.mid(start); LinkResult lr = matchLine(m_lastLine); if (!lr.href.isEmpty()) { appendLine(lr, m_lastLine, onStdErr); } else { append(m_lastLine, onStdErr ? StdErrFormat : StdOutFormat); } } } } void QtOutputFormatter::appendLine(LinkResult lr, const QString &line, bool onStdErr) { append(line.left(lr.start), onStdErr ? StdErrFormat : StdOutFormat); m_linkFormat.setAnchorHref(lr.href); append(line.mid(lr.start, lr.end - lr.start), m_linkFormat); append(line.mid(lr.end), onStdErr ? StdErrFormat : StdOutFormat); } void QtOutputFormatter::handleLink(const QString &href) { if (!href.isEmpty()) { const QRegExp qmlErrorLink(QLatin1String("^(file:///.+):(\\d+):(\\d+)")); if (qmlErrorLink.indexIn(href) != -1) { const QString fileName = QUrl(qmlErrorLink.cap(1)).toLocalFile(); const int line = qmlErrorLink.cap(2).toInt(); const int column = qmlErrorLink.cap(3).toInt(); TextEditor::BaseTextEditor::openEditorAt(fileName, line, column - 1); return; } QRegExp qtErrorLink(QLatin1String("^(.*):(\\d+)$")); if (qtErrorLink.indexIn(href) != 1) { QString fileName = qtErrorLink.cap(1); const int line = qtErrorLink.cap(2).toInt(); QFileInfo fi(fileName); if (fi.isRelative()) { // Yeah fileName is relative, no suprise Qt4Project *pro = m_project.data(); if (pro) { QString baseName = fi.fileName(); foreach (const QString &file, pro->files(Project::AllFiles)) { if (file.endsWith(baseName)) { // pick the first one... fileName = file; break; } } } } TextEditor::BaseTextEditor::openEditorAt(fileName, line, 0); return; } } } <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: TestHierarchicalBoxPipeline.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ // This example demonstrates how hierarchical box (uniform rectilinear) // AMR datasets can be processed using the new vtkHierarchicalBoxDataSet class. // // The command line arguments are: // -I => run in interactive mode; unless this is used, the program will // not allow interaction and exit // -D <path> => path to the data; the data should be in <path>/Data/ #include "vtkCamera.h" #include "vtkCellDataToPointData.h" #include "vtkContourFilter.h" #include "vtkDebugLeaks.h" #include "vtkHierarchicalDataSetGeometryFilter.h" #include "vtkOutlineCornerFilter.h" #include "vtkPolyDataMapper.h" #include "vtkProperty.h" #include "vtkRegressionTestImage.h" #include "vtkRenderer.h" #include "vtkRenderWindow.h" #include "vtkRenderWindowInteractor.h" #include "vtkShrinkPolyData.h" #include "vtkTestHierarchicalDataReader.h" #include "vtkTestUtilities.h" int TestHierarchicalBoxPipeline(int argc, char* argv[]) { // Disable for testing vtkDebugLeaks::PromptUserOff(); // Standard rendering classes vtkRenderer *ren = vtkRenderer::New(); vtkCamera* cam = ren->GetActiveCamera(); cam->SetPosition(-5.1828, 5.89733, 8.97969); cam->SetFocalPoint(14.6491, -2.08677, -8.92362); cam->SetViewUp(0.210794, 0.95813, -0.193784); vtkRenderWindow *renWin = vtkRenderWindow::New(); renWin->AddRenderer(ren); vtkRenderWindowInteractor *iren = vtkRenderWindowInteractor::New(); iren->SetRenderWindow(renWin); char* cfname = vtkTestUtilities::ExpandDataFileName(argc, argv, "Data/chombo3d/chombo3d"); vtkTestHierarchicalDataReader* reader = vtkTestHierarchicalDataReader::New(); reader->SetFileName(cfname); delete[] cfname; // geometry filter vtkHierarchicalDataSetGeometryFilter* geom = vtkHierarchicalDataSetGeometryFilter::New(); geom->SetInputConnection(0, reader->GetOutputPort(0)); vtkShrinkPolyData* shrink = vtkShrinkPolyData::New(); shrink->SetShrinkFactor(0.5); shrink->SetInputConnection(0, geom->GetOutputPort(0)); // Rendering objects vtkPolyDataMapper* shMapper = vtkPolyDataMapper::New(); shMapper->SetInputConnection(0, shrink->GetOutputPort(0)); vtkActor* shActor = vtkActor::New(); shActor->SetMapper(shMapper); shActor->GetProperty()->SetColor(0, 0, 1); ren->AddActor(shActor); // corner outline vtkOutlineCornerFilter* ocf = vtkOutlineCornerFilter::New(); ocf->SetInputConnection(0, reader->GetOutputPort(0)); // geometry filter vtkHierarchicalDataSetGeometryFilter* geom2 = vtkHierarchicalDataSetGeometryFilter::New(); geom2->SetInputConnection(0, ocf->GetOutputPort(0)); // Rendering objects vtkPolyDataMapper* ocMapper = vtkPolyDataMapper::New(); ocMapper->SetInputConnection(0, geom2->GetOutputPort(0)); vtkActor* ocActor = vtkActor::New(); ocActor->SetMapper(ocMapper); ocActor->GetProperty()->SetColor(1, 0, 0); ren->AddActor(ocActor); // cell 2 point and contour vtkCellDataToPointData* c2p = vtkCellDataToPointData::New(); c2p->SetInputConnection(0, reader->GetOutputPort(0)); vtkContourFilter* contour = vtkContourFilter::New(); contour->SetInputConnection(0, c2p->GetOutputPort(0)); contour->SetValue(0, -0.013); contour->SetInputArrayToProcess(0,0,0,vtkDataObject::FIELD_ASSOCIATION_POINTS,"phi"); // geometry filter vtkHierarchicalDataSetGeometryFilter* geom3 = vtkHierarchicalDataSetGeometryFilter::New(); geom3->SetInputConnection(0, contour->GetOutputPort(0)); // Rendering objects vtkPolyDataMapper* contMapper = vtkPolyDataMapper::New(); contMapper->SetInputConnection(0, geom3->GetOutputPort(0)); vtkActor* contActor = vtkActor::New(); contActor->SetMapper(contMapper); contActor->GetProperty()->SetColor(1, 0, 0); ren->AddActor(contActor); // Standard testing code. ocf->Delete(); geom2->Delete(); ocMapper->Delete(); ocActor->Delete(); c2p->Delete(); contour->Delete(); geom3->Delete(); contMapper->Delete(); contActor->Delete(); ren->SetBackground(1,1,1); renWin->SetSize(300,300); renWin->Render(); int retVal = vtkRegressionTestImage( renWin ); if ( retVal == vtkRegressionTester::DO_INTERACTOR) { iren->Start(); } // Cleanup geom->Delete(); shMapper->Delete(); shActor->Delete(); ren->Delete(); renWin->Delete(); iren->Delete(); reader->Delete(); shrink->Delete(); return !retVal; } <commit_msg>ENH: switch to using the new vtkHierarchicalPolyDataMapper<commit_after>/*========================================================================= Program: Visualization Toolkit Module: TestHierarchicalBoxPipeline.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ // This example demonstrates how hierarchical box (uniform rectilinear) // AMR datasets can be processed using the new vtkHierarchicalBoxDataSet class. // // The command line arguments are: // -I => run in interactive mode; unless this is used, the program will // not allow interaction and exit // -D <path> => path to the data; the data should be in <path>/Data/ #include "vtkCamera.h" #include "vtkCellDataToPointData.h" #include "vtkContourFilter.h" #include "vtkDebugLeaks.h" #include "vtkHierarchicalDataSetGeometryFilter.h" #include "vtkOutlineCornerFilter.h" #include "vtkHierarchicalPolyDataMapper.h" #include "vtkProperty.h" #include "vtkRegressionTestImage.h" #include "vtkRenderer.h" #include "vtkRenderWindow.h" #include "vtkRenderWindowInteractor.h" #include "vtkShrinkPolyData.h" #include "vtkTestHierarchicalDataReader.h" #include "vtkTestUtilities.h" int TestHierarchicalBoxPipeline(int argc, char* argv[]) { // Disable for testing vtkDebugLeaks::PromptUserOff(); // Standard rendering classes vtkRenderer *ren = vtkRenderer::New(); vtkCamera* cam = ren->GetActiveCamera(); cam->SetPosition(-5.1828, 5.89733, 8.97969); cam->SetFocalPoint(14.6491, -2.08677, -8.92362); cam->SetViewUp(0.210794, 0.95813, -0.193784); vtkRenderWindow *renWin = vtkRenderWindow::New(); renWin->AddRenderer(ren); vtkRenderWindowInteractor *iren = vtkRenderWindowInteractor::New(); iren->SetRenderWindow(renWin); char* cfname = vtkTestUtilities::ExpandDataFileName(argc, argv, "Data/chombo3d/chombo3d"); vtkTestHierarchicalDataReader* reader = vtkTestHierarchicalDataReader::New(); reader->SetFileName(cfname); delete[] cfname; // geometry filter vtkHierarchicalDataSetGeometryFilter* geom = vtkHierarchicalDataSetGeometryFilter::New(); geom->SetInputConnection(0, reader->GetOutputPort(0)); vtkShrinkPolyData* shrink = vtkShrinkPolyData::New(); shrink->SetShrinkFactor(0.5); shrink->SetInputConnection(0, geom->GetOutputPort(0)); // Rendering objects vtkHierarchicalPolyDataMapper* shMapper = vtkHierarchicalPolyDataMapper::New(); shMapper->SetInputConnection(0, shrink->GetOutputPort(0)); vtkActor* shActor = vtkActor::New(); shActor->SetMapper(shMapper); shActor->GetProperty()->SetColor(0, 0, 1); ren->AddActor(shActor); // corner outline vtkOutlineCornerFilter* ocf = vtkOutlineCornerFilter::New(); ocf->SetInputConnection(0, reader->GetOutputPort(0)); // Rendering objects // This one is actually just a vtkPolyData so it doesn't need a hierarchical // mapper, but we use this one to test hierarchical mapper with polydata input vtkHierarchicalPolyDataMapper* ocMapper = vtkHierarchicalPolyDataMapper::New(); ocMapper->SetInputConnection(0, ocf->GetOutputPort(0)); vtkActor* ocActor = vtkActor::New(); ocActor->SetMapper(ocMapper); ocActor->GetProperty()->SetColor(1, 0, 0); ren->AddActor(ocActor); // cell 2 point and contour vtkCellDataToPointData* c2p = vtkCellDataToPointData::New(); c2p->SetInputConnection(0, reader->GetOutputPort(0)); vtkContourFilter* contour = vtkContourFilter::New(); contour->SetInputConnection(0, c2p->GetOutputPort(0)); contour->SetValue(0, -0.013); contour->SetInputArrayToProcess(0,0,0,vtkDataObject::FIELD_ASSOCIATION_POINTS,"phi"); // Rendering objects vtkHierarchicalPolyDataMapper* contMapper = vtkHierarchicalPolyDataMapper::New(); contMapper->SetInputConnection(0, contour->GetOutputPort(0)); vtkActor* contActor = vtkActor::New(); contActor->SetMapper(contMapper); contActor->GetProperty()->SetColor(1, 0, 0); ren->AddActor(contActor); // Standard testing code. ocf->Delete(); ocMapper->Delete(); ocActor->Delete(); c2p->Delete(); contour->Delete(); contMapper->Delete(); contActor->Delete(); ren->SetBackground(1,1,1); renWin->SetSize(300,300); renWin->Render(); int retVal = vtkRegressionTestImage( renWin ); if ( retVal == vtkRegressionTester::DO_INTERACTOR) { iren->Start(); } // Cleanup geom->Delete(); shMapper->Delete(); shActor->Delete(); ren->Delete(); renWin->Delete(); iren->Delete(); reader->Delete(); shrink->Delete(); return !retVal; } <|endoftext|>
<commit_before><commit_msg>Tests for `Variable::set_shallow`.<commit_after><|endoftext|>
<commit_before>/****************************************************************************** This source file is part of the tomviz project. Copyright Kitware, Inc. This source code is released under the New BSD License, (the "License"). 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 "PassiveAcquisitionWidget.h" #include "ui_PassiveAcquisitionWidget.h" #include "AcquisitionClient.h" #include "ActiveObjects.h" #include "ConnectionDialog.h" #include "InterfaceBuilder.h" #include "StartServerDialog.h" #include "DataSource.h" #include "ModuleManager.h" #include "Pipeline.h" #include "PipelineManager.h" #include <pqApplicationCore.h> #include <pqSettings.h> #include <vtkSMProxy.h> #include <vtkCamera.h> #include <vtkImageData.h> #include <vtkImageProperty.h> #include <vtkImageSlice.h> #include <vtkImageSliceMapper.h> #include <vtkInteractorStyleRubberBand2D.h> #include <vtkRenderWindow.h> #include <vtkRenderer.h> #include <vtkScalarsToColors.h> #include <vtkTIFFReader.h> #include <QBuffer> #include <QCloseEvent> #include <QCoreApplication> #include <QDebug> #include <QDir> #include <QFile> #include <QJsonValueRef> #include <QMessageBox> #include <QNetworkReply> #include <QPalette> #include <QProcess> #include <QPushButton> #include <QRegExp> #include <QTimer> #include <QVBoxLayout> namespace tomviz { const char* PASSIVE_ADAPTER = "tomviz.acquisition.vendors.passive.PassiveWatchSource"; PassiveAcquisitionWidget::PassiveAcquisitionWidget(QWidget* parent) : QWidget(parent), m_ui(new Ui::PassiveAcquisitionWidget), m_client(new AcquisitionClient("http://localhost:8080/acquisition", this)), m_connectParamsWidget(new QWidget), m_watchTimer(new QTimer) { m_ui->setupUi(this); this->setWindowFlags(Qt::Dialog); readSettings(); connect(m_ui->watchPathLineEdit, &QLineEdit::textChanged, this, &PassiveAcquisitionWidget::checkEnableWatchButton); connect(m_ui->connectionsWidget, &ConnectionsWidget::selectionChanged, this, &PassiveAcquisitionWidget::checkEnableWatchButton); connect(m_ui->watchButton, &QPushButton::clicked, [this]() { // Validate the filename regex if (!this->validateRegex()) { return; } this->m_retryCount = 5; this->connectToServer(); }); connect(m_ui->stopWatchingButton, &QPushButton::clicked, this, &PassiveAcquisitionWidget::stopWatching); connect(m_ui->fileNameRegexLineEdit, &QLineEdit::textChanged, [this]() { this->setEnabledRegexGroupsWidget( !m_ui->fileNameRegexLineEdit->text().isEmpty()); }); this->setEnabledRegexGroupsWidget( !m_ui->fileNameRegexLineEdit->text().isEmpty()); connect(m_ui->regexGroupsWidget, &RegexGroupsWidget::groupsChanged, [this]() { this->setEnabledRegexGroupsSubstitutionsWidget( !this->m_ui->regexGroupsWidget->regexGroups().isEmpty()); }); this->setEnabledRegexGroupsSubstitutionsWidget( !this->m_ui->regexGroupsWidget->regexGroups().isEmpty()); this->checkEnableWatchButton(); // Connect signal to clean up any servers we start. auto app = QCoreApplication::instance(); connect(app, &QApplication::aboutToQuit, [this]() { if (this->m_serverProcess != nullptr) { // First disconnect the error signal as we are about pull the rug from // under // the process! disconnect(this->m_serverProcess, &QProcess::errorOccurred, nullptr, nullptr); this->m_serverProcess->terminate(); } }); // Setup regex error label auto palette = m_regexErrorLabel.palette(); palette.setColor(m_regexErrorLabel.foregroundRole(), Qt::red); m_regexErrorLabel.setPalette(palette); connect(m_ui->fileNameRegexLineEdit, &QLineEdit::textChanged, [this]() { this->m_ui->formLayout->removeWidget(&m_regexErrorLabel); this->m_regexErrorLabel.setText(""); }); } PassiveAcquisitionWidget::~PassiveAcquisitionWidget() = default; void PassiveAcquisitionWidget::closeEvent(QCloseEvent* event) { writeSettings(); event->accept(); } void PassiveAcquisitionWidget::readSettings() { auto settings = pqApplicationCore::instance()->settings(); if (!settings->contains("acquisition/geometry")) { return; } settings->beginGroup("acquisition"); setGeometry(settings->value("passive.geometry").toRect()); m_ui->splitter->restoreState( settings->value("passive.splitterSizes").toByteArray()); m_ui->watchPathLineEdit->setText(settings->value("watchPath").toString()); m_ui->fileNameRegexLineEdit->setText( settings->value("fileNameRegex").toString()); settings->endGroup(); } void PassiveAcquisitionWidget::writeSettings() { auto settings = pqApplicationCore::instance()->settings(); settings->beginGroup("acquisition"); settings->setValue("passive.geometry", geometry()); settings->setValue("passive.splitterSizes", m_ui->splitter->saveState()); settings->setValue("watchPath", m_ui->watchPathLineEdit->text()); settings->setValue("fileNameRegex", m_ui->fileNameRegexLineEdit->text()); settings->endGroup(); } void PassiveAcquisitionWidget::connectToServer(bool startServer) { if (this->m_retryCount == 0) { this->displayError("Retry count excceed trying to connect to server."); return; } m_client->setUrl(this->url()); auto request = m_client->connect(this->connectParams()); connect(request, &AcquisitionClientRequest::finished, [this]() { // Now check that we are connected to server that has the right adapter // loaded. auto describeRequest = this->m_client->describe(); connect(describeRequest, &AcquisitionClientRequest::error, this, &PassiveAcquisitionWidget::onError); connect( describeRequest, &AcquisitionClientRequest::finished, [this](const QJsonValue& result) { if (!result.isObject()) { this->onError("Invalid response to describe request:", result); return; } if (result.toObject()["name"] != PASSIVE_ADAPTER) { this->onError( "The server is not running the passive acquisition " "adapter, please restart the server with the correct adapter.", QJsonValue()); return; } // Now we can start watching. this->watchSource(); }); }); connect(request, &AcquisitionClientRequest::error, [startServer, this](const QString& errorMessage, const QJsonValue& errorData) { auto connection = this->m_ui->connectionsWidget->selectedConnection(); // If we are getting a connection refused error and we are trying to // connect // to localhost, try to start the server. if (startServer && errorData.toInt() == QNetworkReply::ConnectionRefusedError && connection->hostName() == "localhost") { this->startLocalServer(); } else { this->onError(errorMessage, errorData); } }); } void PassiveAcquisitionWidget::imageReady(QString mimeType, QByteArray result, int angle) { if (mimeType != "image/tiff") { qDebug() << "image/tiff is the only supported mime type right now.\n" << mimeType << "\n"; return; } QDir dir(QDir::homePath() + "/tomviz-data"); if (!dir.exists()) { dir.mkpath(dir.path()); } QString path = "/tomviz_"; if (angle > 0.0) { path.append('+'); } path.append(QString::number(angle, 'g', 2)); path.append(".tiff"); QFile file(dir.path() + path); file.open(QIODevice::WriteOnly); file.write(result); qDebug() << "Data file:" << file.fileName(); file.close(); vtkNew<vtkTIFFReader> reader; reader->SetFileName(file.fileName().toLatin1()); reader->Update(); m_imageData = reader->GetOutput(); m_imageSlice->GetProperty()->SetInterpolationTypeToNearest(); m_imageSliceMapper->SetInputData(m_imageData.Get()); m_imageSliceMapper->Update(); m_imageSlice->SetMapper(m_imageSliceMapper.Get()); m_renderer->AddViewProp(m_imageSlice.Get()); // If we haven't added it, add our live data source to the pipeline. if (!m_dataSource) { m_dataSource = new DataSource(m_imageData); m_dataSource->setLabel("Live!"); auto pipeline = new Pipeline(m_dataSource); PipelineManager::instance().addPipeline(pipeline); ModuleManager::instance().addDataSource(m_dataSource); pipeline->addDefaultModules(m_dataSource); } else { m_dataSource->appendSlice(m_imageData); } } void PassiveAcquisitionWidget::onError(const QString& errorMessage, const QJsonValue& errorData) { auto message = errorMessage; if (!errorData.toString().isEmpty()) { message = QString("%1\n%2").arg(message).arg(errorData.toString()); } this->stopWatching(); this->displayError(message); } void PassiveAcquisitionWidget::displayError(const QString& errorMessage) { QMessageBox::warning(this, "Acquisition Error", errorMessage, QMessageBox::Ok); } QString PassiveAcquisitionWidget::url() const { auto connection = m_ui->connectionsWidget->selectedConnection(); return QString("http://%1:%2/acquisition") .arg(connection->hostName()) .arg(connection->port()); } void PassiveAcquisitionWidget::watchSource() { this->m_ui->watchButton->setEnabled(false); this->m_ui->stopWatchingButton->setEnabled(true); connect(this->m_watchTimer, &QTimer::timeout, this, [this]() { auto request = m_client->stem_acquire(); connect(request, &AcquisitionClientImageRequest::finished, [this](const QString mimeType, const QByteArray& result, const QJsonObject& meta) { if (!result.isNull()) { int angle = 0; if (meta.contains("angle")) { angle = meta["angle"].toString().toInt(); } this->imageReady(mimeType, result, angle); } }); connect(request, &AcquisitionClientRequest::error, this, &PassiveAcquisitionWidget::onError); }, Qt::UniqueConnection); this->m_watchTimer->start(1000); } QJsonObject PassiveAcquisitionWidget::connectParams() { QJsonObject connectParams{ { "path", m_ui->watchPathLineEdit->text() }, { "fileNameRegex", m_ui->fileNameRegexLineEdit->text() }, }; auto fileNameRegexGroups = m_ui->regexGroupsWidget->regexGroups(); if (!fileNameRegexGroups.isEmpty()) { auto groups = QJsonArray::fromStringList(fileNameRegexGroups); connectParams["fileNameRegexGroups"] = groups; } auto regexGroupsSubstitutions = m_ui->regexGroupsSubstitutionsWidget->substitutions(); if (!regexGroupsSubstitutions.isEmpty()) { QJsonObject substitutions; foreach (RegexGroupSubstitution sub, regexGroupsSubstitutions) { QJsonArray regexToSubs; if (substitutions.contains(sub.groupName())) { regexToSubs = substitutions.value(sub.groupName()).toArray(); } QJsonObject mapping; mapping[sub.regex()] = sub.substitution(); regexToSubs.append(mapping); substitutions[sub.groupName()] = regexToSubs; } connectParams["groupRegexSubstitutions"] = substitutions; } return connectParams; } void PassiveAcquisitionWidget::startLocalServer() { StartServerDialog dialog; auto r = dialog.exec(); if (r != QDialog::Accepted) { return; } auto pythonExecutablePath = dialog.pythonExecutablePath(); QStringList arguments; arguments << "-m" << "tomviz" << "-a" << PASSIVE_ADAPTER << "-r"; this->m_serverProcess = new QProcess(this); this->m_serverProcess->setProgram(pythonExecutablePath); this->m_serverProcess->setArguments(arguments); connect(this->m_serverProcess, &QProcess::errorOccurred, [this](QProcess::ProcessError error) { auto message = QString("Error starting local acquisition: '%1'") .arg(this->m_serverProcess->errorString()); QMessageBox::warning(this, "Server Start Error", message, QMessageBox::Ok); }); connect(this->m_serverProcess, &QProcess::started, [this]() { // Now try to connect and watch. Note we are not asking for server to be // started if the connection fails, this is to prevent us getting into a // connect loop. QTimer::singleShot(200, [this]() { this->m_retryCount--; this->connectToServer(false); }); }); this->m_serverProcess->start(); } void PassiveAcquisitionWidget::checkEnableWatchButton() { auto path = m_ui->watchPathLineEdit->text(); this->m_ui->watchButton->setEnabled( !path.isEmpty() && this->m_ui->connectionsWidget->selectedConnection() != nullptr); } void PassiveAcquisitionWidget::setEnabledRegexGroupsWidget(bool enabled) { this->m_ui->regexGroupsLabel->setEnabled(enabled); this->m_ui->regexGroupsWidget->setEnabled(enabled); } void PassiveAcquisitionWidget::setEnabledRegexGroupsSubstitutionsWidget( bool enabled) { this->m_ui->regexGroupsSubstitutionsLabel->setEnabled(enabled); this->m_ui->regexGroupsSubstitutionsWidget->setEnabled(enabled); } void PassiveAcquisitionWidget::stopWatching() { this->m_watchTimer->stop(); this->m_ui->stopWatchingButton->setEnabled(false); this->m_ui->watchButton->setEnabled(true); } bool PassiveAcquisitionWidget::validateRegex() { auto regExText = m_ui->fileNameRegexLineEdit->text(); if (!regExText.isEmpty()) { QRegExp regExp(regExText); if (!regExp.isValid()) { m_regexErrorLabel.setText(regExp.errorString()); m_ui->formLayout->insertRow(3, "", &m_regexErrorLabel); return false; } } return true; } } <commit_msg>Fix unused warning<commit_after>/****************************************************************************** This source file is part of the tomviz project. Copyright Kitware, Inc. This source code is released under the New BSD License, (the "License"). 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 "PassiveAcquisitionWidget.h" #include "ui_PassiveAcquisitionWidget.h" #include "AcquisitionClient.h" #include "ActiveObjects.h" #include "ConnectionDialog.h" #include "InterfaceBuilder.h" #include "StartServerDialog.h" #include "DataSource.h" #include "ModuleManager.h" #include "Pipeline.h" #include "PipelineManager.h" #include <pqApplicationCore.h> #include <pqSettings.h> #include <vtkSMProxy.h> #include <vtkCamera.h> #include <vtkImageData.h> #include <vtkImageProperty.h> #include <vtkImageSlice.h> #include <vtkImageSliceMapper.h> #include <vtkInteractorStyleRubberBand2D.h> #include <vtkRenderWindow.h> #include <vtkRenderer.h> #include <vtkScalarsToColors.h> #include <vtkTIFFReader.h> #include <QBuffer> #include <QCloseEvent> #include <QCoreApplication> #include <QDebug> #include <QDir> #include <QFile> #include <QJsonValueRef> #include <QMessageBox> #include <QNetworkReply> #include <QPalette> #include <QProcess> #include <QPushButton> #include <QRegExp> #include <QTimer> #include <QVBoxLayout> namespace tomviz { const char* PASSIVE_ADAPTER = "tomviz.acquisition.vendors.passive.PassiveWatchSource"; PassiveAcquisitionWidget::PassiveAcquisitionWidget(QWidget* parent) : QWidget(parent), m_ui(new Ui::PassiveAcquisitionWidget), m_client(new AcquisitionClient("http://localhost:8080/acquisition", this)), m_connectParamsWidget(new QWidget), m_watchTimer(new QTimer) { m_ui->setupUi(this); this->setWindowFlags(Qt::Dialog); readSettings(); connect(m_ui->watchPathLineEdit, &QLineEdit::textChanged, this, &PassiveAcquisitionWidget::checkEnableWatchButton); connect(m_ui->connectionsWidget, &ConnectionsWidget::selectionChanged, this, &PassiveAcquisitionWidget::checkEnableWatchButton); connect(m_ui->watchButton, &QPushButton::clicked, [this]() { // Validate the filename regex if (!this->validateRegex()) { return; } this->m_retryCount = 5; this->connectToServer(); }); connect(m_ui->stopWatchingButton, &QPushButton::clicked, this, &PassiveAcquisitionWidget::stopWatching); connect(m_ui->fileNameRegexLineEdit, &QLineEdit::textChanged, [this]() { this->setEnabledRegexGroupsWidget( !m_ui->fileNameRegexLineEdit->text().isEmpty()); }); this->setEnabledRegexGroupsWidget( !m_ui->fileNameRegexLineEdit->text().isEmpty()); connect(m_ui->regexGroupsWidget, &RegexGroupsWidget::groupsChanged, [this]() { this->setEnabledRegexGroupsSubstitutionsWidget( !this->m_ui->regexGroupsWidget->regexGroups().isEmpty()); }); this->setEnabledRegexGroupsSubstitutionsWidget( !this->m_ui->regexGroupsWidget->regexGroups().isEmpty()); this->checkEnableWatchButton(); // Connect signal to clean up any servers we start. auto app = QCoreApplication::instance(); connect(app, &QApplication::aboutToQuit, [this]() { if (this->m_serverProcess != nullptr) { // First disconnect the error signal as we are about pull the rug from // under // the process! disconnect(this->m_serverProcess, &QProcess::errorOccurred, nullptr, nullptr); this->m_serverProcess->terminate(); } }); // Setup regex error label auto palette = m_regexErrorLabel.palette(); palette.setColor(m_regexErrorLabel.foregroundRole(), Qt::red); m_regexErrorLabel.setPalette(palette); connect(m_ui->fileNameRegexLineEdit, &QLineEdit::textChanged, [this]() { this->m_ui->formLayout->removeWidget(&m_regexErrorLabel); this->m_regexErrorLabel.setText(""); }); } PassiveAcquisitionWidget::~PassiveAcquisitionWidget() = default; void PassiveAcquisitionWidget::closeEvent(QCloseEvent* event) { writeSettings(); event->accept(); } void PassiveAcquisitionWidget::readSettings() { auto settings = pqApplicationCore::instance()->settings(); if (!settings->contains("acquisition/geometry")) { return; } settings->beginGroup("acquisition"); setGeometry(settings->value("passive.geometry").toRect()); m_ui->splitter->restoreState( settings->value("passive.splitterSizes").toByteArray()); m_ui->watchPathLineEdit->setText(settings->value("watchPath").toString()); m_ui->fileNameRegexLineEdit->setText( settings->value("fileNameRegex").toString()); settings->endGroup(); } void PassiveAcquisitionWidget::writeSettings() { auto settings = pqApplicationCore::instance()->settings(); settings->beginGroup("acquisition"); settings->setValue("passive.geometry", geometry()); settings->setValue("passive.splitterSizes", m_ui->splitter->saveState()); settings->setValue("watchPath", m_ui->watchPathLineEdit->text()); settings->setValue("fileNameRegex", m_ui->fileNameRegexLineEdit->text()); settings->endGroup(); } void PassiveAcquisitionWidget::connectToServer(bool startServer) { if (this->m_retryCount == 0) { this->displayError("Retry count excceed trying to connect to server."); return; } m_client->setUrl(this->url()); auto request = m_client->connect(this->connectParams()); connect(request, &AcquisitionClientRequest::finished, [this]() { // Now check that we are connected to server that has the right adapter // loaded. auto describeRequest = this->m_client->describe(); connect(describeRequest, &AcquisitionClientRequest::error, this, &PassiveAcquisitionWidget::onError); connect( describeRequest, &AcquisitionClientRequest::finished, [this](const QJsonValue& result) { if (!result.isObject()) { this->onError("Invalid response to describe request:", result); return; } if (result.toObject()["name"] != PASSIVE_ADAPTER) { this->onError( "The server is not running the passive acquisition " "adapter, please restart the server with the correct adapter.", QJsonValue()); return; } // Now we can start watching. this->watchSource(); }); }); connect(request, &AcquisitionClientRequest::error, [startServer, this](const QString& errorMessage, const QJsonValue& errorData) { auto connection = this->m_ui->connectionsWidget->selectedConnection(); // If we are getting a connection refused error and we are trying to // connect // to localhost, try to start the server. if (startServer && errorData.toInt() == QNetworkReply::ConnectionRefusedError && connection->hostName() == "localhost") { this->startLocalServer(); } else { this->onError(errorMessage, errorData); } }); } void PassiveAcquisitionWidget::imageReady(QString mimeType, QByteArray result, int angle) { if (mimeType != "image/tiff") { qDebug() << "image/tiff is the only supported mime type right now.\n" << mimeType << "\n"; return; } QDir dir(QDir::homePath() + "/tomviz-data"); if (!dir.exists()) { dir.mkpath(dir.path()); } QString path = "/tomviz_"; if (angle > 0.0) { path.append('+'); } path.append(QString::number(angle, 'g', 2)); path.append(".tiff"); QFile file(dir.path() + path); file.open(QIODevice::WriteOnly); file.write(result); qDebug() << "Data file:" << file.fileName(); file.close(); vtkNew<vtkTIFFReader> reader; reader->SetFileName(file.fileName().toLatin1()); reader->Update(); m_imageData = reader->GetOutput(); m_imageSlice->GetProperty()->SetInterpolationTypeToNearest(); m_imageSliceMapper->SetInputData(m_imageData.Get()); m_imageSliceMapper->Update(); m_imageSlice->SetMapper(m_imageSliceMapper.Get()); m_renderer->AddViewProp(m_imageSlice.Get()); // If we haven't added it, add our live data source to the pipeline. if (!m_dataSource) { m_dataSource = new DataSource(m_imageData); m_dataSource->setLabel("Live!"); auto pipeline = new Pipeline(m_dataSource); PipelineManager::instance().addPipeline(pipeline); ModuleManager::instance().addDataSource(m_dataSource); pipeline->addDefaultModules(m_dataSource); } else { m_dataSource->appendSlice(m_imageData); } } void PassiveAcquisitionWidget::onError(const QString& errorMessage, const QJsonValue& errorData) { auto message = errorMessage; if (!errorData.toString().isEmpty()) { message = QString("%1\n%2").arg(message).arg(errorData.toString()); } this->stopWatching(); this->displayError(message); } void PassiveAcquisitionWidget::displayError(const QString& errorMessage) { QMessageBox::warning(this, "Acquisition Error", errorMessage, QMessageBox::Ok); } QString PassiveAcquisitionWidget::url() const { auto connection = m_ui->connectionsWidget->selectedConnection(); return QString("http://%1:%2/acquisition") .arg(connection->hostName()) .arg(connection->port()); } void PassiveAcquisitionWidget::watchSource() { this->m_ui->watchButton->setEnabled(false); this->m_ui->stopWatchingButton->setEnabled(true); connect(this->m_watchTimer, &QTimer::timeout, this, [this]() { auto request = m_client->stem_acquire(); connect(request, &AcquisitionClientImageRequest::finished, [this](const QString mimeType, const QByteArray& result, const QJsonObject& meta) { if (!result.isNull()) { int angle = 0; if (meta.contains("angle")) { angle = meta["angle"].toString().toInt(); } this->imageReady(mimeType, result, angle); } }); connect(request, &AcquisitionClientRequest::error, this, &PassiveAcquisitionWidget::onError); }, Qt::UniqueConnection); this->m_watchTimer->start(1000); } QJsonObject PassiveAcquisitionWidget::connectParams() { QJsonObject connectParams{ { "path", m_ui->watchPathLineEdit->text() }, { "fileNameRegex", m_ui->fileNameRegexLineEdit->text() }, }; auto fileNameRegexGroups = m_ui->regexGroupsWidget->regexGroups(); if (!fileNameRegexGroups.isEmpty()) { auto groups = QJsonArray::fromStringList(fileNameRegexGroups); connectParams["fileNameRegexGroups"] = groups; } auto regexGroupsSubstitutions = m_ui->regexGroupsSubstitutionsWidget->substitutions(); if (!regexGroupsSubstitutions.isEmpty()) { QJsonObject substitutions; foreach (RegexGroupSubstitution sub, regexGroupsSubstitutions) { QJsonArray regexToSubs; if (substitutions.contains(sub.groupName())) { regexToSubs = substitutions.value(sub.groupName()).toArray(); } QJsonObject mapping; mapping[sub.regex()] = sub.substitution(); regexToSubs.append(mapping); substitutions[sub.groupName()] = regexToSubs; } connectParams["groupRegexSubstitutions"] = substitutions; } return connectParams; } void PassiveAcquisitionWidget::startLocalServer() { StartServerDialog dialog; auto r = dialog.exec(); if (r != QDialog::Accepted) { return; } auto pythonExecutablePath = dialog.pythonExecutablePath(); QStringList arguments; arguments << "-m" << "tomviz" << "-a" << PASSIVE_ADAPTER << "-r"; this->m_serverProcess = new QProcess(this); this->m_serverProcess->setProgram(pythonExecutablePath); this->m_serverProcess->setArguments(arguments); connect(this->m_serverProcess, &QProcess::errorOccurred, [this](QProcess::ProcessError error) { Q_UNUSED(error); auto message = QString("Error starting local acquisition: '%1'") .arg(this->m_serverProcess->errorString()); QMessageBox::warning(this, "Server Start Error", message, QMessageBox::Ok); }); connect(this->m_serverProcess, &QProcess::started, [this]() { // Now try to connect and watch. Note we are not asking for server to be // started if the connection fails, this is to prevent us getting into a // connect loop. QTimer::singleShot(200, [this]() { this->m_retryCount--; this->connectToServer(false); }); }); this->m_serverProcess->start(); } void PassiveAcquisitionWidget::checkEnableWatchButton() { auto path = m_ui->watchPathLineEdit->text(); this->m_ui->watchButton->setEnabled( !path.isEmpty() && this->m_ui->connectionsWidget->selectedConnection() != nullptr); } void PassiveAcquisitionWidget::setEnabledRegexGroupsWidget(bool enabled) { this->m_ui->regexGroupsLabel->setEnabled(enabled); this->m_ui->regexGroupsWidget->setEnabled(enabled); } void PassiveAcquisitionWidget::setEnabledRegexGroupsSubstitutionsWidget( bool enabled) { this->m_ui->regexGroupsSubstitutionsLabel->setEnabled(enabled); this->m_ui->regexGroupsSubstitutionsWidget->setEnabled(enabled); } void PassiveAcquisitionWidget::stopWatching() { this->m_watchTimer->stop(); this->m_ui->stopWatchingButton->setEnabled(false); this->m_ui->watchButton->setEnabled(true); } bool PassiveAcquisitionWidget::validateRegex() { auto regExText = m_ui->fileNameRegexLineEdit->text(); if (!regExText.isEmpty()) { QRegExp regExp(regExText); if (!regExp.isValid()) { m_regexErrorLabel.setText(regExp.errorString()); m_ui->formLayout->insertRow(3, "", &m_regexErrorLabel); return false; } } return true; } } <|endoftext|>
<commit_before>#include "invoke_response_message.h" namespace dsa { InvokeResponseMessage::InvokeResponseMessage(const SharedBuffer& buffer) : ResponseMessage(buffer) { parse_dynamic_headers(buffer.data + StaticHeaders::TotalSize, static_headers.header_size - StaticHeaders::TotalSize); } void InvokeResponseMessage::parse_dynamic_headers(const uint8_t* data, size_t size) { while (size > 0) { DynamicHeader* header = DynamicHeader::parse(data, size); uint8_t key = header->key(); if (key == DynamicHeader::Priority) { priority.reset(static_cast<DynamicByteHeader*>(header)); } // else if (key == DynamicHeader::Status) { status.reset(static_cast<DynamicByteHeader*>(header)); } // else if (key == DynamicHeader::SequenceId) { sequence_id.reset(static_cast<DynamicIntHeader*>(header)); } // else if (key == DynamicHeader::PageId) { page_id.reset(static_cast<DynamicIntHeader*>(header)); } // // else if (key == DynamicHeader::AliasCount) { // alias_count.reset(static_cast<DynamicByteHeader*>(header)); //} // // else if (key == DynamicHeader::TargetPath) { // target_path.reset(static_cast<DynamicStringHeader*>(header)); //} // // else if (key == DynamicHeader::PermissionToken) { // permission_token.reset(static_cast<DynamicStringHeader*>(header)); //} // // else if (key == DynamicHeader::MaxPermission) { // max_permission_token.reset(static_cast<DynamicByteHeader*>(header)); //} // // else if (key == DynamicHeader::NoStream) { // no_stream.reset(static_cast<DynamicBoolHeader*>(header)); //} // // else if (key == DynamicHeader::Qos) { // qos.reset(static_cast<DynamicByteHeader*>(header)); //} // // else if (key == DynamicHeader::QueueSize) { // queue_size.reset(static_cast<DynamicByteHeader*>(header)); //} // // else if (key == DynamicHeader::QueueTime) { // queue_time.reset(static_cast<DynamicByteHeader*>(header)); //} // // else if (key == DynamicHeader::UpdateFrequency) { // update_frequency.reset(static_cast<DynamicByteHeader*>(header)); //} // // else if (key == DynamicHeader::BasePath) { // base_path.reset(static_cast<DynamicStringHeader*>(header)); //} // // else if (key == DynamicHeader::SourcePath) { // source_path.reset(static_cast<DynamicStringHeader*>(header)); //} // else if (key == DynamicHeader::Skippable) { skippable.reset(static_cast<DynamicBoolHeader*>(header)); } // } } void InvokeResponseMessage::write_dynamic_data(uint8_t* data) const { if (priority != nullptr) { priority->write(data); data += priority->size(); } if (status != nullptr) { status->write(data); data += status->size(); } if (sequence_id != nullptr) { sequence_id->write(data); data += sequence_id->size(); } if (page_id != nullptr) { page_id->write(data); data += page_id->size(); } //if (alias_count != nullptr) { // alias_count->write(data); // data += alias_count->size(); //} //if (permission_token != nullptr) { // permission_token->write(data); // data += permission_token->size(); //} //if (max_permission != nullptr) { // max_permission->write(data); // data += max_permission->size(); //} //if (no_stream != nullptr) { // no_stream->write(data); // data += no_stream->size(); //} //if (qos != nullptr) { // qos->write(data); // data += qos->size(); //} //if (queue_size != nullptr) { // queue_size->write(data); // data += queue_size->size(); //} //if (queue_time != nullptr) { // queue_time->write(data); // data += queue_time->size(); //} //if (update_frequency != nullptr) { // update_frequency->write(data); // data += update_frequency->size(); //} //if (base_path != nullptr) { // base_path->write(data); // data += base_path->size(); //} //if (source_path != nullptr) { // source_path->write(data); // data += source_path->size(); //} if (skippable != nullptr) { skippable->write(data); data += skippable->size(); } if (body != nullptr) { memcpy(data, body->data, body->size); } } void InvokeResponseMessage::update_static_header() { uint32_t header_size = StaticHeaders::TotalSize; if (priority != nullptr) { header_size += priority->size(); } if (status != nullptr) { header_size += status->size(); } if (sequence_id != nullptr) { header_size += sequence_id->size(); } if (page_id != nullptr) { header_size += page_id->size(); } //if (alias_count != nullptr) { // header_size += alias_count->size(); //} //if (target_path != nullptr) { // header_size += target_path->size(); //} //if (permission_token != nullptr) { // header_size += permission_token->size(); //} //if (max_permission != nullptr) { // header_size += max_permission->size(); //} //if (no_stream != nullptr) { // header_size += no_stream->size(); //} //if (qos != nullptr) { // header_size += qos->size(); //} //if (queue_size != nullptr) { // header_size += queue_size->size(); //} //if (queue_time != nullptr) { // header_size += queue_time->size(); //} //if (update_frequency != nullptr) { // header_size += update_frequency->size(); //} //if (base_path != nullptr) { // header_size += base_path->size(); //} //if (source_path != nullptr) { // header_size += source_path->size(); //} if (skippable != nullptr) { header_size += skippable->size(); } uint32_t message_size = header_size; if (body != nullptr) { message_size += body->size; } static_headers.message_size = message_size; static_headers.header_size = header_size; } } // namespace dsa <commit_msg>changed static cast to dynamic cast<commit_after>#include "invoke_response_message.h" namespace dsa { InvokeResponseMessage::InvokeResponseMessage(const SharedBuffer& buffer) : ResponseMessage(buffer) { parse_dynamic_headers(buffer.data + StaticHeaders::TotalSize, static_headers.header_size - StaticHeaders::TotalSize); } void InvokeResponseMessage::parse_dynamic_headers(const uint8_t* data, size_t size) { while (size > 0) { DynamicHeader* header = DynamicHeader::parse(data, size); uint8_t key = header->key(); if (key == DynamicHeader::Priority) { priority.reset(dynamic_cast<DynamicByteHeader*>(header)); } // else if (key == DynamicHeader::Status) { status.reset(dynamic_cast<DynamicByteHeader*>(header)); } // else if (key == DynamicHeader::SequenceId) { sequence_id.reset(dynamic_cast<DynamicIntHeader*>(header)); } // else if (key == DynamicHeader::PageId) { page_id.reset(dynamic_cast<DynamicIntHeader*>(header)); } // // else if (key == DynamicHeader::AliasCount) { // alias_count.reset(dynamic_cast<DynamicByteHeader*>(header)); //} // // else if (key == DynamicHeader::TargetPath) { // target_path.reset(dynamic_cast<DynamicStringHeader*>(header)); //} // // else if (key == DynamicHeader::PermissionToken) { // permission_token.reset(dynamic_cast<DynamicStringHeader*>(header)); //} // // else if (key == DynamicHeader::MaxPermission) { // max_permission_token.reset(dynamic_cast<DynamicByteHeader*>(header)); //} // // else if (key == DynamicHeader::NoStream) { // no_stream.reset(dynamic_cast<DynamicBoolHeader*>(header)); //} // // else if (key == DynamicHeader::Qos) { // qos.reset(dynamic_cast<DynamicByteHeader*>(header)); //} // // else if (key == DynamicHeader::QueueSize) { // queue_size.reset(dynamic_cast<DynamicByteHeader*>(header)); //} // // else if (key == DynamicHeader::QueueTime) { // queue_time.reset(dynamic_cast<DynamicByteHeader*>(header)); //} // // else if (key == DynamicHeader::UpdateFrequency) { // update_frequency.reset(dynamic_cast<DynamicByteHeader*>(header)); //} // // else if (key == DynamicHeader::BasePath) { // base_path.reset(dynamic_cast<DynamicStringHeader*>(header)); //} // // else if (key == DynamicHeader::SourcePath) { // source_path.reset(dynamic_cast<DynamicStringHeader*>(header)); //} // else if (key == DynamicHeader::Skippable) { skippable.reset(dynamic_cast<DynamicBoolHeader*>(header)); } // } } void InvokeResponseMessage::write_dynamic_data(uint8_t* data) const { if (priority != nullptr) { priority->write(data); data += priority->size(); } if (status != nullptr) { status->write(data); data += status->size(); } if (sequence_id != nullptr) { sequence_id->write(data); data += sequence_id->size(); } if (page_id != nullptr) { page_id->write(data); data += page_id->size(); } //if (alias_count != nullptr) { // alias_count->write(data); // data += alias_count->size(); //} //if (permission_token != nullptr) { // permission_token->write(data); // data += permission_token->size(); //} //if (max_permission != nullptr) { // max_permission->write(data); // data += max_permission->size(); //} //if (no_stream != nullptr) { // no_stream->write(data); // data += no_stream->size(); //} //if (qos != nullptr) { // qos->write(data); // data += qos->size(); //} //if (queue_size != nullptr) { // queue_size->write(data); // data += queue_size->size(); //} //if (queue_time != nullptr) { // queue_time->write(data); // data += queue_time->size(); //} //if (update_frequency != nullptr) { // update_frequency->write(data); // data += update_frequency->size(); //} //if (base_path != nullptr) { // base_path->write(data); // data += base_path->size(); //} //if (source_path != nullptr) { // source_path->write(data); // data += source_path->size(); //} if (skippable != nullptr) { skippable->write(data); data += skippable->size(); } if (body != nullptr) { memcpy(data, body->data, body->size); } } void InvokeResponseMessage::update_static_header() { uint32_t header_size = StaticHeaders::TotalSize; if (priority != nullptr) { header_size += priority->size(); } if (status != nullptr) { header_size += status->size(); } if (sequence_id != nullptr) { header_size += sequence_id->size(); } if (page_id != nullptr) { header_size += page_id->size(); } //if (alias_count != nullptr) { // header_size += alias_count->size(); //} //if (target_path != nullptr) { // header_size += target_path->size(); //} //if (permission_token != nullptr) { // header_size += permission_token->size(); //} //if (max_permission != nullptr) { // header_size += max_permission->size(); //} //if (no_stream != nullptr) { // header_size += no_stream->size(); //} //if (qos != nullptr) { // header_size += qos->size(); //} //if (queue_size != nullptr) { // header_size += queue_size->size(); //} //if (queue_time != nullptr) { // header_size += queue_time->size(); //} //if (update_frequency != nullptr) { // header_size += update_frequency->size(); //} //if (base_path != nullptr) { // header_size += base_path->size(); //} //if (source_path != nullptr) { // header_size += source_path->size(); //} if (skippable != nullptr) { header_size += skippable->size(); } uint32_t message_size = header_size; if (body != nullptr) { message_size += body->size; } static_headers.message_size = message_size; static_headers.header_size = header_size; } } // namespace dsa <|endoftext|>
<commit_before>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: liImageRegistrationConsoleBase.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 2002 Insight Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include <liImageRegistrationConsoleBase.h> #include <FL/fl_ask.H> #include <itkMetaImageIOFactory.h> #include <itkRawImageIO.h> /************************************ * * Constructor * ***********************************/ liImageRegistrationConsoleBase ::liImageRegistrationConsoleBase() { m_FixedImageReader = FixedImageReaderType::New(); m_MovingImageReader = MovingImageReaderType::New(); m_MovingImageWriter = MovingImageWriterType::New(); m_ResampleInputMovingImageFilter = ResampleFilterType::New(); m_ResampleInputMovingImageFilter->SetInput( m_MovingImageReader->GetOutput() ); m_ResampleMovingImageFilter = ResampleFilterType::New(); m_ResampleMovingImageFilter->SetInput( m_MovingImageReader->GetOutput() ); m_InputTransform = AffineTransformType::New(); m_ResampleInputMovingImageFilter->SetTransform( m_InputTransform ); m_ImageRegistrationMethod = ImageRegistrationMethodType::New(); m_ImageRegistrationMethod->SetFixedImage( m_FixedImageReader->GetOutput() ); m_ImageRegistrationMethod->SetMovingImage( m_ResampleInputMovingImageFilter->GetOutput() ); m_MovingImageWriter->SetInput( m_ResampleInputMovingImageFilter->GetOutput() ); itk::MetaImageIOFactory::RegisterOneFactory(); itk::RawImageIOFactory< MovingImageType::PixelType, MovingImageType::ImageDimension >::RegisterOneFactory(); m_FixedImageIsLoaded = false; m_MovingImageIsLoaded = false; this->SelectMetric( meanSquares ); this->SelectTransform( translationTransform ); this->SelectOptimizer( regularStepGradientDescent ); this->SelectInterpolator( nearestNeighborInterpolator ); } /************************************ * * Destructor * ***********************************/ liImageRegistrationConsoleBase ::~liImageRegistrationConsoleBase() { } /************************************ * * Load Fixed Image * ***********************************/ void liImageRegistrationConsoleBase ::LoadFixedImage( const char * filename ) { if( !filename ) { return; } m_FixedImageReader->SetFileName( filename ); m_FixedImageReader->Update(); m_FixedImageIsLoaded = true; } /************************************ * * Load Moving Image * ***********************************/ void liImageRegistrationConsoleBase ::LoadMovingImage( const char * filename ) { if( !filename ) { return; } m_MovingImageReader->SetFileName( filename ); m_MovingImageReader->Update(); m_MovingImageIsLoaded = true; } /************************************ * * Save Moving Image * ***********************************/ void liImageRegistrationConsoleBase ::SaveMovingImage( const char * filename ) { if( !filename ) { return; } /* std::ofstream ofs( filename ); MovingImageType * movingImage = m_ResampleInputMovingImageFilter->GetOutput().GetPointer(); ofs.write( (char*)movingImage->GetBufferPointer(), movingImage->GetBufferedRegion().GetNumberOfPixels() * sizeof( MovingImageType::PixelType ) ); ofs.close(); std::cout << "Image was writen to : " << filename << std::endl; */ m_MovingImageWriter->SetFileName( filename ); m_MovingImageWriter->Write(); } /************************************ * * Show Status * ***********************************/ void liImageRegistrationConsoleBase ::ShowStatus( const char * ) { } /************************************ * * Generate reference image * ***********************************/ void liImageRegistrationConsoleBase ::GenerateMovingImage( void ) { if( !m_MovingImageIsLoaded ) { return; } this->ShowStatus("Transforming the original image..."); m_ResampleInputMovingImageFilter->SetOutputSpacing( m_MovingImageReader->GetOutput()->GetSpacing() ); m_ResampleInputMovingImageFilter->SetOutputOrigin( m_MovingImageReader->GetOutput()->GetOrigin() ); m_ResampleInputMovingImageFilter->SetSize( m_MovingImageReader->GetOutput()->GetLargestPossibleRegion().GetSize() ); m_ResampleInputMovingImageFilter->Update(); this->ShowStatus("FixedImage Image Transformation done"); } /************************************ * * Stop Registration * ***********************************/ void liImageRegistrationConsoleBase ::Stop( void ) { // TODO: add a Stop() method to Optimizers //m_ImageRegistrationMethod->GetOptimizer()->Stop(); } /************************************ * * Execute * ***********************************/ void liImageRegistrationConsoleBase ::Execute( void ) { m_ImageRegistrationMethod->StartRegistration(); } /************************************ * * Generate Mapped MovingImage image * ***********************************/ void liImageRegistrationConsoleBase ::GenerateMappedMovingImage( void ) { if( !m_MovingImageIsLoaded ) { return; } this->ShowStatus("Transforming the reference image..."); m_ResampleMovingImageFilter->Update(); this->ShowStatus("MovingImage Image Transformation done"); } /************************************ * * Update the parameters of the * Transform * ***********************************/ void liImageRegistrationConsoleBase ::UpdateTransformParameters( void ) { } /************************************ * * Select the metric to be used to * compare the images during the * registration process * ***********************************/ void liImageRegistrationConsoleBase ::SelectMetric( MetricIdentifier metricId ) { m_SelectedMetric = metricId; switch( m_SelectedMetric ) { case mutualInformation: { m_ImageRegistrationMethod->SetMetric( MutualInformationMetricType::New() ); break; } case normalizedCorrelation: { m_ImageRegistrationMethod->SetMetric( NormalizedCorrelationImageMetricType::New() ); break; } case patternIntensity: { m_ImageRegistrationMethod->SetMetric( PatternIntensityImageMetricType::New() ); break; } case meanSquares: { m_ImageRegistrationMethod->SetMetric( MeanSquaresMetricType::New() ); break; } default: fl_alert("Unkown type of metric was selected"); return; } } /***************************************** * * Select the optimizer to be used * to explore the transform parameter * space and optimize the metric * ****************************************/ void liImageRegistrationConsoleBase ::SelectOptimizer( OptimizerIdentifier optimizerId ) { m_SelectedOptimizer = optimizerId; switch( m_SelectedOptimizer ) { case gradientDescent: { m_ImageRegistrationMethod->SetOptimizer( itk::GradientDescentOptimizer::New() ); break; } case regularStepGradientDescent: { m_ImageRegistrationMethod->SetOptimizer( itk::RegularStepGradientDescentOptimizer::New() ); break; } case conjugateGradient: { m_ImageRegistrationMethod->SetOptimizer( itk::ConjugateGradientOptimizer::New() ); break; } default: fl_alert("Unkown type of optimizer was selected"); return; } } /***************************************** * * Select the interpolator to be used * to evaluate images at non-grid positions * ****************************************/ void liImageRegistrationConsoleBase ::SelectInterpolator( InterpolatorIdentifier interpolatorId ) { m_SelectedInterpolator = interpolatorId; switch( m_SelectedInterpolator ) { case linearInterpolator: { m_ImageRegistrationMethod->SetInterpolator( itk::LinearInterpolateImageFunction<MovingImageType, double >::New() ); break; } case nearestNeighborInterpolator: { m_ImageRegistrationMethod->SetInterpolator( itk::NearestNeighborInterpolateImageFunction<MovingImageType, double >::New() ); break; } default: fl_alert("Unkown type of optimizer was selected"); return; } } /***************************************** * * Select the Transform to be used * to map the moving image into the * fixed image * ****************************************/ void liImageRegistrationConsoleBase ::SelectTransform( TransformIdentifier transformId ) { m_SelectedTransform = transformId; switch( m_SelectedTransform ) { case translationTransform: { typedef itk::TranslationTransform<double,ImageDimension> TransformType; TransformType::Pointer transform = TransformType::New(); transform->SetIdentity(); m_ImageRegistrationMethod->SetTransform( transform ); m_ImageRegistrationMethod->SetInitialTransformParameters( transform->GetParameters() ); break; } case scaleTransform: { typedef itk::ScaleTransform<double,ImageDimension> TransformType; TransformType::Pointer transform = TransformType::New(); transform->SetIdentity(); m_ImageRegistrationMethod->SetTransform( transform ); m_ImageRegistrationMethod->SetInitialTransformParameters( transform->GetParameters() ); break; } case affineTransform: { typedef itk::AffineTransform<double,ImageDimension> TransformType; TransformType::Pointer transform = TransformType::New(); transform->SetIdentity(); m_ImageRegistrationMethod->SetTransform( transform ); m_ImageRegistrationMethod->SetInitialTransformParameters( transform->GetParameters() ); break; } case rigidTransform: { typedef itk::Rigid3DTransform<double> TransformType; TransformType::Pointer transform = TransformType::New(); transform->SetIdentity(); m_ImageRegistrationMethod->SetTransform( transform ); m_ImageRegistrationMethod->SetInitialTransformParameters( transform->GetParameters() ); break; } default: fl_alert("Unkown type of optimizer was selected"); return; } } <commit_msg>ENH: Built-In IO Factories are no longer required to call RegisterOneFactory()<commit_after>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: liImageRegistrationConsoleBase.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 2002 Insight Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include <liImageRegistrationConsoleBase.h> #include <FL/fl_ask.H> #include <itkRawImageIO.h> /************************************ * * Constructor * ***********************************/ liImageRegistrationConsoleBase ::liImageRegistrationConsoleBase() { m_FixedImageReader = FixedImageReaderType::New(); m_MovingImageReader = MovingImageReaderType::New(); m_MovingImageWriter = MovingImageWriterType::New(); m_ResampleInputMovingImageFilter = ResampleFilterType::New(); m_ResampleInputMovingImageFilter->SetInput( m_MovingImageReader->GetOutput() ); m_ResampleMovingImageFilter = ResampleFilterType::New(); m_ResampleMovingImageFilter->SetInput( m_MovingImageReader->GetOutput() ); m_InputTransform = AffineTransformType::New(); m_ResampleInputMovingImageFilter->SetTransform( m_InputTransform ); m_ImageRegistrationMethod = ImageRegistrationMethodType::New(); m_ImageRegistrationMethod->SetFixedImage( m_FixedImageReader->GetOutput() ); m_ImageRegistrationMethod->SetMovingImage( m_ResampleInputMovingImageFilter->GetOutput() ); m_MovingImageWriter->SetInput( m_ResampleInputMovingImageFilter->GetOutput() ); itk::RawImageIOFactory< MovingImageType::PixelType, MovingImageType::ImageDimension >::RegisterOneFactory(); m_FixedImageIsLoaded = false; m_MovingImageIsLoaded = false; this->SelectMetric( meanSquares ); this->SelectTransform( translationTransform ); this->SelectOptimizer( regularStepGradientDescent ); this->SelectInterpolator( nearestNeighborInterpolator ); } /************************************ * * Destructor * ***********************************/ liImageRegistrationConsoleBase ::~liImageRegistrationConsoleBase() { } /************************************ * * Load Fixed Image * ***********************************/ void liImageRegistrationConsoleBase ::LoadFixedImage( const char * filename ) { if( !filename ) { return; } m_FixedImageReader->SetFileName( filename ); m_FixedImageReader->Update(); m_FixedImageIsLoaded = true; } /************************************ * * Load Moving Image * ***********************************/ void liImageRegistrationConsoleBase ::LoadMovingImage( const char * filename ) { if( !filename ) { return; } m_MovingImageReader->SetFileName( filename ); m_MovingImageReader->Update(); m_MovingImageIsLoaded = true; } /************************************ * * Save Moving Image * ***********************************/ void liImageRegistrationConsoleBase ::SaveMovingImage( const char * filename ) { if( !filename ) { return; } /* std::ofstream ofs( filename ); MovingImageType * movingImage = m_ResampleInputMovingImageFilter->GetOutput().GetPointer(); ofs.write( (char*)movingImage->GetBufferPointer(), movingImage->GetBufferedRegion().GetNumberOfPixels() * sizeof( MovingImageType::PixelType ) ); ofs.close(); std::cout << "Image was writen to : " << filename << std::endl; */ m_MovingImageWriter->SetFileName( filename ); m_MovingImageWriter->Write(); } /************************************ * * Show Status * ***********************************/ void liImageRegistrationConsoleBase ::ShowStatus( const char * ) { } /************************************ * * Generate reference image * ***********************************/ void liImageRegistrationConsoleBase ::GenerateMovingImage( void ) { if( !m_MovingImageIsLoaded ) { return; } this->ShowStatus("Transforming the original image..."); m_ResampleInputMovingImageFilter->SetOutputSpacing( m_MovingImageReader->GetOutput()->GetSpacing() ); m_ResampleInputMovingImageFilter->SetOutputOrigin( m_MovingImageReader->GetOutput()->GetOrigin() ); m_ResampleInputMovingImageFilter->SetSize( m_MovingImageReader->GetOutput()->GetLargestPossibleRegion().GetSize() ); m_ResampleInputMovingImageFilter->Update(); this->ShowStatus("FixedImage Image Transformation done"); } /************************************ * * Stop Registration * ***********************************/ void liImageRegistrationConsoleBase ::Stop( void ) { // TODO: add a Stop() method to Optimizers //m_ImageRegistrationMethod->GetOptimizer()->Stop(); } /************************************ * * Execute * ***********************************/ void liImageRegistrationConsoleBase ::Execute( void ) { m_ImageRegistrationMethod->StartRegistration(); } /************************************ * * Generate Mapped MovingImage image * ***********************************/ void liImageRegistrationConsoleBase ::GenerateMappedMovingImage( void ) { if( !m_MovingImageIsLoaded ) { return; } this->ShowStatus("Transforming the reference image..."); m_ResampleMovingImageFilter->Update(); this->ShowStatus("MovingImage Image Transformation done"); } /************************************ * * Update the parameters of the * Transform * ***********************************/ void liImageRegistrationConsoleBase ::UpdateTransformParameters( void ) { } /************************************ * * Select the metric to be used to * compare the images during the * registration process * ***********************************/ void liImageRegistrationConsoleBase ::SelectMetric( MetricIdentifier metricId ) { m_SelectedMetric = metricId; switch( m_SelectedMetric ) { case mutualInformation: { m_ImageRegistrationMethod->SetMetric( MutualInformationMetricType::New() ); break; } case normalizedCorrelation: { m_ImageRegistrationMethod->SetMetric( NormalizedCorrelationImageMetricType::New() ); break; } case patternIntensity: { m_ImageRegistrationMethod->SetMetric( PatternIntensityImageMetricType::New() ); break; } case meanSquares: { m_ImageRegistrationMethod->SetMetric( MeanSquaresMetricType::New() ); break; } default: fl_alert("Unkown type of metric was selected"); return; } } /***************************************** * * Select the optimizer to be used * to explore the transform parameter * space and optimize the metric * ****************************************/ void liImageRegistrationConsoleBase ::SelectOptimizer( OptimizerIdentifier optimizerId ) { m_SelectedOptimizer = optimizerId; switch( m_SelectedOptimizer ) { case gradientDescent: { m_ImageRegistrationMethod->SetOptimizer( itk::GradientDescentOptimizer::New() ); break; } case regularStepGradientDescent: { m_ImageRegistrationMethod->SetOptimizer( itk::RegularStepGradientDescentOptimizer::New() ); break; } case conjugateGradient: { m_ImageRegistrationMethod->SetOptimizer( itk::ConjugateGradientOptimizer::New() ); break; } default: fl_alert("Unkown type of optimizer was selected"); return; } } /***************************************** * * Select the interpolator to be used * to evaluate images at non-grid positions * ****************************************/ void liImageRegistrationConsoleBase ::SelectInterpolator( InterpolatorIdentifier interpolatorId ) { m_SelectedInterpolator = interpolatorId; switch( m_SelectedInterpolator ) { case linearInterpolator: { m_ImageRegistrationMethod->SetInterpolator( itk::LinearInterpolateImageFunction<MovingImageType, double >::New() ); break; } case nearestNeighborInterpolator: { m_ImageRegistrationMethod->SetInterpolator( itk::NearestNeighborInterpolateImageFunction<MovingImageType, double >::New() ); break; } default: fl_alert("Unkown type of optimizer was selected"); return; } } /***************************************** * * Select the Transform to be used * to map the moving image into the * fixed image * ****************************************/ void liImageRegistrationConsoleBase ::SelectTransform( TransformIdentifier transformId ) { m_SelectedTransform = transformId; switch( m_SelectedTransform ) { case translationTransform: { typedef itk::TranslationTransform<double,ImageDimension> TransformType; TransformType::Pointer transform = TransformType::New(); transform->SetIdentity(); m_ImageRegistrationMethod->SetTransform( transform ); m_ImageRegistrationMethod->SetInitialTransformParameters( transform->GetParameters() ); break; } case scaleTransform: { typedef itk::ScaleTransform<double,ImageDimension> TransformType; TransformType::Pointer transform = TransformType::New(); transform->SetIdentity(); m_ImageRegistrationMethod->SetTransform( transform ); m_ImageRegistrationMethod->SetInitialTransformParameters( transform->GetParameters() ); break; } case affineTransform: { typedef itk::AffineTransform<double,ImageDimension> TransformType; TransformType::Pointer transform = TransformType::New(); transform->SetIdentity(); m_ImageRegistrationMethod->SetTransform( transform ); m_ImageRegistrationMethod->SetInitialTransformParameters( transform->GetParameters() ); break; } case rigidTransform: { typedef itk::Rigid3DTransform<double> TransformType; TransformType::Pointer transform = TransformType::New(); transform->SetIdentity(); m_ImageRegistrationMethod->SetTransform( transform ); m_ImageRegistrationMethod->SetInitialTransformParameters( transform->GetParameters() ); break; } default: fl_alert("Unkown type of optimizer was selected"); return; } } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: datasourceui.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: ihi $ $Date: 2007-11-28 12:42:44 $ * * 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 "datasourceui.hxx" #include "dsmeta.hxx" #include "dsitems.hxx" /** === begin UNO includes === **/ /** === end UNO includes === **/ //........................................................................ namespace dbaui { //........................................................................ /** === begin UNO using === **/ using ::com::sun::star::uno::Reference; using ::com::sun::star::uno::UNO_QUERY; using ::com::sun::star::uno::UNO_QUERY_THROW; using ::com::sun::star::uno::Exception; using ::com::sun::star::uno::RuntimeException; /** === end UNO using === **/ //==================================================================== //= DataSourceUI //==================================================================== //-------------------------------------------------------------------- DataSourceUI::DataSourceUI( DATASOURCE_TYPE _eType ) :m_aDSMeta( DataSourceMetaData( _eType ) ) { } //-------------------------------------------------------------------- DataSourceUI::DataSourceUI( const DataSourceMetaData& _rDSMeta ) :m_aDSMeta( _rDSMeta ) { } //-------------------------------------------------------------------- DataSourceUI::~DataSourceUI() { } //-------------------------------------------------------------------- bool DataSourceUI::hasSetting( const USHORT _nItemId ) const { const AdvancedSettingsSupport& rAdvancedSupport( m_aDSMeta.getAdvancedSettingsSupport() ); switch ( _nItemId ) { case DSID_SQL92CHECK: return rAdvancedSupport.bUseSQL92NamingConstraints; case DSID_APPEND_TABLE_ALIAS: return rAdvancedSupport.bAppendTableAliasInSelect; case DSID_AS_BEFORE_CORRNAME: return rAdvancedSupport.bUseKeywordAsBeforeAlias; case DSID_ENABLEOUTERJOIN: return rAdvancedSupport.bUseBracketedOuterJoinSyntax; case DSID_IGNOREDRIVER_PRIV: return rAdvancedSupport.bIgnoreDriverPrivileges; case DSID_PARAMETERNAMESUBST: return rAdvancedSupport.bParameterNameSubstitution; case DSID_SUPPRESSVERSIONCL: return rAdvancedSupport.bDisplayVersionColumns; case DSID_CATALOG: return rAdvancedSupport.bUseCatalogInSelect; case DSID_SCHEMA: return rAdvancedSupport.bUseSchemaInSelect; case DSID_INDEXAPPENDIX: return rAdvancedSupport.bUseIndexDirectionKeyword; case DSID_DOSLINEENDS: return rAdvancedSupport.bUseDOSLineEnds; case DSID_BOOLEANCOMPARISON: return rAdvancedSupport.bBooleanComparisonMode; case DSID_CHECK_REQUIRED_FIELDS:return rAdvancedSupport.bFormsCheckRequiredFields; case DSID_AUTORETRIEVEENABLED: return rAdvancedSupport.bGeneratedValues; case DSID_AUTOINCREMENTVALUE: return rAdvancedSupport.bGeneratedValues; case DSID_AUTORETRIEVEVALUE: return rAdvancedSupport.bGeneratedValues; case DSID_IGNORECURRENCY: return rAdvancedSupport.bIgnoreCurrency; } OSL_ENSURE( false, "DataSourceUI::hasSetting: this item id is currently not supported!" ); // Support for *all* items is a medium-term goal only. return false; } //........................................................................ } // namespace dbaui //........................................................................ <commit_msg>INTEGRATION: CWS changefileheader (1.4.84); FILE MERGED 2008/03/31 13:27:15 rt 1.4.84.1: #i87441# Change license header to LPGL v3.<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: datasourceui.cxx,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. * ************************************************************************/ #include "datasourceui.hxx" #include "dsmeta.hxx" #include "dsitems.hxx" /** === begin UNO includes === **/ /** === end UNO includes === **/ //........................................................................ namespace dbaui { //........................................................................ /** === begin UNO using === **/ using ::com::sun::star::uno::Reference; using ::com::sun::star::uno::UNO_QUERY; using ::com::sun::star::uno::UNO_QUERY_THROW; using ::com::sun::star::uno::Exception; using ::com::sun::star::uno::RuntimeException; /** === end UNO using === **/ //==================================================================== //= DataSourceUI //==================================================================== //-------------------------------------------------------------------- DataSourceUI::DataSourceUI( DATASOURCE_TYPE _eType ) :m_aDSMeta( DataSourceMetaData( _eType ) ) { } //-------------------------------------------------------------------- DataSourceUI::DataSourceUI( const DataSourceMetaData& _rDSMeta ) :m_aDSMeta( _rDSMeta ) { } //-------------------------------------------------------------------- DataSourceUI::~DataSourceUI() { } //-------------------------------------------------------------------- bool DataSourceUI::hasSetting( const USHORT _nItemId ) const { const AdvancedSettingsSupport& rAdvancedSupport( m_aDSMeta.getAdvancedSettingsSupport() ); switch ( _nItemId ) { case DSID_SQL92CHECK: return rAdvancedSupport.bUseSQL92NamingConstraints; case DSID_APPEND_TABLE_ALIAS: return rAdvancedSupport.bAppendTableAliasInSelect; case DSID_AS_BEFORE_CORRNAME: return rAdvancedSupport.bUseKeywordAsBeforeAlias; case DSID_ENABLEOUTERJOIN: return rAdvancedSupport.bUseBracketedOuterJoinSyntax; case DSID_IGNOREDRIVER_PRIV: return rAdvancedSupport.bIgnoreDriverPrivileges; case DSID_PARAMETERNAMESUBST: return rAdvancedSupport.bParameterNameSubstitution; case DSID_SUPPRESSVERSIONCL: return rAdvancedSupport.bDisplayVersionColumns; case DSID_CATALOG: return rAdvancedSupport.bUseCatalogInSelect; case DSID_SCHEMA: return rAdvancedSupport.bUseSchemaInSelect; case DSID_INDEXAPPENDIX: return rAdvancedSupport.bUseIndexDirectionKeyword; case DSID_DOSLINEENDS: return rAdvancedSupport.bUseDOSLineEnds; case DSID_BOOLEANCOMPARISON: return rAdvancedSupport.bBooleanComparisonMode; case DSID_CHECK_REQUIRED_FIELDS:return rAdvancedSupport.bFormsCheckRequiredFields; case DSID_AUTORETRIEVEENABLED: return rAdvancedSupport.bGeneratedValues; case DSID_AUTOINCREMENTVALUE: return rAdvancedSupport.bGeneratedValues; case DSID_AUTORETRIEVEVALUE: return rAdvancedSupport.bGeneratedValues; case DSID_IGNORECURRENCY: return rAdvancedSupport.bIgnoreCurrency; } OSL_ENSURE( false, "DataSourceUI::hasSetting: this item id is currently not supported!" ); // Support for *all* items is a medium-term goal only. return false; } //........................................................................ } // namespace dbaui //........................................................................ <|endoftext|>
<commit_before>// Copyright (c) 2012 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 "content/renderer/gpu/compositor_output_surface.h" #include "base/command_line.h" #include "base/message_loop/message_loop_proxy.h" #include "cc/output/compositor_frame.h" #include "cc/output/compositor_frame_ack.h" #include "cc/output/output_surface_client.h" #include "content/common/gpu/client/command_buffer_proxy_impl.h" #include "content/common/gpu/client/webgraphicscontext3d_command_buffer_impl.h" #include "content/common/view_messages.h" #include "content/public/common/content_switches.h" #include "content/renderer/render_thread_impl.h" #include "ipc/ipc_forwarding_message_filter.h" #include "ipc/ipc_sync_channel.h" #include "third_party/WebKit/public/platform/WebGraphicsContext3D.h" using WebKit::WebGraphicsContext3D; namespace { // There are several compositor surfaces in a process, but they share the same // compositor thread, so we use a simple int here to track prefer-smoothness. int g_prefer_smoothness_count = 0; } // namespace namespace content { //------------------------------------------------------------------------------ // static IPC::ForwardingMessageFilter* CompositorOutputSurface::CreateFilter( base::TaskRunner* target_task_runner) { uint32 messages_to_filter[] = { ViewMsg_UpdateVSyncParameters::ID, ViewMsg_SwapCompositorFrameAck::ID, #if defined(OS_ANDROID) ViewMsg_BeginFrame::ID #endif }; return new IPC::ForwardingMessageFilter( messages_to_filter, arraysize(messages_to_filter), target_task_runner); } CompositorOutputSurface::CompositorOutputSurface( int32 routing_id, WebGraphicsContext3DCommandBufferImpl* context3D, cc::SoftwareOutputDevice* software_device, bool use_swap_compositor_frame_message) : OutputSurface(scoped_ptr<WebKit::WebGraphicsContext3D>(context3D), make_scoped_ptr(software_device)), use_swap_compositor_frame_message_(use_swap_compositor_frame_message), output_surface_filter_( RenderThreadImpl::current()->compositor_output_surface_filter()), routing_id_(routing_id), prefers_smoothness_(false), main_thread_handle_(base::PlatformThread::CurrentHandle()) { DCHECK(output_surface_filter_.get()); DetachFromThread(); message_sender_ = RenderThreadImpl::current()->sync_message_filter(); DCHECK(message_sender_.get()); } CompositorOutputSurface::~CompositorOutputSurface() { DCHECK(CalledOnValidThread()); SetNeedsBeginFrame(false); if (!HasClient()) return; UpdateSmoothnessTakesPriority(false); if (output_surface_proxy_.get()) output_surface_proxy_->ClearOutputSurface(); output_surface_filter_->RemoveRoute(routing_id_); } bool CompositorOutputSurface::BindToClient( cc::OutputSurfaceClient* client) { DCHECK(CalledOnValidThread()); if (!cc::OutputSurface::BindToClient(client)) return false; output_surface_proxy_ = new CompositorOutputSurfaceProxy(this); output_surface_filter_->AddRoute( routing_id_, base::Bind(&CompositorOutputSurfaceProxy::OnMessageReceived, output_surface_proxy_)); return true; } void CompositorOutputSurface::SwapBuffers(cc::CompositorFrame* frame) { if (use_swap_compositor_frame_message_) { Send(new ViewHostMsg_SwapCompositorFrame(routing_id_, *frame)); DidSwapBuffers(); return; } if (frame->gl_frame_data) { WebGraphicsContext3DCommandBufferImpl* command_buffer = static_cast<WebGraphicsContext3DCommandBufferImpl*>(context3d()); CommandBufferProxyImpl* command_buffer_proxy = command_buffer->GetCommandBufferProxy(); DCHECK(command_buffer_proxy); context3d()->shallowFlushCHROMIUM(); command_buffer_proxy->SetLatencyInfo(frame->metadata.latency_info); } OutputSurface::SwapBuffers(frame); } void CompositorOutputSurface::OnMessageReceived(const IPC::Message& message) { DCHECK(CalledOnValidThread()); if (!HasClient()) return; IPC_BEGIN_MESSAGE_MAP(CompositorOutputSurface, message) IPC_MESSAGE_HANDLER(ViewMsg_UpdateVSyncParameters, OnUpdateVSyncParameters); IPC_MESSAGE_HANDLER(ViewMsg_SwapCompositorFrameAck, OnSwapAck); #if defined(OS_ANDROID) IPC_MESSAGE_HANDLER(ViewMsg_BeginFrame, OnBeginFrame); #endif IPC_END_MESSAGE_MAP() } void CompositorOutputSurface::OnUpdateVSyncParameters( base::TimeTicks timebase, base::TimeDelta interval) { DCHECK(CalledOnValidThread()); OnVSyncParametersChanged(timebase, interval); } #if defined(OS_ANDROID) void CompositorOutputSurface::SetNeedsBeginFrame(bool enable) { DCHECK(CalledOnValidThread()); if (needs_begin_frame_ != enable) Send(new ViewHostMsg_SetNeedsBeginFrame(routing_id_, enable)); OutputSurface::SetNeedsBeginFrame(enable); } void CompositorOutputSurface::OnBeginFrame(const cc::BeginFrameArgs& args) { DCHECK(CalledOnValidThread()); BeginFrame(args); } #endif // defined(OS_ANDROID) void CompositorOutputSurface::OnSwapAck(const cc::CompositorFrameAck& ack) { OnSwapBuffersComplete(&ack); } bool CompositorOutputSurface::Send(IPC::Message* message) { return message_sender_->Send(message); } namespace { #if defined(OS_ANDROID) void SetThreadPriorityToIdle(base::PlatformThreadHandle handle) { base::PlatformThread::SetThreadPriority( handle, base::kThreadPriority_Background); } void SetThreadPriorityToDefault(base::PlatformThreadHandle handle) { base::PlatformThread::SetThreadPriority( handle, base::kThreadPriority_Normal); } #else void SetThreadPriorityToIdle(base::PlatformThreadHandle handle) {} void SetThreadPriorityToDefault(base::PlatformThreadHandle handle) {} #endif } void CompositorOutputSurface::UpdateSmoothnessTakesPriority( bool prefers_smoothness) { #ifndef NDEBUG // If we use different compositor threads, we need to // use an atomic int to track prefer smoothness count. base::PlatformThreadId g_last_thread = base::PlatformThread::CurrentId(); DCHECK_EQ(g_last_thread, base::PlatformThread::CurrentId()); #endif if (prefers_smoothness_ == prefers_smoothness) return; // If this is the first surface to start preferring smoothness, // Throttle the main thread's priority. if (prefers_smoothness_ == false && ++g_prefer_smoothness_count == 1) { SetThreadPriorityToIdle(main_thread_handle_); } // If this is the last surface to stop preferring smoothness, // Reset the main thread's priority to the default. if (prefers_smoothness_ == true && --g_prefer_smoothness_count == 0) { SetThreadPriorityToDefault(main_thread_handle_); } prefers_smoothness_ = prefers_smoothness; } } // namespace content <commit_msg>Do not call PlatformThread::CurrentHandle on windows<commit_after>// Copyright (c) 2012 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 "content/renderer/gpu/compositor_output_surface.h" #include "base/command_line.h" #include "base/message_loop/message_loop_proxy.h" #include "cc/output/compositor_frame.h" #include "cc/output/compositor_frame_ack.h" #include "cc/output/output_surface_client.h" #include "content/common/gpu/client/command_buffer_proxy_impl.h" #include "content/common/gpu/client/webgraphicscontext3d_command_buffer_impl.h" #include "content/common/view_messages.h" #include "content/public/common/content_switches.h" #include "content/renderer/render_thread_impl.h" #include "ipc/ipc_forwarding_message_filter.h" #include "ipc/ipc_sync_channel.h" #include "third_party/WebKit/public/platform/WebGraphicsContext3D.h" using WebKit::WebGraphicsContext3D; namespace { // There are several compositor surfaces in a process, but they share the same // compositor thread, so we use a simple int here to track prefer-smoothness. int g_prefer_smoothness_count = 0; } // namespace namespace content { //------------------------------------------------------------------------------ // static IPC::ForwardingMessageFilter* CompositorOutputSurface::CreateFilter( base::TaskRunner* target_task_runner) { uint32 messages_to_filter[] = { ViewMsg_UpdateVSyncParameters::ID, ViewMsg_SwapCompositorFrameAck::ID, #if defined(OS_ANDROID) ViewMsg_BeginFrame::ID #endif }; return new IPC::ForwardingMessageFilter( messages_to_filter, arraysize(messages_to_filter), target_task_runner); } CompositorOutputSurface::CompositorOutputSurface( int32 routing_id, WebGraphicsContext3DCommandBufferImpl* context3D, cc::SoftwareOutputDevice* software_device, bool use_swap_compositor_frame_message) : OutputSurface(scoped_ptr<WebKit::WebGraphicsContext3D>(context3D), make_scoped_ptr(software_device)), use_swap_compositor_frame_message_(use_swap_compositor_frame_message), output_surface_filter_( RenderThreadImpl::current()->compositor_output_surface_filter()), routing_id_(routing_id), prefers_smoothness_(false), #if defined(OS_WIN) // TODO(epenner): Implement PlatformThread::CurrentHandle() on windows. main_thread_handle_(base::PlatformThreadHandle()) #else main_thread_handle_(base::PlatformThread::CurrentHandle()) #endif { DCHECK(output_surface_filter_.get()); DetachFromThread(); message_sender_ = RenderThreadImpl::current()->sync_message_filter(); DCHECK(message_sender_.get()); } CompositorOutputSurface::~CompositorOutputSurface() { DCHECK(CalledOnValidThread()); SetNeedsBeginFrame(false); if (!HasClient()) return; UpdateSmoothnessTakesPriority(false); if (output_surface_proxy_.get()) output_surface_proxy_->ClearOutputSurface(); output_surface_filter_->RemoveRoute(routing_id_); } bool CompositorOutputSurface::BindToClient( cc::OutputSurfaceClient* client) { DCHECK(CalledOnValidThread()); if (!cc::OutputSurface::BindToClient(client)) return false; output_surface_proxy_ = new CompositorOutputSurfaceProxy(this); output_surface_filter_->AddRoute( routing_id_, base::Bind(&CompositorOutputSurfaceProxy::OnMessageReceived, output_surface_proxy_)); return true; } void CompositorOutputSurface::SwapBuffers(cc::CompositorFrame* frame) { if (use_swap_compositor_frame_message_) { Send(new ViewHostMsg_SwapCompositorFrame(routing_id_, *frame)); DidSwapBuffers(); return; } if (frame->gl_frame_data) { WebGraphicsContext3DCommandBufferImpl* command_buffer = static_cast<WebGraphicsContext3DCommandBufferImpl*>(context3d()); CommandBufferProxyImpl* command_buffer_proxy = command_buffer->GetCommandBufferProxy(); DCHECK(command_buffer_proxy); context3d()->shallowFlushCHROMIUM(); command_buffer_proxy->SetLatencyInfo(frame->metadata.latency_info); } OutputSurface::SwapBuffers(frame); } void CompositorOutputSurface::OnMessageReceived(const IPC::Message& message) { DCHECK(CalledOnValidThread()); if (!HasClient()) return; IPC_BEGIN_MESSAGE_MAP(CompositorOutputSurface, message) IPC_MESSAGE_HANDLER(ViewMsg_UpdateVSyncParameters, OnUpdateVSyncParameters); IPC_MESSAGE_HANDLER(ViewMsg_SwapCompositorFrameAck, OnSwapAck); #if defined(OS_ANDROID) IPC_MESSAGE_HANDLER(ViewMsg_BeginFrame, OnBeginFrame); #endif IPC_END_MESSAGE_MAP() } void CompositorOutputSurface::OnUpdateVSyncParameters( base::TimeTicks timebase, base::TimeDelta interval) { DCHECK(CalledOnValidThread()); OnVSyncParametersChanged(timebase, interval); } #if defined(OS_ANDROID) void CompositorOutputSurface::SetNeedsBeginFrame(bool enable) { DCHECK(CalledOnValidThread()); if (needs_begin_frame_ != enable) Send(new ViewHostMsg_SetNeedsBeginFrame(routing_id_, enable)); OutputSurface::SetNeedsBeginFrame(enable); } void CompositorOutputSurface::OnBeginFrame(const cc::BeginFrameArgs& args) { DCHECK(CalledOnValidThread()); BeginFrame(args); } #endif // defined(OS_ANDROID) void CompositorOutputSurface::OnSwapAck(const cc::CompositorFrameAck& ack) { OnSwapBuffersComplete(&ack); } bool CompositorOutputSurface::Send(IPC::Message* message) { return message_sender_->Send(message); } namespace { #if defined(OS_ANDROID) void SetThreadPriorityToIdle(base::PlatformThreadHandle handle) { base::PlatformThread::SetThreadPriority( handle, base::kThreadPriority_Background); } void SetThreadPriorityToDefault(base::PlatformThreadHandle handle) { base::PlatformThread::SetThreadPriority( handle, base::kThreadPriority_Normal); } #else void SetThreadPriorityToIdle(base::PlatformThreadHandle handle) {} void SetThreadPriorityToDefault(base::PlatformThreadHandle handle) {} #endif } void CompositorOutputSurface::UpdateSmoothnessTakesPriority( bool prefers_smoothness) { #ifndef NDEBUG // If we use different compositor threads, we need to // use an atomic int to track prefer smoothness count. base::PlatformThreadId g_last_thread = base::PlatformThread::CurrentId(); DCHECK_EQ(g_last_thread, base::PlatformThread::CurrentId()); #endif if (prefers_smoothness_ == prefers_smoothness) return; // If this is the first surface to start preferring smoothness, // Throttle the main thread's priority. if (prefers_smoothness_ == false && ++g_prefer_smoothness_count == 1) { SetThreadPriorityToIdle(main_thread_handle_); } // If this is the last surface to stop preferring smoothness, // Reset the main thread's priority to the default. if (prefers_smoothness_ == true && --g_prefer_smoothness_count == 0) { SetThreadPriorityToDefault(main_thread_handle_); } prefers_smoothness_ = prefers_smoothness; } } // namespace content <|endoftext|>
<commit_before>/*------------------------------------------------------------------------------ Copyright (c) 2004 Media Development Loan Fund This file is part of the LiveSupport project. http://livesupport.campware.org/ To report bugs, send an e-mail to bugs@campware.org LiveSupport 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. LiveSupport 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 LiveSupport; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Author : $Author: maroy $ Version : $Revision: 1.12 $ Location : $Source: /home/paul/cvs2svn-livesupport/newcvsrepo/livesupport/modules/playlistExecutor/src/GstreamerPlayer.cxx,v $ ------------------------------------------------------------------------------*/ /* ============================================================ include files */ #ifdef HAVE_CONFIG_H #include "configure.h" #endif #include "LiveSupport/Core/TimeConversion.h" #include "LiveSupport/GstreamerElements/autoplug.h" #include "GstreamerPlayer.h" using namespace boost::posix_time; using namespace LiveSupport::Core; using namespace LiveSupport::PlaylistExecutor; /* =================================================== local data structures */ /* ================================================ local constants & macros */ /** * The name of the config element for this class */ const std::string GstreamerPlayer::configElementNameStr = "gstreamerPlayer"; /** * The name of the audio device attribute. */ static const std::string audioDeviceName = "audioDevice"; /* =============================================== local function prototypes */ /* ============================================================= module code */ /*------------------------------------------------------------------------------ * Configure the Audio Player. *----------------------------------------------------------------------------*/ void GstreamerPlayer :: configure(const xmlpp::Element & element) throw (std::invalid_argument, std::logic_error) { if (element.get_name() != configElementNameStr) { std::string eMsg = "Bad configuration element "; eMsg += element.get_name(); throw std::invalid_argument(eMsg); } const xmlpp::Attribute * attribute; if ((attribute = element.get_attribute(audioDeviceName))) { audioDevice = attribute->get_value(); } } /*------------------------------------------------------------------------------ * Initialize the Audio Player *----------------------------------------------------------------------------*/ void GstreamerPlayer :: initialize(void) throw (std::exception) { if (initialized) { return; } // initialize the gstreamer library if (!gst_init_check(0, 0)) { throw std::runtime_error("couldn't initialize the gstreamer library"); } // initialize the pipeline pipeline = gst_thread_new("audio-player"); // take ownership of the pipeline object gst_object_ref(GST_OBJECT(pipeline)); gst_object_sink(GST_OBJECT(pipeline)); g_signal_connect(pipeline, "error", G_CALLBACK(errorHandler), this); // TODO: read the caps from the config file sinkCaps = gst_caps_new_simple("audio/x-raw-int", "width", G_TYPE_INT, 16, "depth", G_TYPE_INT, 16, "endiannes", G_TYPE_INT, G_BYTE_ORDER, "channels", G_TYPE_INT, 2, "rate", G_TYPE_INT, 44100, NULL); setAudioDevice(audioDevice); // set up other variables initialized = true; } /*------------------------------------------------------------------------------ * Handler for gstreamer errors. *----------------------------------------------------------------------------*/ void GstreamerPlayer :: errorHandler(GstElement * pipeline, GstElement * source, GError * error, gchar * debug, gpointer self) throw () { // TODO: handle error std::cerr << "gstreamer error: " << error->message << std::endl; } /*------------------------------------------------------------------------------ * De-initialize the Gstreamer Player *----------------------------------------------------------------------------*/ void GstreamerPlayer :: deInitialize(void) throw () { if (initialized) { gst_element_set_state(pipeline, GST_STATE_NULL); gst_bin_sync_children_state(GST_BIN(pipeline)); if (!gst_element_get_parent(audiosink)) { // delete manually, if audiosink wasn't added to the pipeline // for some reason gst_object_unref(GST_OBJECT(audiosink)); } gst_object_unref(GST_OBJECT(pipeline)); gst_caps_free(sinkCaps); audiosink = 0; initialized = false; } } /*------------------------------------------------------------------------------ * Attach an event listener. *----------------------------------------------------------------------------*/ void GstreamerPlayer :: attachListener(AudioPlayerEventListener* eventListener) throw () { listeners.push_back(eventListener); } /*------------------------------------------------------------------------------ * Detach an event listener. *----------------------------------------------------------------------------*/ void GstreamerPlayer :: detachListener(AudioPlayerEventListener* eventListener) throw (std::invalid_argument) { ListenerVector::iterator it = listeners.begin(); ListenerVector::iterator end = listeners.end(); while (it != end) { if (*it == eventListener) { listeners.erase(it); return; } ++it; } throw std::invalid_argument("supplied event listener not found"); } /*------------------------------------------------------------------------------ * Send the onStop event to all attached listeners. *----------------------------------------------------------------------------*/ void GstreamerPlayer :: fireOnStopEvent(void) throw () { ListenerVector::iterator it = listeners.begin(); ListenerVector::iterator end = listeners.end(); while (it != end) { (*it)->onStop(); ++it; } } /*------------------------------------------------------------------------------ * An EOS event handler, that will put the pipeline to EOS as well. *----------------------------------------------------------------------------*/ void GstreamerPlayer :: eosEventHandler(GstElement * element, gpointer self) throw () { GstreamerPlayer * player = (GstreamerPlayer*) self; gst_element_set_eos(player->pipeline); player->fireOnStopEvent(); } /*------------------------------------------------------------------------------ * Specify which file to play *----------------------------------------------------------------------------*/ void GstreamerPlayer :: open(const std::string fileUrl) throw (std::invalid_argument) { std::string filePath; GstElement * pipe; GstElement * fakesink; gint64 position; if (isOpen()) { close(); } if (fileUrl.find("file:") == 0) { filePath = fileUrl.substr(5, fileUrl.size()); } else if (fileUrl.find("file://") == 0) { filePath = fileUrl.substr(7, fileUrl.size()); } else { throw std::invalid_argument("badly formed URL or unsupported protocol"); } g_object_ref(G_OBJECT(audiosink)); gst_bin_remove(GST_BIN(pipeline), audiosink); filesrc = gst_element_factory_make("filesrc", "file-source"); g_object_set(G_OBJECT(filesrc), "location", filePath.c_str(), NULL); decoder = ls_gst_autoplug_plug_source(filesrc, "decoder", sinkCaps); if (!decoder) { throw std::invalid_argument(std::string("can't open URL ") + fileUrl); } // connect the decoder unto a fakesink, and iterate on it until the // first bytes come out. this is to make sure that _really_ all // initialiation is done at opening pipe = gst_pipeline_new("pipe"); fakesink = gst_element_factory_make("fakesink", "fakesink"); g_object_ref(G_OBJECT(filesrc)); g_object_ref(G_OBJECT(decoder)); gst_element_link_many(decoder, fakesink, NULL); gst_bin_add_many(GST_BIN(pipe), filesrc, decoder, fakesink, NULL); gst_element_set_state(pipe, GST_STATE_PAUSED); gst_element_set_state(pipe, GST_STATE_PLAYING); position = 0LL; // while (position == 0LL && gst_bin_iterate(GST_BIN(pipe))) { while (position == 0LL) { bool ok; try { // std::cerr << "before\n"; ok = gst_bin_iterate(GST_BIN(pipe)); // std::cerr << "after: " << ok << "\n"; } catch (...) { std::cerr << "exception thrown by gst_bin_iterate()\n"; std::exit(1); } if (!ok) { break; } GstFormat format = GST_FORMAT_DEFAULT; gst_element_query(fakesink, GST_QUERY_POSITION, &format, &position); } gst_element_set_state(pipe, GST_STATE_PAUSED); gst_bin_remove_many(GST_BIN(pipe), filesrc, decoder, NULL); gst_element_unlink(decoder, fakesink); gst_object_unref(GST_OBJECT(pipe)); // connect the decoder to the real audio sink gst_element_link(decoder, audiosink); gst_bin_add_many(GST_BIN(pipeline), filesrc, decoder, audiosink, NULL); // connect the eos signal handler g_signal_connect(decoder, "eos", G_CALLBACK(eosEventHandler), this); gst_element_set_state(pipeline, GST_STATE_PAUSED); gst_bin_sync_children_state(GST_BIN(pipeline)); } /*------------------------------------------------------------------------------ * Tell if we've been opened. *----------------------------------------------------------------------------*/ bool GstreamerPlayer :: isOpen(void) throw () { return decoder != 0; } /*------------------------------------------------------------------------------ * Get the length of the current audio clip. *----------------------------------------------------------------------------*/ Ptr<time_duration>::Ref GstreamerPlayer :: getPlaylength(void) throw (std::logic_error) { Ptr<time_duration>::Ref length; gint64 ns; GstFormat format = GST_FORMAT_TIME; if (!isOpen()) { throw std::logic_error("player not open"); } if (decoder && gst_element_query(decoder, GST_QUERY_TOTAL, &format, &ns) && format == GST_FORMAT_TIME) { // use microsec, as nanosec() is not found by the compiler (?) length.reset(new time_duration(microsec(ns / 1000LL))); } else { length.reset(new time_duration(microsec(0LL))); } return length; } /*------------------------------------------------------------------------------ * Get the current position of the current audio clip. *----------------------------------------------------------------------------*/ Ptr<time_duration>::Ref GstreamerPlayer :: getPosition(void) throw (std::logic_error) { Ptr<time_duration>::Ref length; gint64 ns; GstFormat format = GST_FORMAT_TIME; if (!isOpen()) { throw std::logic_error("player not open"); } if (decoder && gst_element_query(decoder, GST_QUERY_POSITION, &format, &ns) && format == GST_FORMAT_TIME) { // use microsec, as nanosec() is not found by the compiler (?) length.reset(new time_duration(microsec(ns / 1000LL))); } else { length.reset(new time_duration(microsec(0LL))); } return length; } /*------------------------------------------------------------------------------ * Start playing *----------------------------------------------------------------------------*/ void GstreamerPlayer :: start(void) throw (std::logic_error) { if (!isOpen()) { throw std::logic_error("GstreamerPlayer not opened yet"); } if (!isPlaying()) { gst_element_set_state(audiosink, GST_STATE_PAUSED); gst_element_set_state(pipeline, GST_STATE_PLAYING); } } /*------------------------------------------------------------------------------ * Pause the player *----------------------------------------------------------------------------*/ void GstreamerPlayer :: pause(void) throw (std::logic_error) { if (isPlaying()) { gst_element_set_state(pipeline, GST_STATE_PAUSED); } } /*------------------------------------------------------------------------------ * Tell if we're playing *----------------------------------------------------------------------------*/ bool GstreamerPlayer :: isPlaying(void) throw () { return gst_element_get_state(pipeline) == GST_STATE_PLAYING; } /*------------------------------------------------------------------------------ * Stop playing *----------------------------------------------------------------------------*/ void GstreamerPlayer :: stop(void) throw (std::logic_error) { if (!isOpen()) { throw std::logic_error("GstreamerPlayer not opened yet"); } if (isPlaying()) { gst_element_set_state(pipeline, GST_STATE_READY); } } /*------------------------------------------------------------------------------ * Close the currently opened audio file. *----------------------------------------------------------------------------*/ void GstreamerPlayer :: close(void) throw () { if (isPlaying()) { stop(); } gst_element_set_state(pipeline, GST_STATE_NULL); gst_element_unlink(filesrc, decoder); gst_element_unlink(decoder, audiosink); gst_bin_remove(GST_BIN(pipeline), decoder); gst_bin_remove(GST_BIN(pipeline), filesrc); filesrc = 0; decoder = 0; } /*------------------------------------------------------------------------------ * Get the volume of the player. *----------------------------------------------------------------------------*/ unsigned int GstreamerPlayer :: getVolume(void) throw () { return 0; } /*------------------------------------------------------------------------------ * Set the volume of the player. *----------------------------------------------------------------------------*/ void GstreamerPlayer :: setVolume(unsigned int volume) throw () { } /*------------------------------------------------------------------------------ * Set the audio device. *----------------------------------------------------------------------------*/ bool GstreamerPlayer :: setAudioDevice(const std::string &deviceName) throw () { bool oss = deviceName.find("/dev") == 0; bool relink = false; if (deviceName.size() == 0) { return false; } if (audiosink) { bool oldOss = g_strrstr(gst_element_get_name(audiosink), "osssink"); relink = oss && !oldOss; } if (relink && audiosink) { if (decoder) { gst_element_unlink(decoder, audiosink); } gst_bin_remove(GST_BIN(pipeline), audiosink); // FIXME: why unref here? remove should unref already g_object_unref(G_OBJECT(audiosink)); audiosink = 0; } if (!audiosink) { audiosink = oss ? gst_element_factory_make("osssink", "osssink") : gst_element_factory_make("alsasink", "alsasink"); relink = true; } if (!audiosink) { return false; } // it's the same property, "device" for both alsasink and osssink g_object_set(G_OBJECT(audiosink), "device", deviceName.c_str(), NULL); if (relink) { if (decoder) { gst_element_link_filtered(decoder, audiosink, sinkCaps); } gst_bin_add(GST_BIN(pipeline), audiosink); } return true; } <commit_msg>added null-checks around calls in close() see http://bugs.campware.org/view.php?id=1444<commit_after>/*------------------------------------------------------------------------------ Copyright (c) 2004 Media Development Loan Fund This file is part of the LiveSupport project. http://livesupport.campware.org/ To report bugs, send an e-mail to bugs@campware.org LiveSupport 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. LiveSupport 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 LiveSupport; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Author : $Author: maroy $ Version : $Revision: 1.13 $ Location : $Source: /home/paul/cvs2svn-livesupport/newcvsrepo/livesupport/modules/playlistExecutor/src/GstreamerPlayer.cxx,v $ ------------------------------------------------------------------------------*/ /* ============================================================ include files */ #ifdef HAVE_CONFIG_H #include "configure.h" #endif #include "LiveSupport/Core/TimeConversion.h" #include "LiveSupport/GstreamerElements/autoplug.h" #include "GstreamerPlayer.h" using namespace boost::posix_time; using namespace LiveSupport::Core; using namespace LiveSupport::PlaylistExecutor; /* =================================================== local data structures */ /* ================================================ local constants & macros */ /** * The name of the config element for this class */ const std::string GstreamerPlayer::configElementNameStr = "gstreamerPlayer"; /** * The name of the audio device attribute. */ static const std::string audioDeviceName = "audioDevice"; /* =============================================== local function prototypes */ /* ============================================================= module code */ /*------------------------------------------------------------------------------ * Configure the Audio Player. *----------------------------------------------------------------------------*/ void GstreamerPlayer :: configure(const xmlpp::Element & element) throw (std::invalid_argument, std::logic_error) { if (element.get_name() != configElementNameStr) { std::string eMsg = "Bad configuration element "; eMsg += element.get_name(); throw std::invalid_argument(eMsg); } const xmlpp::Attribute * attribute; if ((attribute = element.get_attribute(audioDeviceName))) { audioDevice = attribute->get_value(); } } /*------------------------------------------------------------------------------ * Initialize the Audio Player *----------------------------------------------------------------------------*/ void GstreamerPlayer :: initialize(void) throw (std::exception) { if (initialized) { return; } // initialize the gstreamer library if (!gst_init_check(0, 0)) { throw std::runtime_error("couldn't initialize the gstreamer library"); } // initialize the pipeline pipeline = gst_thread_new("audio-player"); // take ownership of the pipeline object gst_object_ref(GST_OBJECT(pipeline)); gst_object_sink(GST_OBJECT(pipeline)); g_signal_connect(pipeline, "error", G_CALLBACK(errorHandler), this); // TODO: read the caps from the config file sinkCaps = gst_caps_new_simple("audio/x-raw-int", "width", G_TYPE_INT, 16, "depth", G_TYPE_INT, 16, "endiannes", G_TYPE_INT, G_BYTE_ORDER, "channels", G_TYPE_INT, 2, "rate", G_TYPE_INT, 44100, NULL); setAudioDevice(audioDevice); // set up other variables initialized = true; } /*------------------------------------------------------------------------------ * Handler for gstreamer errors. *----------------------------------------------------------------------------*/ void GstreamerPlayer :: errorHandler(GstElement * pipeline, GstElement * source, GError * error, gchar * debug, gpointer self) throw () { // TODO: handle error std::cerr << "gstreamer error: " << error->message << std::endl; } /*------------------------------------------------------------------------------ * De-initialize the Gstreamer Player *----------------------------------------------------------------------------*/ void GstreamerPlayer :: deInitialize(void) throw () { if (initialized) { gst_element_set_state(pipeline, GST_STATE_NULL); gst_bin_sync_children_state(GST_BIN(pipeline)); if (!gst_element_get_parent(audiosink)) { // delete manually, if audiosink wasn't added to the pipeline // for some reason gst_object_unref(GST_OBJECT(audiosink)); } gst_object_unref(GST_OBJECT(pipeline)); gst_caps_free(sinkCaps); audiosink = 0; initialized = false; } } /*------------------------------------------------------------------------------ * Attach an event listener. *----------------------------------------------------------------------------*/ void GstreamerPlayer :: attachListener(AudioPlayerEventListener* eventListener) throw () { listeners.push_back(eventListener); } /*------------------------------------------------------------------------------ * Detach an event listener. *----------------------------------------------------------------------------*/ void GstreamerPlayer :: detachListener(AudioPlayerEventListener* eventListener) throw (std::invalid_argument) { ListenerVector::iterator it = listeners.begin(); ListenerVector::iterator end = listeners.end(); while (it != end) { if (*it == eventListener) { listeners.erase(it); return; } ++it; } throw std::invalid_argument("supplied event listener not found"); } /*------------------------------------------------------------------------------ * Send the onStop event to all attached listeners. *----------------------------------------------------------------------------*/ void GstreamerPlayer :: fireOnStopEvent(void) throw () { ListenerVector::iterator it = listeners.begin(); ListenerVector::iterator end = listeners.end(); while (it != end) { (*it)->onStop(); ++it; } } /*------------------------------------------------------------------------------ * An EOS event handler, that will put the pipeline to EOS as well. *----------------------------------------------------------------------------*/ void GstreamerPlayer :: eosEventHandler(GstElement * element, gpointer self) throw () { GstreamerPlayer * player = (GstreamerPlayer*) self; gst_element_set_eos(player->pipeline); player->fireOnStopEvent(); } /*------------------------------------------------------------------------------ * Specify which file to play *----------------------------------------------------------------------------*/ void GstreamerPlayer :: open(const std::string fileUrl) throw (std::invalid_argument) { std::string filePath; GstElement * pipe; GstElement * fakesink; gint64 position; if (isOpen()) { close(); } if (fileUrl.find("file:") == 0) { filePath = fileUrl.substr(5, fileUrl.size()); } else if (fileUrl.find("file://") == 0) { filePath = fileUrl.substr(7, fileUrl.size()); } else { throw std::invalid_argument("badly formed URL or unsupported protocol"); } g_object_ref(G_OBJECT(audiosink)); gst_bin_remove(GST_BIN(pipeline), audiosink); filesrc = gst_element_factory_make("filesrc", "file-source"); g_object_set(G_OBJECT(filesrc), "location", filePath.c_str(), NULL); decoder = ls_gst_autoplug_plug_source(filesrc, "decoder", sinkCaps); if (!decoder) { throw std::invalid_argument(std::string("can't open URL ") + fileUrl); } // connect the decoder unto a fakesink, and iterate on it until the // first bytes come out. this is to make sure that _really_ all // initialiation is done at opening pipe = gst_pipeline_new("pipe"); fakesink = gst_element_factory_make("fakesink", "fakesink"); g_object_ref(G_OBJECT(filesrc)); g_object_ref(G_OBJECT(decoder)); gst_element_link_many(decoder, fakesink, NULL); gst_bin_add_many(GST_BIN(pipe), filesrc, decoder, fakesink, NULL); gst_element_set_state(pipe, GST_STATE_PAUSED); gst_element_set_state(pipe, GST_STATE_PLAYING); position = 0LL; // while (position == 0LL && gst_bin_iterate(GST_BIN(pipe))) { while (position == 0LL) { bool ok; try { // std::cerr << "before\n"; ok = gst_bin_iterate(GST_BIN(pipe)); // std::cerr << "after: " << ok << "\n"; } catch (...) { std::cerr << "exception thrown by gst_bin_iterate()\n"; std::exit(1); } if (!ok) { break; } GstFormat format = GST_FORMAT_DEFAULT; gst_element_query(fakesink, GST_QUERY_POSITION, &format, &position); } gst_element_set_state(pipe, GST_STATE_PAUSED); gst_bin_remove_many(GST_BIN(pipe), filesrc, decoder, NULL); gst_element_unlink(decoder, fakesink); gst_object_unref(GST_OBJECT(pipe)); // connect the decoder to the real audio sink gst_element_link(decoder, audiosink); gst_bin_add_many(GST_BIN(pipeline), filesrc, decoder, audiosink, NULL); // connect the eos signal handler g_signal_connect(decoder, "eos", G_CALLBACK(eosEventHandler), this); gst_element_set_state(pipeline, GST_STATE_PAUSED); gst_bin_sync_children_state(GST_BIN(pipeline)); } /*------------------------------------------------------------------------------ * Tell if we've been opened. *----------------------------------------------------------------------------*/ bool GstreamerPlayer :: isOpen(void) throw () { return decoder != 0; } /*------------------------------------------------------------------------------ * Get the length of the current audio clip. *----------------------------------------------------------------------------*/ Ptr<time_duration>::Ref GstreamerPlayer :: getPlaylength(void) throw (std::logic_error) { Ptr<time_duration>::Ref length; gint64 ns; GstFormat format = GST_FORMAT_TIME; if (!isOpen()) { throw std::logic_error("player not open"); } if (decoder && gst_element_query(decoder, GST_QUERY_TOTAL, &format, &ns) && format == GST_FORMAT_TIME) { // use microsec, as nanosec() is not found by the compiler (?) length.reset(new time_duration(microsec(ns / 1000LL))); } else { length.reset(new time_duration(microsec(0LL))); } return length; } /*------------------------------------------------------------------------------ * Get the current position of the current audio clip. *----------------------------------------------------------------------------*/ Ptr<time_duration>::Ref GstreamerPlayer :: getPosition(void) throw (std::logic_error) { Ptr<time_duration>::Ref length; gint64 ns; GstFormat format = GST_FORMAT_TIME; if (!isOpen()) { throw std::logic_error("player not open"); } if (decoder && gst_element_query(decoder, GST_QUERY_POSITION, &format, &ns) && format == GST_FORMAT_TIME) { // use microsec, as nanosec() is not found by the compiler (?) length.reset(new time_duration(microsec(ns / 1000LL))); } else { length.reset(new time_duration(microsec(0LL))); } return length; } /*------------------------------------------------------------------------------ * Start playing *----------------------------------------------------------------------------*/ void GstreamerPlayer :: start(void) throw (std::logic_error) { if (!isOpen()) { throw std::logic_error("GstreamerPlayer not opened yet"); } if (!isPlaying()) { gst_element_set_state(audiosink, GST_STATE_PAUSED); gst_element_set_state(pipeline, GST_STATE_PLAYING); } } /*------------------------------------------------------------------------------ * Pause the player *----------------------------------------------------------------------------*/ void GstreamerPlayer :: pause(void) throw (std::logic_error) { if (isPlaying()) { gst_element_set_state(pipeline, GST_STATE_PAUSED); } } /*------------------------------------------------------------------------------ * Tell if we're playing *----------------------------------------------------------------------------*/ bool GstreamerPlayer :: isPlaying(void) throw () { return gst_element_get_state(pipeline) == GST_STATE_PLAYING; } /*------------------------------------------------------------------------------ * Stop playing *----------------------------------------------------------------------------*/ void GstreamerPlayer :: stop(void) throw (std::logic_error) { if (!isOpen()) { throw std::logic_error("GstreamerPlayer not opened yet"); } if (isPlaying()) { gst_element_set_state(pipeline, GST_STATE_READY); } } /*------------------------------------------------------------------------------ * Close the currently opened audio file. *----------------------------------------------------------------------------*/ void GstreamerPlayer :: close(void) throw () { if (isPlaying()) { stop(); } gst_element_set_state(pipeline, GST_STATE_NULL); if (filesrc && decoder) { gst_element_unlink(filesrc, decoder); } if (decoder && audiosink) { gst_element_unlink(decoder, audiosink); } if (decoder) { gst_bin_remove(GST_BIN(pipeline), decoder); } if (filesrc) { gst_bin_remove(GST_BIN(pipeline), filesrc); } filesrc = 0; decoder = 0; } /*------------------------------------------------------------------------------ * Get the volume of the player. *----------------------------------------------------------------------------*/ unsigned int GstreamerPlayer :: getVolume(void) throw () { return 0; } /*------------------------------------------------------------------------------ * Set the volume of the player. *----------------------------------------------------------------------------*/ void GstreamerPlayer :: setVolume(unsigned int volume) throw () { } /*------------------------------------------------------------------------------ * Set the audio device. *----------------------------------------------------------------------------*/ bool GstreamerPlayer :: setAudioDevice(const std::string &deviceName) throw () { bool oss = deviceName.find("/dev") == 0; bool relink = false; if (deviceName.size() == 0) { return false; } if (audiosink) { bool oldOss = g_strrstr(gst_element_get_name(audiosink), "osssink"); relink = oss && !oldOss; } if (relink && audiosink) { if (decoder) { gst_element_unlink(decoder, audiosink); } gst_bin_remove(GST_BIN(pipeline), audiosink); // FIXME: why unref here? remove should unref already g_object_unref(G_OBJECT(audiosink)); audiosink = 0; } if (!audiosink) { audiosink = oss ? gst_element_factory_make("osssink", "osssink") : gst_element_factory_make("alsasink", "alsasink"); relink = true; } if (!audiosink) { return false; } // it's the same property, "device" for both alsasink and osssink g_object_set(G_OBJECT(audiosink), "device", deviceName.c_str(), NULL); if (relink) { if (decoder) { gst_element_link_filtered(decoder, audiosink, sinkCaps); } gst_bin_add(GST_BIN(pipeline), audiosink); } return true; } <|endoftext|>
<commit_before>#ifndef RETHREAD_CANCELLATION_TOKEN_H #define RETHREAD_CANCELLATION_TOKEN_H #include <rethread/detail/utility.hpp> #include <atomic> #include <chrono> #include <condition_variable> #include <mutex> #include <thread> namespace rethread { class cancellation_handler { protected: virtual ~cancellation_handler() { } public: /// @brief Should cancel blocking call virtual void cancel() = 0; /// @brief Should reset cancellation_handler to it's original state /// For each cancel() call, there's _exactly_ one reset() call virtual void reset() { } }; class cancellation_token; namespace this_thread { template<typename Rep, typename Period> inline void sleep_for(const std::chrono::duration<Rep, Period>& duration, const cancellation_token& token); } class cancellation_token { protected: std::atomic<bool> _cancelled{false}; mutable std::atomic<cancellation_handler*> _cancelHandler{nullptr}; public: virtual void cancel() = 0; virtual void reset() = 0; bool is_cancelled() const { return _cancelled.load(std::memory_order_relaxed); } explicit operator bool() const { return !is_cancelled(); } protected: virtual ~cancellation_token() { } template<typename Rep, typename Period> void sleep_for(const std::chrono::duration<Rep, Period>& duration) const { do_sleep_for(std::chrono::duration_cast<std::chrono::nanoseconds>(duration)); } virtual void do_sleep_for(const std::chrono::nanoseconds& duration) const = 0; /// @pre Handler is not registered /// @returns Whether handler was registered. If token was cancelled before registration, this method skips registration and returns false bool try_register_cancellation_handler(cancellation_handler& handler) const { cancellation_handler* h = _cancelHandler.exchange(&handler, std::memory_order_release); RETHREAD_ANNOTATE_BEFORE(std::addressof(_cancelHandler)); if (RETHREAD_UNLIKELY(h != nullptr)) { RETHREAD_ASSERT(h == HazardPointer(), "Cancellation handler already registered!"); return false; } return true; } /// @pre Handler is registered /// @returns Whether unregistration succeed bool try_unregister_cancellation_handler(cancellation_handler& handler) const { cancellation_handler* h = _cancelHandler.exchange(nullptr, std::memory_order_acquire); if (RETHREAD_LIKELY(h == &handler)) return true; RETHREAD_ASSERT(h == HazardPointer(), "Another token was registered!"); _cancelHandler.exchange(h); // restore value return false; } /// @pre Handler is registered /// @post Handler is not registered /// @note Will invoke cancellation_handler::reset() if necessary virtual void unregister_cancellation_handler(cancellation_handler& handler) const = 0; protected: // Dirty trick to optimize register/unregister down to one atomic exchange static cancellation_handler* HazardPointer() { return reinterpret_cast<cancellation_handler*>(1); } private: friend class cancellation_guard_base; template<typename Rep, typename Period> friend void this_thread::sleep_for(const std::chrono::duration<Rep, Period>& duration, const cancellation_token& token); }; class dummy_cancellation_token : public cancellation_token { public: void cancel() override { RETHREAD_THROW(std::logic_error("Dummy cancellation token can't be cancelled!")); } void reset() override { RETHREAD_THROW(std::logic_error("Dummy cancellation token can't be reset!")); } protected: void do_sleep_for(const std::chrono::nanoseconds& duration) const override { std::this_thread::sleep_for(duration); } // Just in case someone skips try_unregister_cancellation_handler and calls this directly void unregister_cancellation_handler(cancellation_handler& h) const override { bool r = try_unregister_cancellation_handler(h); (void)r; RETHREAD_ASSERT(r, "Dummy cancellation token can't be cancelled!"); } }; class cancellation_token_atomic : public cancellation_token { mutable std::mutex _mutex; mutable std::condition_variable _cv; mutable bool _cancelDone{false}; public: cancellation_token_atomic() = default; cancellation_token_atomic(const cancellation_token_atomic&) = delete; cancellation_token_atomic& operator = (const cancellation_token_atomic&) = delete; void cancel() override { cancellation_handler* cancelHandler = nullptr; { std::unique_lock<std::mutex> l(_mutex); if (_cancelled) return; _cancelled = true; cancelHandler = _cancelHandler.exchange(HazardPointer()); RETHREAD_ASSERT(cancelHandler != HazardPointer(), "_cancelled should protect from double-cancelling"); } if (cancelHandler) { RETHREAD_ANNOTATE_AFTER(std::addressof(_cancelHandler)); RETHREAD_ANNOTATE_FORGET(std::addressof(_cancelHandler)); cancelHandler->cancel(); RETHREAD_ANNOTATE_BEFORE(cancelHandler); } { std::unique_lock<std::mutex> l(_mutex); _cancelDone = true; _cv.notify_all(); } } void reset() override { std::unique_lock<std::mutex> l(_mutex); RETHREAD_ASSERT((_cancelHandler.load() || _cancelHandler == HazardPointer()) && (_cancelled == _cancelDone), "Cancellation token is in use!"); _cancelled = false; _cancelDone = false; } protected: void do_sleep_for(const std::chrono::nanoseconds& duration) const override { std::unique_lock<std::mutex> l(_mutex); if (is_cancelled()) return; _cv.wait_for(l, duration); } void unregister_cancellation_handler(cancellation_handler& handler) const override { if (try_unregister_cancellation_handler(handler)) return; std::unique_lock<std::mutex> l(_mutex); _cancelHandler = nullptr; if (!_cancelled) return; while (!_cancelDone) _cv.wait(l); RETHREAD_ANNOTATE_AFTER(std::addressof(handler)); RETHREAD_ANNOTATE_FORGET(std::addressof(handler)); l.unlock(); handler.reset(); } }; class cancellation_guard_base { protected: bool try_register(const cancellation_token& token, cancellation_handler& handler) { return token.try_register_cancellation_handler(handler); } bool try_unregister(const cancellation_token& token, cancellation_handler& handler) { return token.try_unregister_cancellation_handler(handler); } void unregister(const cancellation_token& token, cancellation_handler& handler) { token.unregister_cancellation_handler(handler); } }; class cancellation_guard : public cancellation_guard_base { private: const cancellation_token* _token; cancellation_handler* _handler; public: cancellation_guard(const cancellation_guard&) = delete; cancellation_guard& operator = (const cancellation_guard&) = delete; cancellation_guard() : _token(nullptr), _handler(nullptr) { } cancellation_guard(const cancellation_token& token, cancellation_handler& handler) : _token(nullptr), _handler(&handler) { if (try_register(token, handler)) _token = &token; } cancellation_guard(cancellation_guard&& other) : _token(other._token), _handler(other._handler) { other._token = nullptr; } ~cancellation_guard() { if (!_token || RETHREAD_LIKELY(try_unregister(*_token, *_handler))) return; unregister(*_token, *_handler); } bool is_cancelled() const { return !_token; } }; } #endif <commit_msg>Added explicit ctors definitions to tokens. Removed virtual from cancellation_token dtor - looks like it no longer produces a warning.<commit_after>#ifndef RETHREAD_CANCELLATION_TOKEN_H #define RETHREAD_CANCELLATION_TOKEN_H #include <rethread/detail/utility.hpp> #include <atomic> #include <chrono> #include <condition_variable> #include <mutex> #include <thread> namespace rethread { class cancellation_handler { protected: virtual ~cancellation_handler() { } public: /// @brief Should cancel blocking call virtual void cancel() = 0; /// @brief Should reset cancellation_handler to it's original state /// For each cancel() call, there's _exactly_ one reset() call virtual void reset() { } }; class cancellation_token; namespace this_thread { template<typename Rep, typename Period> inline void sleep_for(const std::chrono::duration<Rep, Period>& duration, const cancellation_token& token); } class cancellation_token { protected: std::atomic<bool> _cancelled{false}; mutable std::atomic<cancellation_handler*> _cancelHandler{nullptr}; public: virtual void cancel() = 0; virtual void reset() = 0; bool is_cancelled() const { return _cancelled.load(std::memory_order_relaxed); } explicit operator bool() const { return !is_cancelled(); } protected: template<typename Rep, typename Period> void sleep_for(const std::chrono::duration<Rep, Period>& duration) const { do_sleep_for(std::chrono::duration_cast<std::chrono::nanoseconds>(duration)); } virtual void do_sleep_for(const std::chrono::nanoseconds& duration) const = 0; /// @pre Handler is not registered /// @returns Whether handler was registered. If token was cancelled before registration, this method skips registration and returns false bool try_register_cancellation_handler(cancellation_handler& handler) const { cancellation_handler* h = _cancelHandler.exchange(&handler, std::memory_order_release); RETHREAD_ANNOTATE_BEFORE(std::addressof(_cancelHandler)); if (RETHREAD_UNLIKELY(h != nullptr)) { RETHREAD_ASSERT(h == HazardPointer(), "Cancellation handler already registered!"); return false; } return true; } /// @pre Handler is registered /// @returns Whether unregistration succeed bool try_unregister_cancellation_handler(cancellation_handler& handler) const { cancellation_handler* h = _cancelHandler.exchange(nullptr, std::memory_order_acquire); if (RETHREAD_LIKELY(h == &handler)) return true; RETHREAD_ASSERT(h == HazardPointer(), "Another token was registered!"); _cancelHandler.exchange(h); // restore value return false; } /// @pre Handler is registered /// @post Handler is not registered /// @note Will invoke cancellation_handler::reset() if necessary virtual void unregister_cancellation_handler(cancellation_handler& handler) const = 0; protected: cancellation_token() = default; cancellation_token(const cancellation_token&) = delete; cancellation_token& operator = (const cancellation_token&) = delete; ~cancellation_token() = default; // Dirty trick to optimize register/unregister down to one atomic exchange static cancellation_handler* HazardPointer() { return reinterpret_cast<cancellation_handler*>(1); } private: friend class cancellation_guard_base; template<typename Rep, typename Period> friend void this_thread::sleep_for(const std::chrono::duration<Rep, Period>& duration, const cancellation_token& token); }; class dummy_cancellation_token : public cancellation_token { public: dummy_cancellation_token() = default; // Base class can't be copied, but can default construct it, because dummy_cancellation_token may never cancelled state dummy_cancellation_token(const dummy_cancellation_token&) : cancellation_token() { } dummy_cancellation_token& operator = (const dummy_cancellation_token&) = delete; ~dummy_cancellation_token() = default; void cancel() override { RETHREAD_THROW(std::logic_error("Dummy cancellation token can't be cancelled!")); } void reset() override { RETHREAD_THROW(std::logic_error("Dummy cancellation token can't be reset!")); } protected: void do_sleep_for(const std::chrono::nanoseconds& duration) const override { std::this_thread::sleep_for(duration); } // Just in case someone skips try_unregister_cancellation_handler and calls this directly void unregister_cancellation_handler(cancellation_handler& h) const override { bool r = try_unregister_cancellation_handler(h); (void)r; RETHREAD_ASSERT(r, "Dummy cancellation token can't be cancelled!"); } }; class cancellation_token_atomic : public cancellation_token { mutable std::mutex _mutex; mutable std::condition_variable _cv; mutable bool _cancelDone{false}; public: cancellation_token_atomic() = default; cancellation_token_atomic(const cancellation_token_atomic&) = delete; cancellation_token_atomic& operator = (const cancellation_token_atomic&) = delete; ~cancellation_token_atomic() = default; void cancel() override { cancellation_handler* cancelHandler = nullptr; { std::unique_lock<std::mutex> l(_mutex); if (_cancelled) return; _cancelled = true; cancelHandler = _cancelHandler.exchange(HazardPointer()); RETHREAD_ASSERT(cancelHandler != HazardPointer(), "_cancelled should protect from double-cancelling"); } if (cancelHandler) { RETHREAD_ANNOTATE_AFTER(std::addressof(_cancelHandler)); RETHREAD_ANNOTATE_FORGET(std::addressof(_cancelHandler)); cancelHandler->cancel(); RETHREAD_ANNOTATE_BEFORE(cancelHandler); } { std::unique_lock<std::mutex> l(_mutex); _cancelDone = true; _cv.notify_all(); } } void reset() override { std::unique_lock<std::mutex> l(_mutex); RETHREAD_ASSERT((_cancelHandler.load() || _cancelHandler == HazardPointer()) && (_cancelled == _cancelDone), "Cancellation token is in use!"); _cancelled = false; _cancelDone = false; } protected: void do_sleep_for(const std::chrono::nanoseconds& duration) const override { std::unique_lock<std::mutex> l(_mutex); if (is_cancelled()) return; _cv.wait_for(l, duration); } void unregister_cancellation_handler(cancellation_handler& handler) const override { if (try_unregister_cancellation_handler(handler)) return; std::unique_lock<std::mutex> l(_mutex); _cancelHandler = nullptr; if (!_cancelled) return; while (!_cancelDone) _cv.wait(l); RETHREAD_ANNOTATE_AFTER(std::addressof(handler)); RETHREAD_ANNOTATE_FORGET(std::addressof(handler)); l.unlock(); handler.reset(); } }; class cancellation_guard_base { protected: bool try_register(const cancellation_token& token, cancellation_handler& handler) { return token.try_register_cancellation_handler(handler); } bool try_unregister(const cancellation_token& token, cancellation_handler& handler) { return token.try_unregister_cancellation_handler(handler); } void unregister(const cancellation_token& token, cancellation_handler& handler) { token.unregister_cancellation_handler(handler); } }; class cancellation_guard : public cancellation_guard_base { private: const cancellation_token* _token; cancellation_handler* _handler; public: cancellation_guard(const cancellation_guard&) = delete; cancellation_guard& operator = (const cancellation_guard&) = delete; cancellation_guard() : _token(nullptr), _handler(nullptr) { } cancellation_guard(const cancellation_token& token, cancellation_handler& handler) : _token(nullptr), _handler(&handler) { if (try_register(token, handler)) _token = &token; } cancellation_guard(cancellation_guard&& other) : _token(other._token), _handler(other._handler) { other._token = nullptr; } ~cancellation_guard() { if (!_token || RETHREAD_LIKELY(try_unregister(*_token, *_handler))) return; unregister(*_token, *_handler); } bool is_cancelled() const { return !_token; } }; } #endif <|endoftext|>
<commit_before>#ifndef RETHREAD_CANCELLATION_TOKEN_H #define RETHREAD_CANCELLATION_TOKEN_H #include <rethread/detail/utility.hpp> #include <atomic> #include <chrono> #include <condition_variable> #include <exception> #include <mutex> #include <thread> namespace rethread { class cancellation_handler { protected: virtual ~cancellation_handler() { } public: /// @brief Should cancel blocking call virtual void cancel() = 0; /// @brief Should reset cancellation_handler to it's original state /// For each cancel() call, there's _exactly_ one reset() call virtual void reset() { } }; class cancellation_token; namespace this_thread { template<typename Rep, typename Period> inline void sleep_for(const std::chrono::duration<Rep, Period>& duration, const cancellation_token& token); } class cancellation_token { public: virtual void cancel() = 0; virtual void reset() = 0; virtual bool is_cancelled() const = 0; explicit operator bool() const { return !is_cancelled(); } protected: virtual ~cancellation_token() { } template<typename Rep, typename Period> void sleep_for(const std::chrono::duration<Rep, Period>& duration) const { do_sleep_for(std::chrono::duration_cast<std::chrono::nanoseconds>(duration)); } virtual void do_sleep_for(const std::chrono::nanoseconds& duration) const = 0; /// @pre Handler is not registered /// @returns Whether handler was registered. If token was cancelled before registration, this method skips registration and returns false virtual bool try_register_cancellation_handler(cancellation_handler& handler) const = 0; /// @pre Handler is registered /// @returns Whether unregistration succeed virtual bool try_unregister_cancellation_handler() const = 0; /// @pre Handler is registered /// @post Handler is not registered /// @note Will invoke cancellation_handle::reset() if necessary virtual void unregister_cancellation_handler() const = 0; private: friend class cancellation_guard_base; template<typename Rep, typename Period> friend void this_thread::sleep_for(const std::chrono::duration<Rep, Period>& duration, const cancellation_token& token); }; class dummy_cancellation_token : public cancellation_token { public: void cancel() override { } void reset() override { } bool is_cancelled() const override { return false; } protected: void do_sleep_for(const std::chrono::nanoseconds& duration) const override { std::this_thread::sleep_for(duration); } bool try_register_cancellation_handler(cancellation_handler&) const override { return true; } bool try_unregister_cancellation_handler() const override { return true; } void unregister_cancellation_handler() const override { } }; class cancellation_token_impl : public cancellation_token { mutable std::mutex _mutex; mutable std::condition_variable _cv; std::atomic<bool> _cancelled{false}; mutable bool _cancelDone{false}; mutable cancellation_handler* _cancelHandler{nullptr}; public: cancellation_token_impl() = default; cancellation_token_impl(const cancellation_token_impl&) = delete; cancellation_token_impl& operator = (const cancellation_token_impl&) = delete; void cancel() override { cancellation_handler* cancelHandler = nullptr; { std::unique_lock<std::mutex> l(_mutex); if (_cancelled) return; cancelHandler = _cancelHandler; _cancelled = true; } if (cancelHandler) cancelHandler->cancel(); { std::unique_lock<std::mutex> l(_mutex); _cancelDone = true; _cv.notify_all(); } } void reset() override { std::unique_lock<std::mutex> l(_mutex); RETHREAD_ASSERT(!_cancelHandler && (_cancelled == _cancelDone), "Cancellation token is in use!"); _cancelled = false; _cancelDone = false; } bool is_cancelled() const override { return _cancelled.load(std::memory_order_relaxed); } protected: void do_sleep_for(const std::chrono::nanoseconds& duration) const override { std::unique_lock<std::mutex> l(_mutex); if (_cancelled) return; _cv.wait_for(l, duration); } bool try_register_cancellation_handler(cancellation_handler& handler) const override { std::unique_lock<std::mutex> l(_mutex); if (_cancelled) return false; RETHREAD_CHECK(!_cancelHandler, std::logic_error("Cancellation handler already registered!")); _cancelHandler = &handler; return true; } bool try_unregister_cancellation_handler() const override { std::unique_lock<std::mutex> l(_mutex); if (_cancelled) return false; _cancelHandler = nullptr; return true; } void unregister_cancellation_handler() const override { std::unique_lock<std::mutex> l(_mutex); RETHREAD_ASSERT(_cancelHandler, "No cancellation_handler!"); cancellation_handler* handler = _cancelHandler; _cancelHandler = nullptr; if (!_cancelled) return; while (!_cancelDone) _cv.wait(l); l.unlock(); handler->reset(); } }; class cancellation_guard_base { protected: bool try_register(const cancellation_token& token, cancellation_handler& handler) { return token.try_register_cancellation_handler(handler); } bool try_unregister(const cancellation_token& token) { return token.try_unregister_cancellation_handler(); } void unregister(const cancellation_token& token) { token.unregister_cancellation_handler(); } }; class cancellation_guard : public cancellation_guard_base { private: const cancellation_token* _token; cancellation_handler* _handler; public: cancellation_guard(const cancellation_guard&) = delete; cancellation_guard& operator = (const cancellation_guard&) = delete; cancellation_guard() : _token(nullptr), _handler(nullptr) { } cancellation_guard(const cancellation_token& token, cancellation_handler& handler) : _token(nullptr), _handler(&handler) { if (try_register(token, handler)) _token = &token; } cancellation_guard(cancellation_guard&& other) : _token(other._token), _handler(other._handler) { other._token = nullptr; } ~cancellation_guard() { if (!_token || RETHREAD_LIKELY(try_unregister(*_token))) return; unregister(*_token); } bool is_cancelled() const { return !_token; } }; } #endif <commit_msg>Replaced throw with assert - it seems more appropriate for the case<commit_after>#ifndef RETHREAD_CANCELLATION_TOKEN_H #define RETHREAD_CANCELLATION_TOKEN_H #include <rethread/detail/utility.hpp> #include <atomic> #include <chrono> #include <condition_variable> #include <mutex> #include <thread> namespace rethread { class cancellation_handler { protected: virtual ~cancellation_handler() { } public: /// @brief Should cancel blocking call virtual void cancel() = 0; /// @brief Should reset cancellation_handler to it's original state /// For each cancel() call, there's _exactly_ one reset() call virtual void reset() { } }; class cancellation_token; namespace this_thread { template<typename Rep, typename Period> inline void sleep_for(const std::chrono::duration<Rep, Period>& duration, const cancellation_token& token); } class cancellation_token { public: virtual void cancel() = 0; virtual void reset() = 0; virtual bool is_cancelled() const = 0; explicit operator bool() const { return !is_cancelled(); } protected: virtual ~cancellation_token() { } template<typename Rep, typename Period> void sleep_for(const std::chrono::duration<Rep, Period>& duration) const { do_sleep_for(std::chrono::duration_cast<std::chrono::nanoseconds>(duration)); } virtual void do_sleep_for(const std::chrono::nanoseconds& duration) const = 0; /// @pre Handler is not registered /// @returns Whether handler was registered. If token was cancelled before registration, this method skips registration and returns false virtual bool try_register_cancellation_handler(cancellation_handler& handler) const = 0; /// @pre Handler is registered /// @returns Whether unregistration succeed virtual bool try_unregister_cancellation_handler() const = 0; /// @pre Handler is registered /// @post Handler is not registered /// @note Will invoke cancellation_handle::reset() if necessary virtual void unregister_cancellation_handler() const = 0; private: friend class cancellation_guard_base; template<typename Rep, typename Period> friend void this_thread::sleep_for(const std::chrono::duration<Rep, Period>& duration, const cancellation_token& token); }; class dummy_cancellation_token : public cancellation_token { public: void cancel() override { } void reset() override { } bool is_cancelled() const override { return false; } protected: void do_sleep_for(const std::chrono::nanoseconds& duration) const override { std::this_thread::sleep_for(duration); } bool try_register_cancellation_handler(cancellation_handler&) const override { return true; } bool try_unregister_cancellation_handler() const override { return true; } void unregister_cancellation_handler() const override { } }; class cancellation_token_impl : public cancellation_token { mutable std::mutex _mutex; mutable std::condition_variable _cv; std::atomic<bool> _cancelled{false}; mutable bool _cancelDone{false}; mutable cancellation_handler* _cancelHandler{nullptr}; public: cancellation_token_impl() = default; cancellation_token_impl(const cancellation_token_impl&) = delete; cancellation_token_impl& operator = (const cancellation_token_impl&) = delete; void cancel() override { cancellation_handler* cancelHandler = nullptr; { std::unique_lock<std::mutex> l(_mutex); if (_cancelled) return; cancelHandler = _cancelHandler; _cancelled = true; } if (cancelHandler) cancelHandler->cancel(); { std::unique_lock<std::mutex> l(_mutex); _cancelDone = true; _cv.notify_all(); } } void reset() override { std::unique_lock<std::mutex> l(_mutex); RETHREAD_ASSERT(!_cancelHandler && (_cancelled == _cancelDone), "Cancellation token is in use!"); _cancelled = false; _cancelDone = false; } bool is_cancelled() const override { return _cancelled.load(std::memory_order_relaxed); } protected: void do_sleep_for(const std::chrono::nanoseconds& duration) const override { std::unique_lock<std::mutex> l(_mutex); if (_cancelled) return; _cv.wait_for(l, duration); } bool try_register_cancellation_handler(cancellation_handler& handler) const override { std::unique_lock<std::mutex> l(_mutex); if (_cancelled) return false; RETHREAD_ASSERT(!_cancelHandler, "Cancellation handler already registered!"); _cancelHandler = &handler; return true; } bool try_unregister_cancellation_handler() const override { std::unique_lock<std::mutex> l(_mutex); if (_cancelled) return false; _cancelHandler = nullptr; return true; } void unregister_cancellation_handler() const override { std::unique_lock<std::mutex> l(_mutex); RETHREAD_ASSERT(_cancelHandler, "No cancellation_handler!"); cancellation_handler* handler = _cancelHandler; _cancelHandler = nullptr; if (!_cancelled) return; while (!_cancelDone) _cv.wait(l); l.unlock(); handler->reset(); } }; class cancellation_guard_base { protected: bool try_register(const cancellation_token& token, cancellation_handler& handler) { return token.try_register_cancellation_handler(handler); } bool try_unregister(const cancellation_token& token) { return token.try_unregister_cancellation_handler(); } void unregister(const cancellation_token& token) { token.unregister_cancellation_handler(); } }; class cancellation_guard : public cancellation_guard_base { private: const cancellation_token* _token; cancellation_handler* _handler; public: cancellation_guard(const cancellation_guard&) = delete; cancellation_guard& operator = (const cancellation_guard&) = delete; cancellation_guard() : _token(nullptr), _handler(nullptr) { } cancellation_guard(const cancellation_token& token, cancellation_handler& handler) : _token(nullptr), _handler(&handler) { if (try_register(token, handler)) _token = &token; } cancellation_guard(cancellation_guard&& other) : _token(other._token), _handler(other._handler) { other._token = nullptr; } ~cancellation_guard() { if (!_token || RETHREAD_LIKELY(try_unregister(*_token))) return; unregister(*_token); } bool is_cancelled() const { return !_token; } }; } #endif <|endoftext|>
<commit_before>#include <stan/math/rev/core.hpp> #include <stan/math/rev/mat/functor/algebra_solver.hpp> #include <test/unit/math/rev/mat/fun/util.hpp> #include <test/unit/math/rev/mat/functor/util_algebra_solver.hpp> #include <test/unit/util.hpp> #include <gtest/gtest.h> #include <iostream> #include <fstream> // Every test exists in duplicate to test the case // where y (the auxiliary parameters) are passed as // data (double type) or parameters (var types). TEST(MathMatrix, simple_Eq) { using stan::math::var; int n_x = 2, n_y = 3; for (int k = 0; k < n_x; k++) { Eigen::Matrix<var, Eigen::Dynamic, 1> y(n_y); y << 5, 4, 2; Eigen::Matrix<var, Eigen::Dynamic, 1> theta = simple_eq_test(simple_eq_functor(), y); Eigen::MatrixXd J(n_x, n_y); J << 4, 5, 0, 0, 0, 1; AVEC y_vec = createAVEC(y(0), y(1), y(2)); VEC g; theta(k).grad(y_vec, g); for (int i = 0; i < n_y; i++) EXPECT_EQ(J(k, i), g[i]); } } TEST(MathMatrix, simple_Eq_dbl) { Eigen::VectorXd y(3); y << 5, 4, 2; Eigen::VectorXd theta = simple_eq_test(simple_eq_functor(), y); } TEST(MathMatrix, simple_Eq_tuned) { using stan::math::var; int n_x = 2, n_y = 3; for (int k = 0; k < n_x; k++) { Eigen::Matrix<var, Eigen::Dynamic, 1> y(n_y); y << 5, 4, 2; double xtol = 1e-6, ftol = 1e-6; int maxfev = 1e+4; Eigen::Matrix<var, Eigen::Dynamic, 1> theta = simple_eq_test(simple_eq_functor(), y, true, xtol, ftol, maxfev); Eigen::MatrixXd J(n_x, n_y); J << 4, 5, 0, 0, 0, 1; AVEC y_vec = createAVEC(y(0), y(1), y(2)); VEC g; theta(k).grad(y_vec, g); for (int i = 0; i < n_y; i++) EXPECT_EQ(J(k, i), g[i]); } } TEST(MathMatrix, simple_Eq_tuned_dbl) { int n_y = 3; Eigen::VectorXd y(n_y); y << 5, 4, 2; double xtol = 1e-6, ftol = 1e-6; int maxfev = 1e+4; Eigen::VectorXd theta = simple_eq_test(simple_eq_functor(), y, true, xtol, ftol, maxfev); } TEST(MathMatrix, non_linear_eq) { using stan::math::var; int n_x = 3, n_y = 3; for (int k = 0; k < n_x; k++) { Eigen::Matrix<var, Eigen::Dynamic, 1> y(n_y); y << 4, 6, 3; Eigen::Matrix<var, Eigen::Dynamic, 1> theta = non_linear_eq_test(non_linear_eq_functor(), y); EXPECT_FLOAT_EQ(-y(0).val(), theta(0).val()); EXPECT_FLOAT_EQ(-y(1).val(), theta(1).val()); EXPECT_FLOAT_EQ(y(2).val(), theta(2).val()); Eigen::MatrixXd J(n_x, n_y); J << -1, 0, 0, 0, -1, 0, 0, 0, 1; AVEC y_vec = createAVEC(y(0), y(1), y(2)); VEC g; theta(k).grad(y_vec, g); double err = 1e-11; for (int i = 0; i < n_y; i++) EXPECT_NEAR(J(k, i), g[i], err); } } TEST(MathMatrix, nonLinearEq_dbl) { int n_y = 3; Eigen::VectorXd y(n_y); y << 4, 6, 3; Eigen::VectorXd theta; theta = non_linear_eq_test(non_linear_eq_functor(), y); EXPECT_FLOAT_EQ(-y(0), theta(0)); EXPECT_FLOAT_EQ(-y(1), theta(1)); EXPECT_FLOAT_EQ(y(2), theta(2)); } TEST(MathMatrix, error_conditions) { using stan::math::var; int n_y = 2; Eigen::Matrix<var, Eigen::Dynamic, 1> y(n_y); y << 4, 6; error_conditions_test(non_linear_eq_functor(), y); } TEST(MathMatrix, error_conditions_dbl) { int n_y = 2; Eigen::VectorXd y(n_y); y << 4, 6; error_conditions_test(non_linear_eq_functor(), y); } TEST(MathMatrix, unsolvable) { using stan::math::var; Eigen::Matrix<var, Eigen::Dynamic, 1> y(2); y << 1, 1; // should be positive unsolvable_test(y); } TEST(MathMatrix, unsolvable_dbl) { Eigen::VectorXd y(2); y << 1, 1; unsolvable_test(y); } TEST(MathMatrix, max_num_steps) { using stan::math::var; Eigen::Matrix<var, Eigen::Dynamic, 1> y(2); y << 1, 1; max_num_steps_test(y); } TEST(MathMatrix, max_num_steps_dbl) { Eigen::VectorXd y(2); y << 1, 1; max_num_steps_test(y); } TEST(MathMatrix, degenerate) { using stan::math::algebra_solver; using stan::math::sum; using stan::math::var; int n_x = 2, n_y = 2; // This first initial guess produces the // solution x = {8, 8} for (int k = 0; k < n_x; k++) { Eigen::Matrix<var, Eigen::Dynamic, 1> y(2); y << 5, 8; Eigen::VectorXd x(2); x << 10, 1; // Initial Guess Eigen::Matrix<var, Eigen::Dynamic, 1> theta = degenerate_test(y, x); EXPECT_EQ(8, theta(0)); EXPECT_EQ(8, theta(1)); Eigen::MatrixXd J(n_x, n_y); J << 0, 1, 0, 1; AVEC y_vec = createAVEC(y(0), y(1)); VEC g; theta(k).grad(y_vec, g); for (int l = 0; l < n_y; l++) EXPECT_EQ(J(k, l), g[l]); } // This next initial guess produces the // solution x = {5, 5} for (int k = 0; k < 1; k++) { Eigen::Matrix<var, Eigen::Dynamic, 1> y(2); y << 5, 8; Eigen::VectorXd x(2); x << 1, 1; // Initial Guess Eigen::Matrix<var, Eigen::Dynamic, 1> theta = degenerate_test(y, x); EXPECT_FLOAT_EQ(5, theta(0).val()); EXPECT_FLOAT_EQ(5, theta(0).val()); Eigen::MatrixXd J(n_x, n_y); J << 1, 0, 1, 0; AVEC y_vec = createAVEC(y(0), y(1)); VEC g; theta(k).grad(y_vec, g); for (int l = 0; l < n_y; l++) EXPECT_NEAR(J(k, l), g[l], 1e-13); } } TEST(MathMatrix, degenerate_dbl) { using stan::math::algebra_solver; using stan::math::var; // This first initial guess produces the // solution x = {8, 8} Eigen::VectorXd y(2); y << 5, 8; Eigen::VectorXd x(2); x << 10, 1; // Initial Guess Eigen::VectorXd theta; theta = degenerate_test(y, x); EXPECT_EQ(8, theta(0)); EXPECT_EQ(8, theta(1)); // This next initial guess produces the // solution x = {5, 5} x << 1, 1; // Initial Guess theta = degenerate_test(y, x); EXPECT_FLOAT_EQ(5, theta(0)); EXPECT_FLOAT_EQ(5, theta(0)); } // unit test to demo issue #696 // system functor init bug issue #696 TEST(MathMatrix, system_functor_constructor) { using stan::math::system_functor; Eigen::VectorXd y(2); y << 5, 8; Eigen::VectorXd x(2); x << 10, 1; std::vector<double> dat{0.0, 0.0}; std::vector<int> dat_int{0, 0}; std::ostream* msgs = 0; int f = 99; system_functor<int, double, double, true> fs(f, x, y, dat, dat_int, msgs); EXPECT_EQ(fs.f_, f); } <commit_msg>fix linting failure<commit_after>#include <stan/math/rev/core.hpp> #include <stan/math/rev/mat/functor/algebra_solver.hpp> #include <test/unit/math/rev/mat/fun/util.hpp> #include <test/unit/math/rev/mat/functor/util_algebra_solver.hpp> #include <test/unit/util.hpp> #include <gtest/gtest.h> #include <iostream> #include <fstream> #include <vector> // Every test exists in duplicate to test the case // where y (the auxiliary parameters) are passed as // data (double type) or parameters (var types). TEST(MathMatrix, simple_Eq) { using stan::math::var; int n_x = 2, n_y = 3; for (int k = 0; k < n_x; k++) { Eigen::Matrix<var, Eigen::Dynamic, 1> y(n_y); y << 5, 4, 2; Eigen::Matrix<var, Eigen::Dynamic, 1> theta = simple_eq_test(simple_eq_functor(), y); Eigen::MatrixXd J(n_x, n_y); J << 4, 5, 0, 0, 0, 1; AVEC y_vec = createAVEC(y(0), y(1), y(2)); VEC g; theta(k).grad(y_vec, g); for (int i = 0; i < n_y; i++) EXPECT_EQ(J(k, i), g[i]); } } TEST(MathMatrix, simple_Eq_dbl) { Eigen::VectorXd y(3); y << 5, 4, 2; Eigen::VectorXd theta = simple_eq_test(simple_eq_functor(), y); } TEST(MathMatrix, simple_Eq_tuned) { using stan::math::var; int n_x = 2, n_y = 3; for (int k = 0; k < n_x; k++) { Eigen::Matrix<var, Eigen::Dynamic, 1> y(n_y); y << 5, 4, 2; double xtol = 1e-6, ftol = 1e-6; int maxfev = 1e+4; Eigen::Matrix<var, Eigen::Dynamic, 1> theta = simple_eq_test(simple_eq_functor(), y, true, xtol, ftol, maxfev); Eigen::MatrixXd J(n_x, n_y); J << 4, 5, 0, 0, 0, 1; AVEC y_vec = createAVEC(y(0), y(1), y(2)); VEC g; theta(k).grad(y_vec, g); for (int i = 0; i < n_y; i++) EXPECT_EQ(J(k, i), g[i]); } } TEST(MathMatrix, simple_Eq_tuned_dbl) { int n_y = 3; Eigen::VectorXd y(n_y); y << 5, 4, 2; double xtol = 1e-6, ftol = 1e-6; int maxfev = 1e+4; Eigen::VectorXd theta = simple_eq_test(simple_eq_functor(), y, true, xtol, ftol, maxfev); } TEST(MathMatrix, non_linear_eq) { using stan::math::var; int n_x = 3, n_y = 3; for (int k = 0; k < n_x; k++) { Eigen::Matrix<var, Eigen::Dynamic, 1> y(n_y); y << 4, 6, 3; Eigen::Matrix<var, Eigen::Dynamic, 1> theta = non_linear_eq_test(non_linear_eq_functor(), y); EXPECT_FLOAT_EQ(-y(0).val(), theta(0).val()); EXPECT_FLOAT_EQ(-y(1).val(), theta(1).val()); EXPECT_FLOAT_EQ(y(2).val(), theta(2).val()); Eigen::MatrixXd J(n_x, n_y); J << -1, 0, 0, 0, -1, 0, 0, 0, 1; AVEC y_vec = createAVEC(y(0), y(1), y(2)); VEC g; theta(k).grad(y_vec, g); double err = 1e-11; for (int i = 0; i < n_y; i++) EXPECT_NEAR(J(k, i), g[i], err); } } TEST(MathMatrix, nonLinearEq_dbl) { int n_y = 3; Eigen::VectorXd y(n_y); y << 4, 6, 3; Eigen::VectorXd theta; theta = non_linear_eq_test(non_linear_eq_functor(), y); EXPECT_FLOAT_EQ(-y(0), theta(0)); EXPECT_FLOAT_EQ(-y(1), theta(1)); EXPECT_FLOAT_EQ(y(2), theta(2)); } TEST(MathMatrix, error_conditions) { using stan::math::var; int n_y = 2; Eigen::Matrix<var, Eigen::Dynamic, 1> y(n_y); y << 4, 6; error_conditions_test(non_linear_eq_functor(), y); } TEST(MathMatrix, error_conditions_dbl) { int n_y = 2; Eigen::VectorXd y(n_y); y << 4, 6; error_conditions_test(non_linear_eq_functor(), y); } TEST(MathMatrix, unsolvable) { using stan::math::var; Eigen::Matrix<var, Eigen::Dynamic, 1> y(2); y << 1, 1; // should be positive unsolvable_test(y); } TEST(MathMatrix, unsolvable_dbl) { Eigen::VectorXd y(2); y << 1, 1; unsolvable_test(y); } TEST(MathMatrix, max_num_steps) { using stan::math::var; Eigen::Matrix<var, Eigen::Dynamic, 1> y(2); y << 1, 1; max_num_steps_test(y); } TEST(MathMatrix, max_num_steps_dbl) { Eigen::VectorXd y(2); y << 1, 1; max_num_steps_test(y); } TEST(MathMatrix, degenerate) { using stan::math::algebra_solver; using stan::math::sum; using stan::math::var; int n_x = 2, n_y = 2; // This first initial guess produces the // solution x = {8, 8} for (int k = 0; k < n_x; k++) { Eigen::Matrix<var, Eigen::Dynamic, 1> y(2); y << 5, 8; Eigen::VectorXd x(2); x << 10, 1; // Initial Guess Eigen::Matrix<var, Eigen::Dynamic, 1> theta = degenerate_test(y, x); EXPECT_EQ(8, theta(0)); EXPECT_EQ(8, theta(1)); Eigen::MatrixXd J(n_x, n_y); J << 0, 1, 0, 1; AVEC y_vec = createAVEC(y(0), y(1)); VEC g; theta(k).grad(y_vec, g); for (int l = 0; l < n_y; l++) EXPECT_EQ(J(k, l), g[l]); } // This next initial guess produces the // solution x = {5, 5} for (int k = 0; k < 1; k++) { Eigen::Matrix<var, Eigen::Dynamic, 1> y(2); y << 5, 8; Eigen::VectorXd x(2); x << 1, 1; // Initial Guess Eigen::Matrix<var, Eigen::Dynamic, 1> theta = degenerate_test(y, x); EXPECT_FLOAT_EQ(5, theta(0).val()); EXPECT_FLOAT_EQ(5, theta(0).val()); Eigen::MatrixXd J(n_x, n_y); J << 1, 0, 1, 0; AVEC y_vec = createAVEC(y(0), y(1)); VEC g; theta(k).grad(y_vec, g); for (int l = 0; l < n_y; l++) EXPECT_NEAR(J(k, l), g[l], 1e-13); } } TEST(MathMatrix, degenerate_dbl) { using stan::math::algebra_solver; using stan::math::var; // This first initial guess produces the // solution x = {8, 8} Eigen::VectorXd y(2); y << 5, 8; Eigen::VectorXd x(2); x << 10, 1; // Initial Guess Eigen::VectorXd theta; theta = degenerate_test(y, x); EXPECT_EQ(8, theta(0)); EXPECT_EQ(8, theta(1)); // This next initial guess produces the // solution x = {5, 5} x << 1, 1; // Initial Guess theta = degenerate_test(y, x); EXPECT_FLOAT_EQ(5, theta(0)); EXPECT_FLOAT_EQ(5, theta(0)); } // unit test to demo issue #696 // system functor init bug issue #696 TEST(MathMatrix, system_functor_constructor) { using stan::math::system_functor; Eigen::VectorXd y(2); y << 5, 8; Eigen::VectorXd x(2); x << 10, 1; std::vector<double> dat{0.0, 0.0}; std::vector<int> dat_int{0, 0}; std::ostream* msgs = 0; int f = 99; system_functor<int, double, double, true> fs(f, x, y, dat, dat_int, msgs); EXPECT_EQ(fs.f_, f); } <|endoftext|>
<commit_before>/*************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Karoliina T. Salminen <karoliina.t.salminen@nokia.com> ** ** This file is part of duicontrolpanel. ** ** ** This program 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 ** and appearing in the file LICENSE.LGPL included in the packaging ** of this file. ** ****************************************************************************/ #include "dcpappletpage.h" DcpAppletPage::DcpAppletPage (DcpAppletObject *applet, int widgetId) : DcpPage(), m_Applet (applet), m_WidgetId (widgetId), m_MainWidget (0) { } DcpAppletPage::~DcpAppletPage () { } void DcpAppletPage::createContent () { } bool DcpAppletPage::hasWidget () const { return true; } void DcpAppletPage::setApplet(DcpAppletObject*, int) { } int DcpAppletPage::widgetId () { return m_WidgetId; } DcpAppletObject* DcpAppletPage::applet() { return m_Applet; } void DcpAppletPage::load () { } void DcpAppletPage::retranslateUi() { } DcpAppletWidget* DcpAppletPage::constructAppletWidget(DcpAppletObject*, DcpPage*, int) { return 0; } bool DcpAppletPage::preventQuit() { return false; } <commit_msg>Fixes the unittests<commit_after>/*************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Karoliina T. Salminen <karoliina.t.salminen@nokia.com> ** ** This file is part of duicontrolpanel. ** ** ** This program 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 ** and appearing in the file LICENSE.LGPL included in the packaging ** of this file. ** ****************************************************************************/ #include "dcpappletpage.h" DcpAppletPage::DcpAppletPage (DcpAppletObject *applet, int widgetId) : DcpPage(), m_Applet (applet), m_WidgetId (widgetId), m_MainWidget (0) { } DcpAppletPage::~DcpAppletPage () { } void DcpAppletPage::createContent () { } bool DcpAppletPage::hasWidget () const { return true; } void DcpAppletPage::setApplet(DcpAppletObject*, int) { } int DcpAppletPage::widgetId () { return m_WidgetId; } DcpAppletObject* DcpAppletPage::applet() { return m_Applet; } void DcpAppletPage::load () { } void DcpAppletPage::retranslateUi() { } DcpAppletWidget* DcpAppletPage::constructAppletWidget(DcpAppletObject*, DcpPage*, int) { return 0; } bool DcpAppletPage::preventQuit() { return false; } void DcpAppletPage::onAutoTitleEnabledChanged () { } <|endoftext|>
<commit_before>#include <exodus/program.h> programinit() var file1; var file2; var targetfilename; var targetdb; var targetname; var sql; dim sqltext; var nlines; var ln; var sourcefilename; var recn; var dictonly; function main() { if (not COMMAND.a(2) or not COMMAND.a(3)) { var syntax = "Syntax is copyfile [<source>:][<sourcefilename>,...] [<targetdb>:[<targetfilename>] {OPTIONS}\n" "\n" "source can be a database name or an sql file containing COPY data like that produced by pg_dump"; abort(syntax); } //parse source var sourcename = ""; var sourcefilenames = COMMAND.a(2); if (index(sourcefilenames,":")) { sourcename = field(sourcefilenames,":",1); sourcefilenames = field(sourcefilenames,":",2); } //parse target targetname = ""; var targetfilenames = COMMAND.a(3); if (index(targetfilenames,":")) { targetname = field(targetfilenames,":",1); targetfilenames = field(targetfilenames,":",2); } //detect sql source sql = sourcename.ends(".sql"); //connect to source db if source not .sql file var sourcedb; if (not sql and not sourcedb.connect(sourcename)) abort(sourcename.quote() ^ " Cannot connect"); //connect to target db if (not targetdb.connect(targetname)) abort(targetname.quote() ^ " Cannot connect"); //dict means filter all and only dict files dictonly = sourcefilenames eq "dict"; if (dictonly and not sql) sourcefilenames = ""; //determins all files in source db if source not .sql if (not sql and not sourcefilenames) { sourcefilenames = sourcedb.listfiles(); targetfilenames = ""; } //go through files one by one if source is a db if (not sql) sourcefilenames.converter(",", FM); for (const var& temp : sourcefilenames) { sourcefilename = temp; //never do dict.all which is an sql view of all dict. files if (sourcefilename eq "dict.all") continue; //filter dict. files if (not sql and dictonly and sourcefilename.substr(1,5) ne "dict.") continue; // source is .sql file if (sql) { //read in the .sql file text targetfilename = ""; var txt; if (not txt.osread(sourcename)) abort(sourcename.quote() ^ " does not exist or cannot be accessed"); //split the sql text into an array nlines = sqltext.split(txt,"\n"); ln = 0; } // source is database else { targetfilename = targetfilenames; if (not targetfilename) targetfilename = sourcefilename; //open source file if (not file1.open(sourcefilename, sourcedb) ) abort(sourcefilename.quote() ^ " cannot be opened in source db " ^ sourcename); //open target file if (not file2.open(targetfilename, targetdb)) { if (not OPTIONS.index("C") or not targetdb.createfile(targetfilename) or not file2.open(targetfilename, targetdb)) abort(targetfilename.quote() ^ " cannot be opened in target db " ^ targetname); } } //speed up targetdb.begintrans(); //select source file if source is db if (not sql) { printl(sourcefilename); file1.select(sourcefilename ^ " (R)"); } //process source file recn = 0; while(getrec()) { //user interrupt if (not mod(recn,1000)) { //print(at(-40), sourcefilename, recn ^ ".", ID); if (esctoexit()) abort(""); } //skip if not changed var oldrec; if (oldrec.read(file2,ID)) { if (RECORD eq oldrec) { print("\tNot changed"); continue; } printl("\tChanged"); } else { printl("\tNew"); } //if (OPTIONS.index("W")) RECORD.write(file2, ID); } //commit all target db updates targetdb.committrans(); printl(); } return 0; } /////////////////// function getrec() { /////////////////// // If source is database then simply readnext RECORD and ID if (not sql) { var result = file1.readnext(RECORD, ID, MV); if (result) { recn++; print(at(-40) ^ recn ^ ".", ID); } return result; } //otherwise get the next file and record from the source .sql file while (true) { ln++; if (ln gt nlines) return false; RECORD = sqltext(ln); // If we dont have a filename then find a line starting COPY and extract filename from it if (not targetfilename) { if (RECORD.field(" ", 1) != "COPY") continue; targetfilename = RECORD.field(" ", 2); // Remove public. from start of filename but not dict. if (targetfilename.starts("public.")) targetfilename = targetfilename.substr(8); // Skip unwanted files if (not dictonly and sourcefilename and not sourcefilename.locateusing(targetfilename, ",")) continue; // Skip file if not dict. and only dicts wanted if (dictonly and not targetfilename.starts("dict.")) { targetfilename = ""; continue; } // Output filename by itself printl(); printl(targetfilename); recn = 0; // Open the target file if (not file2.open(targetfilename, targetdb) ) abort(targetfilename.quote() ^ " cannot be opened in target db " ^ targetname); continue; } // A line with just "\." indicates no more records for the current file if (RECORD eq "\\.") { // Trigger a search for the next line starting COPY targetfilename = ""; continue; } break; } recn++; ID = RECORD.field("\t",1); //RECORD[1,len(ID)+1] = "" RECORD.splicer(1,ID.length()+1,""); gosub unescape(ID); gosub unescape(RECORD); //TRACE(ID) print(at(-40) ^ recn ^ ".", ID); return true; } subroutine unescape(io arg1) { if (not arg1.index("\\")) return; arg1.swapper("\\n","\n"); arg1.swapper("\\b","\b"); arg1.swapper("\\t","\t"); arg1.swapper("\\v","\v"); arg1.swapper("\\f","\f"); arg1.swapper("\\r","\r"); arg1.swapper("\\\\","\\"); return; } programexit() <commit_msg>cli copyfile target can be dir path to output records os files eg PATH/dict.users/user_id<commit_after>#include <exodus/program.h> programinit() var file1; var file2; var targetfilename; var targetdb; var targetname; var targetdir; var sql; dim sqltext; var nlines; var ln; var sourcefilename; var recn; var dictonly; function main() { if (not COMMAND.a(2) or not COMMAND.a(3)) { var syntax = "Syntax is copyfile [SOURCE:][SOURCEFILENAME,...] [TARGET:][TARGETFILENAME] {OPTIONS}\n" "\n" "SOURCE can be a database name or an sql file containing COPY data like that produced by pg_dump\n" "\n" "TARGET can be a database name or a dir path ending /\n" "\n" "SOURCE and TARGET must be followed by : otherwise the default database will used."; abort(syntax); } //parse source var sourcename = ""; var sourcefilenames = COMMAND.a(2); if (index(sourcefilenames,":")) { sourcename = field(sourcefilenames,":",1); sourcefilenames = field(sourcefilenames,":",2); } //parse target targetname = ""; var targetfilenames = COMMAND.a(3); if (index(targetfilenames,":")) { targetname = field(targetfilenames,":",1); targetfilenames = field(targetfilenames,":",2); } //detect sql source sql = sourcename.ends(".sql"); //connect to source db if source not .sql file var sourcedb; if (not sql and not sourcedb.connect(sourcename)) abort(sourcename.quote() ^ " Cannot connect to source"); if (targetname.index("/")) { //flag target is not a db targetdb = ""; //target name will be a dir path if (targetname[-1] ne "/") targetname ^= "/"; } else { //connect to target db if (not targetdb.connect(targetname)) abort(targetname.quote() ^ " Cannot connect to target"); } //dict means filter all and only dict files dictonly = sourcefilenames eq "dict"; if (dictonly and not sql) sourcefilenames = ""; //determins all files in source db if source not .sql if (not sql and not sourcefilenames) { sourcefilenames = sourcedb.listfiles(); targetfilenames = ""; } //go through files one by one if source is a db if (not sql) sourcefilenames.converter(",", FM); for (const var& temp : sourcefilenames) { sourcefilename = temp; //skip dict.all which is an sql view of all dict files if (sourcefilename eq "dict.all") continue; //option to skip all but dict files if (not sql and dictonly and sourcefilename.substr(1,5) ne "dict.") continue; // source is .sql file if (sql) { //read in the .sql file text targetfilename = ""; var txt; if (not txt.osread(sourcename)) abort(sourcename.quote() ^ " does not exist or cannot be accessed"); //split the sql text into an array nlines = sqltext.split(txt,"\n"); ln = 0; } // source is database else { targetfilename = targetfilenames; if (not targetfilename) targetfilename = sourcefilename; //open source file if (not file1.open(sourcefilename, sourcedb) ) abort(sourcefilename.quote() ^ " cannot be opened in source db " ^ sourcename); if (targetdb) { //open target file if (not file2.open(targetfilename, targetdb)) { if (not OPTIONS.index("C") or not targetdb.createfile(targetfilename) or not file2.open(targetfilename, targetdb)) abort(targetfilename.quote() ^ " cannot be opened in target db " ^ targetname); } } else { //create the output dir targetdir = targetname ^ targetfilename ^ "/"; osmkdir(targetdir); } } //speed up targetdb.begintrans(); //select source file if source is db if (not sql) { printl(sourcefilename); file1.select(sourcefilename ^ " (R)"); } //process source file recn = 0; while(getrec()) { //user interrupt if (not mod(recn,1000)) { //print(at(-40), sourcefilename, recn ^ ".", ID); if (esctoexit()) abort(""); } //skip if not changed var oldrec; var exists; if (targetdb) { exists = oldrec.read(file2,ID); } else { exists = oldrec.osread(targetdir ^ ID); gosub escape_text(RECORD); } if (exists) { //skip update if no change if (RECORD eq oldrec) { print("\tNot changed"); continue; } printl("\tChanged"); } else { printl("\tNew"); } if (targetdb) { RECORD.write(file2, ID); } else { oswrite(RECORD, targetdir ^ ID); } } //commit all target db updates targetdb.committrans(); printl(); } return 0; } /////////////////// function getrec() { /////////////////// // If source is database then simply readnext RECORD and ID if (not sql) { var result = file1.readnext(RECORD, ID, MV); if (result) { recn++; print(at(-40) ^ recn ^ ".", ID); } return result; } //otherwise get the next file and record from the source .sql file while (true) { ln++; if (ln gt nlines) return false; RECORD = sqltext(ln); // If we dont have a filename then find a line starting COPY and extract filename from it if (not targetfilename) { if (RECORD.field(" ", 1) != "COPY") continue; targetfilename = RECORD.field(" ", 2); // Remove public. from start of filename but not dict. if (targetfilename.starts("public.")) targetfilename = targetfilename.substr(8); // Skip unwanted files if (not dictonly and sourcefilename and not sourcefilename.locateusing(targetfilename, ",")) continue; // Skip file if not dict. and only dicts wanted if (dictonly and not targetfilename.starts("dict.")) { targetfilename = ""; continue; } // Output filename by itself printl(); printl(targetfilename); recn = 0; // Open the target file if (not file2.open(targetfilename, targetdb) ) abort(targetfilename.quote() ^ " cannot be opened in target db " ^ targetname); continue; } // A line with just "\." indicates no more records for the current file if (RECORD eq "\\.") { // Trigger a search for the next line starting COPY targetfilename = ""; continue; } break; } recn++; ID = RECORD.field("\t",1); //RECORD[1,len(ID)+1] = "" RECORD.splicer(1,ID.length()+1,""); gosub unescape_sql(ID); gosub unescape_sql(RECORD); //TRACE(ID) print(at(-40) ^ recn ^ ".", ID); return true; } subroutine escape_text(io record) { //escape new lines and backslashes record.swapper("\\", "\\\\"); record.swapper("\n", "\\n"); //replace FM with new lines record.converter(FM, "\n"); return; } subroutine unescape_sql(io arg1) { if (not arg1.index("\\")) return; arg1.swapper("\\n","\n"); arg1.swapper("\\b","\b"); arg1.swapper("\\t","\t"); arg1.swapper("\\v","\v"); arg1.swapper("\\f","\f"); arg1.swapper("\\r","\r"); arg1.swapper("\\\\","\\"); return; } programexit() <|endoftext|>
<commit_before>//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // UNSUPPORTED: c++98, c++03, c++11, c++14 // aligned allocation functions are not provided prior to macosx10.13 // XFAIL: macosx10.12 // XFAIL: macosx10.11 // XFAIL: macosx10.10 // XFAIL: macosx10.9 // XFAIL: macosx10.8 // XFAIL: macosx10.7 #include <new> #ifdef _LIBCPP_HAS_NO_ALIGNED_ALLOCATION # error "libc++ should have aligned allocation in C++17 and up when targeting a platform that supports it" #endif int main() { } <commit_msg>Disable the aligned allocation test on old mac versions instead of XFAILing it<commit_after>//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // UNSUPPORTED: c++98, c++03, c++11, c++14 // aligned allocation functions are not provided prior to macosx10.13 // UNSUPPORTED: macosx10.12 // UNSUPPORTED: macosx10.11 // UNSUPPORTED: macosx10.10 // UNSUPPORTED: macosx10.9 // UNSUPPORTED: macosx10.8 // UNSUPPORTED: macosx10.7 #include <new> #ifdef _LIBCPP_HAS_NO_ALIGNED_ALLOCATION # error "libc++ should have aligned allocation in C++17 and up when targeting a platform that supports it" #endif int main() { } <|endoftext|>
<commit_before>/** Copyright (C) 2016 Ultimaker - Released under terms of the AGPLv3 License */ #include "SettingRegistry.h" #include <sstream> #include <iostream> // debug IO #include <libgen.h> // dirname #include <string> #include <cstring> // strtok (split string using delimiters) strcpy #include <fstream> // ifstream (to see if file exists) #include "rapidjson/rapidjson.h" #include "rapidjson/document.h" #include "rapidjson/error/en.h" #include "rapidjson/filereadstream.h" #include "../utils/logoutput.h" namespace cura { SettingRegistry SettingRegistry::instance; // define settingRegistry std::string SettingRegistry::toString(rapidjson::Type type) { switch (type) { case rapidjson::Type::kNullType: return "null"; case rapidjson::Type::kFalseType: return "false"; case rapidjson::Type::kTrueType: return "true"; case rapidjson::Type::kObjectType: return "object"; case rapidjson::Type::kArrayType: return "array"; case rapidjson::Type::kStringType: return "string"; case rapidjson::Type::kNumberType: return "number"; default: return "Unknown"; } } SettingConfig::SettingConfig(std::string key, std::string label) : SettingContainer(key, label) { // std::cerr << key << std::endl; // debug output to show all frontend registered settings... } bool SettingRegistry::settingExists(std::string key) const { return setting_key_to_config.find(key) != setting_key_to_config.end(); } SettingConfig* SettingRegistry::getSettingConfig(std::string key) const { auto it = setting_key_to_config.find(key); if (it == setting_key_to_config.end()) return nullptr; return it->second; } SettingRegistry::SettingRegistry() : setting_definitions("settings", "Settings") { // load search paths from environment variable CURA_ENGINE_SEARCH_PATH char* paths = getenv("CURA_ENGINE_SEARCH_PATH"); if (paths) { #if defined(__linux__) || (defined(__APPLE__) && defined(__MACH__)) char delims[] = ":"; // colon #else char delims[] = ";"; // semicolon #endif char* path = strtok(paths, delims); // search for next path delimited by any of the characters in delims while (path != NULL) { search_paths.emplace(path); path = strtok(NULL, ";:,"); // continue searching in last call to strtok } } } int SettingRegistry::loadJSON(std::string filename, rapidjson::Document& json_document) { FILE* f = fopen(filename.c_str(), "rb"); if (!f) { cura::logError("Couldn't open JSON file.\n"); return 1; } char read_buffer[4096]; rapidjson::FileReadStream reader_stream(f, read_buffer, sizeof(read_buffer)); json_document.ParseStream(reader_stream); fclose(f); if (json_document.HasParseError()) { cura::logError("Error parsing JSON(offset %u): %s\n", (unsigned)json_document.GetErrorOffset(), GetParseError_En(json_document.GetParseError())); return 2; } return 0; } /*! * Check whether a file exists. * from https://techoverflow.net/blog/2013/01/11/cpp-check-if-file-exists/ * * \param filename The path to a filename to check if it exists * \return Whether the file exists. */ bool fexists(const char *filename) { std::ifstream ifile(filename); return (bool)ifile; } bool SettingRegistry::getDefinitionFile(const std::string machine_id, std::string& result) { for (const std::string& search_path : search_paths) { result = search_path + std::string("/") + machine_id + std::string(".def.json"); if (fexists(result.c_str())) { return true; } } return false; } int SettingRegistry::loadExtruderJSONsettings(unsigned int extruder_nr, SettingsBase* settings_base) { if (extruder_nr >= extruder_train_ids.size()) { logWarning("Couldn't load extruder.def.json file for extruder %i. Index out of bounds.\n Loading first extruder definition instead.\n", extruder_nr); extruder_nr = 0; } std::string definition_file; bool found = getDefinitionFile(extruder_train_ids[extruder_nr], definition_file); if (!found) { logError("Couldn't find extruder.def.json file for extruder %i.\n", extruder_nr); return -1; } bool warn_base_file_duplicates = false; return loadJSONsettings(definition_file, settings_base, warn_base_file_duplicates); } int SettingRegistry::loadJSONsettings(std::string filename, SettingsBase* settings_base, bool warn_base_file_duplicates) { rapidjson::Document json_document; log("Loading %s...\n", filename.c_str()); int err = loadJSON(filename, json_document); if (err) { return err; } { // add parent folder to search paths char filename_cstr[filename.size()]; std::strcpy(filename_cstr, filename.c_str()); // copy the string because dirname(.) changes the input string!!! std::string folder_name = std::string(dirname(filename_cstr)); search_paths.emplace(folder_name); } if (json_document.HasMember("inherits") && json_document["inherits"].IsString()) { std::string child_filename; bool found = getDefinitionFile(json_document["inherits"].GetString(), child_filename); if (!found) { cura::logError("Inherited JSON file \"%s\" not found\n", json_document["inherits"].GetString()); return -1; } err = loadJSONsettings(child_filename, settings_base, warn_base_file_duplicates); // load child first if (err) { return err; } err = loadJSONsettingsFromDoc(json_document, settings_base, false); } else { err = loadJSONsettingsFromDoc(json_document, settings_base, warn_base_file_duplicates); } if (json_document.HasMember("metadata") && json_document["metadata"].IsObject()) { const rapidjson::Value& json_metadata = json_document["metadata"]; if (json_metadata.HasMember("machine_extruder_trains") && json_metadata["machine_extruder_trains"].IsObject()) { const rapidjson::Value& json_machine_extruder_trains = json_metadata["machine_extruder_trains"]; for (rapidjson::Value::ConstMemberIterator extr_train_iterator = json_machine_extruder_trains.MemberBegin(); extr_train_iterator != json_machine_extruder_trains.MemberEnd(); ++extr_train_iterator) { int extruder_train_nr = atoi(extr_train_iterator->name.GetString()); if (extruder_train_nr < 0) { continue; } const rapidjson::Value& json_id = extr_train_iterator->value; if (!json_id.IsString()) { continue; } const char* id = json_id.GetString(); if (extruder_train_nr >= (int) extruder_train_ids.size()) { extruder_train_ids.resize(extruder_train_nr + 1); } extruder_train_ids[extruder_train_nr] = std::string(id); } } } return err; } int SettingRegistry::loadJSONsettingsFromDoc(rapidjson::Document& json_document, SettingsBase* settings_base, bool warn_duplicates) { if (!json_document.IsObject()) { cura::logError("JSON file is not an object.\n"); return 3; } { // handle machine name std::string machine_name = "Unknown"; if (json_document.HasMember("name")) { const rapidjson::Value& machine_name_field = json_document["name"]; if (machine_name_field.IsString()) { machine_name = machine_name_field.GetString(); } } SettingConfig& machine_name_setting = addSetting("machine_name", "Machine Name"); machine_name_setting.setDefault(machine_name); machine_name_setting.setType("string"); settings_base->_setSetting(machine_name_setting.getKey(), machine_name_setting.getDefaultValue()); } if (json_document.HasMember("settings")) { std::list<std::string> path; handleChildren(json_document["settings"], path, settings_base, warn_duplicates); } if (json_document.HasMember("overrides")) { const rapidjson::Value& json_object_container = json_document["overrides"]; for (rapidjson::Value::ConstMemberIterator override_iterator = json_object_container.MemberBegin(); override_iterator != json_object_container.MemberEnd(); ++override_iterator) { std::string setting = override_iterator->name.GetString(); SettingConfig* conf = getSettingConfig(setting); if (!conf) //Setting could not be found. { logWarning("Trying to override unknown setting %s.\n", setting.c_str()); continue; } _loadSettingValues(conf, override_iterator, settings_base); } } return 0; } void SettingRegistry::handleChildren(const rapidjson::Value& settings_list, std::list<std::string>& path, SettingsBase* settings_base, bool warn_duplicates) { if (!settings_list.IsObject()) { logError("json settings list is not an object!\n"); return; } for (rapidjson::Value::ConstMemberIterator setting_iterator = settings_list.MemberBegin(); setting_iterator != settings_list.MemberEnd(); ++setting_iterator) { handleSetting(setting_iterator, path, settings_base, warn_duplicates); if (setting_iterator->value.HasMember("children")) { std::list<std::string> path_here = path; path_here.push_back(setting_iterator->name.GetString()); handleChildren(setting_iterator->value["children"], path_here, settings_base, warn_duplicates); } } } bool SettingRegistry::settingIsUsedByEngine(const rapidjson::Value& setting) { if (setting.HasMember("children")) { return false; } else { return true; } } void SettingRegistry::handleSetting(const rapidjson::Value::ConstMemberIterator& json_setting_it, std::list<std::string>& path, SettingsBase* settings_base, bool warn_duplicates) { const rapidjson::Value& json_setting = json_setting_it->value; if (!json_setting.IsObject()) { logError("json setting is not an object!\n"); return; } std::string name = json_setting_it->name.GetString(); if (json_setting.HasMember("type") && json_setting["type"].IsString() && json_setting["type"].GetString() == std::string("category")) { // skip category objects setting_key_to_config[name] = nullptr; // add the category name to the mapping, but don't instantiate a setting config for it. return; } if (settingIsUsedByEngine(json_setting)) { if (!json_setting.HasMember("label") || !json_setting["label"].IsString()) { logError("json setting \"%s\" has no label!\n", name.c_str()); return; } std::string label = json_setting["label"].GetString(); SettingConfig* setting = getSettingConfig(name); if (warn_duplicates && setting) { cura::logWarning("Duplicate definition of setting: %s a.k.a. \"%s\" was already claimed by \"%s\"\n", name.c_str(), label.c_str(), getSettingConfig(name)->getLabel().c_str()); } if (!setting) { setting = &addSetting(name, label); } _loadSettingValues(setting, json_setting_it, settings_base); } else { setting_key_to_config[name] = nullptr; // add the setting name to the mapping, but don't instantiate a setting config for it. } } SettingConfig& SettingRegistry::addSetting(std::string name, std::string label) { SettingConfig* config = setting_definitions.addChild(name, label); setting_key_to_config[name] = config; return *config; } void SettingRegistry::loadDefault(const rapidjson::GenericValue< rapidjson::UTF8< char > >::ConstMemberIterator& json_object_it, SettingConfig* config) { const rapidjson::Value& setting_content = json_object_it->value; if (setting_content.HasMember("default_value")) { const rapidjson::Value& dflt = setting_content["default_value"]; if (dflt.IsString()) { config->setDefault(dflt.GetString()); } else if (dflt.IsTrue()) { config->setDefault("true"); } else if (dflt.IsFalse()) { config->setDefault("false"); } else if (dflt.IsNumber()) { std::ostringstream ss; ss << dflt.GetDouble(); config->setDefault(ss.str()); } // arrays are ignored because machine_extruder_trains needs to be handled separately else { logWarning("WARNING: Unrecognized data type in JSON: %s has type %s\n", json_object_it->name.GetString(), toString(dflt.GetType()).c_str()); } } } void SettingRegistry::_loadSettingValues(SettingConfig* config, const rapidjson::GenericValue< rapidjson::UTF8< char > >::ConstMemberIterator& json_object_it, SettingsBase* settings_base) { const rapidjson::Value& data = json_object_it->value; /// Fill the setting config object with data we have in the json file. if (data.HasMember("type") && data["type"].IsString()) { config->setType(data["type"].GetString()); } if (config->getType() == std::string("polygon") || config->getType() == std::string("polygons")) { // skip polygon settings : not implemented yet and not used yet (TODO) // logWarning("WARNING: Loading polygon setting %s not implemented...\n", json_object_it->name.GetString()); return; } loadDefault(json_object_it, config); if (data.HasMember("unit") && data["unit"].IsString()) { config->setUnit(data["unit"].GetString()); } settings_base->_setSetting(config->getKey(), config->getDefaultValue()); } }//namespace cura <commit_msg>fix: don't retrieve the machine name from the json document, but from the settings (CURA-2360)<commit_after>/** Copyright (C) 2016 Ultimaker - Released under terms of the AGPLv3 License */ #include "SettingRegistry.h" #include <sstream> #include <iostream> // debug IO #include <libgen.h> // dirname #include <string> #include <cstring> // strtok (split string using delimiters) strcpy #include <fstream> // ifstream (to see if file exists) #include "rapidjson/rapidjson.h" #include "rapidjson/document.h" #include "rapidjson/error/en.h" #include "rapidjson/filereadstream.h" #include "../utils/logoutput.h" namespace cura { SettingRegistry SettingRegistry::instance; // define settingRegistry std::string SettingRegistry::toString(rapidjson::Type type) { switch (type) { case rapidjson::Type::kNullType: return "null"; case rapidjson::Type::kFalseType: return "false"; case rapidjson::Type::kTrueType: return "true"; case rapidjson::Type::kObjectType: return "object"; case rapidjson::Type::kArrayType: return "array"; case rapidjson::Type::kStringType: return "string"; case rapidjson::Type::kNumberType: return "number"; default: return "Unknown"; } } SettingConfig::SettingConfig(std::string key, std::string label) : SettingContainer(key, label) { // std::cerr << key << std::endl; // debug output to show all frontend registered settings... } bool SettingRegistry::settingExists(std::string key) const { return setting_key_to_config.find(key) != setting_key_to_config.end(); } SettingConfig* SettingRegistry::getSettingConfig(std::string key) const { auto it = setting_key_to_config.find(key); if (it == setting_key_to_config.end()) return nullptr; return it->second; } SettingRegistry::SettingRegistry() : setting_definitions("settings", "Settings") { // load search paths from environment variable CURA_ENGINE_SEARCH_PATH char* paths = getenv("CURA_ENGINE_SEARCH_PATH"); if (paths) { #if defined(__linux__) || (defined(__APPLE__) && defined(__MACH__)) char delims[] = ":"; // colon #else char delims[] = ";"; // semicolon #endif char* path = strtok(paths, delims); // search for next path delimited by any of the characters in delims while (path != NULL) { search_paths.emplace(path); path = strtok(NULL, ";:,"); // continue searching in last call to strtok } } } int SettingRegistry::loadJSON(std::string filename, rapidjson::Document& json_document) { FILE* f = fopen(filename.c_str(), "rb"); if (!f) { cura::logError("Couldn't open JSON file.\n"); return 1; } char read_buffer[4096]; rapidjson::FileReadStream reader_stream(f, read_buffer, sizeof(read_buffer)); json_document.ParseStream(reader_stream); fclose(f); if (json_document.HasParseError()) { cura::logError("Error parsing JSON(offset %u): %s\n", (unsigned)json_document.GetErrorOffset(), GetParseError_En(json_document.GetParseError())); return 2; } return 0; } /*! * Check whether a file exists. * from https://techoverflow.net/blog/2013/01/11/cpp-check-if-file-exists/ * * \param filename The path to a filename to check if it exists * \return Whether the file exists. */ bool fexists(const char *filename) { std::ifstream ifile(filename); return (bool)ifile; } bool SettingRegistry::getDefinitionFile(const std::string machine_id, std::string& result) { for (const std::string& search_path : search_paths) { result = search_path + std::string("/") + machine_id + std::string(".def.json"); if (fexists(result.c_str())) { return true; } } return false; } int SettingRegistry::loadExtruderJSONsettings(unsigned int extruder_nr, SettingsBase* settings_base) { if (extruder_nr >= extruder_train_ids.size()) { logWarning("Couldn't load extruder.def.json file for extruder %i. Index out of bounds.\n Loading first extruder definition instead.\n", extruder_nr); extruder_nr = 0; } std::string definition_file; bool found = getDefinitionFile(extruder_train_ids[extruder_nr], definition_file); if (!found) { logError("Couldn't find extruder.def.json file for extruder %i.\n", extruder_nr); return -1; } bool warn_base_file_duplicates = false; return loadJSONsettings(definition_file, settings_base, warn_base_file_duplicates); } int SettingRegistry::loadJSONsettings(std::string filename, SettingsBase* settings_base, bool warn_base_file_duplicates) { rapidjson::Document json_document; log("Loading %s...\n", filename.c_str()); int err = loadJSON(filename, json_document); if (err) { return err; } { // add parent folder to search paths char filename_cstr[filename.size()]; std::strcpy(filename_cstr, filename.c_str()); // copy the string because dirname(.) changes the input string!!! std::string folder_name = std::string(dirname(filename_cstr)); search_paths.emplace(folder_name); } if (json_document.HasMember("inherits") && json_document["inherits"].IsString()) { std::string child_filename; bool found = getDefinitionFile(json_document["inherits"].GetString(), child_filename); if (!found) { cura::logError("Inherited JSON file \"%s\" not found\n", json_document["inherits"].GetString()); return -1; } err = loadJSONsettings(child_filename, settings_base, warn_base_file_duplicates); // load child first if (err) { return err; } err = loadJSONsettingsFromDoc(json_document, settings_base, false); } else { err = loadJSONsettingsFromDoc(json_document, settings_base, warn_base_file_duplicates); } if (json_document.HasMember("metadata") && json_document["metadata"].IsObject()) { const rapidjson::Value& json_metadata = json_document["metadata"]; if (json_metadata.HasMember("machine_extruder_trains") && json_metadata["machine_extruder_trains"].IsObject()) { const rapidjson::Value& json_machine_extruder_trains = json_metadata["machine_extruder_trains"]; for (rapidjson::Value::ConstMemberIterator extr_train_iterator = json_machine_extruder_trains.MemberBegin(); extr_train_iterator != json_machine_extruder_trains.MemberEnd(); ++extr_train_iterator) { int extruder_train_nr = atoi(extr_train_iterator->name.GetString()); if (extruder_train_nr < 0) { continue; } const rapidjson::Value& json_id = extr_train_iterator->value; if (!json_id.IsString()) { continue; } const char* id = json_id.GetString(); if (extruder_train_nr >= (int) extruder_train_ids.size()) { extruder_train_ids.resize(extruder_train_nr + 1); } extruder_train_ids[extruder_train_nr] = std::string(id); } } } return err; } int SettingRegistry::loadJSONsettingsFromDoc(rapidjson::Document& json_document, SettingsBase* settings_base, bool warn_duplicates) { if (!json_document.IsObject()) { cura::logError("JSON file is not an object.\n"); return 3; } if (json_document.HasMember("settings")) { std::list<std::string> path; handleChildren(json_document["settings"], path, settings_base, warn_duplicates); } if (json_document.HasMember("overrides")) { const rapidjson::Value& json_object_container = json_document["overrides"]; for (rapidjson::Value::ConstMemberIterator override_iterator = json_object_container.MemberBegin(); override_iterator != json_object_container.MemberEnd(); ++override_iterator) { std::string setting = override_iterator->name.GetString(); SettingConfig* conf = getSettingConfig(setting); if (!conf) //Setting could not be found. { logWarning("Trying to override unknown setting %s.\n", setting.c_str()); continue; } _loadSettingValues(conf, override_iterator, settings_base); } } return 0; } void SettingRegistry::handleChildren(const rapidjson::Value& settings_list, std::list<std::string>& path, SettingsBase* settings_base, bool warn_duplicates) { if (!settings_list.IsObject()) { logError("json settings list is not an object!\n"); return; } for (rapidjson::Value::ConstMemberIterator setting_iterator = settings_list.MemberBegin(); setting_iterator != settings_list.MemberEnd(); ++setting_iterator) { handleSetting(setting_iterator, path, settings_base, warn_duplicates); if (setting_iterator->value.HasMember("children")) { std::list<std::string> path_here = path; path_here.push_back(setting_iterator->name.GetString()); handleChildren(setting_iterator->value["children"], path_here, settings_base, warn_duplicates); } } } bool SettingRegistry::settingIsUsedByEngine(const rapidjson::Value& setting) { if (setting.HasMember("children")) { return false; } else { return true; } } void SettingRegistry::handleSetting(const rapidjson::Value::ConstMemberIterator& json_setting_it, std::list<std::string>& path, SettingsBase* settings_base, bool warn_duplicates) { const rapidjson::Value& json_setting = json_setting_it->value; if (!json_setting.IsObject()) { logError("json setting is not an object!\n"); return; } std::string name = json_setting_it->name.GetString(); if (json_setting.HasMember("type") && json_setting["type"].IsString() && json_setting["type"].GetString() == std::string("category")) { // skip category objects setting_key_to_config[name] = nullptr; // add the category name to the mapping, but don't instantiate a setting config for it. return; } if (settingIsUsedByEngine(json_setting)) { if (!json_setting.HasMember("label") || !json_setting["label"].IsString()) { logError("json setting \"%s\" has no label!\n", name.c_str()); return; } std::string label = json_setting["label"].GetString(); SettingConfig* setting = getSettingConfig(name); if (warn_duplicates && setting) { cura::logWarning("Duplicate definition of setting: %s a.k.a. \"%s\" was already claimed by \"%s\"\n", name.c_str(), label.c_str(), getSettingConfig(name)->getLabel().c_str()); } if (!setting) { setting = &addSetting(name, label); } _loadSettingValues(setting, json_setting_it, settings_base); } else { setting_key_to_config[name] = nullptr; // add the setting name to the mapping, but don't instantiate a setting config for it. } } SettingConfig& SettingRegistry::addSetting(std::string name, std::string label) { SettingConfig* config = setting_definitions.addChild(name, label); setting_key_to_config[name] = config; return *config; } void SettingRegistry::loadDefault(const rapidjson::GenericValue< rapidjson::UTF8< char > >::ConstMemberIterator& json_object_it, SettingConfig* config) { const rapidjson::Value& setting_content = json_object_it->value; if (setting_content.HasMember("default_value")) { const rapidjson::Value& dflt = setting_content["default_value"]; if (dflt.IsString()) { config->setDefault(dflt.GetString()); } else if (dflt.IsTrue()) { config->setDefault("true"); } else if (dflt.IsFalse()) { config->setDefault("false"); } else if (dflt.IsNumber()) { std::ostringstream ss; ss << dflt.GetDouble(); config->setDefault(ss.str()); } // arrays are ignored because machine_extruder_trains needs to be handled separately else { logWarning("WARNING: Unrecognized data type in JSON: %s has type %s\n", json_object_it->name.GetString(), toString(dflt.GetType()).c_str()); } } } void SettingRegistry::_loadSettingValues(SettingConfig* config, const rapidjson::GenericValue< rapidjson::UTF8< char > >::ConstMemberIterator& json_object_it, SettingsBase* settings_base) { const rapidjson::Value& data = json_object_it->value; /// Fill the setting config object with data we have in the json file. if (data.HasMember("type") && data["type"].IsString()) { config->setType(data["type"].GetString()); } if (config->getType() == std::string("polygon") || config->getType() == std::string("polygons")) { // skip polygon settings : not implemented yet and not used yet (TODO) // logWarning("WARNING: Loading polygon setting %s not implemented...\n", json_object_it->name.GetString()); return; } loadDefault(json_object_it, config); if (data.HasMember("unit") && data["unit"].IsString()) { config->setUnit(data["unit"].GetString()); } settings_base->_setSetting(config->getKey(), config->getDefaultValue()); } }//namespace cura <|endoftext|>
<commit_before>#include "command.hh" #include "common-args.hh" #include "shared.hh" #include "eval.hh" #include "flake/flake.hh" #include "store-api.hh" #include "fetchers.hh" #include "registry.hh" using namespace nix; using namespace nix::flake; struct CmdRegistryList : StoreCommand { std::string description() override { return "list available Nix flakes"; } void run(nix::ref<nix::Store> store) override { using namespace fetchers; auto registries = getRegistries(store); for (auto & registry : registries) { for (auto & entry : registry->entries) { // FIXME: format nicely logger->stdout("%s %s %s", registry->type == Registry::Flag ? "flags " : registry->type == Registry::User ? "user " : registry->type == Registry::System ? "system" : "global", entry.from.to_string(), entry.to.to_string()); } } } }; struct CmdRegistryAdd : MixEvalArgs, Command { std::string fromUrl, toUrl; std::string description() override { return "add/replace flake in user flake registry"; } CmdRegistryAdd() { expectArg("from-url", &fromUrl); expectArg("to-url", &toUrl); } void run() override { auto fromRef = parseFlakeRef(fromUrl); auto toRef = parseFlakeRef(toUrl); fetchers::Attrs extraAttrs; if (toRef.subdir != "") extraAttrs["dir"] = toRef.subdir; auto userRegistry = fetchers::getUserRegistry(); userRegistry->remove(fromRef.input); userRegistry->add(fromRef.input, toRef.input, extraAttrs); userRegistry->write(fetchers::getUserRegistryPath()); } }; struct CmdRegistryRemove : virtual Args, MixEvalArgs, Command { std::string url; std::string description() override { return "remove flake from user flake registry"; } CmdRegistryRemove() { expectArg("url", &url); } void run() override { auto userRegistry = fetchers::getUserRegistry(); userRegistry->remove(parseFlakeRef(url).input); userRegistry->write(fetchers::getUserRegistryPath()); } }; struct CmdRegistryPin : virtual Args, EvalCommand { std::string url; std::string description() override { return "pin a flake to its current version in user flake registry"; } CmdRegistryPin() { expectArg("url", &url); } void run(nix::ref<nix::Store> store) override { auto ref = parseFlakeRef(url); auto userRegistry = fetchers::getUserRegistry(); userRegistry->remove(ref.input); auto [tree, resolved] = ref.resolve(store).input.fetch(store); fetchers::Attrs extraAttrs; if (ref.subdir != "") extraAttrs["dir"] = ref.subdir; userRegistry->add(ref.input, resolved, extraAttrs); } }; struct CmdRegistry : virtual MultiCommand, virtual Command { CmdRegistry() : MultiCommand({ {"list", []() { return make_ref<CmdRegistryList>(); }}, {"add", []() { return make_ref<CmdRegistryAdd>(); }}, {"remove", []() { return make_ref<CmdRegistryRemove>(); }}, {"pin", []() { return make_ref<CmdRegistryPin>(); }}, }) { } std::string description() override { return "manage the flake registry"; } Category category() override { return catSecondary; } void run() override { if (!command) throw UsageError("'nix registry' requires a sub-command."); command->second->prepare(); command->second->run(); } void printHelp(const string & programName, std::ostream & out) override { MultiCommand::printHelp(programName, out); } }; static auto r1 = registerCommand<CmdRegistry>("registry"); <commit_msg>Save changes made by "nix registry pin" to user registry<commit_after>#include "command.hh" #include "common-args.hh" #include "shared.hh" #include "eval.hh" #include "flake/flake.hh" #include "store-api.hh" #include "fetchers.hh" #include "registry.hh" using namespace nix; using namespace nix::flake; struct CmdRegistryList : StoreCommand { std::string description() override { return "list available Nix flakes"; } void run(nix::ref<nix::Store> store) override { using namespace fetchers; auto registries = getRegistries(store); for (auto & registry : registries) { for (auto & entry : registry->entries) { // FIXME: format nicely logger->stdout("%s %s %s", registry->type == Registry::Flag ? "flags " : registry->type == Registry::User ? "user " : registry->type == Registry::System ? "system" : "global", entry.from.to_string(), entry.to.to_string()); } } } }; struct CmdRegistryAdd : MixEvalArgs, Command { std::string fromUrl, toUrl; std::string description() override { return "add/replace flake in user flake registry"; } CmdRegistryAdd() { expectArg("from-url", &fromUrl); expectArg("to-url", &toUrl); } void run() override { auto fromRef = parseFlakeRef(fromUrl); auto toRef = parseFlakeRef(toUrl); fetchers::Attrs extraAttrs; if (toRef.subdir != "") extraAttrs["dir"] = toRef.subdir; auto userRegistry = fetchers::getUserRegistry(); userRegistry->remove(fromRef.input); userRegistry->add(fromRef.input, toRef.input, extraAttrs); userRegistry->write(fetchers::getUserRegistryPath()); } }; struct CmdRegistryRemove : virtual Args, MixEvalArgs, Command { std::string url; std::string description() override { return "remove flake from user flake registry"; } CmdRegistryRemove() { expectArg("url", &url); } void run() override { auto userRegistry = fetchers::getUserRegistry(); userRegistry->remove(parseFlakeRef(url).input); userRegistry->write(fetchers::getUserRegistryPath()); } }; struct CmdRegistryPin : virtual Args, EvalCommand { std::string url; std::string description() override { return "pin a flake to its current version in user flake registry"; } CmdRegistryPin() { expectArg("url", &url); } void run(nix::ref<nix::Store> store) override { auto ref = parseFlakeRef(url); auto userRegistry = fetchers::getUserRegistry(); userRegistry->remove(ref.input); auto [tree, resolved] = ref.resolve(store).input.fetch(store); fetchers::Attrs extraAttrs; if (ref.subdir != "") extraAttrs["dir"] = ref.subdir; userRegistry->add(ref.input, resolved, extraAttrs); userRegistry->write(fetchers::getUserRegistryPath()); } }; struct CmdRegistry : virtual MultiCommand, virtual Command { CmdRegistry() : MultiCommand({ {"list", []() { return make_ref<CmdRegistryList>(); }}, {"add", []() { return make_ref<CmdRegistryAdd>(); }}, {"remove", []() { return make_ref<CmdRegistryRemove>(); }}, {"pin", []() { return make_ref<CmdRegistryPin>(); }}, }) { } std::string description() override { return "manage the flake registry"; } Category category() override { return catSecondary; } void run() override { if (!command) throw UsageError("'nix registry' requires a sub-command."); command->second->prepare(); command->second->run(); } void printHelp(const string & programName, std::ostream & out) override { MultiCommand::printHelp(programName, out); } }; static auto r1 = registerCommand<CmdRegistry>("registry"); <|endoftext|>
<commit_before>#include "OSMC_driver.hpp" #include <algorithm> const int OSMC_driver::_max_speed_ = 130; const int OSMC_driver::MINREQSPEED = 30; OSMC_driver::OSMC_driver() { lvgoal = 0; rvgoal = 0; m_connected = false; encoder = NULL; #ifndef MOTOR_SIMULATE ai.initLink(OSMC_IF_BOARD); encoder = new quadCoderDriver(); #endif m_connected = true; set_motors(0, 0); } OSMC_driver::OSMC_driver(byte motor_iface, byte encoder_iface) { lvgoal = 0; rvgoal = 0; m_connected = false; encoder = NULL; #ifndef MOTOR_SIMULATE ai.initLink(motor_iface); encoder = new quadCoderDriver(encoder_iface); #endif m_connected = true; set_motors(0, 0); } OSMC_driver::~OSMC_driver() { delete encoder; } #if 0 OSMC_driver::connect() { ai.initLink(OSMC_IF_BOARD); m_connected = true; } #endif bool OSMC_driver::getEncoderData(new_encoder_pk_t& pk) { return encoder->getEncoderState(pk); } bool OSMC_driver::getEncoderVel(double& rvel, double& lvel) { return encoder->getEncoderVel(rvel, lvel); } current_reply_t OSMC_driver::getCurrentData() { ai.sendCommand(MC_GET_RL_CURR_VAL, NULL, 0); byte retcmd = 0; byte* data = NULL; ai.recvCommand(retcmd, data); current_reply_t out; memcpy(&out, data, sizeof(current_reply_t)); delete[] data; return out; } bool OSMC_driver::set_motors(int leftVelocity, int rightVelocity) { byte leftDutyCycle = std::min(abs(leftVelocity), 255); byte leftDir = (leftVelocity < 0) ? MC_MOTOR_REVERSE : MC_MOTOR_FORWARD; byte rightDutyCycle = std::min(abs(rightVelocity), 255); byte rightDir = (rightVelocity < 0) ? MC_MOTOR_REVERSE : MC_MOTOR_FORWARD; return setmotorPWM(rightDir, rightDutyCycle, leftDir, leftDutyCycle); } int OSMC_driver::set_heading(int iFwdVelocity, int iRotation) { // convert int left = iFwdVelocity + iRotation ; int right = iFwdVelocity - iRotation ; if (true) { // scale speed left = int( float(left) * float(_max_speed_) / float(255) ) ; right = int( float(right) * float(_max_speed_) / float(255) ) ; } else { // cap speed if (left > _max_speed_) left = _max_speed_ ; if (right > _max_speed_) right = _max_speed_ ; } // motors don't respond until certain output is reached if (right != 0) right += MINREQSPEED ; if (left != 0) left += MINREQSPEED ; // do it! return this->set_motors( left , right ); } #ifndef MOTOR_SIMULATE bool OSMC_driver::setmotorPWM(byte rightDir, byte rightDutyCycle, byte leftDir, byte leftDutyCycle) { speed_set_t cmdpk; cmdpk.sr = rightDutyCycle; cmdpk.rightDir = rightDir; cmdpk.sl = leftDutyCycle; cmdpk.leftDir = leftDir; std::cout << "r: " << (int)rightDutyCycle << "l: " << (int)leftDutyCycle << std::endl; if(ai.sendCommand(MC_SET_RL_DUTY_CYCLE, &cmdpk, sizeof(speed_set_t))) { return true; } byte cmdresp; byte* data = NULL; if(ai.recvCommand(cmdresp, data)) { return true; } if(data != NULL) { delete[] data; } ldir = leftDir; lpwm = leftDutyCycle; rdir = rightDir; rpwm = rightDutyCycle; return false; } #else bool OSMC_driver::setmotorPWM(byte rightDir, byte rightDutyCycle, byte leftDir, byte leftDutyCycle) { int sr = (rightDir == MC_MOTOR_FORWARD) ? int(rightDutyCycle) : -int(rightDutyCycle); int sl = (leftDir == MC_MOTOR_FORWARD) ? int(leftDutyCycle) : -int(leftDutyCycle); std::cout << "right: " << sr << "\tleft: " << sl << std::endl; if((rightDir == MC_MOTOR_REVERSE) || (leftDir == MC_MOTOR_REVERSE)) { //atach dbg here std::cout << "robot is moving backwards!!!" << std::endl; } return false; } #endif joystick_reply_t OSMC_driver::getJoystickData() { ai.sendCommand(MC_GET_JOYSTICK, NULL, 0); byte retcmd = 0; byte* data = NULL; ai.recvCommand(retcmd, data); joystick_reply_t out; memcpy(&out, data, sizeof(current_reply_t)); delete[] data; return out; } // start dumb + hysteresis control code void OSMC_driver::getNewVel_dumb(const double rtarget, const double ltarget, const double rvel, const double lvel, const int rmset, const int lmset, int& out_rmset, int& out_lmset) { int posstep = 1; int negstep = -1; double thresh = .03; double lerror = ltarget - lvel; double rerror = rtarget - rvel; if(lerror > thresh) { out_lmset = lmset + posstep; } else if(lerror < -thresh) { out_lmset = lmset + negstep; } else { out_lmset = lmset; } if(rerror > thresh) { out_rmset = rmset + posstep; } else if(rerror < -thresh) { out_rmset = rmset + negstep; } else { out_rmset = rmset; } } void OSMC_driver::setVel_pd(double left, double right) { lvgoal = left; rvgoal = right; } bool OSMC_driver::updateVel_pd() { double now_rvel, now_lvel; timeval now_t; gettimeofday(&now_t, NULL); encoder->getEncoderVel(now_rvel, now_lvel); double now_t_d = double(now_t.tv_sec) + double(1e-6)*double(now_t.tv_usec); double dt = now_t_d - t; int out_lmset, out_rmset; getNewVel_pd(now_lvel, now_rvel, dt, out_rmset, out_lmset); t = now_t_d; return set_motors(out_lmset, out_rmset); } void OSMC_driver::getNewVel_pd(const double now_lvel, const double now_rvel, const double dt, int& out_r, int& out_l) { const double kp = .1; const double kd = .1; double lerror = lvgoal - now_lvel; double rerror = rvgoal - now_rvel; double lerror_slope = (lerror - last_l_error) / dt; double rerror_slope = (rerror - last_r_error) / dt; out_l = -kp*lerror + -kd*lerror_slope; out_r = -kp*rerror + -kd*rerror_slope; //persist the stuff that needs to be saved last_l_error = lerror; last_r_error = rerror; } void OSMC_driver::getLastPWMSent(byte& r, byte& l) { r = rpwm; l = lpwm; } <commit_msg><commit_after>#include "OSMC_driver.hpp" #include <algorithm> const int OSMC_driver::_max_speed_ = 130; const int OSMC_driver::MINREQSPEED = 30; OSMC_driver::OSMC_driver() { lvgoal = 0; rvgoal = 0; m_connected = false; encoder = NULL; #ifndef MOTOR_SIMULATE ai.initLink(OSMC_IF_BOARD); encoder = new quadCoderDriver(); #endif m_connected = true; set_motors(0, 0); } OSMC_driver::OSMC_driver(byte motor_iface, byte encoder_iface) { lvgoal = 0; rvgoal = 0; m_connected = false; encoder = NULL; #ifndef MOTOR_SIMULATE ai.initLink(motor_iface); encoder = new quadCoderDriver(encoder_iface); #endif m_connected = true; set_motors(0, 0); } OSMC_driver::~OSMC_driver() { delete encoder; } #if 0 OSMC_driver::connect() { ai.initLink(OSMC_IF_BOARD); m_connected = true; } #endif bool OSMC_driver::getEncoderData(new_encoder_pk_t& pk) { return encoder->getEncoderState(pk); } bool OSMC_driver::getEncoderVel(double& rvel, double& lvel) { return encoder->getEncoderVel(rvel, lvel); } current_reply_t OSMC_driver::getCurrentData() { ai.sendCommand(MC_GET_RL_CURR_VAL, NULL, 0); byte retcmd = 0; byte* data = NULL; ai.recvCommand(retcmd, data); current_reply_t out; memcpy(&out, data, sizeof(current_reply_t)); delete[] data; return out; } bool OSMC_driver::set_motors(int leftVelocity, int rightVelocity) { byte leftDutyCycle = std::min(abs(leftVelocity), 255); byte leftDir = (leftVelocity < 0) ? MC_MOTOR_REVERSE : MC_MOTOR_FORWARD; byte rightDutyCycle = std::min(abs(rightVelocity), 255); byte rightDir = (rightVelocity < 0) ? MC_MOTOR_REVERSE : MC_MOTOR_FORWARD; return setmotorPWM(rightDir, rightDutyCycle, leftDir, leftDutyCycle); } int OSMC_driver::set_heading(int iFwdVelocity, int iRotation) { // convert int left = iFwdVelocity + iRotation ; int right = iFwdVelocity - iRotation ; if (true) { // scale speed left = int( float(left) * float(_max_speed_) / float(255) ) ; right = int( float(right) * float(_max_speed_) / float(255) ) ; } else { // cap speed if (left > _max_speed_) left = _max_speed_ ; if (right > _max_speed_) right = _max_speed_ ; } // motors don't respond until certain output is reached if (right != 0) right += MINREQSPEED ; if (left != 0) left += MINREQSPEED ; // do it! return this->set_motors( left , right ); } #ifndef MOTOR_SIMULATE bool OSMC_driver::setmotorPWM(byte rightDir, byte rightDutyCycle, byte leftDir, byte leftDutyCycle) { speed_set_t cmdpk; cmdpk.sr = rightDutyCycle; cmdpk.rightDir = rightDir; cmdpk.sl = leftDutyCycle; cmdpk.leftDir = leftDir; std::cout << "r: " << (int)rightDutyCycle << "l: " << (int)leftDutyCycle << std::endl; if(ai.sendCommand(MC_SET_RL_DUTY_CYCLE, &cmdpk, sizeof(speed_set_t))) { return true; } byte cmdresp; byte* data = NULL; if(ai.recvCommand(cmdresp, data)) { return true; } if(data != NULL) { delete[] data; } ldir = leftDir; lpwm = leftDutyCycle; rdir = rightDir; rpwm = rightDutyCycle; return false; } #else bool OSMC_driver::setmotorPWM(byte rightDir, byte rightDutyCycle, byte leftDir, byte leftDutyCycle) { int sr = (rightDir == MC_MOTOR_FORWARD) ? int(rightDutyCycle) : -int(rightDutyCycle); int sl = (leftDir == MC_MOTOR_FORWARD) ? int(leftDutyCycle) : -int(leftDutyCycle); std::cout << "right: " << sr << "\tleft: " << sl << std::endl; if((rightDir == MC_MOTOR_REVERSE) || (leftDir == MC_MOTOR_REVERSE)) { //atach dbg here std::cout << "robot is moving backwards!!!" << std::endl; } return false; } #endif joystick_reply_t OSMC_driver::getJoystickData() { ai.sendCommand(MC_GET_JOYSTICK, NULL, 0); byte retcmd = 0; byte* data = NULL; ai.recvCommand(retcmd, data); joystick_reply_t out; memcpy(&out, data, sizeof(current_reply_t)); delete[] data; return out; } // start dumb + hysteresis control code void OSMC_driver::getNewVel_dumb(const double rtarget, const double ltarget, const double rvel, const double lvel, const int rmset, const int lmset, int& out_rmset, int& out_lmset) { int posstep = 1; int negstep = -1; double thresh = .03; double lerror = ltarget - lvel; double rerror = rtarget - rvel; if(lerror > thresh) { out_lmset = lmset + posstep; } else if(lerror < -thresh) { out_lmset = lmset + negstep; } else { out_lmset = lmset; } if(rerror > thresh) { out_rmset = rmset + posstep; } else if(rerror < -thresh) { out_rmset = rmset + negstep; } else { out_rmset = rmset; } } void OSMC_driver::setVel_pd(double left, double right) { lvgoal = left; rvgoal = right; } bool OSMC_driver::updateVel_pd() { double now_rvel, now_lvel; timeval now_t; gettimeofday(&now_t, NULL); encoder->getEncoderVel(now_rvel, now_lvel); double now_t_d = double(now_t.tv_sec) + double(1e-6)*double(now_t.tv_usec); double dt = now_t_d - t; int out_lmset, out_rmset; getNewVel_pd(now_lvel, now_rvel, dt, out_rmset, out_lmset); t = now_t_d; return set_motors(out_lmset, out_rmset); } //this won't change the sign of the pwm freq void OSMC_driver::getNewVel_pd(const double now_lvel, const double now_rvel, const double dt, int& out_r, int& out_l) { const double kp = .1; const double kd = .1; double lerror = lvgoal - now_lvel; double rerror = rvgoal - now_rvel; double lerror_slope = (lerror - last_l_error) / dt; double rerror_slope = (rerror - last_r_error) / dt; out_l = lpwm + -kp*lerror + -kd*lerror_slope; out_r = rpwm + -kp*rerror + -kd*rerror_slope; //persist the stuff that needs to be saved last_l_error = lerror; last_r_error = rerror; } void OSMC_driver::getLastPWMSent(byte& r, byte& l) { r = rpwm; l = lpwm; } <|endoftext|>
<commit_before>#include "CollisionSkeleton.h" #include "CollisionShapes.h" #include "kinematics/Shape.h" #include <cmath> #include "utils/LoadOpengl.h" #include "utils/UtilsMath.h" using namespace std; using namespace Eigen; using namespace utils; namespace collision_checking{ CollisionSkeletonNode::CollisionSkeletonNode(kinematics::BodyNode* _bodyNode) { mBodyNode = _bodyNode; if (mBodyNode->getShape()->getShapeType() == kinematics::Shape::P_ELLIPSOID) { mMesh = createEllipsoid<fcl::RSS>(mBodyNode->getShape()->getDim()[0], mBodyNode->getShape()->getDim()[1], mBodyNode->getShape()->getDim()[2]); } else if (mBodyNode->getShape()->getShapeType() == kinematics::Shape::P_CUBE) { mMesh = createCube<fcl::RSS>(mBodyNode->getShape()->getDim()[0], mBodyNode->getShape()->getDim()[1], mBodyNode->getShape()->getDim()[2]); } else { mMesh = createMesh<fcl::RSS>(mBodyNode->getShape()->getDim()[0], mBodyNode->getShape()->getDim()[1], mBodyNode->getShape()->getDim()[2], _bodyNode->getShape()->getVizMesh()); } } CollisionSkeletonNode::~CollisionSkeletonNode() { delete mMesh; } int CollisionSkeletonNode::checkCollision(CollisionSkeletonNode* _otherNode, vector<ContactPoint>& _result, int _num_max_contact) { evalRT(); _otherNode->evalRT(); fcl::CollisionResult res; fcl::CollisionRequest req; req.num_max_contacts = _num_max_contact; fcl::collide(mMesh, mFclWorldTrans, _otherNode->mMesh, _otherNode->mFclWorldTrans, req, res); int start, size; start = _result.size(); size = 0; int numCoplanarContacts = 0; int numNoContacts = 0; int numContacts = 0; for(int i = 0; i < res.numContacts();i++) { // for each pair of intersecting triangles, we create two contact points ContactPoint pair1, pair2; pair1.bd1 = mBodyNode; pair1.bd2 = _otherNode->mBodyNode; pair1.bdID1 = this->mBodynodeID; pair1.bdID2 = _otherNode->mBodynodeID; pair1.collisionSkeletonNode1 = this; pair1.collisionSkeletonNode2 = _otherNode; fcl::Vec3f v; pair1.triID1 = res.getContact(i).b1; pair1.triID2 = res.getContact(i).b2; pair1.penetrationDepth = res.getContact(i).penetration_depth; pair2 = pair1; int contactResult = evalContactPosition(res, _otherNode, i, pair1.point, pair2.point, pair1.contactTri); pair2.contactTri = pair1.contactTri; if(contactResult == COPLANAR_CONTACT) { numCoplanarContacts++; // if(numContacts != 0 || numCoplanarContacts > 1) if (numContacts > 2) continue; } else if(contactResult == NO_CONTACT) { numNoContacts++; continue; } else { numContacts++; } v = res.getContact(i).normal; pair1.normal = Vector3d(v[0], v[1], v[2]); pair2.normal = Vector3d(v[0], v[1], v[2]); _result.push_back(pair1); _result.push_back(pair2); size+=2; } if(res.numContacts()==0) return 0; const double ZERO = 0.000001; const double ZERO2 = ZERO*ZERO; vector<int> deleteIDs; size = _result.size() - start; deleteIDs.clear(); // mark all the repeated points for (int i = start; i < start + size; i++) for (int j = i + 1; j < start + size; j++) { Vector3d diff = _result[i].point - _result[j].point; if (diff.dot(diff) < 3 * ZERO2) { deleteIDs.push_back(i); break; } } // delete repeated points for (int i = deleteIDs.size() - 1; i >= 0; i--) _result.erase(_result.begin() + deleteIDs[i]); size = _result.size() - start; deleteIDs.clear(); // remove all the co-linear contact points bool bremove; for (int i = start; i < start + size; i++) { bremove = false; for (int j = start; j < start + size; j++) { if (j == i) continue; if (bremove) break; for (int k = j + 1; k < start + size; k++) { if (i == k) continue; Vector3d v = (_result[i].point - _result[j].point).cross(_result[i].point - _result[k].point); if (v.dot(v) < ZERO2 && ((_result[i].point - _result[j].point).dot(_result[i].point - _result[k].point) < 0)) { bremove = true; break; } } } if (bremove) deleteIDs.push_back(i); } for (int i = deleteIDs.size() - 1; i >= 0; i--) _result.erase(_result.begin() + deleteIDs[i]); int collisionNum = res.numContacts(); //return numCoplanarContacts*100+numNoContacts; return collisionNum; } void CollisionSkeletonNode::evalRT() { Vector3d p = mBodyNode->getWorldCOM(); mWorldTrans = mBodyNode->getWorldTransform(); mWorldTrans.col(3).topRows(3) = p; mFclWorldTrans = fcl::Transform3f(fcl::Matrix3f(mWorldTrans(0,0), mWorldTrans(0,1), mWorldTrans(0,2), mWorldTrans(1,0), mWorldTrans(1,1), mWorldTrans(1,2), mWorldTrans(2,0), mWorldTrans(2,1), mWorldTrans(2,2)), fcl::Vec3f(p[0], p[1], p[2])); } int CollisionSkeletonNode::evalContactPosition(fcl::CollisionResult& _result, CollisionSkeletonNode* _other, int _idx, Vector3d& _contactPosition1, Vector3d& _contactPosition2, ContactTriangle& _contactTri ) { int id1, id2; fcl::Triangle tri1, tri2; CollisionSkeletonNode* node1 = this; CollisionSkeletonNode* node2 = _other; id1 = _result.getContact(_idx).b1; id2 = _result.getContact(_idx).b2; tri1 = node1->mMesh->tri_indices[id1]; tri2 = node2->mMesh->tri_indices[id2]; fcl::Vec3f v1, v2, v3, p1, p2, p3; v1 = node1->mMesh->vertices[tri1[0]]; v2 = node1->mMesh->vertices[tri1[1]]; v3 = node1->mMesh->vertices[tri1[2]]; p1 = node2->mMesh->vertices[tri2[0]]; p2 = node2->mMesh->vertices[tri2[1]]; p3 = node2->mMesh->vertices[tri2[2]]; fcl::Vec3f contact1, contact2; v1 = node1->TransformVertex(v1); v2 = node1->TransformVertex(v2); v3 = node1->TransformVertex(v3); p1 = node2->TransformVertex(p1); p2 = node2->TransformVertex(p2); p3 = node2->TransformVertex(p3); int testRes = FFtest(v1, v2, v3, p1, p2, p3, contact1, contact2); _contactTri.v1 = v1; _contactTri.v2 = v2; _contactTri.v3 = v3; _contactTri.u1 = p1; _contactTri.u2 = p2; _contactTri.u3 = p3; if (testRes == COPLANAR_CONTACT) { double area1 = triArea(v1, v2, v3); double area2 = triArea(p1, p2, p3); // cout << "this node = " << this->mBodynodeID << " other node = " << _other->mBodynodeID << endl; if (area1 < area2) contact1 = v1 + v2 + v3; else contact1 = p1 + p2 + p3; contact1[0] /= 3.0; contact1[1] /= 3.0; contact1[2] /= 3.0; contact2 = contact1; // cout << contact1[0] << " " << contact1[1] << " " << contact1[2] << endl; } _contactPosition1 = Vector3d(contact1[0], contact1[1], contact1[2]); _contactPosition2 = Vector3d(contact2[0], contact2[1], contact2[2]); return testRes; } void CollisionSkeletonNode::drawCollisionTriangle(int _tri) { fcl::Triangle Tri = mMesh->tri_indices[_tri]; glVertex3f(mMesh->vertices[Tri[0]][0], mMesh->vertices[Tri[0]][1], mMesh->vertices[Tri[0]][2]); glVertex3f(mMesh->vertices[Tri[1]][0], mMesh->vertices[Tri[1]][1], mMesh->vertices[Tri[1]][2]); glVertex3f(mMesh->vertices[Tri[2]][0], mMesh->vertices[Tri[2]][1], mMesh->vertices[Tri[2]][2]); } void CollisionSkeletonNode::drawCollisionSkeletonNode(bool _bTrans) { evalRT(); double M[16]; for(int i=0;i<4;i++) for(int j=0;j<4;j++) M[j*4+i] = mWorldTrans(i, j); fcl::Vec3f v1, v2, v3; glPushMatrix(); if(_bTrans) glMultMatrixd(M); glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); glBegin(GL_TRIANGLES); for(int i = 0;i < mMesh->num_tris; i++) { fcl::Triangle tri = mMesh->tri_indices[i]; glVertex3f(mMesh->vertices[tri[0]][0], mMesh->vertices[tri[0]][1], mMesh->vertices[tri[0]][2]); glVertex3f(mMesh->vertices[tri[1]][0], mMesh->vertices[tri[1]][1], mMesh->vertices[tri[1]][2]); glVertex3f(mMesh->vertices[tri[2]][0], mMesh->vertices[tri[2]][1], mMesh->vertices[tri[2]][2]); } glEnd(); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glPopMatrix(); } SkeletonCollision::~SkeletonCollision() { for(int i=0;i<mCollisionSkeletonNodeList.size();i++) delete mCollisionSkeletonNodeList[i]; } void SkeletonCollision::addCollisionSkeletonNode(kinematics::BodyNode *_bd, bool _bRecursive) { if (_bRecursive == false || _bd->getNumChildJoints() == 0) { CollisionSkeletonNode* csnode = new CollisionSkeletonNode(_bd); csnode->mBodynodeID = mCollisionSkeletonNodeList.size(); mCollisionSkeletonNodeList.push_back(csnode); mBodyNodeHash[_bd] = csnode; } else { addCollisionSkeletonNode(_bd, false); for (int i = 0; i < _bd->getNumChildJoints(); i++) addCollisionSkeletonNode(_bd->getChildNode(i), true); } } void SkeletonCollision::checkCollision(bool bConsiderGround) { int num_max_contact = 100; clearAllContacts(); int numCollision = 0; for (int i = 0; i < mCollisionSkeletonNodeList.size(); i++) { for (int j = i + 1; j < mCollisionSkeletonNodeList.size(); j++) { if (mCollisionSkeletonNodeList[i]->mBodyNode->getParentNode() == mCollisionSkeletonNodeList[j]->mBodyNode || mCollisionSkeletonNodeList[j]->mBodyNode->getParentNode() == mCollisionSkeletonNodeList[i]->mBodyNode) continue; if (mCollisionSkeletonNodeList[i]->mBodyNode->getSkel() == mCollisionSkeletonNodeList[j]->mBodyNode->getSkel()) continue; numCollision += mCollisionSkeletonNodeList[i]->checkCollision(mCollisionSkeletonNodeList[j], mContactPointList, num_max_contact); } } mNumTriIntersection = numCollision; } void SkeletonCollision::draw() { for(int i=0;i<mCollisionSkeletonNodeList.size();i++) mCollisionSkeletonNodeList[i]->drawCollisionSkeletonNode(); } } <commit_msg>Need to request contact information from FCL.<commit_after>#include "CollisionSkeleton.h" #include "CollisionShapes.h" #include "kinematics/Shape.h" #include <cmath> #include "utils/LoadOpengl.h" #include "utils/UtilsMath.h" using namespace std; using namespace Eigen; using namespace utils; namespace collision_checking{ CollisionSkeletonNode::CollisionSkeletonNode(kinematics::BodyNode* _bodyNode) { mBodyNode = _bodyNode; if (mBodyNode->getShape()->getShapeType() == kinematics::Shape::P_ELLIPSOID) { mMesh = createEllipsoid<fcl::RSS>(mBodyNode->getShape()->getDim()[0], mBodyNode->getShape()->getDim()[1], mBodyNode->getShape()->getDim()[2]); } else if (mBodyNode->getShape()->getShapeType() == kinematics::Shape::P_CUBE) { mMesh = createCube<fcl::RSS>(mBodyNode->getShape()->getDim()[0], mBodyNode->getShape()->getDim()[1], mBodyNode->getShape()->getDim()[2]); } else { mMesh = createMesh<fcl::RSS>(mBodyNode->getShape()->getDim()[0], mBodyNode->getShape()->getDim()[1], mBodyNode->getShape()->getDim()[2], _bodyNode->getShape()->getVizMesh()); } } CollisionSkeletonNode::~CollisionSkeletonNode() { delete mMesh; } int CollisionSkeletonNode::checkCollision(CollisionSkeletonNode* _otherNode, vector<ContactPoint>& _result, int _num_max_contact) { evalRT(); _otherNode->evalRT(); fcl::CollisionResult res; fcl::CollisionRequest req; req.enable_contact = true; req.num_max_contacts = _num_max_contact; fcl::collide(mMesh, mFclWorldTrans, _otherNode->mMesh, _otherNode->mFclWorldTrans, req, res); int start, size; start = _result.size(); size = 0; int numCoplanarContacts = 0; int numNoContacts = 0; int numContacts = 0; for(int i = 0; i < res.numContacts();i++) { // for each pair of intersecting triangles, we create two contact points ContactPoint pair1, pair2; pair1.bd1 = mBodyNode; pair1.bd2 = _otherNode->mBodyNode; pair1.bdID1 = this->mBodynodeID; pair1.bdID2 = _otherNode->mBodynodeID; pair1.collisionSkeletonNode1 = this; pair1.collisionSkeletonNode2 = _otherNode; fcl::Vec3f v; pair1.triID1 = res.getContact(i).b1; pair1.triID2 = res.getContact(i).b2; pair1.penetrationDepth = res.getContact(i).penetration_depth; pair2 = pair1; int contactResult = evalContactPosition(res, _otherNode, i, pair1.point, pair2.point, pair1.contactTri); pair2.contactTri = pair1.contactTri; if(contactResult == COPLANAR_CONTACT) { numCoplanarContacts++; // if(numContacts != 0 || numCoplanarContacts > 1) if (numContacts > 2) continue; } else if(contactResult == NO_CONTACT) { numNoContacts++; continue; } else { numContacts++; } v = res.getContact(i).normal; pair1.normal = Vector3d(v[0], v[1], v[2]); pair2.normal = Vector3d(v[0], v[1], v[2]); _result.push_back(pair1); _result.push_back(pair2); size+=2; } if(res.numContacts()==0) return 0; const double ZERO = 0.000001; const double ZERO2 = ZERO*ZERO; vector<int> deleteIDs; size = _result.size() - start; deleteIDs.clear(); // mark all the repeated points for (int i = start; i < start + size; i++) for (int j = i + 1; j < start + size; j++) { Vector3d diff = _result[i].point - _result[j].point; if (diff.dot(diff) < 3 * ZERO2) { deleteIDs.push_back(i); break; } } // delete repeated points for (int i = deleteIDs.size() - 1; i >= 0; i--) _result.erase(_result.begin() + deleteIDs[i]); size = _result.size() - start; deleteIDs.clear(); // remove all the co-linear contact points bool bremove; for (int i = start; i < start + size; i++) { bremove = false; for (int j = start; j < start + size; j++) { if (j == i) continue; if (bremove) break; for (int k = j + 1; k < start + size; k++) { if (i == k) continue; Vector3d v = (_result[i].point - _result[j].point).cross(_result[i].point - _result[k].point); if (v.dot(v) < ZERO2 && ((_result[i].point - _result[j].point).dot(_result[i].point - _result[k].point) < 0)) { bremove = true; break; } } } if (bremove) deleteIDs.push_back(i); } for (int i = deleteIDs.size() - 1; i >= 0; i--) _result.erase(_result.begin() + deleteIDs[i]); int collisionNum = res.numContacts(); //return numCoplanarContacts*100+numNoContacts; return collisionNum; } void CollisionSkeletonNode::evalRT() { Vector3d p = mBodyNode->getWorldCOM(); mWorldTrans = mBodyNode->getWorldTransform(); mWorldTrans.col(3).topRows(3) = p; mFclWorldTrans = fcl::Transform3f(fcl::Matrix3f(mWorldTrans(0,0), mWorldTrans(0,1), mWorldTrans(0,2), mWorldTrans(1,0), mWorldTrans(1,1), mWorldTrans(1,2), mWorldTrans(2,0), mWorldTrans(2,1), mWorldTrans(2,2)), fcl::Vec3f(p[0], p[1], p[2])); } int CollisionSkeletonNode::evalContactPosition(fcl::CollisionResult& _result, CollisionSkeletonNode* _other, int _idx, Vector3d& _contactPosition1, Vector3d& _contactPosition2, ContactTriangle& _contactTri ) { int id1, id2; fcl::Triangle tri1, tri2; CollisionSkeletonNode* node1 = this; CollisionSkeletonNode* node2 = _other; id1 = _result.getContact(_idx).b1; id2 = _result.getContact(_idx).b2; tri1 = node1->mMesh->tri_indices[id1]; tri2 = node2->mMesh->tri_indices[id2]; fcl::Vec3f v1, v2, v3, p1, p2, p3; v1 = node1->mMesh->vertices[tri1[0]]; v2 = node1->mMesh->vertices[tri1[1]]; v3 = node1->mMesh->vertices[tri1[2]]; p1 = node2->mMesh->vertices[tri2[0]]; p2 = node2->mMesh->vertices[tri2[1]]; p3 = node2->mMesh->vertices[tri2[2]]; fcl::Vec3f contact1, contact2; v1 = node1->TransformVertex(v1); v2 = node1->TransformVertex(v2); v3 = node1->TransformVertex(v3); p1 = node2->TransformVertex(p1); p2 = node2->TransformVertex(p2); p3 = node2->TransformVertex(p3); int testRes = FFtest(v1, v2, v3, p1, p2, p3, contact1, contact2); _contactTri.v1 = v1; _contactTri.v2 = v2; _contactTri.v3 = v3; _contactTri.u1 = p1; _contactTri.u2 = p2; _contactTri.u3 = p3; if (testRes == COPLANAR_CONTACT) { double area1 = triArea(v1, v2, v3); double area2 = triArea(p1, p2, p3); // cout << "this node = " << this->mBodynodeID << " other node = " << _other->mBodynodeID << endl; if (area1 < area2) contact1 = v1 + v2 + v3; else contact1 = p1 + p2 + p3; contact1[0] /= 3.0; contact1[1] /= 3.0; contact1[2] /= 3.0; contact2 = contact1; // cout << contact1[0] << " " << contact1[1] << " " << contact1[2] << endl; } _contactPosition1 = Vector3d(contact1[0], contact1[1], contact1[2]); _contactPosition2 = Vector3d(contact2[0], contact2[1], contact2[2]); return testRes; } void CollisionSkeletonNode::drawCollisionTriangle(int _tri) { fcl::Triangle Tri = mMesh->tri_indices[_tri]; glVertex3f(mMesh->vertices[Tri[0]][0], mMesh->vertices[Tri[0]][1], mMesh->vertices[Tri[0]][2]); glVertex3f(mMesh->vertices[Tri[1]][0], mMesh->vertices[Tri[1]][1], mMesh->vertices[Tri[1]][2]); glVertex3f(mMesh->vertices[Tri[2]][0], mMesh->vertices[Tri[2]][1], mMesh->vertices[Tri[2]][2]); } void CollisionSkeletonNode::drawCollisionSkeletonNode(bool _bTrans) { evalRT(); double M[16]; for(int i=0;i<4;i++) for(int j=0;j<4;j++) M[j*4+i] = mWorldTrans(i, j); fcl::Vec3f v1, v2, v3; glPushMatrix(); if(_bTrans) glMultMatrixd(M); glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); glBegin(GL_TRIANGLES); for(int i = 0;i < mMesh->num_tris; i++) { fcl::Triangle tri = mMesh->tri_indices[i]; glVertex3f(mMesh->vertices[tri[0]][0], mMesh->vertices[tri[0]][1], mMesh->vertices[tri[0]][2]); glVertex3f(mMesh->vertices[tri[1]][0], mMesh->vertices[tri[1]][1], mMesh->vertices[tri[1]][2]); glVertex3f(mMesh->vertices[tri[2]][0], mMesh->vertices[tri[2]][1], mMesh->vertices[tri[2]][2]); } glEnd(); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glPopMatrix(); } SkeletonCollision::~SkeletonCollision() { for(int i=0;i<mCollisionSkeletonNodeList.size();i++) delete mCollisionSkeletonNodeList[i]; } void SkeletonCollision::addCollisionSkeletonNode(kinematics::BodyNode *_bd, bool _bRecursive) { if (_bRecursive == false || _bd->getNumChildJoints() == 0) { CollisionSkeletonNode* csnode = new CollisionSkeletonNode(_bd); csnode->mBodynodeID = mCollisionSkeletonNodeList.size(); mCollisionSkeletonNodeList.push_back(csnode); mBodyNodeHash[_bd] = csnode; } else { addCollisionSkeletonNode(_bd, false); for (int i = 0; i < _bd->getNumChildJoints(); i++) addCollisionSkeletonNode(_bd->getChildNode(i), true); } } void SkeletonCollision::checkCollision(bool bConsiderGround) { int num_max_contact = 100; clearAllContacts(); int numCollision = 0; for (int i = 0; i < mCollisionSkeletonNodeList.size(); i++) { for (int j = i + 1; j < mCollisionSkeletonNodeList.size(); j++) { if (mCollisionSkeletonNodeList[i]->mBodyNode->getParentNode() == mCollisionSkeletonNodeList[j]->mBodyNode || mCollisionSkeletonNodeList[j]->mBodyNode->getParentNode() == mCollisionSkeletonNodeList[i]->mBodyNode) continue; if (mCollisionSkeletonNodeList[i]->mBodyNode->getSkel() == mCollisionSkeletonNodeList[j]->mBodyNode->getSkel()) continue; numCollision += mCollisionSkeletonNodeList[i]->checkCollision(mCollisionSkeletonNodeList[j], mContactPointList, num_max_contact); } } mNumTriIntersection = numCollision; } void SkeletonCollision::draw() { for(int i=0;i<mCollisionSkeletonNodeList.size();i++) mCollisionSkeletonNodeList[i]->drawCollisionSkeletonNode(); } } <|endoftext|>
<commit_before>#include <core/mat4.h> #include "core/draw.h" #include "core/random.h" #include "core/shufflebag.h" #include "core/filesystem.h" #include "core/mat4.h" #include "core/axisangle.h" #include "core/aabb.h" #include "core/texturetypes.h" #include "core/filesystemimagegenerator.h" #include "core/path.h" #include "core/os.h" #include "core/range.h" #include "core/camera.h" #include "core/stringutils.h" #include "core/stdutils.h" #include <render/init.h> #include <render/debuggl.h> #include <render/materialshader.h> #include <render/compiledmesh.h> #include <render/texturecache.h> #include "render/shaderattribute3d.h" #include "render/texture.h" #include "render/world.h" #include "render/viewport.h" #include "render/materialshadercache.h" #include "render/defaultfiles.h" #include "window/imguilibrary.h" #include "window/timer.h" #include "window/imgui_ext.h" #include "window/fpscontroller.h" #include "window/sdllibrary.h" #include "window/sdlwindow.h" #include "window/sdlglcontext.h" #include "window/filesystem.h" #include "editor/browser.h" #include "editor/scimed.h" #include "imgui/imgui.h" #include <SDL.h> #include <iostream> #include <memory> ImVec2 operator+(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2{lhs.x + rhs.x, lhs.y + rhs.y}; } struct StyleData { ScimedConfig scc = ScimedConfig{}; CanvasConfig cc = CanvasConfig{}; }; struct GenericWindow { std::string name; bool open = true; virtual void Run(StyleData* style_data) = 0; }; struct ScimedWindow : public GenericWindow { Scimed scimed; void Run(StyleData* style_data) override { scimed.Run(style_data->cc, style_data->scc); } }; template <typename CreateWindowFunction> void OpenOrFocusWindow( std::vector<std::shared_ptr<GenericWindow>>* windows, const std::string& title_name, CreateWindowFunction create_window_function) { const auto found = Search(*windows, [&](std::shared_ptr<GenericWindow>& wind) -> bool { return wind->name == title_name; }); if(found == windows->end()) { windows->emplace_back(create_window_function(title_name)); } else { ImGui::SetNextWindowFocus(); ImGui::Begin(title_name.c_str()); ImGui::End(); } } int main(int argc, char** argv) { SdlLibrary sdl; if(sdl.ok == false) { return -1; } int width = 1280; int height = 720; SdlWindow window{"Euphoria Demo", width, height}; if(window.window == nullptr) { return -1; } SdlGlContext context{&window}; if(context.context == nullptr) { return -1; } Init init{SDL_GL_GetProcAddress}; if(init.ok == false) { return -4; } SetupOpenglDebug(); const auto current_directory = GetCurrentDirectory(); const auto base_path = GetBasePath(); const auto pref_path = GetPrefPath(); ImguiLibrary imgui{window.window, pref_path}; ImGui::StyleColorsLight(); Viewport viewport{ Recti::FromWidthHeight(width, height).SetBottomLeftToCopy(0, 0)}; viewport.Activate(); FileSystem file_system; auto catalog = FileSystemRootCatalog::AddRoot(&file_system); FileSystemRootFolder::AddRoot(&file_system, current_directory); FileSystemImageGenerator::AddRoot(&file_system, "img-plain"); SetupDefaultFiles(catalog); TextureCache texture_cache{&file_system}; bool running = true; FileBrowser browser{&file_system}; browser.Refresh(); std::vector<std::shared_ptr<GenericWindow>> scimeds; StyleData style_data = StyleData{}; while(running) { SDL_Event e; while(SDL_PollEvent(&e) != 0) { imgui.ProcessEvents(&e); switch(e.type) { case SDL_QUIT: running = false; break; default: // ignore other events break; } } imgui.StartNewFrame(); if(ImGui::BeginMainMenuBar()) { if(ImGui::BeginMenu("File")) { if(ImGui::MenuItem("Exit", "Ctrl+Q")) { running = false; } ImGui::EndMenu(); } if(ImGui::BeginMenu("Window")) { for(const auto& window : scimeds) { if(ImGui::MenuItem(window->name.c_str())) { ImGui::SetNextWindowFocus(); ImGui::Begin(window->name.c_str()); ImGui::End(); } } ImGui::EndMenu(); } } ImGui::EndMainMenuBar(); if(ImGui::Begin("Solution explorer")) { if(browser.Run()) { const auto file = browser.GetSelectedFile(); OpenOrFocusWindow( &scimeds, Str{} << "Scimed: " << file, [&](const std::string& title_name) -> std::shared_ptr<GenericWindow> { auto scimed = std::make_shared<ScimedWindow>(); scimed->name = title_name; scimed->scimed.LoadFile(&texture_cache, &file_system, file); return scimed; }); } } ImGui::End(); for(auto& scimed : scimeds) { ImGui::SetNextWindowSize(ImVec2{300, 300}, ImGuiCond_FirstUseEver); if(ImGui::Begin(scimed->name.c_str(), &scimed->open)) { scimed->Run(&style_data); } ImGui::End(); } // ImGui::ShowMetricsWindow(); init.ClearScreen(Color::Wheat); imgui.Render(); RemoveMatching(&scimeds, [](const std::shared_ptr<GenericWindow>& window) { return !window->open; }); SDL_GL_SwapWindow(window.window); } return 0; } <commit_msg>working on style editor<commit_after>#include <core/mat4.h> #include "core/draw.h" #include "core/random.h" #include "core/shufflebag.h" #include "core/filesystem.h" #include "core/mat4.h" #include "core/axisangle.h" #include "core/aabb.h" #include "core/texturetypes.h" #include "core/filesystemimagegenerator.h" #include "core/path.h" #include "core/os.h" #include "core/range.h" #include "core/camera.h" #include "core/stringutils.h" #include "core/stdutils.h" #include <render/init.h> #include <render/debuggl.h> #include <render/materialshader.h> #include <render/compiledmesh.h> #include <render/texturecache.h> #include "render/shaderattribute3d.h" #include "render/texture.h" #include "render/world.h" #include "render/viewport.h" #include "render/materialshadercache.h" #include "render/defaultfiles.h" #include "window/imguilibrary.h" #include "window/timer.h" #include "window/imgui_ext.h" #include "window/fpscontroller.h" #include "window/sdllibrary.h" #include "window/sdlwindow.h" #include "window/sdlglcontext.h" #include "window/filesystem.h" #include "editor/browser.h" #include "editor/scimed.h" #include "imgui/imgui.h" #include <SDL.h> #include <iostream> #include <memory> ImVec2 operator+(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2{lhs.x + rhs.x, lhs.y + rhs.y}; } struct StyleData { ScimedConfig scc = ScimedConfig{}; CanvasConfig cc = CanvasConfig{}; }; struct GenericWindow { std::string name; bool open = true; virtual void Run(StyleData* style_data) = 0; }; template <typename CreateWindowFunction> void OpenOrFocusWindow( std::vector<std::shared_ptr<GenericWindow>>* windows, const std::string& title_name, CreateWindowFunction create_window_function) { const auto found = Search(*windows, [&](std::shared_ptr<GenericWindow>& wind) -> bool { return wind->name == title_name; }); if(found == windows->end()) { auto the_window = create_window_function(); the_window->name = title_name; windows->emplace_back(the_window); } else { ImGui::SetNextWindowFocus(); ImGui::Begin(title_name.c_str()); ImGui::End(); } } struct ScimedWindow : public GenericWindow { Scimed scimed; void Run(StyleData* style_data) override { scimed.Run(style_data->cc, style_data->scc); } }; struct StyleEditorWindow : GenericWindow { ImVec4 color; void Run(StyleData* s) override { ImGui::ColorEdit4("Color", &color.x); } }; void OpenOrFocusStyleEditor(std::vector<std::shared_ptr<GenericWindow>>* windows) { OpenOrFocusWindow(windows, "Style editor", []() { return std::make_shared<StyleEditorWindow>(); }); } int main(int argc, char** argv) { SdlLibrary sdl; if(sdl.ok == false) { return -1; } int width = 1280; int height = 720; SdlWindow window{"Euphoria Demo", width, height}; if(window.window == nullptr) { return -1; } SdlGlContext context{&window}; if(context.context == nullptr) { return -1; } Init init{SDL_GL_GetProcAddress}; if(init.ok == false) { return -4; } SetupOpenglDebug(); const auto current_directory = GetCurrentDirectory(); const auto base_path = GetBasePath(); const auto pref_path = GetPrefPath(); ImguiLibrary imgui{window.window, pref_path}; ImGui::StyleColorsLight(); Viewport viewport{ Recti::FromWidthHeight(width, height).SetBottomLeftToCopy(0, 0)}; viewport.Activate(); FileSystem file_system; auto catalog = FileSystemRootCatalog::AddRoot(&file_system); FileSystemRootFolder::AddRoot(&file_system, current_directory); FileSystemImageGenerator::AddRoot(&file_system, "img-plain"); SetupDefaultFiles(catalog); TextureCache texture_cache{&file_system}; bool running = true; FileBrowser browser{&file_system}; browser.Refresh(); std::vector<std::shared_ptr<GenericWindow>> scimeds; StyleData style_data = StyleData{}; OpenOrFocusStyleEditor(&scimeds); while(running) { SDL_Event e; while(SDL_PollEvent(&e) != 0) { imgui.ProcessEvents(&e); switch(e.type) { case SDL_QUIT: running = false; break; default: // ignore other events break; } } imgui.StartNewFrame(); if(ImGui::BeginMainMenuBar()) { if(ImGui::BeginMenu("File")) { if(ImGui::MenuItem("Exit", "Ctrl+Q")) { running = false; } if(ImGui::MenuItem("Style editor")) { OpenOrFocusStyleEditor(&scimeds); } ImGui::EndMenu(); } if(ImGui::BeginMenu("Window")) { for(const auto& window : scimeds) { if(ImGui::MenuItem(window->name.c_str())) { ImGui::SetNextWindowFocus(); ImGui::Begin(window->name.c_str()); ImGui::End(); } } ImGui::EndMenu(); } } ImGui::EndMainMenuBar(); if(ImGui::Begin("Solution explorer")) { if(browser.Run()) { const auto file = browser.GetSelectedFile(); OpenOrFocusWindow( &scimeds, Str{} << "Scimed: " << file, [&]() -> std::shared_ptr<GenericWindow> { auto scimed = std::make_shared<ScimedWindow>(); scimed->scimed.LoadFile(&texture_cache, &file_system, file); return scimed; }); } } ImGui::End(); for(auto& scimed : scimeds) { ImGui::SetNextWindowSize(ImVec2{300, 300}, ImGuiCond_FirstUseEver); if(ImGui::Begin(scimed->name.c_str(), &scimed->open)) { scimed->Run(&style_data); } ImGui::End(); } // ImGui::ShowMetricsWindow(); init.ClearScreen(Color::Wheat); imgui.Render(); RemoveMatching(&scimeds, [](const std::shared_ptr<GenericWindow>& window) { return !window->open; }); SDL_GL_SwapWindow(window.window); } return 0; } <|endoftext|>
<commit_before>#include "splineinverter.h" #include "spline.h" #include <algorithm> #define PI 3.14159265359 template <typename T> int sign(T val) { return (T(0) < val) - (val < T(0)); } SplineInverter::SplineInverter(const std::shared_ptr<Spline> &spline, int samplesPerT) :spline(spline), sampleStep(1 / double(samplesPerT)), slopeTolerance(0.01) { //first step is to populate the splineSamples map //we're going to have sampled T values sorted by x coordinate double currentT = 0; double maxT = spline->getMaxT(); while(currentT < maxT) { auto sampledPoint = spline->getPosition(currentT); SplineSample sample; sample.position = sampledPoint; sample.t = currentT; splineSamples.push_back(sample); currentT += sampleStep; } //if the spline isn't a loop and the final t value isn't very very close to maxT, we have to add a sample for maxT double lastT = splineSamples.at(splineSamples.size() - 1).t; if(!spline->isLoop() && abs(lastT / maxT - 1) > .0001) { auto sampledPoint = spline->getPosition(maxT); SplineSample sample; sample.position = sampledPoint; sample.t = maxT; splineSamples.push_back(sample); } std::sort(splineSamples.begin(), splineSamples.end()); } SplineInverter::~SplineInverter() { } double SplineInverter::findClosestFast(const Vector3D &queryPoint) const { double closestSampleT = findClosestSample(queryPoint); double sampleDistanceSlope = getDistanceSlope(queryPoint, closestSampleT); //if the slope is very close to 0, just return the sampled point if(abs(sampleDistanceSlope) < slopeTolerance) return closestSampleT; //if the spline is not a loop there are a few special cases to account for if(!spline->isLoop()) { //if closest sample T is 0, we are on an end. so if the slope is positive, we have to just return the end if(abs(closestSampleT) < .0001 && sampleDistanceSlope > 0) return closestSampleT; //if the closest sample T is max T we are on an end. so if the slope is negative, just return the end if(abs(closestSampleT / spline->getMaxT() - 1) < .0001 && sampleDistanceSlope < 0) return closestSampleT; } //step forwards or backwards in the spline until we find a point where the distance slope has flipped sign //because "currentsample" is the closest point, the "next" sample's slope MUST have a different sign //otherwise that sample would be closer //note: this assumption is only true if the samples are close together double bigT, littleT; if(sampleDistanceSlope > 0) { //the distance slope is < 0, so the spline is moving towards the query point at closestSampleT bigT = closestSampleT; littleT = closestSampleT - sampleStep; } else { //the distance slope is < 0, so the spline is moving towards the query point at closestSampleT bigT = closestSampleT + sampleStep; littleT = closestSampleT; } //we know that the actual closest point is now between littleT and bigT //use the circle projection method to find the actual closest point, using the Ts as bounds return circleProjectionMethod(queryPoint, littleT, bigT); } double SplineInverter::findClosestPrecise(const Vector3D &queryPoint) const { double closestSampleT = findClosestSample(queryPoint); double sampleDistanceSlope = getDistanceSlope(queryPoint, closestSampleT); //if the slope is very close to 0, just return the sampled point if(abs(sampleDistanceSlope) < slopeTolerance) return closestSampleT; //if the spline is not a loop there are a few special cases to account for if(!spline->isLoop()) { //if closest sample T is 0, we are on an end. so if the slope is positive, we have to just return the end if(abs(closestSampleT) < .0001 && sampleDistanceSlope > 0) return closestSampleT; //if the closest sample T is max T we are on an end. so if the slope is negative, just return the end if(abs(closestSampleT / spline->getMaxT() - 1) < .0001 && sampleDistanceSlope < 0) return closestSampleT; } //step forwards or backwards in the spline until we find a point where the distance slope has flipped sign //because "currentsample" is the closest point, the "next" sample's slope MUST have a different sign //otherwise that sample would be closer //note: this assumption is only true if the samples are close together double bigT, littleT; if(sampleDistanceSlope > 0) { //the distance slope is < 0, so the spline is moving towards the query point at closestSampleT bigT = closestSampleT; littleT = closestSampleT - sampleStep; } else { //the distance slope is < 0, so the spline is moving towards the query point at closestSampleT bigT = closestSampleT + sampleStep; littleT = closestSampleT; } //we know that the actual closest point is now between littleT and bigT //use the circle projection method to find the actual closest point, using the Ts as bounds return bisectionMethod(queryPoint, littleT, bigT); } double SplineInverter::findClosestSample(const Vector3D &queryPoint) const { //find the index of the lower bound of the query point, by x value int lower = findSampleIndex(queryPoint.x()); //find the index of the upper bound of x int upper = lower + 1; auto data = splineSamples.data(); //use the sweep and prune algorithm to find the closest point in euclidean distance double closestT = data[lower].t; double minimumDistanceSq = (queryPoint - data[lower].position).lengthSquared(); //keep searching for closer entries with a smaller X value than closestT until //we hit the beginning of the list, or until the x distance is larger than the closest total distance while(--lower >= 0) { double t = data[lower].t; double x = data[lower].position.x(); //if the x distance between these two points is larger than the distance between the two closest points //then we cannot possibly find a closer point, so break double dx = x - queryPoint.x(); if(dx * dx > minimumDistanceSq) break; //see if this point is closer than the current closest double currentdistanceSq = (queryPoint - data[lower].position).lengthSquared(); if(currentdistanceSq < minimumDistanceSq) { minimumDistanceSq = currentdistanceSq; closestT = t; } } //we want to perform the same search in the +x direction too while(upper < splineSamples.size()) { double t = data[upper].t; double x = data[upper].position.x(); //if the x distance between these two points is larger than the distance between the two closest points //then we cannot possibly find a closer point, so break double dx = x - queryPoint.x(); if(dx * dx > minimumDistanceSq) break; //see if this point is closer than the current closest double currentdistanceSq = (queryPoint - data[upper].position).lengthSquared(); if(currentdistanceSq < minimumDistanceSq) { minimumDistanceSq = currentdistanceSq; closestT = t; } upper++; } return closestT; } double SplineInverter::bisectionMethod(const Vector3D &queryPoint, double lowerBound, double upperBound) const { //we need to use the bisection method until acceleration at both the uper bound and lower bound are positive //otherwise it's not guaranteed to converge on a result, and if it does it'll probably be wrong D: double lowerValue = getDistanceSlope(queryPoint, lowerBound); double upperValue = getDistanceSlope(queryPoint, upperBound); //make sure a has y<0 and b has y>0. if its the other way around, swap them if(lowerValue > upperValue) { auto tempValue = lowerValue; lowerValue = upperValue; upperValue = tempValue; auto temp = lowerBound; lowerBound = upperBound; upperBound = temp; } //use the bisection method (essentially binary search) to find the value double middle = (lowerBound + upperBound) * 0.5; double middleValue = getDistanceSlope(queryPoint, middle); while(abs(middleValue) > slopeTolerance) { if(middleValue > 0) { upperBound = middle; upperValue = middleValue; } else { lowerBound = middle; lowerValue = middleValue; } middle = (lowerBound + upperBound) * 0.5; middleValue = getDistanceSlope(queryPoint, middle); } return middle; } double SplineInverter::circleProjectionMethod(const Vector3D &queryPoint, double lowerBound, double upperBound) const { //long story short: we're going to project the query point on a circle arc //that travels between the position at lowerBound, and the position at upperBound //the radius of the circle will be determined by the angle between the tangents //at lowerBound and upperBound //if the angle is very small then the radius will be very large which //will lead to the arc behaving like a straight line //if the angle is very large then the radius will be smaller which will //result in the t value being projected onto a more curved surface //the idea is that the curve will roughly match the curve of the actual spline //there are more accurate calculation methods like the bisection method, //but this is a reasonable approximation and way faster auto lowerResult = spline->getTangent(lowerBound); auto upperResult = spline->getTangent(upperBound); Vector3D sampleDisplacement = upperResult.position - lowerResult.position; Vector3D queryDisplacement = queryPoint - lowerResult.position; double sampleLength = sampleDisplacement.length(); Vector3D sampleDirection = sampleDisplacement / sampleLength; //project the query vector onto the sample vector double projection = Vector3D::dotProduct(sampleDirection, queryDisplacement); //compute the angle between the before and after velocities Vector3D lowerTangentDirection = lowerResult.tangent.normalized(); Vector3D upperTangentDirection = upperResult.tangent.normalized(); double cosTangentAngle = Vector3D::dotProduct(upperTangentDirection, lowerTangentDirection); //if the cos(angle) between the velocities is almost 1, there is essentially a straight line between the two points //if that's the case, we should just project the point onto that line if(cosTangentAngle > .99999) { double percent = projection / sampleLength; return lowerBound + percent * (upperBound - lowerBound); } else { //reject the projection to get a vector perpendicular to the sample vector out to the query point Vector3D queryRejection = queryDisplacement - projection * sampleDirection; //find the dot product between the rejection and the average acceleration, both non-normalized Vector3D averageCurvature = upperResult.tangent - lowerResult.tangent; double curvatureDot = Vector3D::dotProduct(averageCurvature,queryRejection); //construct an isoceles tringle whose base is the sample displacement, and whose opposite angle is the velocity angle double arcAngle = acos(cosTangentAngle); double h = sampleLength * 0.5 / tan(arcAngle * 0.5); //find the apex point Vector3D apex = (lowerResult.position + upperResult.position) * 0.5 + queryRejection.normalized() * h * sign(curvatureDot); //find the vectors that go from apex to the sample point, and from apex to the query point Vector3D sampleVector = lowerResult.position - apex; Vector3D queryVector = queryPoint - apex; //find the angle between these double queryAngle = acos(Vector3D::dotProduct(sampleVector.normalized(), queryVector.normalized())); double percent = queryAngle / arcAngle; return lowerBound + percent * (upperBound - lowerBound); } } int SplineInverter::findSampleIndex(double xValue) const { //we want to find the segment whos t0 and t1 values bound x auto data = splineSamples.data(); //if xValue is lower than the lowest sample's x value, return the lowest sample if(data[0].position.x() > xValue) return 0; int maxIndex = splineSamples.size() - 1; if(data[maxIndex].position.x() < xValue) return maxIndex; //perform a binary search on segmentData int currentMin = 0; int currentMax = maxIndex; int currentIndex = (currentMin + currentMax) / 2; //keep looping as long as this index does not bound x while((currentIndex != maxIndex) && (data[currentIndex].position.x() > xValue || data[currentIndex + 1].position.x() < xValue)) { //if the current index is greater than x, search the left half of the array if(data[currentIndex].position.x() > xValue) { currentMax = currentIndex - 1; } //the only other possibility is that the next index is less than x, so search the right half of the array else { currentMin = currentIndex + 1; } currentIndex = (currentMin + currentMax) / 2; } return currentIndex; } double SplineInverter::getDistanceSlope(const Vector3D &queryPoint, double t) const { auto result = spline->getTangent(t); //get the displacement from the spline at T to the query point Vector3D displacement = result.position - queryPoint; //find projection of spline velocity onto displacement return Vector3D::dotProduct(displacement.normalized(), result.tangent); } <commit_msg>Fixed outdated comment<commit_after>#include "splineinverter.h" #include "spline.h" #include <algorithm> #define PI 3.14159265359 template <typename T> int sign(T val) { return (T(0) < val) - (val < T(0)); } SplineInverter::SplineInverter(const std::shared_ptr<Spline> &spline, int samplesPerT) :spline(spline), sampleStep(1 / double(samplesPerT)), slopeTolerance(0.01) { //first step is to populate the splineSamples map //we're going to have sampled T values sorted by x coordinate double currentT = 0; double maxT = spline->getMaxT(); while(currentT < maxT) { auto sampledPoint = spline->getPosition(currentT); SplineSample sample; sample.position = sampledPoint; sample.t = currentT; splineSamples.push_back(sample); currentT += sampleStep; } //if the spline isn't a loop and the final t value isn't very very close to maxT, we have to add a sample for maxT double lastT = splineSamples.at(splineSamples.size() - 1).t; if(!spline->isLoop() && abs(lastT / maxT - 1) > .0001) { auto sampledPoint = spline->getPosition(maxT); SplineSample sample; sample.position = sampledPoint; sample.t = maxT; splineSamples.push_back(sample); } std::sort(splineSamples.begin(), splineSamples.end()); } SplineInverter::~SplineInverter() { } double SplineInverter::findClosestFast(const Vector3D &queryPoint) const { double closestSampleT = findClosestSample(queryPoint); double sampleDistanceSlope = getDistanceSlope(queryPoint, closestSampleT); //if the slope is very close to 0, just return the sampled point if(abs(sampleDistanceSlope) < slopeTolerance) return closestSampleT; //if the spline is not a loop there are a few special cases to account for if(!spline->isLoop()) { //if closest sample T is 0, we are on an end. so if the slope is positive, we have to just return the end if(abs(closestSampleT) < .0001 && sampleDistanceSlope > 0) return closestSampleT; //if the closest sample T is max T we are on an end. so if the slope is negative, just return the end if(abs(closestSampleT / spline->getMaxT() - 1) < .0001 && sampleDistanceSlope < 0) return closestSampleT; } //step forwards or backwards in the spline until we find a point where the distance slope has flipped sign //because "currentsample" is the closest point, the "next" sample's slope MUST have a different sign //otherwise that sample would be closer //note: this assumption is only true if the samples are close together double bigT, littleT; if(sampleDistanceSlope > 0) { //the distance slope is < 0, so the spline is moving towards the query point at closestSampleT bigT = closestSampleT; littleT = closestSampleT - sampleStep; } else { //the distance slope is < 0, so the spline is moving towards the query point at closestSampleT bigT = closestSampleT + sampleStep; littleT = closestSampleT; } //we know that the actual closest point is now between littleT and bigT //use the circle projection method to find the actual closest point, using the Ts as bounds return circleProjectionMethod(queryPoint, littleT, bigT); } double SplineInverter::findClosestPrecise(const Vector3D &queryPoint) const { double closestSampleT = findClosestSample(queryPoint); double sampleDistanceSlope = getDistanceSlope(queryPoint, closestSampleT); //if the slope is very close to 0, just return the sampled point if(abs(sampleDistanceSlope) < slopeTolerance) return closestSampleT; //if the spline is not a loop there are a few special cases to account for if(!spline->isLoop()) { //if closest sample T is 0, we are on an end. so if the slope is positive, we have to just return the end if(abs(closestSampleT) < .0001 && sampleDistanceSlope > 0) return closestSampleT; //if the closest sample T is max T we are on an end. so if the slope is negative, just return the end if(abs(closestSampleT / spline->getMaxT() - 1) < .0001 && sampleDistanceSlope < 0) return closestSampleT; } //step forwards or backwards in the spline until we find a point where the distance slope has flipped sign //because "currentsample" is the closest point, the "next" sample's slope MUST have a different sign //otherwise that sample would be closer //note: this assumption is only true if the samples are close together double bigT, littleT; if(sampleDistanceSlope > 0) { //the distance slope is < 0, so the spline is moving towards the query point at closestSampleT bigT = closestSampleT; littleT = closestSampleT - sampleStep; } else { //the distance slope is < 0, so the spline is moving towards the query point at closestSampleT bigT = closestSampleT + sampleStep; littleT = closestSampleT; } //we know that the actual closest point is now between littleT and bigT //use the circle projection method to find the actual closest point, using the Ts as bounds return bisectionMethod(queryPoint, littleT, bigT); } double SplineInverter::findClosestSample(const Vector3D &queryPoint) const { //find the index of the lower bound of the query point, by x value int lower = findSampleIndex(queryPoint.x()); //find the index of the upper bound of x int upper = lower + 1; auto data = splineSamples.data(); //use the sweep and prune algorithm to find the closest point in euclidean distance double closestT = data[lower].t; double minimumDistanceSq = (queryPoint - data[lower].position).lengthSquared(); //keep searching for closer entries with a smaller X value than closestT until //we hit the beginning of the list, or until the x distance is larger than the closest total distance while(--lower >= 0) { double t = data[lower].t; double x = data[lower].position.x(); //if the x distance between these two points is larger than the distance between the two closest points //then we cannot possibly find a closer point, so break double dx = x - queryPoint.x(); if(dx * dx > minimumDistanceSq) break; //see if this point is closer than the current closest double currentdistanceSq = (queryPoint - data[lower].position).lengthSquared(); if(currentdistanceSq < minimumDistanceSq) { minimumDistanceSq = currentdistanceSq; closestT = t; } } //we want to perform the same search in the +x direction too while(upper < splineSamples.size()) { double t = data[upper].t; double x = data[upper].position.x(); //if the x distance between these two points is larger than the distance between the two closest points //then we cannot possibly find a closer point, so break double dx = x - queryPoint.x(); if(dx * dx > minimumDistanceSq) break; //see if this point is closer than the current closest double currentdistanceSq = (queryPoint - data[upper].position).lengthSquared(); if(currentdistanceSq < minimumDistanceSq) { minimumDistanceSq = currentdistanceSq; closestT = t; } upper++; } return closestT; } double SplineInverter::bisectionMethod(const Vector3D &queryPoint, double lowerBound, double upperBound) const { //we need to use the bisection method until the slope of the distance is 0. //when this happens we have found a local minimum or global minimum double lowerValue = getDistanceSlope(queryPoint, lowerBound); double upperValue = getDistanceSlope(queryPoint, upperBound); //make sure a has y<0 and b has y>0. if its the other way around, swap them if(lowerValue > upperValue) { auto tempValue = lowerValue; lowerValue = upperValue; upperValue = tempValue; auto temp = lowerBound; lowerBound = upperBound; upperBound = temp; } //use the bisection method (essentially binary search) to find the value double middle = (lowerBound + upperBound) * 0.5; double middleValue = getDistanceSlope(queryPoint, middle); while(abs(middleValue) > slopeTolerance) { if(middleValue > 0) { upperBound = middle; upperValue = middleValue; } else { lowerBound = middle; lowerValue = middleValue; } middle = (lowerBound + upperBound) * 0.5; middleValue = getDistanceSlope(queryPoint, middle); } return middle; } double SplineInverter::circleProjectionMethod(const Vector3D &queryPoint, double lowerBound, double upperBound) const { //long story short: we're going to project the query point on a circle arc //that travels between the position at lowerBound, and the position at upperBound //the radius of the circle will be determined by the angle between the tangents //at lowerBound and upperBound //if the angle is very small then the radius will be very large which //will lead to the arc behaving like a straight line //if the angle is very large then the radius will be smaller which will //result in the t value being projected onto a more curved surface //the idea is that the curve will roughly match the curve of the actual spline //there are more accurate calculation methods like the bisection method, //but this is a reasonable approximation and way faster auto lowerResult = spline->getTangent(lowerBound); auto upperResult = spline->getTangent(upperBound); Vector3D sampleDisplacement = upperResult.position - lowerResult.position; Vector3D queryDisplacement = queryPoint - lowerResult.position; double sampleLength = sampleDisplacement.length(); Vector3D sampleDirection = sampleDisplacement / sampleLength; //project the query vector onto the sample vector double projection = Vector3D::dotProduct(sampleDirection, queryDisplacement); //compute the angle between the before and after velocities Vector3D lowerTangentDirection = lowerResult.tangent.normalized(); Vector3D upperTangentDirection = upperResult.tangent.normalized(); double cosTangentAngle = Vector3D::dotProduct(upperTangentDirection, lowerTangentDirection); //if the cos(angle) between the velocities is almost 1, there is essentially a straight line between the two points //if that's the case, we should just project the point onto that line if(cosTangentAngle > .99999) { double percent = projection / sampleLength; return lowerBound + percent * (upperBound - lowerBound); } else { //reject the projection to get a vector perpendicular to the sample vector out to the query point Vector3D queryRejection = queryDisplacement - projection * sampleDirection; //find the dot product between the rejection and the average acceleration, both non-normalized Vector3D averageCurvature = upperResult.tangent - lowerResult.tangent; double curvatureDot = Vector3D::dotProduct(averageCurvature,queryRejection); //construct an isoceles tringle whose base is the sample displacement, and whose opposite angle is the velocity angle double arcAngle = acos(cosTangentAngle); double h = sampleLength * 0.5 / tan(arcAngle * 0.5); //find the apex point Vector3D apex = (lowerResult.position + upperResult.position) * 0.5 + queryRejection.normalized() * h * sign(curvatureDot); //find the vectors that go from apex to the sample point, and from apex to the query point Vector3D sampleVector = lowerResult.position - apex; Vector3D queryVector = queryPoint - apex; //find the angle between these double queryAngle = acos(Vector3D::dotProduct(sampleVector.normalized(), queryVector.normalized())); double percent = queryAngle / arcAngle; return lowerBound + percent * (upperBound - lowerBound); } } int SplineInverter::findSampleIndex(double xValue) const { //we want to find the segment whos t0 and t1 values bound x auto data = splineSamples.data(); //if xValue is lower than the lowest sample's x value, return the lowest sample if(data[0].position.x() > xValue) return 0; int maxIndex = splineSamples.size() - 1; if(data[maxIndex].position.x() < xValue) return maxIndex; //perform a binary search on segmentData int currentMin = 0; int currentMax = maxIndex; int currentIndex = (currentMin + currentMax) / 2; //keep looping as long as this index does not bound x while((currentIndex != maxIndex) && (data[currentIndex].position.x() > xValue || data[currentIndex + 1].position.x() < xValue)) { //if the current index is greater than x, search the left half of the array if(data[currentIndex].position.x() > xValue) { currentMax = currentIndex - 1; } //the only other possibility is that the next index is less than x, so search the right half of the array else { currentMin = currentIndex + 1; } currentIndex = (currentMin + currentMax) / 2; } return currentIndex; } double SplineInverter::getDistanceSlope(const Vector3D &queryPoint, double t) const { auto result = spline->getTangent(t); //get the displacement from the spline at T to the query point Vector3D displacement = result.position - queryPoint; //find projection of spline velocity onto displacement return Vector3D::dotProduct(displacement.normalized(), result.tangent); } <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2010 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 <QtTest/QtTest> #include <qdocumentgallery.h> QTM_USE_NAMESPACE Q_DECLARE_METATYPE(QGalleryProperty::Attributes); class tst_QDocumentGallery : public QObject { Q_OBJECT private Q_SLOTS: void isRequestSupported(); void itemTypeProperties_data(); void itemTypeProperties(); void propertyAttributes_data(); void propertyAttributes(); private: QDocumentGallery gallery; }; void tst_QDocumentGallery::isRequestSupported() { #if defined(Q_OS_UNIX) && !defined(QT_NO_DBUS) const bool platformSupported = true; #else const bool platformSupported = false; #endif QCOMPARE(gallery.isRequestSupported(QGalleryAbstractRequest::Item), platformSupported); QCOMPARE(gallery.isRequestSupported(QGalleryAbstractRequest::Query), platformSupported); QCOMPARE(gallery.isRequestSupported(QGalleryAbstractRequest::Count), platformSupported); QCOMPARE(gallery.isRequestSupported(QGalleryAbstractRequest::Url), platformSupported); QCOMPARE(gallery.isRequestSupported(QGalleryAbstractRequest::Remove), platformSupported); } void tst_QDocumentGallery::itemTypeProperties_data() { QTest::addColumn<QString>("itemType"); QTest::addColumn<QStringList>("propertyNames"); QTest::newRow("null item type") << QString() << QStringList(); QTest::newRow("non-existent item type") << QString::fromLatin1("Hello") << QStringList(); const QStringList fileProperties = QStringList() #if defined(Q_OS_UNIX) && !defined(QT_NO_DBUS) << QDocumentGallery::copyright << QDocumentGallery::fileName << QDocumentGallery::language << QDocumentGallery::lastAccessed << QDocumentGallery::lastModified << QDocumentGallery::mimeType << QDocumentGallery::thumbnailImage << QDocumentGallery::thumbnailPixmap #endif ; QTest::newRow("File") << QString(QDocumentGallery::File) << (QStringList(fileProperties) #if defined(Q_OS_UNIX) && !defined(QT_NO_DBUS) << QDocumentGallery::author << QDocumentGallery::description << QDocumentGallery::keywords << QDocumentGallery::rating << QDocumentGallery::subject << QDocumentGallery::title #endif ); QTest::newRow("Audio") << QString(QDocumentGallery::Audio) << (QStringList(fileProperties) #if defined(Q_OS_UNIX) && !defined(QT_NO_DBUS) << QDocumentGallery::albumArtist << QDocumentGallery::albumTitle << QDocumentGallery::artist << QDocumentGallery::audioBitRate << QDocumentGallery::audioCodec << QDocumentGallery::channelCount << QDocumentGallery::description << QDocumentGallery::discNumber << QDocumentGallery::duration << QDocumentGallery::genre << QDocumentGallery::lastPlayed << QDocumentGallery::lyrics << QDocumentGallery::performer << QDocumentGallery::playCount << QDocumentGallery::sampleRate << QDocumentGallery::title << QDocumentGallery::trackNumber #endif ); QTest::newRow("Album") << QString(QDocumentGallery::Album) << (QStringList() #if defined(Q_OS_UNIX) && !defined(QT_NO_DBUS) << QDocumentGallery::artist << QDocumentGallery::duration << QDocumentGallery::title << QDocumentGallery::trackCount #endif ); } void tst_QDocumentGallery::itemTypeProperties() { QFETCH(QString, itemType); QFETCH(QStringList, propertyNames); QStringList galleryPropertyNames = gallery.itemTypePropertyNames(itemType); propertyNames.sort(); galleryPropertyNames.sort(); QCOMPARE(galleryPropertyNames, propertyNames); } void tst_QDocumentGallery::propertyAttributes_data() { QTest::addColumn<QString>("itemType"); QTest::addColumn<QString>("propertyName"); QTest::addColumn<QGalleryProperty::Attributes>("propertyAttributes"); QTest::newRow("Null itemType, propertyName") << QString() << QString() << QGalleryProperty::Attributes(); QTest::newRow("Null itemType, invalid propertyName") << QString() << QString::fromLatin1("Goodbye") << QGalleryProperty::Attributes(); QTest::newRow("Null itemType, valid propertyName") << QString() << QString(QDocumentGallery::fileName) << QGalleryProperty::Attributes(); QTest::newRow("Invalid itemType, invalid propertyName") << QString::fromLatin1("Hello") << QString::fromLatin1("Goodbye") << QGalleryProperty::Attributes(); QTest::newRow("Invalid itemType, valid propertyName") << QString::fromLatin1("Hello") << QString(QDocumentGallery::fileName) << QGalleryProperty::Attributes(); QTest::newRow("Valid itemType, invalid propertyName") << QString(QDocumentGallery::File) << QString::fromLatin1("Goodbye") << QGalleryProperty::Attributes(); QTest::newRow("File.fileName") << QString(QDocumentGallery::File) << QString(QDocumentGallery::fileName) #if defined(Q_OS_UNIX) && !defined(QT_NO_DBUS) << (QGalleryProperty::CanRead | QGalleryProperty::CanFilter | QGalleryProperty::CanSort); #else << QGalleryProperty::Attributes(); #endif QTest::newRow("Audio.albumTitle") << QString(QDocumentGallery::Audio) << QString(QDocumentGallery::albumTitle) #if defined(Q_OS_UNIX) && !defined(QT_NO_DBUS) << (QGalleryProperty::CanRead | QGalleryProperty::CanWrite | QGalleryProperty::CanFilter | QGalleryProperty::CanSort); #else << QGalleryProperty::Attributes(); #endif QTest::newRow("Album.duration") << QString(QDocumentGallery::Album) << QString(QDocumentGallery::duration) #if defined(Q_OS_UNIX) && !defined(QT_NO_DBUS) << QGalleryProperty::Attributes(QGalleryProperty::CanRead); #else << QGalleryProperty::Attributes(); #endif } void tst_QDocumentGallery::propertyAttributes() { QFETCH(QString, itemType); QFETCH(QString, propertyName); QFETCH(QGalleryProperty::Attributes, propertyAttributes); QCOMPARE(int(gallery.propertyAttributes(propertyName, itemType)), int(propertyAttributes)); } #include "tst_qdocumentgallery.moc" QTEST_MAIN(tst_QDocumentGallery) <commit_msg>Update QDocumentGallery test with new properties.<commit_after>/**************************************************************************** ** ** Copyright (C) 2010 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 <QtTest/QtTest> #include <qdocumentgallery.h> QTM_USE_NAMESPACE Q_DECLARE_METATYPE(QGalleryProperty::Attributes); class tst_QDocumentGallery : public QObject { Q_OBJECT private Q_SLOTS: void isRequestSupported(); void itemTypeProperties_data(); void itemTypeProperties(); void propertyAttributes_data(); void propertyAttributes(); private: QDocumentGallery gallery; }; void tst_QDocumentGallery::isRequestSupported() { #if defined(Q_OS_UNIX) && !defined(QT_NO_DBUS) const bool platformSupported = true; #else const bool platformSupported = false; #endif QCOMPARE(gallery.isRequestSupported(QGalleryAbstractRequest::Item), platformSupported); QCOMPARE(gallery.isRequestSupported(QGalleryAbstractRequest::Query), platformSupported); QCOMPARE(gallery.isRequestSupported(QGalleryAbstractRequest::Count), platformSupported); QCOMPARE(gallery.isRequestSupported(QGalleryAbstractRequest::Url), platformSupported); QCOMPARE(gallery.isRequestSupported(QGalleryAbstractRequest::Remove), platformSupported); } void tst_QDocumentGallery::itemTypeProperties_data() { QTest::addColumn<QString>("itemType"); QTest::addColumn<QStringList>("propertyNames"); QTest::newRow("null item type") << QString() << QStringList(); QTest::newRow("non-existent item type") << QString::fromLatin1("Hello") << QStringList(); const QStringList fileProperties = QStringList() #if defined(Q_OS_UNIX) && !defined(QT_NO_DBUS) << QDocumentGallery::copyright << QDocumentGallery::fileName << QDocumentGallery::fileSize << QDocumentGallery::language << QDocumentGallery::lastAccessed << QDocumentGallery::lastModified << QDocumentGallery::mimeType #ifndef Q_WS_MAEMO_5 << QDocumentGallery::previewImage << QDocumentGallery::previewPixmap #endif << QDocumentGallery::thumbnailImage << QDocumentGallery::thumbnailPixmap #endif ; QTest::newRow("File") << QString(QDocumentGallery::File) << (QStringList(fileProperties) #if defined(Q_OS_UNIX) && !defined(QT_NO_DBUS) << QDocumentGallery::author << QDocumentGallery::description << QDocumentGallery::keywords << QDocumentGallery::rating << QDocumentGallery::subject << QDocumentGallery::title #endif ); QTest::newRow("Audio") << QString(QDocumentGallery::Audio) << (QStringList(fileProperties) #if defined(Q_OS_UNIX) && !defined(QT_NO_DBUS) << QDocumentGallery::albumArtist << QDocumentGallery::albumTitle << QDocumentGallery::artist << QDocumentGallery::audioBitRate << QDocumentGallery::audioCodec << QDocumentGallery::channelCount << QDocumentGallery::description << QDocumentGallery::discNumber << QDocumentGallery::duration << QDocumentGallery::genre << QDocumentGallery::lastPlayed << QDocumentGallery::lyrics << QDocumentGallery::performer << QDocumentGallery::playCount << QDocumentGallery::sampleRate << QDocumentGallery::title << QDocumentGallery::trackNumber #endif ); QTest::newRow("Album") << QString(QDocumentGallery::Album) << (QStringList() #if defined(Q_OS_UNIX) && !defined(QT_NO_DBUS) << QDocumentGallery::artist << QDocumentGallery::duration << QDocumentGallery::title << QDocumentGallery::trackCount #endif ); } void tst_QDocumentGallery::itemTypeProperties() { QFETCH(QString, itemType); QFETCH(QStringList, propertyNames); QStringList galleryPropertyNames = gallery.itemTypePropertyNames(itemType); propertyNames.sort(); galleryPropertyNames.sort(); QCOMPARE(galleryPropertyNames, propertyNames); } void tst_QDocumentGallery::propertyAttributes_data() { QTest::addColumn<QString>("itemType"); QTest::addColumn<QString>("propertyName"); QTest::addColumn<QGalleryProperty::Attributes>("propertyAttributes"); QTest::newRow("Null itemType, propertyName") << QString() << QString() << QGalleryProperty::Attributes(); QTest::newRow("Null itemType, invalid propertyName") << QString() << QString::fromLatin1("Goodbye") << QGalleryProperty::Attributes(); QTest::newRow("Null itemType, valid propertyName") << QString() << QString(QDocumentGallery::fileName) << QGalleryProperty::Attributes(); QTest::newRow("Invalid itemType, invalid propertyName") << QString::fromLatin1("Hello") << QString::fromLatin1("Goodbye") << QGalleryProperty::Attributes(); QTest::newRow("Invalid itemType, valid propertyName") << QString::fromLatin1("Hello") << QString(QDocumentGallery::fileName) << QGalleryProperty::Attributes(); QTest::newRow("Valid itemType, invalid propertyName") << QString(QDocumentGallery::File) << QString::fromLatin1("Goodbye") << QGalleryProperty::Attributes(); QTest::newRow("File.fileName") << QString(QDocumentGallery::File) << QString(QDocumentGallery::fileName) #if defined(Q_OS_UNIX) && !defined(QT_NO_DBUS) << (QGalleryProperty::CanRead | QGalleryProperty::CanFilter | QGalleryProperty::CanSort); #else << QGalleryProperty::Attributes(); #endif QTest::newRow("Audio.albumTitle") << QString(QDocumentGallery::Audio) << QString(QDocumentGallery::albumTitle) #if defined(Q_OS_UNIX) && !defined(QT_NO_DBUS) << (QGalleryProperty::CanRead | QGalleryProperty::CanWrite | QGalleryProperty::CanFilter | QGalleryProperty::CanSort); #else << QGalleryProperty::Attributes(); #endif QTest::newRow("Album.duration") << QString(QDocumentGallery::Album) << QString(QDocumentGallery::duration) #if defined(Q_OS_UNIX) && !defined(QT_NO_DBUS) << QGalleryProperty::Attributes(QGalleryProperty::CanRead); #else << QGalleryProperty::Attributes(); #endif } void tst_QDocumentGallery::propertyAttributes() { QFETCH(QString, itemType); QFETCH(QString, propertyName); QFETCH(QGalleryProperty::Attributes, propertyAttributes); QCOMPARE(int(gallery.propertyAttributes(propertyName, itemType)), int(propertyAttributes)); } #include "tst_qdocumentgallery.moc" QTEST_MAIN(tst_QDocumentGallery) <|endoftext|>
<commit_before>#ifndef ANY_HPP #define ANY_HPP #include <memory> namespace shadow { // abstract base class providing interface to held value // holds no type information, intended as building block for a more complex type // that holds type information through a reflection mechanism class holder_base { public: virtual holder_base* clone() const = 0; virtual ~holder_base() = default; }; // concrete subclass holding value of any type template <class T> class holder : public holder_base { public: // this is necessary for any to access raw value friend class any; public: explicit holder(const T& value) : value_(value) { } virtual holder_base* clone() const override { return new holder(value_); } private: T value_; }; // specialization for type void, represents empty value template <> class holder<void> : public holder_base { public: virtual holder_base* clone() const override { return new holder(); } }; // type erasure wrapper for value of any type class any { public: // construct empty any (holds 'void') any() : holder_(std::make_unique<holder<void>>()) { } // construct empty with a held value of type T template <class T> any(const T& value) : holder_(std::make_unique<holder<T>>(value)) { } // copy construct, relies on holder implementation of clone any(const any& other) : holder_(other.holder_->clone()) { } any(any&&) = default; any& operator=(any other) { holder_ = std::move(other.holder_); return *this; } public: // unsafe interaction with underlying value, intended to be used by higher // level reflection mechanism that holds information about the type of held // value template <class T> T& get() { return static_cast<holder<T>*>(holder_.get())->value_; } template <class T> const T& get() const { return static_cast<holder<T>*>(holder_.get())->value_; } private: std::unique_ptr<holder_base> holder_; }; } // namespace shadow #endif <commit_msg>Change constructor of holder to take argument by value and move. modified: include/any.hpp<commit_after>#ifndef ANY_HPP #define ANY_HPP #include <memory> #include <utility> namespace shadow { // abstract base class providing interface to held value // holds no type information, intended as building block for a more complex type // that holds type information through a reflection mechanism class holder_base { public: virtual holder_base* clone() const = 0; virtual ~holder_base() = default; }; // concrete subclass holding value of any type template <class T> class holder : public holder_base { public: // this is necessary for any to access raw value friend class any; public: explicit holder(T value) : value_(std::move(value)) { } virtual holder_base* clone() const override { return new holder(value_); } private: T value_; }; // specialization for type void, represents empty value template <> class holder<void> : public holder_base { public: virtual holder_base* clone() const override { return new holder(); } }; // type erasure wrapper for value of any type class any { public: // construct empty any (holds 'void') any() : holder_(std::make_unique<holder<void>>()) { } // construct empty with a held value of type T template <class T> any(const T& value) : holder_(std::make_unique<holder<T>>(value)) { } // copy construct, relies on holder implementation of clone any(const any& other) : holder_(other.holder_->clone()) { } any(any&&) = default; any& operator=(any other) { holder_ = std::move(other.holder_); return *this; } public: // unsafe interaction with underlying value, intended to be used by higher // level reflection mechanism that holds information about the type of held // value template <class T> T& get() { return static_cast<holder<T>*>(holder_.get())->value_; } template <class T> const T& get() const { return static_cast<holder<T>*>(holder_.get())->value_; } private: std::unique_ptr<holder_base> holder_; }; } // namespace shadow #endif <|endoftext|>