text
stringlengths
54
60.6k
<commit_before>#include "clientmodel.h" #include "guiconstants.h" #include "optionsmodel.h" #include "addresstablemodel.h" #include "transactiontablemodel.h" #include "main.h" #include "ui_interface.h" #include <QDateTime> #include <QTimer> static const int64 nClientStartupTime = GetTime(); ClientModel::ClientModel(OptionsModel *optionsModel, QObject *parent) : QObject(parent), optionsModel(optionsModel), cachedNumBlocks(0), cachedNumBlocksOfPeers(0), pollTimer(0) { numBlocksAtStartup = -1; pollTimer = new QTimer(this); pollTimer->setInterval(MODEL_UPDATE_DELAY); pollTimer->start(); connect(pollTimer, SIGNAL(timeout()), this, SLOT(updateTimer())); subscribeToCoreSignals(); } ClientModel::~ClientModel() { unsubscribeFromCoreSignals(); } int ClientModel::getNumConnections() const { return vNodes.size(); } int ClientModel::getNumBlocks() const { return nBestHeight; } int ClientModel::getNumBlocksAtStartup() { if (numBlocksAtStartup == -1) numBlocksAtStartup = getNumBlocks(); return numBlocksAtStartup; } QDateTime ClientModel::getLastBlockDate() const { return QDateTime::fromTime_t(pindexBest->GetBlockTime()); } void ClientModel::updateTimer() { // Some quantities (such as number of blocks) change so fast that we don't want to be notified for each change. // Periodically check and update with a timer. int newNumBlocks = getNumBlocks(); int newNumBlocksOfPeers = getNumBlocksOfPeers(); if(cachedNumBlocks != newNumBlocks || cachedNumBlocksOfPeers != newNumBlocksOfPeers) emit numBlocksChanged(newNumBlocks, newNumBlocksOfPeers); cachedNumBlocks = newNumBlocks; cachedNumBlocksOfPeers = newNumBlocksOfPeers; } void ClientModel::updateNumConnections(int numConnections) { emit numConnectionsChanged(numConnections); } void ClientModel::updateAlert(const QString &hash, int status) { // Show error message notification for new alert if(status == CT_NEW) { uint256 hash_256; hash_256.SetHex(hash.toStdString()); CAlert alert = CAlert::getAlertByHash(hash_256); if(!alert.IsNull()) { emit error(tr("Network Alert"), QString::fromStdString(alert.strStatusBar), false); } } // Emit a numBlocksChanged when the status message changes, // so that the view recomputes and updates the status bar. emit numBlocksChanged(getNumBlocks(), getNumBlocksOfPeers()); } bool ClientModel::isTestNet() const { return fTestNet; } bool ClientModel::inInitialBlockDownload() const { return IsInitialBlockDownload(); } int ClientModel::getNumBlocksOfPeers() const { return GetNumBlocksOfPeers(); } QString ClientModel::getStatusBarWarnings() const { return QString::fromStdString(GetWarnings("statusbar")); } OptionsModel *ClientModel::getOptionsModel() { return optionsModel; } QString ClientModel::formatFullVersion() const { return QString::fromStdString(FormatFullVersion()); } QString ClientModel::formatBuildDate() const { return QString::fromStdString(CLIENT_DATE); } QString ClientModel::clientName() const { return QString::fromStdString(CLIENT_NAME); } QString ClientModel::formatClientStartupTime() const { return QDateTime::fromTime_t(nClientStartupTime).toString(); } // Handlers for core signals static void NotifyBlocksChanged(ClientModel *clientmodel) { // This notification is too frequent. Don't trigger a signal. // Don't remove it, though, as it might be useful later. } static void NotifyNumConnectionsChanged(ClientModel *clientmodel, int newNumConnections) { // Too noisy: OutputDebugStringF("NotifyNumConnectionsChanged %i\n", newNumConnections); QMetaObject::invokeMethod(clientmodel, "updateNumConnections", Qt::QueuedConnection, Q_ARG(int, newNumConnections)); } static void NotifyAlertChanged(ClientModel *clientmodel, const uint256 &hash, ChangeType status) { OutputDebugStringF("NotifyAlertChanged %s status=%i\n", hash.GetHex().c_str(), status); QMetaObject::invokeMethod(clientmodel, "updateAlert", Qt::QueuedConnection, Q_ARG(QString, QString::fromStdString(hash.GetHex())), Q_ARG(int, status)); } void ClientModel::subscribeToCoreSignals() { // Connect signals to client uiInterface.NotifyBlocksChanged.connect(boost::bind(NotifyBlocksChanged, this)); uiInterface.NotifyNumConnectionsChanged.connect(boost::bind(NotifyNumConnectionsChanged, this, _1)); uiInterface.NotifyAlertChanged.connect(boost::bind(NotifyAlertChanged, this, _1, _2)); } void ClientModel::unsubscribeFromCoreSignals() { // Disconnect signals from client uiInterface.NotifyBlocksChanged.disconnect(boost::bind(NotifyBlocksChanged, this)); uiInterface.NotifyNumConnectionsChanged.disconnect(boost::bind(NotifyNumConnectionsChanged, this, _1)); uiInterface.NotifyAlertChanged.disconnect(boost::bind(NotifyAlertChanged, this, _1, _2)); } <commit_msg>only update cached values in ClientModel::updateTimer() when they are changed<commit_after>#include "clientmodel.h" #include "guiconstants.h" #include "optionsmodel.h" #include "addresstablemodel.h" #include "transactiontablemodel.h" #include "main.h" #include "ui_interface.h" #include <QDateTime> #include <QTimer> static const int64 nClientStartupTime = GetTime(); ClientModel::ClientModel(OptionsModel *optionsModel, QObject *parent) : QObject(parent), optionsModel(optionsModel), cachedNumBlocks(0), cachedNumBlocksOfPeers(0), pollTimer(0) { numBlocksAtStartup = -1; pollTimer = new QTimer(this); pollTimer->setInterval(MODEL_UPDATE_DELAY); pollTimer->start(); connect(pollTimer, SIGNAL(timeout()), this, SLOT(updateTimer())); subscribeToCoreSignals(); } ClientModel::~ClientModel() { unsubscribeFromCoreSignals(); } int ClientModel::getNumConnections() const { return vNodes.size(); } int ClientModel::getNumBlocks() const { return nBestHeight; } int ClientModel::getNumBlocksAtStartup() { if (numBlocksAtStartup == -1) numBlocksAtStartup = getNumBlocks(); return numBlocksAtStartup; } QDateTime ClientModel::getLastBlockDate() const { return QDateTime::fromTime_t(pindexBest->GetBlockTime()); } void ClientModel::updateTimer() { // Some quantities (such as number of blocks) change so fast that we don't want to be notified for each change. // Periodically check and update with a timer. int newNumBlocks = getNumBlocks(); int newNumBlocksOfPeers = getNumBlocksOfPeers(); if(cachedNumBlocks != newNumBlocks || cachedNumBlocksOfPeers != newNumBlocksOfPeers) { cachedNumBlocks = newNumBlocks; cachedNumBlocksOfPeers = newNumBlocksOfPeers; emit numBlocksChanged(newNumBlocks, newNumBlocksOfPeers); } } void ClientModel::updateNumConnections(int numConnections) { emit numConnectionsChanged(numConnections); } void ClientModel::updateAlert(const QString &hash, int status) { // Show error message notification for new alert if(status == CT_NEW) { uint256 hash_256; hash_256.SetHex(hash.toStdString()); CAlert alert = CAlert::getAlertByHash(hash_256); if(!alert.IsNull()) { emit error(tr("Network Alert"), QString::fromStdString(alert.strStatusBar), false); } } // Emit a numBlocksChanged when the status message changes, // so that the view recomputes and updates the status bar. emit numBlocksChanged(getNumBlocks(), getNumBlocksOfPeers()); } bool ClientModel::isTestNet() const { return fTestNet; } bool ClientModel::inInitialBlockDownload() const { return IsInitialBlockDownload(); } int ClientModel::getNumBlocksOfPeers() const { return GetNumBlocksOfPeers(); } QString ClientModel::getStatusBarWarnings() const { return QString::fromStdString(GetWarnings("statusbar")); } OptionsModel *ClientModel::getOptionsModel() { return optionsModel; } QString ClientModel::formatFullVersion() const { return QString::fromStdString(FormatFullVersion()); } QString ClientModel::formatBuildDate() const { return QString::fromStdString(CLIENT_DATE); } QString ClientModel::clientName() const { return QString::fromStdString(CLIENT_NAME); } QString ClientModel::formatClientStartupTime() const { return QDateTime::fromTime_t(nClientStartupTime).toString(); } // Handlers for core signals static void NotifyBlocksChanged(ClientModel *clientmodel) { // This notification is too frequent. Don't trigger a signal. // Don't remove it, though, as it might be useful later. } static void NotifyNumConnectionsChanged(ClientModel *clientmodel, int newNumConnections) { // Too noisy: OutputDebugStringF("NotifyNumConnectionsChanged %i\n", newNumConnections); QMetaObject::invokeMethod(clientmodel, "updateNumConnections", Qt::QueuedConnection, Q_ARG(int, newNumConnections)); } static void NotifyAlertChanged(ClientModel *clientmodel, const uint256 &hash, ChangeType status) { OutputDebugStringF("NotifyAlertChanged %s status=%i\n", hash.GetHex().c_str(), status); QMetaObject::invokeMethod(clientmodel, "updateAlert", Qt::QueuedConnection, Q_ARG(QString, QString::fromStdString(hash.GetHex())), Q_ARG(int, status)); } void ClientModel::subscribeToCoreSignals() { // Connect signals to client uiInterface.NotifyBlocksChanged.connect(boost::bind(NotifyBlocksChanged, this)); uiInterface.NotifyNumConnectionsChanged.connect(boost::bind(NotifyNumConnectionsChanged, this, _1)); uiInterface.NotifyAlertChanged.connect(boost::bind(NotifyAlertChanged, this, _1, _2)); } void ClientModel::unsubscribeFromCoreSignals() { // Disconnect signals from client uiInterface.NotifyBlocksChanged.disconnect(boost::bind(NotifyBlocksChanged, this)); uiInterface.NotifyNumConnectionsChanged.disconnect(boost::bind(NotifyNumConnectionsChanged, this, _1)); uiInterface.NotifyAlertChanged.disconnect(boost::bind(NotifyAlertChanged, this, _1, _2)); } <|endoftext|>
<commit_before>// ------------------------------------------------------------------------ // Pion is a development platform for building Reactors that process Events // ------------------------------------------------------------------------ // Copyright (C) 2007-2008 Atomic Labs, Inc. (http://www.atomiclabs.com) // // Pion is free software: you can redistribute it and/or modify it under the // terms of the GNU Affero General Public License as published by the Free // Software Foundation, either version 3 of the License, or (at your option) // any later version. // // Pion 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 Pion. If not, see <http://www.gnu.org/licenses/>. // #include <pion/PionConfig.hpp> #include <pion/platform/ConfigManager.hpp> #include <boost/test/unit_test.hpp> using namespace pion; using namespace pion::platform; BOOST_AUTO_TEST_CASE(checkCreateUUID) { std::string UUID = ConfigManager::createUUID(); BOOST_CHECK_EQUAL(UUID.length(), static_cast<std::size_t>(36)); } BOOST_AUTO_TEST_CASE(checkResolveRelativePathThatIsRelative) { std::string base_path("/opt/pion/config/platform.xml"); std::string relative_path("../ui"); #if defined(_MSC_VER) BOOST_CHECK_EQUAL(ConfigManager::resolveRelativePath(base_path, relative_path), "c:\\opt\\pion\\config\\..\\ui"); #else BOOST_CHECK_EQUAL(ConfigManager::resolveRelativePath(base_path, relative_path), "/opt/pion/ui"); #endif } BOOST_AUTO_TEST_CASE(checkResolveRelativePathThatIsNotRelative) { std::string base_path("/opt/pion/config/platform.xml"); #if defined(_MSC_VER) std::string relative_path("C:\\opt\\pion\\ui"); BOOST_CHECK_EQUAL(ConfigManager::resolveRelativePath(base_path, relative_path), "C:\\opt\\pion\\ui"); #else std::string relative_path("/opt/pion/ui"); BOOST_CHECK_EQUAL(ConfigManager::resolveRelativePath(base_path, relative_path), "/opt/pion/ui"); #endif } <commit_msg>Updated checkResolveRelativePathThatIsRelative so it passes again for MSVC.<commit_after>// ------------------------------------------------------------------------ // Pion is a development platform for building Reactors that process Events // ------------------------------------------------------------------------ // Copyright (C) 2007-2008 Atomic Labs, Inc. (http://www.atomiclabs.com) // // Pion is free software: you can redistribute it and/or modify it under the // terms of the GNU Affero General Public License as published by the Free // Software Foundation, either version 3 of the License, or (at your option) // any later version. // // Pion 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 Pion. If not, see <http://www.gnu.org/licenses/>. // #include <pion/PionConfig.hpp> #include <pion/platform/ConfigManager.hpp> #include <boost/test/unit_test.hpp> using namespace pion; using namespace pion::platform; BOOST_AUTO_TEST_CASE(checkCreateUUID) { std::string UUID = ConfigManager::createUUID(); BOOST_CHECK_EQUAL(UUID.length(), static_cast<std::size_t>(36)); } BOOST_AUTO_TEST_CASE(checkResolveRelativePathThatIsRelative) { std::string base_path("/opt/pion/config/platform.xml"); std::string relative_path("../ui"); #if defined(_MSC_VER) BOOST_CHECK_EQUAL(ConfigManager::resolveRelativePath(base_path, relative_path), "c:\\opt\\pion\\ui"); #else BOOST_CHECK_EQUAL(ConfigManager::resolveRelativePath(base_path, relative_path), "/opt/pion/ui"); #endif } BOOST_AUTO_TEST_CASE(checkResolveRelativePathThatIsNotRelative) { std::string base_path("/opt/pion/config/platform.xml"); #if defined(_MSC_VER) std::string relative_path("C:\\opt\\pion\\ui"); BOOST_CHECK_EQUAL(ConfigManager::resolveRelativePath(base_path, relative_path), "C:\\opt\\pion\\ui"); #else std::string relative_path("/opt/pion/ui"); BOOST_CHECK_EQUAL(ConfigManager::resolveRelativePath(base_path, relative_path), "/opt/pion/ui"); #endif } <|endoftext|>
<commit_before>#include "clientmodel.h" #include "guiconstants.h" #include "optionsmodel.h" #include "addresstablemodel.h" #include "transactiontablemodel.h" #include "alert.h" #include "main.h" #include "ui_interface.h" #include <QDateTime> #include <QTimer> static const int64 nClientStartupTime = GetTime(); ClientModel::ClientModel(OptionsModel *optionsModel, QObject *parent) : QObject(parent), optionsModel(optionsModel), cachedNumBlocks(0), cachedNumBlocksOfPeers(0), numBlocksAtStartup(-1), pollTimer(0) { pollTimer = new QTimer(this); pollTimer->setInterval(MODEL_UPDATE_DELAY); pollTimer->start(); connect(pollTimer, SIGNAL(timeout()), this, SLOT(updateTimer())); subscribeToCoreSignals(); } ClientModel::~ClientModel() { unsubscribeFromCoreSignals(); } int ClientModel::getNumConnections() const { return vNodes.size(); } int ClientModel::getNumBlocks() const { return nBestHeight; } int ClientModel::getNumBlocksAtStartup() { if (numBlocksAtStartup == -1) numBlocksAtStartup = getNumBlocks(); return numBlocksAtStartup; } QDateTime ClientModel::getLastBlockDate() const { return QDateTime::fromTime_t(pindexBest->GetBlockTime()); } void ClientModel::updateTimer() { // Some quantities (such as number of blocks) change so fast that we don't want to be notified for each change. // Periodically check and update with a timer. int newNumBlocks = getNumBlocks(); int newNumBlocksOfPeers = getNumBlocksOfPeers(); if(cachedNumBlocks != newNumBlocks || cachedNumBlocksOfPeers != newNumBlocksOfPeers) { cachedNumBlocks = newNumBlocks; cachedNumBlocksOfPeers = newNumBlocksOfPeers; // ensure we return the maximum of newNumBlocksOfPeers and newNumBlocks to not create weird displays in the GUI emit numBlocksChanged(newNumBlocks, std::max(newNumBlocksOfPeers, newNumBlocks)); } } void ClientModel::updateNumConnections(int numConnections) { emit numConnectionsChanged(numConnections); } void ClientModel::updateAlert(const QString &hash, int status) { // Show error message notification for new alert if(status == CT_NEW) { uint256 hash_256; hash_256.SetHex(hash.toStdString()); CAlert alert = CAlert::getAlertByHash(hash_256); if(!alert.IsNull()) { emit message(tr("Network Alert"), QString::fromStdString(alert.strStatusBar), CClientUIInterface::ICON_ERROR); } } emit alertsChanged(getStatusBarWarnings()); } bool ClientModel::isTestNet() const { return fTestNet; } bool ClientModel::inInitialBlockDownload() const { return IsInitialBlockDownload(); } enum BlockSource ClientModel::getBlockSource() const { if (fReindex) return BLOCK_SOURCE_REINDEX; if (fImporting) return BLOCK_SOURCE_DISK; return BLOCK_SOURCE_NETWORK; } int ClientModel::getNumBlocksOfPeers() const { return GetNumBlocksOfPeers(); } QString ClientModel::getStatusBarWarnings() const { return QString::fromStdString(GetWarnings("statusbar")); } OptionsModel *ClientModel::getOptionsModel() { return optionsModel; } QString ClientModel::formatFullVersion() const { return QString::fromStdString(FormatFullVersion()); } QString ClientModel::formatBuildDate() const { return QString::fromStdString(CLIENT_DATE); } bool ClientModel::isReleaseVersion() const { return CLIENT_VERSION_IS_RELEASE; } QString ClientModel::clientName() const { return QString::fromStdString(CLIENT_NAME); } QString ClientModel::formatClientStartupTime() const { return QDateTime::fromTime_t(nClientStartupTime).toString(); } // Handlers for core signals static void NotifyBlocksChanged(ClientModel *clientmodel) { // This notification is too frequent. Don't trigger a signal. // Don't remove it, though, as it might be useful later. } static void NotifyNumConnectionsChanged(ClientModel *clientmodel, int newNumConnections) { // Too noisy: OutputDebugStringF("NotifyNumConnectionsChanged %i\n", newNumConnections); QMetaObject::invokeMethod(clientmodel, "updateNumConnections", Qt::QueuedConnection, Q_ARG(int, newNumConnections)); } static void NotifyAlertChanged(ClientModel *clientmodel, const uint256 &hash, ChangeType status) { OutputDebugStringF("NotifyAlertChanged %s status=%i\n", hash.GetHex().c_str(), status); QMetaObject::invokeMethod(clientmodel, "updateAlert", Qt::QueuedConnection, Q_ARG(QString, QString::fromStdString(hash.GetHex())), Q_ARG(int, status)); } void ClientModel::subscribeToCoreSignals() { // Connect signals to client uiInterface.NotifyBlocksChanged.connect(boost::bind(NotifyBlocksChanged, this)); uiInterface.NotifyNumConnectionsChanged.connect(boost::bind(NotifyNumConnectionsChanged, this, _1)); uiInterface.NotifyAlertChanged.connect(boost::bind(NotifyAlertChanged, this, _1, _2)); } void ClientModel::unsubscribeFromCoreSignals() { // Disconnect signals from client uiInterface.NotifyBlocksChanged.disconnect(boost::bind(NotifyBlocksChanged, this)); uiInterface.NotifyNumConnectionsChanged.disconnect(boost::bind(NotifyNumConnectionsChanged, this, _1)); uiInterface.NotifyAlertChanged.disconnect(boost::bind(NotifyAlertChanged, this, _1, _2)); } <commit_msg>Prevent Qt crash at startup with an empty data directory<commit_after>#include "clientmodel.h" #include "guiconstants.h" #include "optionsmodel.h" #include "addresstablemodel.h" #include "transactiontablemodel.h" #include "alert.h" #include "main.h" #include "ui_interface.h" #include <QDateTime> #include <QTimer> static const int64 nClientStartupTime = GetTime(); ClientModel::ClientModel(OptionsModel *optionsModel, QObject *parent) : QObject(parent), optionsModel(optionsModel), cachedNumBlocks(0), cachedNumBlocksOfPeers(0), numBlocksAtStartup(-1), pollTimer(0) { pollTimer = new QTimer(this); pollTimer->setInterval(MODEL_UPDATE_DELAY); pollTimer->start(); connect(pollTimer, SIGNAL(timeout()), this, SLOT(updateTimer())); subscribeToCoreSignals(); } ClientModel::~ClientModel() { unsubscribeFromCoreSignals(); } int ClientModel::getNumConnections() const { return vNodes.size(); } int ClientModel::getNumBlocks() const { return nBestHeight; } int ClientModel::getNumBlocksAtStartup() { if (numBlocksAtStartup == -1) numBlocksAtStartup = getNumBlocks(); return numBlocksAtStartup; } QDateTime ClientModel::getLastBlockDate() const { if (pindexBest) return QDateTime::fromTime_t(pindexBest->GetBlockTime()); else return QDateTime::fromTime_t(1231006505); // Genesis block's time } void ClientModel::updateTimer() { // Some quantities (such as number of blocks) change so fast that we don't want to be notified for each change. // Periodically check and update with a timer. int newNumBlocks = getNumBlocks(); int newNumBlocksOfPeers = getNumBlocksOfPeers(); if(cachedNumBlocks != newNumBlocks || cachedNumBlocksOfPeers != newNumBlocksOfPeers) { cachedNumBlocks = newNumBlocks; cachedNumBlocksOfPeers = newNumBlocksOfPeers; // ensure we return the maximum of newNumBlocksOfPeers and newNumBlocks to not create weird displays in the GUI emit numBlocksChanged(newNumBlocks, std::max(newNumBlocksOfPeers, newNumBlocks)); } } void ClientModel::updateNumConnections(int numConnections) { emit numConnectionsChanged(numConnections); } void ClientModel::updateAlert(const QString &hash, int status) { // Show error message notification for new alert if(status == CT_NEW) { uint256 hash_256; hash_256.SetHex(hash.toStdString()); CAlert alert = CAlert::getAlertByHash(hash_256); if(!alert.IsNull()) { emit message(tr("Network Alert"), QString::fromStdString(alert.strStatusBar), CClientUIInterface::ICON_ERROR); } } emit alertsChanged(getStatusBarWarnings()); } bool ClientModel::isTestNet() const { return fTestNet; } bool ClientModel::inInitialBlockDownload() const { return IsInitialBlockDownload(); } enum BlockSource ClientModel::getBlockSource() const { if (fReindex) return BLOCK_SOURCE_REINDEX; if (fImporting) return BLOCK_SOURCE_DISK; return BLOCK_SOURCE_NETWORK; } int ClientModel::getNumBlocksOfPeers() const { return GetNumBlocksOfPeers(); } QString ClientModel::getStatusBarWarnings() const { return QString::fromStdString(GetWarnings("statusbar")); } OptionsModel *ClientModel::getOptionsModel() { return optionsModel; } QString ClientModel::formatFullVersion() const { return QString::fromStdString(FormatFullVersion()); } QString ClientModel::formatBuildDate() const { return QString::fromStdString(CLIENT_DATE); } bool ClientModel::isReleaseVersion() const { return CLIENT_VERSION_IS_RELEASE; } QString ClientModel::clientName() const { return QString::fromStdString(CLIENT_NAME); } QString ClientModel::formatClientStartupTime() const { return QDateTime::fromTime_t(nClientStartupTime).toString(); } // Handlers for core signals static void NotifyBlocksChanged(ClientModel *clientmodel) { // This notification is too frequent. Don't trigger a signal. // Don't remove it, though, as it might be useful later. } static void NotifyNumConnectionsChanged(ClientModel *clientmodel, int newNumConnections) { // Too noisy: OutputDebugStringF("NotifyNumConnectionsChanged %i\n", newNumConnections); QMetaObject::invokeMethod(clientmodel, "updateNumConnections", Qt::QueuedConnection, Q_ARG(int, newNumConnections)); } static void NotifyAlertChanged(ClientModel *clientmodel, const uint256 &hash, ChangeType status) { OutputDebugStringF("NotifyAlertChanged %s status=%i\n", hash.GetHex().c_str(), status); QMetaObject::invokeMethod(clientmodel, "updateAlert", Qt::QueuedConnection, Q_ARG(QString, QString::fromStdString(hash.GetHex())), Q_ARG(int, status)); } void ClientModel::subscribeToCoreSignals() { // Connect signals to client uiInterface.NotifyBlocksChanged.connect(boost::bind(NotifyBlocksChanged, this)); uiInterface.NotifyNumConnectionsChanged.connect(boost::bind(NotifyNumConnectionsChanged, this, _1)); uiInterface.NotifyAlertChanged.connect(boost::bind(NotifyAlertChanged, this, _1, _2)); } void ClientModel::unsubscribeFromCoreSignals() { // Disconnect signals from client uiInterface.NotifyBlocksChanged.disconnect(boost::bind(NotifyBlocksChanged, this)); uiInterface.NotifyNumConnectionsChanged.disconnect(boost::bind(NotifyNumConnectionsChanged, this, _1)); uiInterface.NotifyAlertChanged.disconnect(boost::bind(NotifyAlertChanged, this, _1, _2)); } <|endoftext|>
<commit_before>/* * Copyright (c) 2012 ARM Limited * All rights reserved. * * The license below extends only to copyright in the software and shall * not be construed as granting a license to any other intellectual * property including but not limited to intellectual property relating * to a hardware implementation of the functionality of the software * licensed hereunder. You may use the software subject to the license * terms below provided that you ensure that this notice is replicated * unmodified and in its entirety in all distributions of the software, * modified or unmodified, in source code or in binary form. * * Copyright (c) 2006 The Regents of The University of Michigan * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Authors: Ali Saidi * Andreas Hansson */ #include "base/trace.hh" #include "debug/Drain.hh" #include "debug/PacketQueue.hh" #include "mem/packet_queue.hh" using namespace std; PacketQueue::PacketQueue(EventManager& _em, const std::string& _label) : em(_em), sendEvent(this), drainManager(NULL), label(_label), waitingOnRetry(false) { } PacketQueue::~PacketQueue() { } void PacketQueue::retry() { DPRINTF(PacketQueue, "Queue %s received retry\n", name()); assert(waitingOnRetry); sendDeferredPacket(); } bool PacketQueue::checkFunctional(PacketPtr pkt) { pkt->pushLabel(label); DeferredPacketIterator i = transmitList.begin(); DeferredPacketIterator end = transmitList.end(); bool found = false; while (!found && i != end) { // If the buffered packet contains data, and it overlaps the // current packet, then update data found = pkt->checkFunctional(i->pkt); ++i; } pkt->popLabel(); return found; } void PacketQueue::schedSendEvent(Tick when) { // if we are waiting on a retry, do not schedule a send event, and // instead rely on retry being called if (waitingOnRetry) { assert(!sendEvent.scheduled()); return; } if (!sendEvent.scheduled()) { em.schedule(&sendEvent, when); } else if (sendEvent.when() > when) { em.reschedule(&sendEvent, when); } } void PacketQueue::schedSendTiming(PacketPtr pkt, Tick when, bool send_as_snoop) { // we can still send a packet before the end of this tick assert(when >= curTick()); // express snoops should never be queued assert(!pkt->isExpressSnoop()); // nothing on the list, or earlier than current front element, // schedule an event if (transmitList.empty() || when < transmitList.front().tick) { // note that currently we ignore a potentially outstanding retry // and could in theory put a new packet at the head of the // transmit list before retrying the existing packet transmitList.push_front(DeferredPacket(when, pkt, send_as_snoop)); schedSendEvent(when); return; } // list is non-empty and this belongs at the end if (when >= transmitList.back().tick) { transmitList.push_back(DeferredPacket(when, pkt, send_as_snoop)); return; } // this belongs in the middle somewhere, insertion sort DeferredPacketIterator i = transmitList.begin(); ++i; // already checked for insertion at front while (i != transmitList.end() && when >= i->tick) ++i; transmitList.insert(i, DeferredPacket(when, pkt, send_as_snoop)); } void PacketQueue::trySendTiming() { assert(deferredPacketReady()); // take the next packet off the list here, as we might return to // ourselves through the sendTiming call below DeferredPacket dp = transmitList.front(); transmitList.pop_front(); // use the appropriate implementation of sendTiming based on the // type of port associated with the queue, and whether the packet // is to be sent as a snoop or not waitingOnRetry = !sendTiming(dp.pkt, dp.sendAsSnoop); if (waitingOnRetry) { // put the packet back at the front of the list (packet should // not have changed since it wasn't accepted) assert(!sendEvent.scheduled()); transmitList.push_front(dp); } } void PacketQueue::scheduleSend(Tick time) { // the next ready time is either determined by the next deferred packet, // or in the cache through the MSHR ready time Tick nextReady = std::min(deferredPacketReadyTime(), time); if (nextReady != MaxTick) { // if the sendTiming caused someone else to call our // recvTiming we could already have an event scheduled, check if (!sendEvent.scheduled()) em.schedule(&sendEvent, std::max(nextReady, curTick() + 1)); } else { // no more to send, so if we're draining, we may be done if (drainManager && transmitList.empty() && !sendEvent.scheduled()) { DPRINTF(Drain, "PacketQueue done draining," "processing drain event\n"); drainManager->signalDrainDone(); drainManager = NULL; } } } void PacketQueue::sendDeferredPacket() { // try to send what is on the list, this will set waitingOnRetry // accordingly trySendTiming(); // if we succeeded and are not waiting for a retry, schedule the // next send if (!waitingOnRetry) { scheduleSend(); } } void PacketQueue::processSendEvent() { assert(!waitingOnRetry); sendDeferredPacket(); } unsigned int PacketQueue::drain(DrainManager *dm) { if (transmitList.empty() && !sendEvent.scheduled()) return 0; DPRINTF(Drain, "PacketQueue not drained\n"); drainManager = dm; return 1; } MasterPacketQueue::MasterPacketQueue(EventManager& _em, MasterPort& _masterPort, const std::string _label) : PacketQueue(_em, _label), masterPort(_masterPort) { } bool MasterPacketQueue::sendTiming(PacketPtr pkt, bool send_as_snoop) { // attempt to send the packet and return according to the outcome if (!send_as_snoop) return masterPort.sendTimingReq(pkt); else return masterPort.sendTimingSnoopResp(pkt); } SlavePacketQueue::SlavePacketQueue(EventManager& _em, SlavePort& _slavePort, const std::string _label) : PacketQueue(_em, _label), slavePort(_slavePort) { } bool SlavePacketQueue::sendTiming(PacketPtr pkt, bool send_as_snoop) { // we should never have queued snoop requests assert(!send_as_snoop); return slavePort.sendTimingResp(pkt); } <commit_msg>mem: Add sanity check to packet queue size<commit_after>/* * Copyright (c) 2012 ARM Limited * All rights reserved. * * The license below extends only to copyright in the software and shall * not be construed as granting a license to any other intellectual * property including but not limited to intellectual property relating * to a hardware implementation of the functionality of the software * licensed hereunder. You may use the software subject to the license * terms below provided that you ensure that this notice is replicated * unmodified and in its entirety in all distributions of the software, * modified or unmodified, in source code or in binary form. * * Copyright (c) 2006 The Regents of The University of Michigan * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Authors: Ali Saidi * Andreas Hansson */ #include "base/trace.hh" #include "debug/Drain.hh" #include "debug/PacketQueue.hh" #include "mem/packet_queue.hh" using namespace std; PacketQueue::PacketQueue(EventManager& _em, const std::string& _label) : em(_em), sendEvent(this), drainManager(NULL), label(_label), waitingOnRetry(false) { } PacketQueue::~PacketQueue() { } void PacketQueue::retry() { DPRINTF(PacketQueue, "Queue %s received retry\n", name()); assert(waitingOnRetry); sendDeferredPacket(); } bool PacketQueue::checkFunctional(PacketPtr pkt) { pkt->pushLabel(label); DeferredPacketIterator i = transmitList.begin(); DeferredPacketIterator end = transmitList.end(); bool found = false; while (!found && i != end) { // If the buffered packet contains data, and it overlaps the // current packet, then update data found = pkt->checkFunctional(i->pkt); ++i; } pkt->popLabel(); return found; } void PacketQueue::schedSendEvent(Tick when) { // if we are waiting on a retry, do not schedule a send event, and // instead rely on retry being called if (waitingOnRetry) { assert(!sendEvent.scheduled()); return; } if (!sendEvent.scheduled()) { em.schedule(&sendEvent, when); } else if (sendEvent.when() > when) { em.reschedule(&sendEvent, when); } } void PacketQueue::schedSendTiming(PacketPtr pkt, Tick when, bool send_as_snoop) { // we can still send a packet before the end of this tick assert(when >= curTick()); // express snoops should never be queued assert(!pkt->isExpressSnoop()); // add a very basic sanity check on the port to ensure the // invisible buffer is not growing beyond reasonable limits if (transmitList.size() > 100) { panic("Packet queue %s has grown beyond 100 packets\n", name()); } // nothing on the list, or earlier than current front element, // schedule an event if (transmitList.empty() || when < transmitList.front().tick) { // note that currently we ignore a potentially outstanding retry // and could in theory put a new packet at the head of the // transmit list before retrying the existing packet transmitList.push_front(DeferredPacket(when, pkt, send_as_snoop)); schedSendEvent(when); return; } // list is non-empty and this belongs at the end if (when >= transmitList.back().tick) { transmitList.push_back(DeferredPacket(when, pkt, send_as_snoop)); return; } // this belongs in the middle somewhere, insertion sort DeferredPacketIterator i = transmitList.begin(); ++i; // already checked for insertion at front while (i != transmitList.end() && when >= i->tick) ++i; transmitList.insert(i, DeferredPacket(when, pkt, send_as_snoop)); } void PacketQueue::trySendTiming() { assert(deferredPacketReady()); // take the next packet off the list here, as we might return to // ourselves through the sendTiming call below DeferredPacket dp = transmitList.front(); transmitList.pop_front(); // use the appropriate implementation of sendTiming based on the // type of port associated with the queue, and whether the packet // is to be sent as a snoop or not waitingOnRetry = !sendTiming(dp.pkt, dp.sendAsSnoop); if (waitingOnRetry) { // put the packet back at the front of the list (packet should // not have changed since it wasn't accepted) assert(!sendEvent.scheduled()); transmitList.push_front(dp); } } void PacketQueue::scheduleSend(Tick time) { // the next ready time is either determined by the next deferred packet, // or in the cache through the MSHR ready time Tick nextReady = std::min(deferredPacketReadyTime(), time); if (nextReady != MaxTick) { // if the sendTiming caused someone else to call our // recvTiming we could already have an event scheduled, check if (!sendEvent.scheduled()) em.schedule(&sendEvent, std::max(nextReady, curTick() + 1)); } else { // no more to send, so if we're draining, we may be done if (drainManager && transmitList.empty() && !sendEvent.scheduled()) { DPRINTF(Drain, "PacketQueue done draining," "processing drain event\n"); drainManager->signalDrainDone(); drainManager = NULL; } } } void PacketQueue::sendDeferredPacket() { // try to send what is on the list, this will set waitingOnRetry // accordingly trySendTiming(); // if we succeeded and are not waiting for a retry, schedule the // next send if (!waitingOnRetry) { scheduleSend(); } } void PacketQueue::processSendEvent() { assert(!waitingOnRetry); sendDeferredPacket(); } unsigned int PacketQueue::drain(DrainManager *dm) { if (transmitList.empty() && !sendEvent.scheduled()) return 0; DPRINTF(Drain, "PacketQueue not drained\n"); drainManager = dm; return 1; } MasterPacketQueue::MasterPacketQueue(EventManager& _em, MasterPort& _masterPort, const std::string _label) : PacketQueue(_em, _label), masterPort(_masterPort) { } bool MasterPacketQueue::sendTiming(PacketPtr pkt, bool send_as_snoop) { // attempt to send the packet and return according to the outcome if (!send_as_snoop) return masterPort.sendTimingReq(pkt); else return masterPort.sendTimingSnoopResp(pkt); } SlavePacketQueue::SlavePacketQueue(EventManager& _em, SlavePort& _slavePort, const std::string _label) : PacketQueue(_em, _label), slavePort(_slavePort) { } bool SlavePacketQueue::sendTiming(PacketPtr pkt, bool send_as_snoop) { // we should never have queued snoop requests assert(!send_as_snoop); return slavePort.sendTimingResp(pkt); } <|endoftext|>
<commit_before>// Copyright (c) 2011-2021 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <qt/walletframe.h> #include <fs.h> #include <node/ui_interface.h> #include <psbt.h> #include <qt/guiutil.h> #include <qt/overviewpage.h> #include <qt/psbtoperationsdialog.h> #include <qt/walletmodel.h> #include <qt/walletview.h> #include <util/system.h> #include <cassert> #include <fstream> #include <string> #include <QApplication> #include <QClipboard> #include <QGroupBox> #include <QHBoxLayout> #include <QLabel> #include <QPushButton> #include <QVBoxLayout> WalletFrame::WalletFrame(const PlatformStyle* _platformStyle, QWidget* parent) : QFrame(parent), platformStyle(_platformStyle), m_size_hint(OverviewPage{platformStyle, nullptr}.sizeHint()) { // Leave HBox hook for adding a list view later QHBoxLayout *walletFrameLayout = new QHBoxLayout(this); setContentsMargins(0,0,0,0); walletStack = new QStackedWidget(this); walletFrameLayout->setContentsMargins(0,0,0,0); walletFrameLayout->addWidget(walletStack); // hbox for no wallet QGroupBox* no_wallet_group = new QGroupBox(walletStack); QVBoxLayout* no_wallet_layout = new QVBoxLayout(no_wallet_group); QLabel *noWallet = new QLabel(tr("No wallet has been loaded.\nGo to File > Open Wallet to load a wallet.\n- OR -")); noWallet->setAlignment(Qt::AlignCenter); no_wallet_layout->addWidget(noWallet, 0, Qt::AlignHCenter | Qt::AlignBottom); // A button for create wallet dialog QPushButton* create_wallet_button = new QPushButton(tr("Create a new wallet"), walletStack); connect(create_wallet_button, &QPushButton::clicked, this, &WalletFrame::createWalletButtonClicked); no_wallet_layout->addWidget(create_wallet_button, 0, Qt::AlignHCenter | Qt::AlignTop); no_wallet_group->setLayout(no_wallet_layout); walletStack->addWidget(no_wallet_group); } WalletFrame::~WalletFrame() { } void WalletFrame::setClientModel(ClientModel *_clientModel) { this->clientModel = _clientModel; for (auto i = mapWalletViews.constBegin(); i != mapWalletViews.constEnd(); ++i) { i.value()->setClientModel(_clientModel); } } bool WalletFrame::addView(WalletView* walletView) { if (!clientModel) return false; if (mapWalletViews.count(walletView->getWalletModel()) > 0) return false; walletView->setClientModel(clientModel); walletView->showOutOfSyncWarning(bOutOfSync); WalletView* current_wallet_view = currentWalletView(); if (current_wallet_view) { walletView->setCurrentIndex(current_wallet_view->currentIndex()); } else { walletView->gotoOverviewPage(); } walletStack->addWidget(walletView); mapWalletViews[walletView->getWalletModel()] = walletView; return true; } void WalletFrame::setCurrentWallet(WalletModel* wallet_model) { if (mapWalletViews.count(wallet_model) == 0) return; // Stop the effect of hidden widgets on the size hint of the shown one in QStackedWidget. WalletView* view_about_to_hide = currentWalletView(); if (view_about_to_hide) { QSizePolicy sp = view_about_to_hide->sizePolicy(); sp.setHorizontalPolicy(QSizePolicy::Ignored); view_about_to_hide->setSizePolicy(sp); } WalletView *walletView = mapWalletViews.value(wallet_model); assert(walletView); // Set or restore the default QSizePolicy which could be set to QSizePolicy::Ignored previously. QSizePolicy sp = walletView->sizePolicy(); sp.setHorizontalPolicy(QSizePolicy::Preferred); walletView->setSizePolicy(sp); walletView->updateGeometry(); walletStack->setCurrentWidget(walletView); Q_EMIT currentWalletSet(); } void WalletFrame::removeWallet(WalletModel* wallet_model) { if (mapWalletViews.count(wallet_model) == 0) return; WalletView *walletView = mapWalletViews.take(wallet_model); walletStack->removeWidget(walletView); delete walletView; } void WalletFrame::removeAllWallets() { QMap<WalletModel*, WalletView*>::const_iterator i; for (i = mapWalletViews.constBegin(); i != mapWalletViews.constEnd(); ++i) walletStack->removeWidget(i.value()); mapWalletViews.clear(); } bool WalletFrame::handlePaymentRequest(const SendCoinsRecipient &recipient) { WalletView *walletView = currentWalletView(); if (!walletView) return false; return walletView->handlePaymentRequest(recipient); } void WalletFrame::showOutOfSyncWarning(bool fShow) { bOutOfSync = fShow; QMap<WalletModel*, WalletView*>::const_iterator i; for (i = mapWalletViews.constBegin(); i != mapWalletViews.constEnd(); ++i) i.value()->showOutOfSyncWarning(fShow); } void WalletFrame::gotoOverviewPage() { QMap<WalletModel*, WalletView*>::const_iterator i; for (i = mapWalletViews.constBegin(); i != mapWalletViews.constEnd(); ++i) i.value()->gotoOverviewPage(); } void WalletFrame::gotoHistoryPage() { QMap<WalletModel*, WalletView*>::const_iterator i; for (i = mapWalletViews.constBegin(); i != mapWalletViews.constEnd(); ++i) i.value()->gotoHistoryPage(); } void WalletFrame::gotoReceiveCoinsPage() { QMap<WalletModel*, WalletView*>::const_iterator i; for (i = mapWalletViews.constBegin(); i != mapWalletViews.constEnd(); ++i) i.value()->gotoReceiveCoinsPage(); } void WalletFrame::gotoSendCoinsPage(QString addr) { QMap<WalletModel*, WalletView*>::const_iterator i; for (i = mapWalletViews.constBegin(); i != mapWalletViews.constEnd(); ++i) i.value()->gotoSendCoinsPage(addr); } void WalletFrame::gotoSignMessageTab(QString addr) { WalletView *walletView = currentWalletView(); if (walletView) walletView->gotoSignMessageTab(addr); } void WalletFrame::gotoVerifyMessageTab(QString addr) { WalletView *walletView = currentWalletView(); if (walletView) walletView->gotoVerifyMessageTab(addr); } void WalletFrame::gotoLoadPSBT(bool from_clipboard) { std::string data; if (from_clipboard) { std::string raw = QApplication::clipboard()->text().toStdString(); bool invalid; data = DecodeBase64(raw, &invalid); if (invalid) { Q_EMIT message(tr("Error"), tr("Unable to decode PSBT from clipboard (invalid base64)"), CClientUIInterface::MSG_ERROR); return; } } else { QString filename = GUIUtil::getOpenFileName(this, tr("Load Transaction Data"), QString(), tr("Partially Signed Transaction (*.psbt)"), nullptr); if (filename.isEmpty()) return; if (GetFileSize(filename.toLocal8Bit().data(), MAX_FILE_SIZE_PSBT) == MAX_FILE_SIZE_PSBT) { Q_EMIT message(tr("Error"), tr("PSBT file must be smaller than 100 MiB"), CClientUIInterface::MSG_ERROR); return; } std::ifstream in{filename.toLocal8Bit().data(), std::ios::binary}; data = std::string(std::istreambuf_iterator<char>{in}, {}); } std::string error; PartiallySignedTransaction psbtx; if (!DecodeRawPSBT(psbtx, data, error)) { Q_EMIT message(tr("Error"), tr("Unable to decode PSBT") + "\n" + QString::fromStdString(error), CClientUIInterface::MSG_ERROR); return; } auto dlg = new PSBTOperationsDialog(this, currentWalletModel(), clientModel); dlg->openWithPSBT(psbtx); GUIUtil::ShowModalDialogAsynchronously(dlg); } void WalletFrame::encryptWallet() { WalletView *walletView = currentWalletView(); if (walletView) walletView->encryptWallet(); } void WalletFrame::backupWallet() { WalletView *walletView = currentWalletView(); if (walletView) walletView->backupWallet(); } void WalletFrame::changePassphrase() { WalletView *walletView = currentWalletView(); if (walletView) walletView->changePassphrase(); } void WalletFrame::unlockWallet() { WalletView *walletView = currentWalletView(); if (walletView) walletView->unlockWallet(); } void WalletFrame::usedSendingAddresses() { WalletView *walletView = currentWalletView(); if (walletView) walletView->usedSendingAddresses(); } void WalletFrame::usedReceivingAddresses() { WalletView *walletView = currentWalletView(); if (walletView) walletView->usedReceivingAddresses(); } WalletView* WalletFrame::currentWalletView() const { return qobject_cast<WalletView*>(walletStack->currentWidget()); } WalletModel* WalletFrame::currentWalletModel() const { WalletView* wallet_view = currentWalletView(); return wallet_view ? wallet_view->getWalletModel() : nullptr; } <commit_msg>gui: Load Base64 PSBT string from file<commit_after>// Copyright (c) 2011-2021 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <qt/walletframe.h> #include <fs.h> #include <node/ui_interface.h> #include <psbt.h> #include <qt/guiutil.h> #include <qt/overviewpage.h> #include <qt/psbtoperationsdialog.h> #include <qt/walletmodel.h> #include <qt/walletview.h> #include <util/system.h> #include <cassert> #include <fstream> #include <string> #include <QApplication> #include <QClipboard> #include <QGroupBox> #include <QHBoxLayout> #include <QLabel> #include <QPushButton> #include <QVBoxLayout> WalletFrame::WalletFrame(const PlatformStyle* _platformStyle, QWidget* parent) : QFrame(parent), platformStyle(_platformStyle), m_size_hint(OverviewPage{platformStyle, nullptr}.sizeHint()) { // Leave HBox hook for adding a list view later QHBoxLayout *walletFrameLayout = new QHBoxLayout(this); setContentsMargins(0,0,0,0); walletStack = new QStackedWidget(this); walletFrameLayout->setContentsMargins(0,0,0,0); walletFrameLayout->addWidget(walletStack); // hbox for no wallet QGroupBox* no_wallet_group = new QGroupBox(walletStack); QVBoxLayout* no_wallet_layout = new QVBoxLayout(no_wallet_group); QLabel *noWallet = new QLabel(tr("No wallet has been loaded.\nGo to File > Open Wallet to load a wallet.\n- OR -")); noWallet->setAlignment(Qt::AlignCenter); no_wallet_layout->addWidget(noWallet, 0, Qt::AlignHCenter | Qt::AlignBottom); // A button for create wallet dialog QPushButton* create_wallet_button = new QPushButton(tr("Create a new wallet"), walletStack); connect(create_wallet_button, &QPushButton::clicked, this, &WalletFrame::createWalletButtonClicked); no_wallet_layout->addWidget(create_wallet_button, 0, Qt::AlignHCenter | Qt::AlignTop); no_wallet_group->setLayout(no_wallet_layout); walletStack->addWidget(no_wallet_group); } WalletFrame::~WalletFrame() { } void WalletFrame::setClientModel(ClientModel *_clientModel) { this->clientModel = _clientModel; for (auto i = mapWalletViews.constBegin(); i != mapWalletViews.constEnd(); ++i) { i.value()->setClientModel(_clientModel); } } bool WalletFrame::addView(WalletView* walletView) { if (!clientModel) return false; if (mapWalletViews.count(walletView->getWalletModel()) > 0) return false; walletView->setClientModel(clientModel); walletView->showOutOfSyncWarning(bOutOfSync); WalletView* current_wallet_view = currentWalletView(); if (current_wallet_view) { walletView->setCurrentIndex(current_wallet_view->currentIndex()); } else { walletView->gotoOverviewPage(); } walletStack->addWidget(walletView); mapWalletViews[walletView->getWalletModel()] = walletView; return true; } void WalletFrame::setCurrentWallet(WalletModel* wallet_model) { if (mapWalletViews.count(wallet_model) == 0) return; // Stop the effect of hidden widgets on the size hint of the shown one in QStackedWidget. WalletView* view_about_to_hide = currentWalletView(); if (view_about_to_hide) { QSizePolicy sp = view_about_to_hide->sizePolicy(); sp.setHorizontalPolicy(QSizePolicy::Ignored); view_about_to_hide->setSizePolicy(sp); } WalletView *walletView = mapWalletViews.value(wallet_model); assert(walletView); // Set or restore the default QSizePolicy which could be set to QSizePolicy::Ignored previously. QSizePolicy sp = walletView->sizePolicy(); sp.setHorizontalPolicy(QSizePolicy::Preferred); walletView->setSizePolicy(sp); walletView->updateGeometry(); walletStack->setCurrentWidget(walletView); Q_EMIT currentWalletSet(); } void WalletFrame::removeWallet(WalletModel* wallet_model) { if (mapWalletViews.count(wallet_model) == 0) return; WalletView *walletView = mapWalletViews.take(wallet_model); walletStack->removeWidget(walletView); delete walletView; } void WalletFrame::removeAllWallets() { QMap<WalletModel*, WalletView*>::const_iterator i; for (i = mapWalletViews.constBegin(); i != mapWalletViews.constEnd(); ++i) walletStack->removeWidget(i.value()); mapWalletViews.clear(); } bool WalletFrame::handlePaymentRequest(const SendCoinsRecipient &recipient) { WalletView *walletView = currentWalletView(); if (!walletView) return false; return walletView->handlePaymentRequest(recipient); } void WalletFrame::showOutOfSyncWarning(bool fShow) { bOutOfSync = fShow; QMap<WalletModel*, WalletView*>::const_iterator i; for (i = mapWalletViews.constBegin(); i != mapWalletViews.constEnd(); ++i) i.value()->showOutOfSyncWarning(fShow); } void WalletFrame::gotoOverviewPage() { QMap<WalletModel*, WalletView*>::const_iterator i; for (i = mapWalletViews.constBegin(); i != mapWalletViews.constEnd(); ++i) i.value()->gotoOverviewPage(); } void WalletFrame::gotoHistoryPage() { QMap<WalletModel*, WalletView*>::const_iterator i; for (i = mapWalletViews.constBegin(); i != mapWalletViews.constEnd(); ++i) i.value()->gotoHistoryPage(); } void WalletFrame::gotoReceiveCoinsPage() { QMap<WalletModel*, WalletView*>::const_iterator i; for (i = mapWalletViews.constBegin(); i != mapWalletViews.constEnd(); ++i) i.value()->gotoReceiveCoinsPage(); } void WalletFrame::gotoSendCoinsPage(QString addr) { QMap<WalletModel*, WalletView*>::const_iterator i; for (i = mapWalletViews.constBegin(); i != mapWalletViews.constEnd(); ++i) i.value()->gotoSendCoinsPage(addr); } void WalletFrame::gotoSignMessageTab(QString addr) { WalletView *walletView = currentWalletView(); if (walletView) walletView->gotoSignMessageTab(addr); } void WalletFrame::gotoVerifyMessageTab(QString addr) { WalletView *walletView = currentWalletView(); if (walletView) walletView->gotoVerifyMessageTab(addr); } void WalletFrame::gotoLoadPSBT(bool from_clipboard) { std::string data; if (from_clipboard) { std::string raw = QApplication::clipboard()->text().toStdString(); bool invalid; data = DecodeBase64(raw, &invalid); if (invalid) { Q_EMIT message(tr("Error"), tr("Unable to decode PSBT from clipboard (invalid base64)"), CClientUIInterface::MSG_ERROR); return; } } else { QString filename = GUIUtil::getOpenFileName(this, tr("Load Transaction Data"), QString(), tr("Partially Signed Transaction (*.psbt)"), nullptr); if (filename.isEmpty()) return; if (GetFileSize(filename.toLocal8Bit().data(), MAX_FILE_SIZE_PSBT) == MAX_FILE_SIZE_PSBT) { Q_EMIT message(tr("Error"), tr("PSBT file must be smaller than 100 MiB"), CClientUIInterface::MSG_ERROR); return; } std::ifstream in{filename.toLocal8Bit().data(), std::ios::binary}; data = std::string(std::istreambuf_iterator<char>{in}, {}); // Some psbt files may be base64 strings in the file rather than binary data bool invalid = false; std::string b64_dec = data; b64_dec.erase(b64_dec.find_last_not_of(" \t\n\r\f\v") + 1); // Trim trailing whitespace b64_dec = DecodeBase64(b64_dec, &invalid); if (!invalid) { data = b64_dec; } } std::string error; PartiallySignedTransaction psbtx; if (!DecodeRawPSBT(psbtx, data, error)) { Q_EMIT message(tr("Error"), tr("Unable to decode PSBT") + "\n" + QString::fromStdString(error), CClientUIInterface::MSG_ERROR); return; } auto dlg = new PSBTOperationsDialog(this, currentWalletModel(), clientModel); dlg->openWithPSBT(psbtx); GUIUtil::ShowModalDialogAsynchronously(dlg); } void WalletFrame::encryptWallet() { WalletView *walletView = currentWalletView(); if (walletView) walletView->encryptWallet(); } void WalletFrame::backupWallet() { WalletView *walletView = currentWalletView(); if (walletView) walletView->backupWallet(); } void WalletFrame::changePassphrase() { WalletView *walletView = currentWalletView(); if (walletView) walletView->changePassphrase(); } void WalletFrame::unlockWallet() { WalletView *walletView = currentWalletView(); if (walletView) walletView->unlockWallet(); } void WalletFrame::usedSendingAddresses() { WalletView *walletView = currentWalletView(); if (walletView) walletView->usedSendingAddresses(); } void WalletFrame::usedReceivingAddresses() { WalletView *walletView = currentWalletView(); if (walletView) walletView->usedReceivingAddresses(); } WalletView* WalletFrame::currentWalletView() const { return qobject_cast<WalletView*>(walletStack->currentWidget()); } WalletModel* WalletFrame::currentWalletModel() const { WalletView* wallet_view = currentWalletView(); return wallet_view ? wallet_view->getWalletModel() : nullptr; } <|endoftext|>
<commit_before>#include "SLAPrint.hpp" #include "ClipperUtils.hpp" #include "ExtrusionEntity.hpp" #include "Fill/Fill.hpp" #include "Geometry.hpp" #include "Surface.hpp" #include <iostream> #include <complex> #include <cstdio> namespace Slic3r { void SLAPrint::slice() { TriangleMesh mesh = this->model->mesh(); mesh.repair(); // align to origin taking raft into account this->bb = mesh.bounding_box(); if (this->config.raft_layers > 0) { this->bb.min.x -= this->config.raft_offset.value; this->bb.min.y -= this->config.raft_offset.value; this->bb.max.x += this->config.raft_offset.value; this->bb.max.y += this->config.raft_offset.value; } mesh.translate(0, 0, -bb.min.z); this->bb.translate(0, 0, -bb.min.z); // if we are generating a raft, first_layer_height will not affect mesh slicing const float lh = this->config.layer_height.value; const float first_lh = this->config.first_layer_height.value; // generate the list of Z coordinates for mesh slicing // (we slice each layer at half of its thickness) this->layers.clear(); { const float first_slice_lh = (this->config.raft_layers > 0) ? lh : first_lh; this->layers.push_back(Layer(first_slice_lh/2, first_slice_lh)); } while (this->layers.back().print_z + lh/2 <= mesh.stl.stats.max.z) { this->layers.push_back(Layer(this->layers.back().print_z + lh/2, this->layers.back().print_z + lh)); } // perform slicing and generate layers { std::vector<float> slice_z; for (size_t i = 0; i < this->layers.size(); ++i) slice_z.push_back(this->layers[i].slice_z); std::vector<ExPolygons> slices; TriangleMeshSlicer<Z>(&mesh).slice(slice_z, &slices); for (size_t i = 0; i < slices.size(); ++i) this->layers[i].slices.expolygons = slices[i]; } // generate infill if (this->config.fill_density < 100) { std::unique_ptr<Fill> fill(Fill::new_from_type(this->config.fill_pattern.value)); fill->bounding_box.merge(Point::new_scale(bb.min.x, bb.min.y)); fill->bounding_box.merge(Point::new_scale(bb.max.x, bb.max.y)); fill->min_spacing = this->config.get_abs_value("infill_extrusion_width", this->config.layer_height.value); fill->angle = Geometry::deg2rad(this->config.fill_angle.value); fill->density = this->config.fill_density.value/100; parallelize<size_t>( 0, this->layers.size()-1, boost::bind(&SLAPrint::_infill_layer, this, _1, fill.get()), this->config.threads.value ); } // generate support material this->sm_pillars.clear(); ExPolygons overhangs; if (this->config.support_material) { // flatten and merge all the overhangs { Polygons pp; for (std::vector<Layer>::const_iterator it = this->layers.begin()+1; it != this->layers.end(); ++it) pp += diff(it->slices, (it - 1)->slices); overhangs = union_ex(pp); } // generate points following the shape of each island Points pillars_pos; const coordf_t spacing = scale_(this->config.support_material_spacing); const coordf_t radius = scale_(this->sm_pillars_radius()); for (ExPolygons::const_iterator it = overhangs.begin(); it != overhangs.end(); ++it) { // leave a radius/2 gap between pillars and contour to prevent lateral adhesion for (float inset = radius * 1.5;; inset += spacing) { // inset according to the configured spacing Polygons curr = offset(*it, -inset); if (curr.empty()) break; // generate points along the contours for (Polygons::const_iterator pg = curr.begin(); pg != curr.end(); ++pg) { Points pp = pg->equally_spaced_points(spacing); for (Points::const_iterator p = pp.begin(); p != pp.end(); ++p) pillars_pos.push_back(*p); } } } // for each pillar, check which layers it applies to for (Points::const_iterator p = pillars_pos.begin(); p != pillars_pos.end(); ++p) { SupportPillar pillar(*p); bool object_hit = false; // check layers top-down for (int i = this->layers.size()-1; i >= 0; --i) { // check whether point is void in this layer if (!this->layers[i].slices.contains(*p)) { // no slice contains the point, so it's in the void if (pillar.top_layer > 0) { // we have a pillar, so extend it pillar.bottom_layer = i + this->config.raft_layers; } else if (object_hit) { // we don't have a pillar and we're below the object, so create one pillar.top_layer = i + this->config.raft_layers; } } else { if (pillar.top_layer > 0) { // we have a pillar which is not needed anymore, so store it and initialize a new potential pillar this->sm_pillars.push_back(pillar); pillar = SupportPillar(*p); } object_hit = true; } } if (pillar.top_layer > 0) this->sm_pillars.push_back(pillar); } } // generate a solid raft if requested // (do this after support material because we take support material shape into account) if (this->config.raft_layers > 0) { ExPolygons raft = this->layers.front().slices + overhangs; // take support material into account raft = offset_ex(raft, scale_(this->config.raft_offset)); for (int i = this->config.raft_layers; i >= 1; --i) { this->layers.insert(this->layers.begin(), Layer(0, first_lh + lh * (i-1))); this->layers.front().slices = raft; } // prepend total raft height to all sliced layers for (size_t i = this->config.raft_layers; i < this->layers.size(); ++i) this->layers[i].print_z += first_lh + lh * (this->config.raft_layers-1); } } void SLAPrint::_infill_layer(size_t i, const Fill* _fill) { Layer &layer = this->layers[i]; const float shell_thickness = this->config.get_abs_value("perimeter_extrusion_width", this->config.layer_height.value); // In order to detect what regions of this layer need to be solid, // perform an intersection with layers within the requested shell thickness. Polygons internal = layer.slices; for (size_t j = 0; j < this->layers.size(); ++j) { const Layer &other = this->layers[j]; if (std::abs(other.print_z - layer.print_z) > shell_thickness) continue; if (j == 0 || j == this->layers.size()-1) { internal.clear(); break; } else if (i != j) { internal = intersection(internal, other.slices); if (internal.empty()) break; } } // If we have no internal infill, just print the whole layer as a solid slice. if (internal.empty()) return; layer.solid = false; const Polygons infill = offset(layer.slices, -scale_(shell_thickness)); // Generate solid infill layer.solid_infill << diff_ex(infill, internal, true); // Generate internal infill { std::unique_ptr<Fill> fill(_fill->clone()); fill->layer_id = i; fill->z = layer.print_z; ExtrusionPath templ(erInternalInfill); templ.width = fill->spacing(); const ExPolygons internal_ex = intersection_ex(infill, internal); for (ExPolygons::const_iterator it = internal_ex.begin(); it != internal_ex.end(); ++it) { Polylines polylines = fill->fill_surface(Surface(stInternal, *it)); layer.infill.append(polylines, templ); } } // Generate perimeter(s). layer.perimeters << diff_ex( layer.slices, offset(layer.slices, -scale_(shell_thickness)) ); } void SLAPrint::write_svg(const std::string &outputfile) const { const Sizef3 size = this->bb.size(); const double support_material_radius = sm_pillars_radius(); FILE* f = fopen(outputfile.c_str(), "w"); fprintf(f, "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n" "<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.0//EN\" \"http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd\">\n" "<svg width=\"%f\" height=\"%f\" xmlns=\"http://www.w3.org/2000/svg\" xmlns:svg=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" xmlns:slic3r=\"http://slic3r.org/namespaces/slic3r\" viewport-fill=\"black\">\n" "<!-- Generated using Slic3r %s http://slic3r.org/ -->\n" , size.x, size.y, SLIC3R_VERSION); for (size_t i = 0; i < this->layers.size(); ++i) { const Layer &layer = this->layers[i]; fprintf(f, "\t<g id=\"layer%zu\" slic3r:z=\"%0.4f\" slic3r:slice-z=\"%0.4f\" slic3r:layer-height=\"%0.4f\">\n", i, layer.print_z, layer.slice_z, layer.print_z - ((i == 0) ? 0. : this->layers[i-1].print_z) ); if (layer.solid) { const ExPolygons &slices = layer.slices.expolygons; for (ExPolygons::const_iterator it = slices.begin(); it != slices.end(); ++it) { std::string pd = this->_SVG_path_d(*it); fprintf(f,"\t\t<path d=\"%s\" style=\"fill: %s; stroke: %s; stroke-width: %s; fill-type: evenodd\" slic3r:area=\"%0.4f\" />\n", pd.c_str(), "white", "black", "0", unscale(unscale(it->area())) ); } } else { // Perimeters. for (ExPolygons::const_iterator it = layer.perimeters.expolygons.begin(); it != layer.perimeters.expolygons.end(); ++it) { std::string pd = this->_SVG_path_d(*it); fprintf(f,"\t\t<path d=\"%s\" style=\"fill: %s; stroke: %s; stroke-width: %s; fill-type: evenodd\" slic3r:type=\"perimeter\" />\n", pd.c_str(), "white", "black", "0" ); } // Solid infill. for (ExPolygons::const_iterator it = layer.solid_infill.expolygons.begin(); it != layer.solid_infill.expolygons.end(); ++it) { std::string pd = this->_SVG_path_d(*it); fprintf(f,"\t\t<path d=\"%s\" style=\"fill: %s; stroke: %s; stroke-width: %s; fill-type: evenodd\" slic3r:type=\"infill\" />\n", pd.c_str(), "white", "black", "0" ); } // Internal infill. for (ExtrusionEntitiesPtr::const_iterator it = layer.infill.entities.begin(); it != layer.infill.entities.end(); ++it) { const ExPolygons infill = union_ex((*it)->grow()); for (ExPolygons::const_iterator e = infill.begin(); e != infill.end(); ++e) { std::string pd = this->_SVG_path_d(*e); fprintf(f,"\t\t<path d=\"%s\" style=\"fill: %s; stroke: %s; stroke-width: %s; fill-type: evenodd\" slic3r:type=\"infill\" />\n", pd.c_str(), "white", "black", "0" ); } } } // don't print support material in raft layers if (i >= (size_t)this->config.raft_layers) { // look for support material pillars belonging to this layer for (std::vector<SupportPillar>::const_iterator it = this->sm_pillars.begin(); it != this->sm_pillars.end(); ++it) { if (!(it->top_layer >= i && it->bottom_layer <= i)) continue; // generate a conic tip float radius = fminf( support_material_radius, (it->top_layer - i + 1) * this->config.layer_height.value ); fprintf(f,"\t\t<circle cx=\"%f\" cy=\"%f\" r=\"%f\" stroke-width=\"0\" fill=\"white\" slic3r:type=\"support\" />\n", unscale(it->x) - this->bb.min.x, size.y - (unscale(it->y) - this->bb.min.y), radius ); } } fprintf(f,"\t</g>\n"); } fprintf(f,"</svg>\n"); } coordf_t SLAPrint::sm_pillars_radius() const { coordf_t radius = this->config.support_material_extrusion_width.get_abs_value(this->config.support_material_spacing)/2; if (radius == 0) radius = this->config.support_material_spacing / 3; // auto return radius; } std::string SLAPrint::_SVG_path_d(const Polygon &polygon) const { const Sizef3 size = this->bb.size(); std::ostringstream d; d << "M "; for (Points::const_iterator p = polygon.points.begin(); p != polygon.points.end(); ++p) { d << unscale(p->x) - this->bb.min.x << " "; d << size.y - (unscale(p->y) - this->bb.min.y) << " "; // mirror Y coordinates as SVG uses downwards Y } d << "z"; return d.str(); } std::string SLAPrint::_SVG_path_d(const ExPolygon &expolygon) const { std::string pd; const Polygons pp = expolygon; for (Polygons::const_iterator mp = pp.begin(); mp != pp.end(); ++mp) pd += this->_SVG_path_d(*mp) + " "; return pd; } } <commit_msg>Hotfix: Set minimum spacing to 0.3 if the provided configuration option is 0. Avoids a crash with infill density < 100% on SLA prints.<commit_after>#include "SLAPrint.hpp" #include "ClipperUtils.hpp" #include "ExtrusionEntity.hpp" #include "Fill/Fill.hpp" #include "Geometry.hpp" #include "Surface.hpp" #include <iostream> #include <complex> #include <cstdio> namespace Slic3r { void SLAPrint::slice() { TriangleMesh mesh = this->model->mesh(); mesh.repair(); // align to origin taking raft into account this->bb = mesh.bounding_box(); if (this->config.raft_layers > 0) { this->bb.min.x -= this->config.raft_offset.value; this->bb.min.y -= this->config.raft_offset.value; this->bb.max.x += this->config.raft_offset.value; this->bb.max.y += this->config.raft_offset.value; } mesh.translate(0, 0, -bb.min.z); this->bb.translate(0, 0, -bb.min.z); // if we are generating a raft, first_layer_height will not affect mesh slicing const float lh = this->config.layer_height.value; const float first_lh = this->config.first_layer_height.value; // generate the list of Z coordinates for mesh slicing // (we slice each layer at half of its thickness) this->layers.clear(); { const float first_slice_lh = (this->config.raft_layers > 0) ? lh : first_lh; this->layers.push_back(Layer(first_slice_lh/2, first_slice_lh)); } while (this->layers.back().print_z + lh/2 <= mesh.stl.stats.max.z) { this->layers.push_back(Layer(this->layers.back().print_z + lh/2, this->layers.back().print_z + lh)); } // perform slicing and generate layers { std::vector<float> slice_z; for (size_t i = 0; i < this->layers.size(); ++i) slice_z.push_back(this->layers[i].slice_z); std::vector<ExPolygons> slices; TriangleMeshSlicer<Z>(&mesh).slice(slice_z, &slices); for (size_t i = 0; i < slices.size(); ++i) this->layers[i].slices.expolygons = slices[i]; } this->config.get_abs_value("infill_extrusion_width", this->config.layer_height.value); // generate infill if (this->config.fill_density < 100) { std::unique_ptr<Fill> fill(Fill::new_from_type(this->config.fill_pattern.value)); fill->bounding_box.merge(Point::new_scale(bb.min.x, bb.min.y)); fill->bounding_box.merge(Point::new_scale(bb.max.x, bb.max.y)); fill->min_spacing = ( this->config.get_abs_value("infill_extrusion_width", this->config.layer_height.value) > 0 ? this->config.get_abs_value("infill_extrusion_width", this->config.layer_height.value) : 0.3); fill->angle = Geometry::deg2rad(this->config.fill_angle.value); fill->density = this->config.fill_density.value/100; parallelize<size_t>( 0, this->layers.size()-1, boost::bind(&SLAPrint::_infill_layer, this, _1, fill.get()), this->config.threads.value ); } // generate support material this->sm_pillars.clear(); ExPolygons overhangs; if (this->config.support_material) { // flatten and merge all the overhangs { Polygons pp; for (std::vector<Layer>::const_iterator it = this->layers.begin()+1; it != this->layers.end(); ++it) pp += diff(it->slices, (it - 1)->slices); overhangs = union_ex(pp); } // generate points following the shape of each island Points pillars_pos; const coordf_t spacing = scale_(this->config.support_material_spacing); const coordf_t radius = scale_(this->sm_pillars_radius()); for (ExPolygons::const_iterator it = overhangs.begin(); it != overhangs.end(); ++it) { // leave a radius/2 gap between pillars and contour to prevent lateral adhesion for (float inset = radius * 1.5;; inset += spacing) { // inset according to the configured spacing Polygons curr = offset(*it, -inset); if (curr.empty()) break; // generate points along the contours for (Polygons::const_iterator pg = curr.begin(); pg != curr.end(); ++pg) { Points pp = pg->equally_spaced_points(spacing); for (Points::const_iterator p = pp.begin(); p != pp.end(); ++p) pillars_pos.push_back(*p); } } } // for each pillar, check which layers it applies to for (Points::const_iterator p = pillars_pos.begin(); p != pillars_pos.end(); ++p) { SupportPillar pillar(*p); bool object_hit = false; // check layers top-down for (int i = this->layers.size()-1; i >= 0; --i) { // check whether point is void in this layer if (!this->layers[i].slices.contains(*p)) { // no slice contains the point, so it's in the void if (pillar.top_layer > 0) { // we have a pillar, so extend it pillar.bottom_layer = i + this->config.raft_layers; } else if (object_hit) { // we don't have a pillar and we're below the object, so create one pillar.top_layer = i + this->config.raft_layers; } } else { if (pillar.top_layer > 0) { // we have a pillar which is not needed anymore, so store it and initialize a new potential pillar this->sm_pillars.push_back(pillar); pillar = SupportPillar(*p); } object_hit = true; } } if (pillar.top_layer > 0) this->sm_pillars.push_back(pillar); } } // generate a solid raft if requested // (do this after support material because we take support material shape into account) if (this->config.raft_layers > 0) { ExPolygons raft = this->layers.front().slices + overhangs; // take support material into account raft = offset_ex(raft, scale_(this->config.raft_offset)); for (int i = this->config.raft_layers; i >= 1; --i) { this->layers.insert(this->layers.begin(), Layer(0, first_lh + lh * (i-1))); this->layers.front().slices = raft; } // prepend total raft height to all sliced layers for (size_t i = this->config.raft_layers; i < this->layers.size(); ++i) this->layers[i].print_z += first_lh + lh * (this->config.raft_layers-1); } } void SLAPrint::_infill_layer(size_t i, const Fill* _fill) { Layer &layer = this->layers[i]; const float shell_thickness = this->config.get_abs_value("perimeter_extrusion_width", this->config.layer_height.value); // In order to detect what regions of this layer need to be solid, // perform an intersection with layers within the requested shell thickness. Polygons internal = layer.slices; for (size_t j = 0; j < this->layers.size(); ++j) { const Layer &other = this->layers[j]; if (std::abs(other.print_z - layer.print_z) > shell_thickness) continue; if (j == 0 || j == this->layers.size()-1) { internal.clear(); break; } else if (i != j) { internal = intersection(internal, other.slices); if (internal.empty()) break; } } // If we have no internal infill, just print the whole layer as a solid slice. if (internal.empty()) return; layer.solid = false; const Polygons infill = offset(layer.slices, -scale_(shell_thickness)); // Generate solid infill layer.solid_infill << diff_ex(infill, internal, true); // Generate internal infill { std::unique_ptr<Fill> fill(_fill->clone()); fill->layer_id = i; fill->z = layer.print_z; ExtrusionPath templ(erInternalInfill); templ.width = fill->spacing(); const ExPolygons internal_ex = intersection_ex(infill, internal); for (ExPolygons::const_iterator it = internal_ex.begin(); it != internal_ex.end(); ++it) { Polylines polylines = fill->fill_surface(Surface(stInternal, *it)); layer.infill.append(polylines, templ); } } // Generate perimeter(s). layer.perimeters << diff_ex( layer.slices, offset(layer.slices, -scale_(shell_thickness)) ); } void SLAPrint::write_svg(const std::string &outputfile) const { const Sizef3 size = this->bb.size(); const double support_material_radius = sm_pillars_radius(); FILE* f = fopen(outputfile.c_str(), "w"); fprintf(f, "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n" "<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.0//EN\" \"http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd\">\n" "<svg width=\"%f\" height=\"%f\" xmlns=\"http://www.w3.org/2000/svg\" xmlns:svg=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" xmlns:slic3r=\"http://slic3r.org/namespaces/slic3r\" viewport-fill=\"black\">\n" "<!-- Generated using Slic3r %s http://slic3r.org/ -->\n" , size.x, size.y, SLIC3R_VERSION); for (size_t i = 0; i < this->layers.size(); ++i) { const Layer &layer = this->layers[i]; fprintf(f, "\t<g id=\"layer%zu\" slic3r:z=\"%0.4f\" slic3r:slice-z=\"%0.4f\" slic3r:layer-height=\"%0.4f\">\n", i, layer.print_z, layer.slice_z, layer.print_z - ((i == 0) ? 0. : this->layers[i-1].print_z) ); if (layer.solid) { const ExPolygons &slices = layer.slices.expolygons; for (ExPolygons::const_iterator it = slices.begin(); it != slices.end(); ++it) { std::string pd = this->_SVG_path_d(*it); fprintf(f,"\t\t<path d=\"%s\" style=\"fill: %s; stroke: %s; stroke-width: %s; fill-type: evenodd\" slic3r:area=\"%0.4f\" />\n", pd.c_str(), "white", "black", "0", unscale(unscale(it->area())) ); } } else { // Perimeters. for (ExPolygons::const_iterator it = layer.perimeters.expolygons.begin(); it != layer.perimeters.expolygons.end(); ++it) { std::string pd = this->_SVG_path_d(*it); fprintf(f,"\t\t<path d=\"%s\" style=\"fill: %s; stroke: %s; stroke-width: %s; fill-type: evenodd\" slic3r:type=\"perimeter\" />\n", pd.c_str(), "white", "black", "0" ); } // Solid infill. for (ExPolygons::const_iterator it = layer.solid_infill.expolygons.begin(); it != layer.solid_infill.expolygons.end(); ++it) { std::string pd = this->_SVG_path_d(*it); fprintf(f,"\t\t<path d=\"%s\" style=\"fill: %s; stroke: %s; stroke-width: %s; fill-type: evenodd\" slic3r:type=\"infill\" />\n", pd.c_str(), "white", "black", "0" ); } // Internal infill. for (ExtrusionEntitiesPtr::const_iterator it = layer.infill.entities.begin(); it != layer.infill.entities.end(); ++it) { const ExPolygons infill = union_ex((*it)->grow()); for (ExPolygons::const_iterator e = infill.begin(); e != infill.end(); ++e) { std::string pd = this->_SVG_path_d(*e); fprintf(f,"\t\t<path d=\"%s\" style=\"fill: %s; stroke: %s; stroke-width: %s; fill-type: evenodd\" slic3r:type=\"infill\" />\n", pd.c_str(), "white", "black", "0" ); } } } // don't print support material in raft layers if (i >= (size_t)this->config.raft_layers) { // look for support material pillars belonging to this layer for (std::vector<SupportPillar>::const_iterator it = this->sm_pillars.begin(); it != this->sm_pillars.end(); ++it) { if (!(it->top_layer >= i && it->bottom_layer <= i)) continue; // generate a conic tip float radius = fminf( support_material_radius, (it->top_layer - i + 1) * this->config.layer_height.value ); fprintf(f,"\t\t<circle cx=\"%f\" cy=\"%f\" r=\"%f\" stroke-width=\"0\" fill=\"white\" slic3r:type=\"support\" />\n", unscale(it->x) - this->bb.min.x, size.y - (unscale(it->y) - this->bb.min.y), radius ); } } fprintf(f,"\t</g>\n"); } fprintf(f,"</svg>\n"); } coordf_t SLAPrint::sm_pillars_radius() const { coordf_t radius = this->config.support_material_extrusion_width.get_abs_value(this->config.support_material_spacing)/2; if (radius == 0) radius = this->config.support_material_spacing / 3; // auto return radius; } std::string SLAPrint::_SVG_path_d(const Polygon &polygon) const { const Sizef3 size = this->bb.size(); std::ostringstream d; d << "M "; for (Points::const_iterator p = polygon.points.begin(); p != polygon.points.end(); ++p) { d << unscale(p->x) - this->bb.min.x << " "; d << size.y - (unscale(p->y) - this->bb.min.y) << " "; // mirror Y coordinates as SVG uses downwards Y } d << "z"; return d.str(); } std::string SLAPrint::_SVG_path_d(const ExPolygon &expolygon) const { std::string pd; const Polygons pp = expolygon; for (Polygons::const_iterator mp = pp.begin(); mp != pp.end(); ++mp) pd += this->_SVG_path_d(*mp) + " "; return pd; } } <|endoftext|>
<commit_before>/** * @author: Jeff Thompson * See COPYING for copyright and distribution information. */ #ifndef NDN_KEY_HPP #define NDN_KEY_HPP #include <vector> #include "c/key.h" #include "Name.hpp" namespace ndn { class KeyLocator { public: KeyLocator() : type_((ndn_KeyLocatorType)-1), keyNameType_((ndn_KeyNameType)-1) { } /** * Set the keyLocatorStruct to point to the values in this key locator, without copying any memory. * WARNING: The resulting pointers in keyLocatorStruct are invalid after a further use of this object which could reallocate memory. * @param keyLocatorStruct a C ndn_KeyLocator struct where the name components array is already allocated. */ void get(struct ndn_KeyLocator &keyLocatorStruct) const; /** * Clear this key locator, and set the values by copying from the ndn_KeyLocator struct. * @param keyLocatorStruct a C ndn_KeyLocator struct */ void set(const struct ndn_KeyLocator &keyLocatorStruct); ndn_KeyLocatorType getType() const { return type_; } const std::vector<unsigned char> &getKeyData() const { return keyData_; } const Name &getKeyName() const { return keyName_; } Name &getKeyName() { return keyName_; } ndn_KeyNameType getKeyNameType() const { return keyNameType_; } void setType(ndn_KeyLocatorType type) { type_ = type; } void setKeyData(const std::vector<unsigned char> &keyData) { keyData_ = keyData; } void setKeyData(const unsigned char *keyData, unsigned int keyDataLength) { setVector(keyData_, keyData, keyDataLength); } /** * @deprecated Use getKeyData(). */ const std::vector<unsigned char> &getKeyOrCertificate() const { return getKeyData(); } /** * @deprecated Use setKeyData. */ void setKeyOrCertificate(const std::vector<unsigned char> &keyData) { setKeyData(keyData); } /** * @deprecated Use setKeyData. */ void setKeyOrCertificate(const unsigned char *keyData, unsigned int keyDataLength) { setKeyData(keyData, keyDataLength); } void setKeyNameType(ndn_KeyNameType keyNameType) { keyNameType_ = keyNameType; } private: ndn_KeyLocatorType type_; /**< -1 for none */ std::vector<unsigned char> keyData_; /**< A pointer to a pre-allocated buffer for the key data as follows: * If type_ is ndn_KeyLocatorType_KEY, the key data. * If type_ is ndn_KeyLocatorType_CERTIFICATE, the certificate data. * If type_ is ndn_KeyLocatorType_KEYNAME and keyNameType_ is ndn_KeyNameType_PUBLISHER_PUBLIC_KEY_DIGEST, the publisher public key digest. * If type_ is ndn_KeyLocatorType_KEYNAME and keyNameType_ is ndn_KeyNameType_PUBLISHER_CERTIFICATE_DIGEST, the publisher certificate digest. * If type_ is ndn_KeyLocatorType_KEYNAME and keyNameType_ is ndn_KeyNameType_PUBLISHER_ISSUER_KEY_DIGEST, the publisher issuer key digest. * If type_ is ndn_KeyLocatorType_KEYNAME and keyNameType_ is ndn_KeyNameType_PUBLISHER_ISSUER_CERTIFICATE_DIGEST, the publisher issuer certificate digest. */ Name keyName_; /**< The key name (only used if type_ is ndn_KeyLocatorType_KEYNAME.) */ ndn_KeyNameType keyNameType_; /**< The type of data for keyName_ (only used if type_ is ndn_KeyLocatorType_KEYNAME.) */ }; } #endif <commit_msg>Fix typo for inlcude name.hpp<commit_after>/** * @author: Jeff Thompson * See COPYING for copyright and distribution information. */ #ifndef NDN_KEY_HPP #define NDN_KEY_HPP #include <vector> #include "c/key.h" #include "name.hpp" namespace ndn { class KeyLocator { public: KeyLocator() : type_((ndn_KeyLocatorType)-1), keyNameType_((ndn_KeyNameType)-1) { } /** * Set the keyLocatorStruct to point to the values in this key locator, without copying any memory. * WARNING: The resulting pointers in keyLocatorStruct are invalid after a further use of this object which could reallocate memory. * @param keyLocatorStruct a C ndn_KeyLocator struct where the name components array is already allocated. */ void get(struct ndn_KeyLocator &keyLocatorStruct) const; /** * Clear this key locator, and set the values by copying from the ndn_KeyLocator struct. * @param keyLocatorStruct a C ndn_KeyLocator struct */ void set(const struct ndn_KeyLocator &keyLocatorStruct); ndn_KeyLocatorType getType() const { return type_; } const std::vector<unsigned char> &getKeyData() const { return keyData_; } const Name &getKeyName() const { return keyName_; } Name &getKeyName() { return keyName_; } ndn_KeyNameType getKeyNameType() const { return keyNameType_; } void setType(ndn_KeyLocatorType type) { type_ = type; } void setKeyData(const std::vector<unsigned char> &keyData) { keyData_ = keyData; } void setKeyData(const unsigned char *keyData, unsigned int keyDataLength) { setVector(keyData_, keyData, keyDataLength); } /** * @deprecated Use getKeyData(). */ const std::vector<unsigned char> &getKeyOrCertificate() const { return getKeyData(); } /** * @deprecated Use setKeyData. */ void setKeyOrCertificate(const std::vector<unsigned char> &keyData) { setKeyData(keyData); } /** * @deprecated Use setKeyData. */ void setKeyOrCertificate(const unsigned char *keyData, unsigned int keyDataLength) { setKeyData(keyData, keyDataLength); } void setKeyNameType(ndn_KeyNameType keyNameType) { keyNameType_ = keyNameType; } private: ndn_KeyLocatorType type_; /**< -1 for none */ std::vector<unsigned char> keyData_; /**< A pointer to a pre-allocated buffer for the key data as follows: * If type_ is ndn_KeyLocatorType_KEY, the key data. * If type_ is ndn_KeyLocatorType_CERTIFICATE, the certificate data. * If type_ is ndn_KeyLocatorType_KEYNAME and keyNameType_ is ndn_KeyNameType_PUBLISHER_PUBLIC_KEY_DIGEST, the publisher public key digest. * If type_ is ndn_KeyLocatorType_KEYNAME and keyNameType_ is ndn_KeyNameType_PUBLISHER_CERTIFICATE_DIGEST, the publisher certificate digest. * If type_ is ndn_KeyLocatorType_KEYNAME and keyNameType_ is ndn_KeyNameType_PUBLISHER_ISSUER_KEY_DIGEST, the publisher issuer key digest. * If type_ is ndn_KeyLocatorType_KEYNAME and keyNameType_ is ndn_KeyNameType_PUBLISHER_ISSUER_CERTIFICATE_DIGEST, the publisher issuer certificate digest. */ Name keyName_; /**< The key name (only used if type_ is ndn_KeyLocatorType_KEYNAME.) */ ndn_KeyNameType keyNameType_; /**< The type of data for keyName_ (only used if type_ is ndn_KeyLocatorType_KEYNAME.) */ }; } #endif <|endoftext|>
<commit_before>/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org Copyright (c) 2000-2009 Torus Knot Software Ltd Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------------- */ #include "OgreGLSLESExtSupport.h" #include "OgreLogManager.h" namespace Ogre { //----------------------------------------------------------------------------- String logObjectInfo(const String& msg, const GLuint obj) { String logMessage = msg; if (obj > 0) { GLint infologLength = 0; if(glIsShader(obj)) { glGetShaderiv(obj, GL_INFO_LOG_LENGTH, &infologLength); GL_CHECK_ERROR } else if(glIsProgram(obj)) { glGetProgramiv(obj, GL_INFO_LOG_LENGTH, &infologLength); GL_CHECK_ERROR } if (infologLength > 0) { GLint charsWritten = 0; //GLchar * infoLog = OGRE_NEW GLchar[infologLength]; char * infoLog = new char [infologLength]; infoLog[0] = 0; if(glIsShader(obj)) { glGetShaderInfoLog(obj, infologLength, &charsWritten, infoLog); GL_CHECK_ERROR } else if(glIsProgram(obj)) { glGetProgramInfoLog(obj, infologLength, &charsWritten, infoLog); GL_CHECK_ERROR } if (strlen(infoLog) > 0) { logMessage += "\n" + String(infoLog); } LogManager::getSingleton().logMessage(logMessage); OGRE_DELETE [] infoLog; } } return logMessage; } } // namespace Ogre <commit_msg>GLES2 render system: removed end of line chars from the compile result to log function - - so there will be less empty lines in the log.<commit_after>/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org Copyright (c) 2000-2009 Torus Knot Software Ltd Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------------- */ #include "OgreGLSLESExtSupport.h" #include "OgreLogManager.h" namespace Ogre { //----------------------------------------------------------------------------- String logObjectInfo(const String& msg, const GLuint obj) { String logMessage = msg; if (obj > 0) { GLint infologLength = 0; if(glIsShader(obj)) { glGetShaderiv(obj, GL_INFO_LOG_LENGTH, &infologLength); GL_CHECK_ERROR } else if(glIsProgram(obj)) { glGetProgramiv(obj, GL_INFO_LOG_LENGTH, &infologLength); GL_CHECK_ERROR } if (infologLength > 1) { GLint charsWritten = 0; //GLchar * infoLog = OGRE_NEW GLchar[infologLength]; char * infoLog = new char [infologLength]; infoLog[0] = 0; if(glIsShader(obj)) { glGetShaderInfoLog(obj, infologLength, &charsWritten, infoLog); GL_CHECK_ERROR } else if(glIsProgram(obj)) { glGetProgramInfoLog(obj, infologLength, &charsWritten, infoLog); GL_CHECK_ERROR } if (strlen(infoLog) > 0) { logMessage += "\n" + String(infoLog); } OGRE_DELETE [] infoLog; if (logMessage.size() > 0) { // remove ends of line in the end - so there will be no empty lines in the log. while( logMessage[logMessage.size() - 1] == '\n' ) { logMessage.erase(logMessage.size() - 1, 1); } LogManager::getSingleton().logMessage(logMessage); } } } return logMessage; } } // namespace Ogre <|endoftext|>
<commit_before>// Copyright 2014 The Crashpad 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 "util/mach/mach_message_server.h" #include <limits> #include "base/mac/mach_logging.h" #include "base/mac/scoped_mach_vm.h" #include "util/misc/clock.h" namespace crashpad { namespace { const int kNanosecondsPerMillisecond = 1E6; // TimerRunning determines whether |deadline| has passed. If |deadline| is in // the future, |*remaining_ms| is set to the number of milliseconds remaining, // which will always be a positive value, and this function returns true. If // |deadline| is zero (indicating that no timer is in effect), |*remaining_ms| // is set to zero and this function returns true. Otherwise, this function // returns false. |deadline| is specified on the same time base as is returned // by ClockMonotonicNanoseconds(). bool TimerRunning(uint64_t deadline, mach_msg_timeout_t* remaining_ms) { if (!deadline) { *remaining_ms = MACH_MSG_TIMEOUT_NONE; return true; } uint64_t now = ClockMonotonicNanoseconds(); if (now >= deadline) { return false; } uint64_t remaining = deadline - now; // Round to the nearest millisecond, taking care not to overflow. const int kHalfMillisecondInNanoseconds = kNanosecondsPerMillisecond / 2; mach_msg_timeout_t remaining_mach; if (remaining <= std::numeric_limits<uint64_t>::max() - kHalfMillisecondInNanoseconds) { remaining_mach = (remaining + kHalfMillisecondInNanoseconds) / kNanosecondsPerMillisecond; } else { remaining_mach = remaining / kNanosecondsPerMillisecond; } if (remaining_mach == MACH_MSG_TIMEOUT_NONE) { return false; } *remaining_ms = remaining_mach; return true; } } // namespace // This implementation is based on 10.9.4 // xnu-2422.110.17/libsyscall/mach/mach_msg.c mach_msg_server_once(), but // adapted to local style using scopers, replacing the server callback function // and |max_size| parameter with a C++ interface, and with the addition of the // the |persistent| parameter allowing this function to serve as a stand-in for // mach_msg_server(), the |nonblocking| parameter to control blocking directly, // and the |timeout_ms| parameter allowing this function to not block // indefinitely. // // static mach_msg_return_t MachMessageServer::Run(Interface* interface, mach_port_t receive_port, mach_msg_options_t options, Persistent persistent, Nonblocking nonblocking, ReceiveLarge receive_large, mach_msg_timeout_t timeout_ms) { options &= ~(MACH_RCV_MSG | MACH_SEND_MSG); mach_msg_options_t timeout_options = MACH_RCV_TIMEOUT | MACH_SEND_TIMEOUT | MACH_RCV_INTERRUPT | MACH_SEND_INTERRUPT; uint64_t deadline; if (nonblocking == kNonblocking) { options |= timeout_options; deadline = 0; } else if (timeout_ms != MACH_MSG_TIMEOUT_NONE) { options |= timeout_options; deadline = ClockMonotonicNanoseconds() + implicit_cast<uint64_t>(timeout_ms) * kNanosecondsPerMillisecond; } else { options &= ~timeout_options; deadline = 0; } if (receive_large == kReceiveLargeResize) { options |= MACH_RCV_LARGE; } else { options &= ~MACH_RCV_LARGE; } mach_msg_size_t trailer_alloc = REQUESTED_TRAILER_SIZE(options); mach_msg_size_t max_request_size = interface->MachMessageServerRequestSize(); mach_msg_size_t request_alloc = round_page(round_msg(max_request_size) + trailer_alloc); // mach_msg_server() and mach_msg_server_once() invert this condition, but // their interpretation is incorrect. When it is desirable to retry a receive // attempt that returns MACH_RCV_TOO_LARGE with a larger receive buffer, it is // also desirable to use the full receive buffer rounded up to a page size for // the initial receive attempt. On the other hand, when this behavior is not // requested, there is no reason to attempt receiving messages any larger than // expected. mach_msg_size_t request_size = (receive_large == kReceiveLargeResize) ? round_msg(max_request_size) + trailer_alloc : request_alloc; mach_msg_size_t max_reply_size = interface->MachMessageServerReplySize(); // mach_msg_server() and mach_msg_server_once() would consider whether // |options| contains MACH_SEND_TRAILER and include MAX_TRAILER_SIZE in this // computation if it does, but that option is ineffective on OS X. mach_msg_size_t reply_alloc = round_page(max_reply_size); kern_return_t kr; do { mach_msg_size_t this_request_alloc = request_alloc; mach_msg_size_t this_request_size = request_size; base::mac::ScopedMachVM request_scoper; mach_msg_header_t* request_header = nullptr; while (!request_scoper.address()) { vm_address_t request_addr; kr = vm_allocate(mach_task_self(), &request_addr, this_request_alloc, VM_FLAGS_ANYWHERE | VM_MAKE_TAG(VM_MEMORY_MACH_MSG)); if (kr != KERN_SUCCESS) { return kr; } base::mac::ScopedMachVM trial_request_scoper(request_addr, this_request_alloc); request_header = reinterpret_cast<mach_msg_header_t*>(request_addr); bool run_mach_msg_receive = false; do { // If |options| contains MACH_RCV_INTERRUPT, retry mach_msg() in a loop // when it returns MACH_RCV_INTERRUPTED to recompute |remaining_ms| // rather than allowing mach_msg() to retry using the original timeout // value. See 10.9.4 xnu-2422.110.17/libsyscall/mach/mach_msg.c // mach_msg(). mach_msg_timeout_t remaining_ms; if (!TimerRunning(deadline, &remaining_ms)) { return MACH_RCV_TIMED_OUT; } kr = mach_msg(request_header, options | MACH_RCV_MSG, 0, this_request_size, receive_port, remaining_ms, MACH_PORT_NULL); if (kr == MACH_RCV_TOO_LARGE && receive_large == kReceiveLargeIgnore) { MACH_LOG(WARNING, kr) << "mach_msg: ignoring large message"; run_mach_msg_receive = true; } else if (kr == MACH_RCV_INTERRUPTED) { run_mach_msg_receive = true; } } while (run_mach_msg_receive); if (kr == MACH_MSG_SUCCESS) { request_scoper.swap(trial_request_scoper); } else if (kr == MACH_RCV_TOO_LARGE && receive_large == kReceiveLargeResize) { this_request_size = round_page(round_msg(request_header->msgh_size) + trailer_alloc); this_request_alloc = this_request_size; } else { return kr; } } vm_address_t reply_addr; kr = vm_allocate(mach_task_self(), &reply_addr, reply_alloc, VM_FLAGS_ANYWHERE | VM_MAKE_TAG(VM_MEMORY_MACH_MSG)); if (kr != KERN_SUCCESS) { return kr; } base::mac::ScopedMachVM reply_scoper(reply_addr, reply_alloc); mach_msg_header_t* reply_header = reinterpret_cast<mach_msg_header_t*>(reply_addr); bool destroy_complex_request = false; interface->MachMessageServerFunction( request_header, reply_header, &destroy_complex_request); if (!(reply_header->msgh_bits & MACH_MSGH_BITS_COMPLEX)) { // This only works if the reply message is not complex, because otherwise, // the location of the RetCode field is not known. It should be possible // to locate the RetCode field by looking beyond the descriptors in a // complex reply message, but this is not currently done. This behavior // has not proven itself necessary in practice, and it’s not done by // mach_msg_server() or mach_msg_server_once() either. mig_reply_error_t* reply_mig = reinterpret_cast<mig_reply_error_t*>(reply_header); if (reply_mig->RetCode == MIG_NO_REPLY) { reply_header->msgh_remote_port = MACH_PORT_NULL; } else if (reply_mig->RetCode != KERN_SUCCESS && request_header->msgh_bits & MACH_MSGH_BITS_COMPLEX) { destroy_complex_request = true; } } if (destroy_complex_request && request_header->msgh_bits & MACH_MSGH_BITS_COMPLEX) { request_header->msgh_remote_port = MACH_PORT_NULL; mach_msg_destroy(request_header); } if (reply_header->msgh_remote_port != MACH_PORT_NULL) { // If the reply port right is a send-once right, the send won’t block even // if the remote side isn’t waiting for a message. No timeout is used, // which keeps the communication on the kernel’s fast path. If the reply // port right is a send right, MACH_SEND_TIMEOUT is used to avoid blocking // indefinitely. This duplicates the logic in 10.9.4 // xnu-2422.110.17/libsyscall/mach/mach_msg.c mach_msg_server_once(). mach_msg_option_t send_options = options | MACH_SEND_MSG | (MACH_MSGH_BITS_REMOTE(reply_header->msgh_bits) == MACH_MSG_TYPE_MOVE_SEND_ONCE ? 0 : MACH_SEND_TIMEOUT); bool running; do { // If |options| contains MACH_SEND_INTERRUPT, retry mach_msg() in a loop // when it returns MACH_SEND_INTERRUPTED to recompute |remaining_ms| // rather than allowing mach_msg() to retry using the original timeout // value. See 10.9.4 xnu-2422.110.17/libsyscall/mach/mach_msg.c // mach_msg(). mach_msg_timeout_t remaining_ms; running = TimerRunning(deadline, &remaining_ms); if (!running) { // Don’t return just yet. If the timer ran out in between the time the // request was received and now, at least try to send the response. remaining_ms = 0; } kr = mach_msg(reply_header, send_options, reply_header->msgh_size, 0, MACH_PORT_NULL, remaining_ms, MACH_PORT_NULL); } while (kr == MACH_SEND_INTERRUPTED); if (kr != KERN_SUCCESS) { if (kr == MACH_SEND_INVALID_DEST || kr == MACH_SEND_TIMED_OUT) { mach_msg_destroy(reply_header); } return kr; } if (!running) { // The reply message was sent successfuly, so act as though the deadline // was reached before or during the subsequent receive operation when in // persistent mode, and just return success when not in persistent mode. return (persistent == kPersistent) ? MACH_RCV_TIMED_OUT : kr; } } } while (persistent == kPersistent); return kr; } } // namespace crashpad <commit_msg>Undo a68594234262.<commit_after>// Copyright 2014 The Crashpad 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 "util/mach/mach_message_server.h" #include <limits> #include "base/mac/mach_logging.h" #include "base/mac/scoped_mach_vm.h" #include "util/misc/clock.h" namespace crashpad { namespace { const int kNanosecondsPerMillisecond = 1E6; // TimerRunning determines whether |deadline| has passed. If |deadline| is in // the future, |*remaining_ms| is set to the number of milliseconds remaining, // which will always be a positive value, and this function returns true. If // |deadline| is zero (indicating that no timer is in effect), |*remaining_ms| // is set to zero and this function returns true. Otherwise, this function // returns false. |deadline| is specified on the same time base as is returned // by ClockMonotonicNanoseconds(). bool TimerRunning(uint64_t deadline, mach_msg_timeout_t* remaining_ms) { if (!deadline) { *remaining_ms = MACH_MSG_TIMEOUT_NONE; return true; } uint64_t now = ClockMonotonicNanoseconds(); if (now >= deadline) { return false; } uint64_t remaining = deadline - now; // Round to the nearest millisecond, taking care not to overflow. const int kHalfMillisecondInNanoseconds = kNanosecondsPerMillisecond / 2; mach_msg_timeout_t remaining_mach; if (remaining <= std::numeric_limits<uint64_t>::max() - kHalfMillisecondInNanoseconds) { remaining_mach = (remaining + kHalfMillisecondInNanoseconds) / kNanosecondsPerMillisecond; } else { remaining_mach = remaining / kNanosecondsPerMillisecond; } if (remaining_mach == MACH_MSG_TIMEOUT_NONE) { return false; } *remaining_ms = remaining_mach; return true; } } // namespace // This implementation is based on 10.9.4 // xnu-2422.110.17/libsyscall/mach/mach_msg.c mach_msg_server_once(), but // adapted to local style using scopers, replacing the server callback function // and |max_size| parameter with a C++ interface, and with the addition of the // the |persistent| parameter allowing this function to serve as a stand-in for // mach_msg_server(), the |nonblocking| parameter to control blocking directly, // and the |timeout_ms| parameter allowing this function to not block // indefinitely. // // static mach_msg_return_t MachMessageServer::Run(Interface* interface, mach_port_t receive_port, mach_msg_options_t options, Persistent persistent, Nonblocking nonblocking, ReceiveLarge receive_large, mach_msg_timeout_t timeout_ms) { options &= ~(MACH_RCV_MSG | MACH_SEND_MSG); mach_msg_options_t timeout_options = MACH_RCV_TIMEOUT | MACH_SEND_TIMEOUT | MACH_RCV_INTERRUPT | MACH_SEND_INTERRUPT; uint64_t deadline; if (nonblocking == kNonblocking) { options |= timeout_options; deadline = 0; } else if (timeout_ms != MACH_MSG_TIMEOUT_NONE) { options |= timeout_options; deadline = ClockMonotonicNanoseconds() + implicit_cast<uint64_t>(timeout_ms) * kNanosecondsPerMillisecond; } else { options &= ~timeout_options; deadline = 0; } if (receive_large == kReceiveLargeResize) { options |= MACH_RCV_LARGE; } else { options &= ~MACH_RCV_LARGE; } mach_msg_size_t trailer_alloc = REQUESTED_TRAILER_SIZE(options); mach_msg_size_t expected_request_size = interface->MachMessageServerRequestSize(); mach_msg_size_t request_alloc = round_page(round_msg(expected_request_size) + trailer_alloc); mach_msg_size_t request_size = (receive_large == kReceiveLargeResize) ? request_alloc : round_msg(expected_request_size) + trailer_alloc; mach_msg_size_t max_reply_size = interface->MachMessageServerReplySize(); // mach_msg_server() and mach_msg_server_once() would consider whether // |options| contains MACH_SEND_TRAILER and include MAX_TRAILER_SIZE in this // computation if it does, but that option is ineffective on OS X. mach_msg_size_t reply_alloc = round_page(max_reply_size); kern_return_t kr; do { mach_msg_size_t this_request_alloc = request_alloc; mach_msg_size_t this_request_size = request_size; base::mac::ScopedMachVM request_scoper; mach_msg_header_t* request_header = nullptr; while (!request_scoper.address()) { vm_address_t request_addr; kr = vm_allocate(mach_task_self(), &request_addr, this_request_alloc, VM_FLAGS_ANYWHERE | VM_MAKE_TAG(VM_MEMORY_MACH_MSG)); if (kr != KERN_SUCCESS) { return kr; } base::mac::ScopedMachVM trial_request_scoper(request_addr, this_request_alloc); request_header = reinterpret_cast<mach_msg_header_t*>(request_addr); bool run_mach_msg_receive = false; do { // If |options| contains MACH_RCV_INTERRUPT, retry mach_msg() in a loop // when it returns MACH_RCV_INTERRUPTED to recompute |remaining_ms| // rather than allowing mach_msg() to retry using the original timeout // value. See 10.9.4 xnu-2422.110.17/libsyscall/mach/mach_msg.c // mach_msg(). mach_msg_timeout_t remaining_ms; if (!TimerRunning(deadline, &remaining_ms)) { return MACH_RCV_TIMED_OUT; } kr = mach_msg(request_header, options | MACH_RCV_MSG, 0, this_request_size, receive_port, remaining_ms, MACH_PORT_NULL); if (kr == MACH_RCV_TOO_LARGE && receive_large == kReceiveLargeIgnore) { MACH_LOG(WARNING, kr) << "mach_msg: ignoring large message"; run_mach_msg_receive = true; } else if (kr == MACH_RCV_INTERRUPTED) { run_mach_msg_receive = true; } } while (run_mach_msg_receive); if (kr == MACH_MSG_SUCCESS) { request_scoper.swap(trial_request_scoper); } else if (kr == MACH_RCV_TOO_LARGE && receive_large == kReceiveLargeResize) { this_request_size = round_page(round_msg(request_header->msgh_size) + trailer_alloc); this_request_alloc = this_request_size; } else { return kr; } } vm_address_t reply_addr; kr = vm_allocate(mach_task_self(), &reply_addr, reply_alloc, VM_FLAGS_ANYWHERE | VM_MAKE_TAG(VM_MEMORY_MACH_MSG)); if (kr != KERN_SUCCESS) { return kr; } base::mac::ScopedMachVM reply_scoper(reply_addr, reply_alloc); mach_msg_header_t* reply_header = reinterpret_cast<mach_msg_header_t*>(reply_addr); bool destroy_complex_request = false; interface->MachMessageServerFunction( request_header, reply_header, &destroy_complex_request); if (!(reply_header->msgh_bits & MACH_MSGH_BITS_COMPLEX)) { // This only works if the reply message is not complex, because otherwise, // the location of the RetCode field is not known. It should be possible // to locate the RetCode field by looking beyond the descriptors in a // complex reply message, but this is not currently done. This behavior // has not proven itself necessary in practice, and it’s not done by // mach_msg_server() or mach_msg_server_once() either. mig_reply_error_t* reply_mig = reinterpret_cast<mig_reply_error_t*>(reply_header); if (reply_mig->RetCode == MIG_NO_REPLY) { reply_header->msgh_remote_port = MACH_PORT_NULL; } else if (reply_mig->RetCode != KERN_SUCCESS && request_header->msgh_bits & MACH_MSGH_BITS_COMPLEX) { destroy_complex_request = true; } } if (destroy_complex_request && request_header->msgh_bits & MACH_MSGH_BITS_COMPLEX) { request_header->msgh_remote_port = MACH_PORT_NULL; mach_msg_destroy(request_header); } if (reply_header->msgh_remote_port != MACH_PORT_NULL) { // If the reply port right is a send-once right, the send won’t block even // if the remote side isn’t waiting for a message. No timeout is used, // which keeps the communication on the kernel’s fast path. If the reply // port right is a send right, MACH_SEND_TIMEOUT is used to avoid blocking // indefinitely. This duplicates the logic in 10.9.4 // xnu-2422.110.17/libsyscall/mach/mach_msg.c mach_msg_server_once(). mach_msg_option_t send_options = options | MACH_SEND_MSG | (MACH_MSGH_BITS_REMOTE(reply_header->msgh_bits) == MACH_MSG_TYPE_MOVE_SEND_ONCE ? 0 : MACH_SEND_TIMEOUT); bool running; do { // If |options| contains MACH_SEND_INTERRUPT, retry mach_msg() in a loop // when it returns MACH_SEND_INTERRUPTED to recompute |remaining_ms| // rather than allowing mach_msg() to retry using the original timeout // value. See 10.9.4 xnu-2422.110.17/libsyscall/mach/mach_msg.c // mach_msg(). mach_msg_timeout_t remaining_ms; running = TimerRunning(deadline, &remaining_ms); if (!running) { // Don’t return just yet. If the timer ran out in between the time the // request was received and now, at least try to send the response. remaining_ms = 0; } kr = mach_msg(reply_header, send_options, reply_header->msgh_size, 0, MACH_PORT_NULL, remaining_ms, MACH_PORT_NULL); } while (kr == MACH_SEND_INTERRUPTED); if (kr != KERN_SUCCESS) { if (kr == MACH_SEND_INVALID_DEST || kr == MACH_SEND_TIMED_OUT) { mach_msg_destroy(reply_header); } return kr; } if (!running) { // The reply message was sent successfuly, so act as though the deadline // was reached before or during the subsequent receive operation when in // persistent mode, and just return success when not in persistent mode. return (persistent == kPersistent) ? MACH_RCV_TIMED_OUT : kr; } } } while (persistent == kPersistent); return kr; } } // namespace crashpad <|endoftext|>
<commit_before>//----------------------------------------------- // // This file is part of the Siv3D Engine. // // Copyright (c) 2008-2019 Ryo Suzuki // Copyright (c) 2016-2019 OpenSiv3D Project // // Licensed under the MIT License. // //----------------------------------------------- # pragma once # include <type_traits> # include <limits> # include <cmath> namespace s3d { /// <summary> /// 表現できる最大の数値 /// </summary> template <class Type> constexpr Type Largest = std::numeric_limits<Type>::max(); /// <summary> /// 表現できる最小の数値 /// </summary> template <class Type> constexpr Type Smallest = std::numeric_limits<Type>::lowest(); /// <summary> /// 正の無限大 /// </summary> template <class Type> constexpr Type Inf = std::numeric_limits<Type>::infinity(); /// <summary> /// 数値が非数 (NaN) であるかを示します。 /// </summary> /// <param name="value"> /// 数値 /// </param> /// <returns> /// 数値が非数 (NaN) である場合 true, それ以外の場合は false /// </returns> template <class Type> [[nodiscard]] inline bool IsNaN([[maybe_unused]] const Type value) { if constexpr (std::is_floating_point_v<Type>) { return std::isnan(value); } else { return false; } } /// <summary> /// 数値が有限値であるかを示します。 /// </summary> /// <param name="value"> /// 数値 /// </param> /// <returns> /// 数値が有限値である場合 true, それ以外の場合は false /// </returns> template <class Type> [[nodiscard]] inline bool IsFinite([[maybe_unused]] const Type value) { if constexpr (std::is_floating_point_v<Type>) { return std::isfinite(value); } else { return true; } } /// <summary> /// 数値が無限であるかを示します。 /// </summary> /// <param name="value"> /// 数値 /// </param> /// <returns> /// 数値が無限である場合 true, それ以外の場合は false /// </returns> template <class Type> [[nodiscard]] inline bool IsInfinity([[maybe_unused]] const Type value) { if constexpr (std::is_floating_point_v<Type>) { return std::isinf(value); } else { return false; } } } <commit_msg>QNaN, SNaN<commit_after>//----------------------------------------------- // // This file is part of the Siv3D Engine. // // Copyright (c) 2008-2019 Ryo Suzuki // Copyright (c) 2016-2019 OpenSiv3D Project // // Licensed under the MIT License. // //----------------------------------------------- # pragma once # include <type_traits> # include <limits> # include <cmath> namespace s3d { /// <summary> /// 表現できる最大の数値 /// </summary> template <class Type> constexpr Type Largest = std::numeric_limits<Type>::max(); /// <summary> /// 表現できる最小の数値 /// </summary> template <class Type> constexpr Type Smallest = std::numeric_limits<Type>::lowest(); /// <summary> /// 正の無限大 /// </summary> template <class FloatingPoint> constexpr FloatingPoint Inf = std::numeric_limits<FloatingPoint>::infinity(); /// <summary> /// qNaN /// </summary> template <class FloatingPoint> constexpr FloatingPoint QNaN = std::numeric_limits<FloatingPoint>::quiet_NaN(); /// <summary> /// sNaN /// </summary> template <class FloatingPoint> constexpr FloatingPoint SNaN = std::numeric_limits<FloatingPoint>::signaling_NaN(); /// <summary> /// 数値が非数 (NaN) であるかを示します。 /// </summary> /// <param name="value"> /// 数値 /// </param> /// <returns> /// 数値が非数 (NaN) である場合 true, それ以外の場合は false /// </returns> template <class Type> [[nodiscard]] inline bool IsNaN([[maybe_unused]] const Type value) { if constexpr (std::is_floating_point_v<Type>) { return std::isnan(value); } else { return false; } } /// <summary> /// 数値が有限値であるかを示します。 /// </summary> /// <param name="value"> /// 数値 /// </param> /// <returns> /// 数値が有限値である場合 true, それ以外の場合は false /// </returns> template <class Type> [[nodiscard]] inline bool IsFinite([[maybe_unused]] const Type value) { if constexpr (std::is_floating_point_v<Type>) { return std::isfinite(value); } else { return true; } } /// <summary> /// 数値が無限であるかを示します。 /// </summary> /// <param name="value"> /// 数値 /// </param> /// <returns> /// 数値が無限である場合 true, それ以外の場合は false /// </returns> template <class Type> [[nodiscard]] inline bool IsInfinity([[maybe_unused]] const Type value) { if constexpr (std::is_floating_point_v<Type>) { return std::isinf(value); } else { return false; } } } <|endoftext|>
<commit_before>// // Created by mrjaqbq on 07.03.16. // #include <algorithm> #include <Utils/TypeInfo.h> #include <Utils/MemorySizes.h> #include "Core/EngineApis.h" #include "Core/MemoryModule.h" #include "Core/WindowManager.h" #include "Core/Input/InputManager.h" #include "Core/Resources/ResourceManager.h" #include "Core/Resources/Mesh/MeshManager.h" #include "Core/Resources/Shader/ShaderManager.h" #include "Core/Resources/Texture/TextureManager.h" #include "Core/Resources/Material/MaterialManager.h" #include "Core/Gfx/BufferManager.h" #include "Core/Gfx/Renderer.h" #include "Core/Logic/Scene.h" #include "Core/GameTime.h" #include "Core/Engine.h" #include "Core/Logger.h" #include "Core/Config.h" #ifdef CreateWindow #undef CreateWindow #endif namespace Core { Engine::Engine(std::string name, std::size_t memorySize) : Name(name), _isDone(false), _cleanedUp(false) { MemoryModule .reset(new Core::MemoryModule(memorySize)); Config .reset(new Core::Config(MemoryModule.get().requestMemoryBlock(Memory::KB(1), "Config Block"))); Renderer .reset(CreateManager<Gfx::Renderer>(Memory::KB(100))); BufferManager .reset(CreateManager<Gfx::BufferManager>(Memory::KB(100))); MeshManager .reset(CreateManager<Resources::MeshManager>(Memory::KB(100))); TextureManager .reset(CreateManager<Resources::TextureManager>(Memory::MB(4))); MaterialManager .reset(CreateManager<Resources::MaterialManager>(Memory::KB(100))); ShaderManager .reset(CreateManager<Resources::ShaderManager>(Memory::KB(100))); WindowManager .reset(CreateManager<Core::WindowManager>(Memory::KB(10))); InputManager .reset(CreateManager<Core::InputManager>(Memory::KB(10))); } auto Engine::CreateWindow() const noexcept -> Window::handle_t { auto handle = WindowManager.get().createNew(((std::string)Config.get().WindowTitle).c_str(), Config.get().WindowWidth, Config.get().WindowHeight); auto* window = WindowManager.get().tryGet(handle); if(window != nullptr) { if(!OpenGL::registerWindow(*window)) { Logger::error("Unable to register window in OpenGL!"); } } else { Logger::error("Unable to create window!"); } return handle; } auto Engine::LoadConfig(std::string path) -> bool { return Config->Load(path); } auto Engine::Initialize() -> bool { bool video = OpenGL::initialize(); if(video) SDL_Init(SDL_INIT_GAMECONTROLLER); return video; } auto Engine::SwitchScene(borrowed_ptr<Logic::Scene> scene) -> void { // todo: refactor to handle instead of raw pointer if(activeScene) activeScene->End(); activeScene = scene; if(activeScene) activeScene->Start(); } // todo: remove window from here auto Engine::Draw(const Core::Window& window, Core::GameTime& time) -> void { OpenGL::beginDraw(window); if(activeScene) activeScene->Draw(time, Renderer.get()); Renderer->draw(); OpenGL::endDraw(window); } auto Engine::ProcessEvents(Core::GameTime& time) -> void { if(ShouldClose()) return; SDL_Event event; while(SDL_PollEvent(&event)) { switch(event.type) { case SDL_QUIT: Quit(); break; case SDL_WINDOWEVENT: WindowManager->handleWindowEvent(event); break; default: InputManager->handleInputEvent(event, time); break; } } } void Engine::Update(GameTime &time) { if(activeScene) activeScene->Update(time); } double Engine::GetCurrentTime() { return SDL_GetTicks() / 1000.0; } auto Engine::Quit() -> void { WindowManager->closeAllWindows(); _isDone = true; } auto Engine::CleanUp() -> void { if(_cleanedUp) return; Logger::info("Cleaning up..."); Memory::Delete(MemoryModule->masterBlock(), InputManager); Memory::Delete(MemoryModule->masterBlock(), WindowManager); Memory::Delete(MemoryModule->masterBlock(), BufferManager); Memory::Delete(MemoryModule->masterBlock(), MeshManager); Memory::Delete(MemoryModule->masterBlock(), TextureManager); Memory::Delete(MemoryModule->masterBlock(), MaterialManager); Memory::Delete(MemoryModule->masterBlock(), ShaderManager); Memory::Delete(MemoryModule->masterBlock(), Renderer); SDL_QuitSubSystem( SDL_INIT_VIDEO ); SDL_Quit(); Logger::info("Cleaned up!"); Memory::SafeDelete(Config); Memory::SafeDelete(MemoryModule); _cleanedUp = true; } bool Engine::WasCleanedUp() { return _cleanedUp; } bool Engine::ShouldClose() { return _isDone || WasCleanedUp(); } } <commit_msg>Fixed SDL gamecontroller subsystem initialization<commit_after>// // Created by mrjaqbq on 07.03.16. // #include <algorithm> #include <Utils/TypeInfo.h> #include <Utils/MemorySizes.h> #include "Core/EngineApis.h" #include "Core/MemoryModule.h" #include "Core/WindowManager.h" #include "Core/Input/InputManager.h" #include "Core/Resources/ResourceManager.h" #include "Core/Resources/Mesh/MeshManager.h" #include "Core/Resources/Shader/ShaderManager.h" #include "Core/Resources/Texture/TextureManager.h" #include "Core/Resources/Material/MaterialManager.h" #include "Core/Gfx/BufferManager.h" #include "Core/Gfx/Renderer.h" #include "Core/Logic/Scene.h" #include "Core/GameTime.h" #include "Core/Engine.h" #include "Core/Logger.h" #include "Core/Config.h" #ifdef CreateWindow #undef CreateWindow #endif namespace Core { Engine::Engine(std::string name, std::size_t memorySize) : Name(name), _isDone(false), _cleanedUp(false) { MemoryModule .reset(new Core::MemoryModule(memorySize)); Config .reset(new Core::Config(MemoryModule.get().requestMemoryBlock(Memory::KB(1), "Config Block"))); Renderer .reset(CreateManager<Gfx::Renderer>(Memory::KB(100))); BufferManager .reset(CreateManager<Gfx::BufferManager>(Memory::KB(100))); MeshManager .reset(CreateManager<Resources::MeshManager>(Memory::KB(100))); TextureManager .reset(CreateManager<Resources::TextureManager>(Memory::MB(4))); MaterialManager .reset(CreateManager<Resources::MaterialManager>(Memory::KB(100))); ShaderManager .reset(CreateManager<Resources::ShaderManager>(Memory::KB(100))); WindowManager .reset(CreateManager<Core::WindowManager>(Memory::KB(10))); InputManager .reset(CreateManager<Core::InputManager>(Memory::KB(10))); } auto Engine::CreateWindow() const noexcept -> Window::handle_t { auto handle = WindowManager.get().createNew(((std::string)Config.get().WindowTitle).c_str(), Config.get().WindowWidth, Config.get().WindowHeight); auto* window = WindowManager.get().tryGet(handle); if(window != nullptr) { if(!OpenGL::registerWindow(*window)) { Logger::error("Unable to register window in OpenGL!"); } } else { Logger::error("Unable to create window!"); } return handle; } auto Engine::LoadConfig(std::string path) -> bool { return Config->Load(path); } auto Engine::Initialize() -> bool { bool video = OpenGL::initialize(); if(video) SDL_InitSubSystem(SDL_INIT_GAMECONTROLLER); return video; } auto Engine::SwitchScene(borrowed_ptr<Logic::Scene> scene) -> void { // todo: refactor to handle instead of raw pointer if(activeScene) activeScene->End(); activeScene = scene; if(activeScene) activeScene->Start(); } // todo: remove window from here auto Engine::Draw(const Core::Window& window, Core::GameTime& time) -> void { OpenGL::beginDraw(window); if(activeScene) activeScene->Draw(time, Renderer.get()); Renderer->draw(); OpenGL::endDraw(window); } auto Engine::ProcessEvents(Core::GameTime& time) -> void { if(ShouldClose()) return; SDL_Event event; while(SDL_PollEvent(&event)) { switch(event.type) { case SDL_QUIT: Quit(); break; case SDL_WINDOWEVENT: WindowManager->handleWindowEvent(event); break; default: InputManager->handleInputEvent(event, time); break; } } } void Engine::Update(GameTime &time) { if(activeScene) activeScene->Update(time); } double Engine::GetCurrentTime() { return SDL_GetTicks() / 1000.0; } auto Engine::Quit() -> void { WindowManager->closeAllWindows(); _isDone = true; } auto Engine::CleanUp() -> void { if(_cleanedUp) return; Logger::info("Cleaning up..."); Memory::Delete(MemoryModule->masterBlock(), InputManager); Memory::Delete(MemoryModule->masterBlock(), WindowManager); Memory::Delete(MemoryModule->masterBlock(), BufferManager); Memory::Delete(MemoryModule->masterBlock(), MeshManager); Memory::Delete(MemoryModule->masterBlock(), TextureManager); Memory::Delete(MemoryModule->masterBlock(), MaterialManager); Memory::Delete(MemoryModule->masterBlock(), ShaderManager); Memory::Delete(MemoryModule->masterBlock(), Renderer); SDL_QuitSubSystem( SDL_INIT_VIDEO ); SDL_Quit(); Logger::info("Cleaned up!"); Memory::SafeDelete(Config); Memory::SafeDelete(MemoryModule); _cleanedUp = true; } bool Engine::WasCleanedUp() { return _cleanedUp; } bool Engine::ShouldClose() { return _isDone || WasCleanedUp(); } } <|endoftext|>
<commit_before>/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file **/ #include "modules/planning/common/speed/st_boundary.h" #include <algorithm> #include "modules/common/log.h" namespace apollo { namespace planning { using Vec2d = common::math::Vec2d; StBoundary::StBoundary( const std::vector<std::pair<STPoint, STPoint>>& point_pairs) { CHECK(IsValid(point_pairs)); for (size_t i = 0; i < point_pairs.size(); ++i) { upper_points_.emplace_back(point_pairs[i].first.t(), point_pairs[i].first.s()); lower_points_.emplace_back(point_pairs[i].second.t(), point_pairs[i].second.s()); } points_.reserve(upper_points_.size() + lower_points_.size()); points_.insert(points_.end(), lower_points_.begin(), lower_points_.end()); points_.insert(points_.end(), upper_points_.rbegin(), upper_points_.rend()); BuildFromPoints(); for (const auto& point : points_) { min_s_ = std::fmin(min_s_, point.y()); min_t_ = std::fmin(min_t_, point.x()); max_s_ = std::fmax(max_s_, point.y()); max_t_ = std::fmax(max_t_, point.x()); } } bool StBoundary::IsValid( const std::vector<std::pair<STPoint, STPoint>>& point_pairs) { // TODO(Liangliang): implement this function. return true; } bool StBoundary::IsPointInBoundary(const STPoint& st_point) const { return IsPointIn(st_point); } STPoint StBoundary::BottomLeftPoint() const { DCHECK(!points_.empty()) << "StBoundary has zero points."; return STPoint(lower_points_.front()); } STPoint StBoundary::BottomRightPoint() const { DCHECK(!points_.empty()) << "StBoundary has zero points."; return STPoint(lower_points_.back()); } STPoint StBoundary::TopRightPoint() const { DCHECK(!points_.empty()) << "StBoundary has zero points."; return STPoint(upper_points_.back()); } STPoint StBoundary::TopLeftPoint() const { DCHECK(!points_.empty()) << "StBoundary has zero points."; return STPoint(upper_points_.front()); } StBoundary::BoundaryType StBoundary::boundary_type() const { return boundary_type_; } void StBoundary::SetBoundaryType(const BoundaryType& boundary_type) { boundary_type_ = boundary_type; } const std::string& StBoundary::id() const { return id_; } void StBoundary::SetId(const std::string& id) { id_ = id; } double StBoundary::characteristic_length() const { return characteristic_length_; } void StBoundary::SetCharacteristicLength(const double characteristic_length) { characteristic_length_ = characteristic_length; } bool StBoundary::GetUnblockSRange(const double curr_time, double* s_upper, double* s_lower) const { const common::math::LineSegment2d segment = {Vec2d(curr_time, 0.0), Vec2d(curr_time, s_high_limit_)}; *s_upper = s_high_limit_; *s_lower = 0.0; Vec2d p_s_first; Vec2d p_s_second; if (!GetOverlap(segment, &p_s_first, &p_s_second)) { ADEBUG << "curr_time[" << curr_time << "] is out of the coverage scope of the boundary."; return false; } if (boundary_type_ == BoundaryType::STOP || boundary_type_ == BoundaryType::YIELD || boundary_type_ == BoundaryType::FOLLOW) { *s_upper = std::fmin(*s_upper, std::fmin(p_s_first.y(), p_s_second.y())); } else if (boundary_type_ == BoundaryType::OVERTAKE) { // overtake *s_lower = std::fmax(*s_lower, std::fmax(p_s_first.y(), p_s_second.y())); } else { AERROR << "boundary_type is not supported. boundary_type: " << static_cast<int>(boundary_type_); return false; } return true; } bool StBoundary::GetBoundarySRange(const double curr_time, double* s_upper, double* s_lower) const { const common::math::LineSegment2d segment = {Vec2d(curr_time, 0.0), Vec2d(curr_time, s_high_limit_)}; *s_upper = s_high_limit_; *s_lower = 0.0; Vec2d p_s_first; Vec2d p_s_second; if (!GetOverlap(segment, &p_s_first, &p_s_second)) { ADEBUG << "curr_time[" << curr_time << "] is out of the coverage scope of the boundary."; return false; } *s_upper = std::fmin(*s_upper, std::fmax(p_s_first.y(), p_s_second.y())); *s_lower = std::fmax(*s_lower, std::fmin(p_s_first.y(), p_s_second.y())); return true; } double StBoundary::min_s() const { return min_s_; } double StBoundary::min_t() const { return min_t_; } double StBoundary::max_s() const { return max_s_; } double StBoundary::max_t() const { return max_t_; } } // namespace planning } // namespace apollo <commit_msg>Planning: implemented IsValid function in st_boundary.cc<commit_after>/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file **/ #include "modules/planning/common/speed/st_boundary.h" #include <algorithm> #include "modules/common/log.h" namespace apollo { namespace planning { using Vec2d = common::math::Vec2d; StBoundary::StBoundary( const std::vector<std::pair<STPoint, STPoint>>& point_pairs) { CHECK(IsValid(point_pairs)); for (size_t i = 0; i < point_pairs.size(); ++i) { lower_points_.emplace_back(point_pairs[i].first.t(), point_pairs[i].first.s()); upper_points_.emplace_back(point_pairs[i].second.t(), point_pairs[i].second.s()); } points_.reserve(upper_points_.size() + lower_points_.size()); points_.insert(points_.end(), lower_points_.begin(), lower_points_.end()); points_.insert(points_.end(), upper_points_.rbegin(), upper_points_.rend()); BuildFromPoints(); for (const auto& point : points_) { min_s_ = std::fmin(min_s_, point.y()); min_t_ = std::fmin(min_t_, point.x()); max_s_ = std::fmax(max_s_, point.y()); max_t_ = std::fmax(max_t_, point.x()); } } bool StBoundary::IsValid( const std::vector<std::pair<STPoint, STPoint>>& point_pairs) { if (point_pairs.size() < 2) { AERROR << "point_pairs.size() must > 2. current point_pairs.size() = " << point_pairs.size(); return false; } constexpr double kStBoundaryEpsilon = 1e-9; constexpr double kMinDeltaT = 1e-6; for (size_t i = 0; i < point_pairs.size(); ++i) { const auto& curr_lower = point_pairs[i].first; const auto& curr_upper = point_pairs[i].second; if (curr_upper.s() < curr_lower.s()) { return false; } if (std::fabs(curr_lower.t() - curr_upper.t()) > kStBoundaryEpsilon) { return false; } if (i + 1 != point_pairs.size()) { const auto& next_lower = point_pairs[i + 1].first; const auto& next_upper = point_pairs[i + 1].second; if (std::fmax(curr_lower.t(), curr_upper.t()) + kMinDeltaT >= std::fmin(next_lower.t(), next_upper.t())) { return false; } } } return true; } bool StBoundary::IsPointInBoundary(const STPoint& st_point) const { return IsPointIn(st_point); } STPoint StBoundary::BottomLeftPoint() const { DCHECK(!points_.empty()) << "StBoundary has zero points."; return STPoint(lower_points_.front()); } STPoint StBoundary::BottomRightPoint() const { DCHECK(!points_.empty()) << "StBoundary has zero points."; return STPoint(lower_points_.back()); } STPoint StBoundary::TopRightPoint() const { DCHECK(!points_.empty()) << "StBoundary has zero points."; return STPoint(upper_points_.back()); } STPoint StBoundary::TopLeftPoint() const { DCHECK(!points_.empty()) << "StBoundary has zero points."; return STPoint(upper_points_.front()); } StBoundary::BoundaryType StBoundary::boundary_type() const { return boundary_type_; } void StBoundary::SetBoundaryType(const BoundaryType& boundary_type) { boundary_type_ = boundary_type; } const std::string& StBoundary::id() const { return id_; } void StBoundary::SetId(const std::string& id) { id_ = id; } double StBoundary::characteristic_length() const { return characteristic_length_; } void StBoundary::SetCharacteristicLength(const double characteristic_length) { characteristic_length_ = characteristic_length; } bool StBoundary::GetUnblockSRange(const double curr_time, double* s_upper, double* s_lower) const { const common::math::LineSegment2d segment = {Vec2d(curr_time, 0.0), Vec2d(curr_time, s_high_limit_)}; *s_upper = s_high_limit_; *s_lower = 0.0; Vec2d p_s_first; Vec2d p_s_second; if (!GetOverlap(segment, &p_s_first, &p_s_second)) { ADEBUG << "curr_time[" << curr_time << "] is out of the coverage scope of the boundary."; return false; } if (boundary_type_ == BoundaryType::STOP || boundary_type_ == BoundaryType::YIELD || boundary_type_ == BoundaryType::FOLLOW) { *s_upper = std::fmin(*s_upper, std::fmin(p_s_first.y(), p_s_second.y())); } else if (boundary_type_ == BoundaryType::OVERTAKE) { // overtake *s_lower = std::fmax(*s_lower, std::fmax(p_s_first.y(), p_s_second.y())); } else { AERROR << "boundary_type is not supported. boundary_type: " << static_cast<int>(boundary_type_); return false; } return true; } bool StBoundary::GetBoundarySRange(const double curr_time, double* s_upper, double* s_lower) const { const common::math::LineSegment2d segment = {Vec2d(curr_time, 0.0), Vec2d(curr_time, s_high_limit_)}; *s_upper = s_high_limit_; *s_lower = 0.0; Vec2d p_s_first; Vec2d p_s_second; if (!GetOverlap(segment, &p_s_first, &p_s_second)) { ADEBUG << "curr_time[" << curr_time << "] is out of the coverage scope of the boundary."; return false; } *s_upper = std::fmin(*s_upper, std::fmax(p_s_first.y(), p_s_second.y())); *s_lower = std::fmax(*s_lower, std::fmin(p_s_first.y(), p_s_second.y())); return true; } double StBoundary::min_s() const { return min_s_; } double StBoundary::min_t() const { return min_t_; } double StBoundary::max_s() const { return max_s_; } double StBoundary::max_t() const { return max_t_; } } // namespace planning } // namespace apollo <|endoftext|>
<commit_before><commit_msg>change order of var in PDFExtOutDevData to suppress waring<commit_after><|endoftext|>
<commit_before>/* * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "webrtc/modules/video_coding/main/source/receiver.h" #include <assert.h> #include "webrtc/modules/video_coding/main/source/encoded_frame.h" #include "webrtc/modules/video_coding/main/source/internal_defines.h" #include "webrtc/modules/video_coding/main/source/media_opt_util.h" #include "webrtc/system_wrappers/interface/clock.h" #include "webrtc/system_wrappers/interface/trace.h" #include "webrtc/system_wrappers/interface/trace_event.h" namespace webrtc { enum { kMaxReceiverDelayMs = 10000 }; VCMReceiver::VCMReceiver(VCMTiming* timing, Clock* clock, EventFactory* event_factory, int32_t vcm_id, int32_t receiver_id, bool master) : crit_sect_(CriticalSectionWrapper::CreateCriticalSection()), vcm_id_(vcm_id), clock_(clock), receiver_id_(receiver_id), master_(master), jitter_buffer_(clock_, event_factory, vcm_id, receiver_id, master), timing_(timing), render_wait_event_(event_factory->CreateEvent()), state_(kPassive), max_video_delay_ms_(kMaxVideoDelayMs) {} VCMReceiver::~VCMReceiver() { render_wait_event_->Set(); delete crit_sect_; } void VCMReceiver::Reset() { CriticalSectionScoped cs(crit_sect_); if (!jitter_buffer_.Running()) { jitter_buffer_.Start(); } else { jitter_buffer_.Flush(); } render_wait_event_->Reset(); if (master_) { state_ = kReceiving; } else { state_ = kPassive; } } int32_t VCMReceiver::Initialize() { CriticalSectionScoped cs(crit_sect_); Reset(); if (!master_) { SetNackMode(kNoNack, -1, -1); } return VCM_OK; } void VCMReceiver::UpdateRtt(uint32_t rtt) { jitter_buffer_.UpdateRtt(rtt); } int32_t VCMReceiver::InsertPacket(const VCMPacket& packet, uint16_t frame_width, uint16_t frame_height) { if (packet.frameType == kVideoFrameKey) { WEBRTC_TRACE(webrtc::kTraceInfo, webrtc::kTraceVideoCoding, VCMId(vcm_id_, receiver_id_), "Inserting key frame packet seqnum=%u, timestamp=%u", packet.seqNum, packet.timestamp); } // Insert the packet into the jitter buffer. The packet can either be empty or // contain media at this point. bool retransmitted = false; const VCMFrameBufferEnum ret = jitter_buffer_.InsertPacket(packet, &retransmitted); if (ret == kOldPacket) { return VCM_OK; } else if (ret == kFlushIndicator) { return VCM_FLUSH_INDICATOR; } else if (ret < 0) { WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideoCoding, VCMId(vcm_id_, receiver_id_), "Error inserting packet seqnum=%u, timestamp=%u", packet.seqNum, packet.timestamp); return VCM_JITTER_BUFFER_ERROR; } if (ret == kCompleteSession && !retransmitted) { // We don't want to include timestamps which have suffered from // retransmission here, since we compensate with extra retransmission // delay within the jitter estimate. timing_->IncomingTimestamp(packet.timestamp, clock_->TimeInMilliseconds()); } if (master_) { // Only trace the primary receiver to make it possible to parse and plot // the trace file. WEBRTC_TRACE(webrtc::kTraceDebug, webrtc::kTraceVideoCoding, VCMId(vcm_id_, receiver_id_), "Packet seqnum=%u timestamp=%u inserted at %u", packet.seqNum, packet.timestamp, MaskWord64ToUWord32(clock_->TimeInMilliseconds())); } return VCM_OK; } VCMEncodedFrame* VCMReceiver::FrameForDecoding( uint16_t max_wait_time_ms, int64_t& next_render_time_ms, bool render_timing, VCMReceiver* dual_receiver) { const int64_t start_time_ms = clock_->TimeInMilliseconds(); uint32_t frame_timestamp = 0; // Exhaust wait time to get a complete frame for decoding. bool found_frame = jitter_buffer_.NextCompleteTimestamp( max_wait_time_ms, &frame_timestamp); if (!found_frame) { // Get an incomplete frame when enabled. const bool dual_receiver_enabled_and_passive = (dual_receiver != NULL && dual_receiver->State() == kPassive && dual_receiver->NackMode() == kNack); if (dual_receiver_enabled_and_passive && !jitter_buffer_.CompleteSequenceWithNextFrame()) { // Jitter buffer state might get corrupt with this frame. dual_receiver->CopyJitterBufferStateFromReceiver(*this); } found_frame = jitter_buffer_.NextMaybeIncompleteTimestamp( &frame_timestamp); } if (!found_frame) { return NULL; } // We have a frame - Set timing and render timestamp. timing_->SetJitterDelay(jitter_buffer_.EstimatedJitterMs()); const int64_t now_ms = clock_->TimeInMilliseconds(); timing_->UpdateCurrentDelay(frame_timestamp); next_render_time_ms = timing_->RenderTimeMs(frame_timestamp, now_ms); // Check render timing. bool timing_error = false; // Assume that render timing errors are due to changes in the video stream. if (next_render_time_ms < 0) { timing_error = true; } else if (abs(next_render_time_ms - now_ms) > max_video_delay_ms_) { WEBRTC_TRACE(webrtc::kTraceWarning, webrtc::kTraceVideoCoding, VCMId(vcm_id_, receiver_id_), "This frame is out of our delay bounds, resetting jitter " "buffer: %d > %d", static_cast<int>(abs(next_render_time_ms - now_ms)), max_video_delay_ms_); timing_error = true; } else if (static_cast<int>(timing_->TargetVideoDelay()) > max_video_delay_ms_) { WEBRTC_TRACE(webrtc::kTraceWarning, webrtc::kTraceVideoCoding, VCMId(vcm_id_, receiver_id_), "More than %u ms target delay. Flushing jitter buffer and" "resetting timing.", max_video_delay_ms_); timing_error = true; } if (timing_error) { // Timing error => reset timing and flush the jitter buffer. jitter_buffer_.Flush(); timing_->Reset(); return NULL; } if (!render_timing) { // Decode frame as close as possible to the render timestamp. const int32_t available_wait_time = max_wait_time_ms - static_cast<int32_t>(clock_->TimeInMilliseconds() - start_time_ms); uint16_t new_max_wait_time = static_cast<uint16_t>( VCM_MAX(available_wait_time, 0)); uint32_t wait_time_ms = timing_->MaxWaitingTime( next_render_time_ms, clock_->TimeInMilliseconds()); if (new_max_wait_time < wait_time_ms) { // We're not allowed to wait until the frame is supposed to be rendered, // waiting as long as we're allowed to avoid busy looping, and then return // NULL. Next call to this function might return the frame. render_wait_event_->Wait(max_wait_time_ms); return NULL; } // Wait until it's time to render. render_wait_event_->Wait(wait_time_ms); } // Extract the frame from the jitter buffer and set the render time. VCMEncodedFrame* frame = jitter_buffer_.ExtractAndSetDecode(frame_timestamp); if (frame == NULL) { return NULL; } frame->SetRenderTime(next_render_time_ms); TRACE_EVENT_ASYNC_STEP1("webrtc", "Video", frame->TimeStamp(), "SetRenderTS", "render_time", next_render_time_ms); if (dual_receiver != NULL) { dual_receiver->UpdateState(*frame); } if (!frame->Complete()) { // Update stats for incomplete frames. bool retransmitted = false; const int64_t last_packet_time_ms = jitter_buffer_.LastPacketTime(frame, &retransmitted); if (last_packet_time_ms >= 0 && !retransmitted) { // We don't want to include timestamps which have suffered from // retransmission here, since we compensate with extra retransmission // delay within the jitter estimate. timing_->IncomingTimestamp(frame_timestamp, last_packet_time_ms); } } return frame; } void VCMReceiver::ReleaseFrame(VCMEncodedFrame* frame) { jitter_buffer_.ReleaseFrame(frame); } void VCMReceiver::ReceiveStatistics(uint32_t* bitrate, uint32_t* framerate) { assert(bitrate); assert(framerate); jitter_buffer_.IncomingRateStatistics(framerate, bitrate); } void VCMReceiver::ReceivedFrameCount(VCMFrameCount* frame_count) const { assert(frame_count); jitter_buffer_.FrameStatistics(&frame_count->numDeltaFrames, &frame_count->numKeyFrames); } uint32_t VCMReceiver::DiscardedPackets() const { return jitter_buffer_.num_discarded_packets(); } void VCMReceiver::SetNackMode(VCMNackMode nackMode, int low_rtt_nack_threshold_ms, int high_rtt_nack_threshold_ms) { CriticalSectionScoped cs(crit_sect_); // Default to always having NACK enabled in hybrid mode. jitter_buffer_.SetNackMode(nackMode, low_rtt_nack_threshold_ms, high_rtt_nack_threshold_ms); if (!master_) { state_ = kPassive; // The dual decoder defaults to passive. } } void VCMReceiver::SetNackSettings(size_t max_nack_list_size, int max_packet_age_to_nack, int max_incomplete_time_ms) { jitter_buffer_.SetNackSettings(max_nack_list_size, max_packet_age_to_nack, max_incomplete_time_ms); } VCMNackMode VCMReceiver::NackMode() const { CriticalSectionScoped cs(crit_sect_); return jitter_buffer_.nack_mode(); } VCMNackStatus VCMReceiver::NackList(uint16_t* nack_list, uint16_t size, uint16_t* nack_list_length) { bool request_key_frame = false; uint16_t* internal_nack_list = jitter_buffer_.GetNackList( nack_list_length, &request_key_frame); if (*nack_list_length > size) { *nack_list_length = 0; return kNackNeedMoreMemory; } if (internal_nack_list != NULL && *nack_list_length > 0) { memcpy(nack_list, internal_nack_list, *nack_list_length * sizeof(uint16_t)); } if (request_key_frame) { return kNackKeyFrameRequest; } return kNackOk; } // Decide whether we should change decoder state. This should be done if the // dual decoder has caught up with the decoder decoding with packet losses. bool VCMReceiver::DualDecoderCaughtUp(VCMEncodedFrame* dual_frame, VCMReceiver& dual_receiver) const { if (dual_frame == NULL) { return false; } if (jitter_buffer_.LastDecodedTimestamp() == dual_frame->TimeStamp()) { dual_receiver.UpdateState(kWaitForPrimaryDecode); return true; } return false; } void VCMReceiver::CopyJitterBufferStateFromReceiver( const VCMReceiver& receiver) { jitter_buffer_.CopyFrom(receiver.jitter_buffer_); } VCMReceiverState VCMReceiver::State() const { CriticalSectionScoped cs(crit_sect_); return state_; } void VCMReceiver::SetDecodeErrorMode(VCMDecodeErrorMode decode_error_mode) { jitter_buffer_.SetDecodeErrorMode(decode_error_mode); } VCMDecodeErrorMode VCMReceiver::DecodeErrorMode() const { return jitter_buffer_.decode_error_mode(); } int VCMReceiver::SetMinReceiverDelay(int desired_delay_ms) { CriticalSectionScoped cs(crit_sect_); if (desired_delay_ms < 0 || desired_delay_ms > kMaxReceiverDelayMs) { return -1; } max_video_delay_ms_ = desired_delay_ms + kMaxVideoDelayMs; // Initializing timing to the desired delay. timing_->set_min_playout_delay(desired_delay_ms); return 0; } int VCMReceiver::RenderBufferSizeMs() { uint32_t timestamp_start = 0u; uint32_t timestamp_end = 0u; // Render timestamps are computed just prior to decoding. Therefore this is // only an estimate based on frames' timestamps and current timing state. jitter_buffer_.RenderBufferSize(&timestamp_start, &timestamp_end); if (timestamp_start == timestamp_end) { return 0; } // Update timing. const int64_t now_ms = clock_->TimeInMilliseconds(); timing_->SetJitterDelay(jitter_buffer_.EstimatedJitterMs()); // Get render timestamps. uint32_t render_start = timing_->RenderTimeMs(timestamp_start, now_ms); uint32_t render_end = timing_->RenderTimeMs(timestamp_end, now_ms); return render_end - render_start; } void VCMReceiver::UpdateState(VCMReceiverState new_state) { CriticalSectionScoped cs(crit_sect_); assert(!(state_ == kPassive && new_state == kWaitForPrimaryDecode)); state_ = new_state; } void VCMReceiver::UpdateState(const VCMEncodedFrame& frame) { if (jitter_buffer_.nack_mode() == kNoNack) { // Dual decoder mode has not been enabled. return; } // Update the dual receiver state. if (frame.Complete() && frame.FrameType() == kVideoFrameKey) { UpdateState(kPassive); } if (State() == kWaitForPrimaryDecode && frame.Complete() && !frame.MissingFrame()) { UpdateState(kPassive); } if (frame.MissingFrame() || !frame.Complete()) { // State was corrupted, enable dual receiver. UpdateState(kReceiving); } } } // namespace webrtc <commit_msg>Avoid recursively taking critical section.<commit_after>/* * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "webrtc/modules/video_coding/main/source/receiver.h" #include <assert.h> #include "webrtc/modules/video_coding/main/source/encoded_frame.h" #include "webrtc/modules/video_coding/main/source/internal_defines.h" #include "webrtc/modules/video_coding/main/source/media_opt_util.h" #include "webrtc/system_wrappers/interface/clock.h" #include "webrtc/system_wrappers/interface/trace.h" #include "webrtc/system_wrappers/interface/trace_event.h" namespace webrtc { enum { kMaxReceiverDelayMs = 10000 }; VCMReceiver::VCMReceiver(VCMTiming* timing, Clock* clock, EventFactory* event_factory, int32_t vcm_id, int32_t receiver_id, bool master) : crit_sect_(CriticalSectionWrapper::CreateCriticalSection()), vcm_id_(vcm_id), clock_(clock), receiver_id_(receiver_id), master_(master), jitter_buffer_(clock_, event_factory, vcm_id, receiver_id, master), timing_(timing), render_wait_event_(event_factory->CreateEvent()), state_(kPassive), max_video_delay_ms_(kMaxVideoDelayMs) {} VCMReceiver::~VCMReceiver() { render_wait_event_->Set(); delete crit_sect_; } void VCMReceiver::Reset() { CriticalSectionScoped cs(crit_sect_); if (!jitter_buffer_.Running()) { jitter_buffer_.Start(); } else { jitter_buffer_.Flush(); } render_wait_event_->Reset(); if (master_) { state_ = kReceiving; } else { state_ = kPassive; } } int32_t VCMReceiver::Initialize() { Reset(); CriticalSectionScoped cs(crit_sect_); if (!master_) { SetNackMode(kNoNack, -1, -1); } return VCM_OK; } void VCMReceiver::UpdateRtt(uint32_t rtt) { jitter_buffer_.UpdateRtt(rtt); } int32_t VCMReceiver::InsertPacket(const VCMPacket& packet, uint16_t frame_width, uint16_t frame_height) { if (packet.frameType == kVideoFrameKey) { WEBRTC_TRACE(webrtc::kTraceInfo, webrtc::kTraceVideoCoding, VCMId(vcm_id_, receiver_id_), "Inserting key frame packet seqnum=%u, timestamp=%u", packet.seqNum, packet.timestamp); } // Insert the packet into the jitter buffer. The packet can either be empty or // contain media at this point. bool retransmitted = false; const VCMFrameBufferEnum ret = jitter_buffer_.InsertPacket(packet, &retransmitted); if (ret == kOldPacket) { return VCM_OK; } else if (ret == kFlushIndicator) { return VCM_FLUSH_INDICATOR; } else if (ret < 0) { WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideoCoding, VCMId(vcm_id_, receiver_id_), "Error inserting packet seqnum=%u, timestamp=%u", packet.seqNum, packet.timestamp); return VCM_JITTER_BUFFER_ERROR; } if (ret == kCompleteSession && !retransmitted) { // We don't want to include timestamps which have suffered from // retransmission here, since we compensate with extra retransmission // delay within the jitter estimate. timing_->IncomingTimestamp(packet.timestamp, clock_->TimeInMilliseconds()); } if (master_) { // Only trace the primary receiver to make it possible to parse and plot // the trace file. WEBRTC_TRACE(webrtc::kTraceDebug, webrtc::kTraceVideoCoding, VCMId(vcm_id_, receiver_id_), "Packet seqnum=%u timestamp=%u inserted at %u", packet.seqNum, packet.timestamp, MaskWord64ToUWord32(clock_->TimeInMilliseconds())); } return VCM_OK; } VCMEncodedFrame* VCMReceiver::FrameForDecoding( uint16_t max_wait_time_ms, int64_t& next_render_time_ms, bool render_timing, VCMReceiver* dual_receiver) { const int64_t start_time_ms = clock_->TimeInMilliseconds(); uint32_t frame_timestamp = 0; // Exhaust wait time to get a complete frame for decoding. bool found_frame = jitter_buffer_.NextCompleteTimestamp( max_wait_time_ms, &frame_timestamp); if (!found_frame) { // Get an incomplete frame when enabled. const bool dual_receiver_enabled_and_passive = (dual_receiver != NULL && dual_receiver->State() == kPassive && dual_receiver->NackMode() == kNack); if (dual_receiver_enabled_and_passive && !jitter_buffer_.CompleteSequenceWithNextFrame()) { // Jitter buffer state might get corrupt with this frame. dual_receiver->CopyJitterBufferStateFromReceiver(*this); } found_frame = jitter_buffer_.NextMaybeIncompleteTimestamp( &frame_timestamp); } if (!found_frame) { return NULL; } // We have a frame - Set timing and render timestamp. timing_->SetJitterDelay(jitter_buffer_.EstimatedJitterMs()); const int64_t now_ms = clock_->TimeInMilliseconds(); timing_->UpdateCurrentDelay(frame_timestamp); next_render_time_ms = timing_->RenderTimeMs(frame_timestamp, now_ms); // Check render timing. bool timing_error = false; // Assume that render timing errors are due to changes in the video stream. if (next_render_time_ms < 0) { timing_error = true; } else if (abs(next_render_time_ms - now_ms) > max_video_delay_ms_) { WEBRTC_TRACE(webrtc::kTraceWarning, webrtc::kTraceVideoCoding, VCMId(vcm_id_, receiver_id_), "This frame is out of our delay bounds, resetting jitter " "buffer: %d > %d", static_cast<int>(abs(next_render_time_ms - now_ms)), max_video_delay_ms_); timing_error = true; } else if (static_cast<int>(timing_->TargetVideoDelay()) > max_video_delay_ms_) { WEBRTC_TRACE(webrtc::kTraceWarning, webrtc::kTraceVideoCoding, VCMId(vcm_id_, receiver_id_), "More than %u ms target delay. Flushing jitter buffer and" "resetting timing.", max_video_delay_ms_); timing_error = true; } if (timing_error) { // Timing error => reset timing and flush the jitter buffer. jitter_buffer_.Flush(); timing_->Reset(); return NULL; } if (!render_timing) { // Decode frame as close as possible to the render timestamp. const int32_t available_wait_time = max_wait_time_ms - static_cast<int32_t>(clock_->TimeInMilliseconds() - start_time_ms); uint16_t new_max_wait_time = static_cast<uint16_t>( VCM_MAX(available_wait_time, 0)); uint32_t wait_time_ms = timing_->MaxWaitingTime( next_render_time_ms, clock_->TimeInMilliseconds()); if (new_max_wait_time < wait_time_ms) { // We're not allowed to wait until the frame is supposed to be rendered, // waiting as long as we're allowed to avoid busy looping, and then return // NULL. Next call to this function might return the frame. render_wait_event_->Wait(max_wait_time_ms); return NULL; } // Wait until it's time to render. render_wait_event_->Wait(wait_time_ms); } // Extract the frame from the jitter buffer and set the render time. VCMEncodedFrame* frame = jitter_buffer_.ExtractAndSetDecode(frame_timestamp); if (frame == NULL) { return NULL; } frame->SetRenderTime(next_render_time_ms); TRACE_EVENT_ASYNC_STEP1("webrtc", "Video", frame->TimeStamp(), "SetRenderTS", "render_time", next_render_time_ms); if (dual_receiver != NULL) { dual_receiver->UpdateState(*frame); } if (!frame->Complete()) { // Update stats for incomplete frames. bool retransmitted = false; const int64_t last_packet_time_ms = jitter_buffer_.LastPacketTime(frame, &retransmitted); if (last_packet_time_ms >= 0 && !retransmitted) { // We don't want to include timestamps which have suffered from // retransmission here, since we compensate with extra retransmission // delay within the jitter estimate. timing_->IncomingTimestamp(frame_timestamp, last_packet_time_ms); } } return frame; } void VCMReceiver::ReleaseFrame(VCMEncodedFrame* frame) { jitter_buffer_.ReleaseFrame(frame); } void VCMReceiver::ReceiveStatistics(uint32_t* bitrate, uint32_t* framerate) { assert(bitrate); assert(framerate); jitter_buffer_.IncomingRateStatistics(framerate, bitrate); } void VCMReceiver::ReceivedFrameCount(VCMFrameCount* frame_count) const { assert(frame_count); jitter_buffer_.FrameStatistics(&frame_count->numDeltaFrames, &frame_count->numKeyFrames); } uint32_t VCMReceiver::DiscardedPackets() const { return jitter_buffer_.num_discarded_packets(); } void VCMReceiver::SetNackMode(VCMNackMode nackMode, int low_rtt_nack_threshold_ms, int high_rtt_nack_threshold_ms) { CriticalSectionScoped cs(crit_sect_); // Default to always having NACK enabled in hybrid mode. jitter_buffer_.SetNackMode(nackMode, low_rtt_nack_threshold_ms, high_rtt_nack_threshold_ms); if (!master_) { state_ = kPassive; // The dual decoder defaults to passive. } } void VCMReceiver::SetNackSettings(size_t max_nack_list_size, int max_packet_age_to_nack, int max_incomplete_time_ms) { jitter_buffer_.SetNackSettings(max_nack_list_size, max_packet_age_to_nack, max_incomplete_time_ms); } VCMNackMode VCMReceiver::NackMode() const { CriticalSectionScoped cs(crit_sect_); return jitter_buffer_.nack_mode(); } VCMNackStatus VCMReceiver::NackList(uint16_t* nack_list, uint16_t size, uint16_t* nack_list_length) { bool request_key_frame = false; uint16_t* internal_nack_list = jitter_buffer_.GetNackList( nack_list_length, &request_key_frame); if (*nack_list_length > size) { *nack_list_length = 0; return kNackNeedMoreMemory; } if (internal_nack_list != NULL && *nack_list_length > 0) { memcpy(nack_list, internal_nack_list, *nack_list_length * sizeof(uint16_t)); } if (request_key_frame) { return kNackKeyFrameRequest; } return kNackOk; } // Decide whether we should change decoder state. This should be done if the // dual decoder has caught up with the decoder decoding with packet losses. bool VCMReceiver::DualDecoderCaughtUp(VCMEncodedFrame* dual_frame, VCMReceiver& dual_receiver) const { if (dual_frame == NULL) { return false; } if (jitter_buffer_.LastDecodedTimestamp() == dual_frame->TimeStamp()) { dual_receiver.UpdateState(kWaitForPrimaryDecode); return true; } return false; } void VCMReceiver::CopyJitterBufferStateFromReceiver( const VCMReceiver& receiver) { jitter_buffer_.CopyFrom(receiver.jitter_buffer_); } VCMReceiverState VCMReceiver::State() const { CriticalSectionScoped cs(crit_sect_); return state_; } void VCMReceiver::SetDecodeErrorMode(VCMDecodeErrorMode decode_error_mode) { jitter_buffer_.SetDecodeErrorMode(decode_error_mode); } VCMDecodeErrorMode VCMReceiver::DecodeErrorMode() const { return jitter_buffer_.decode_error_mode(); } int VCMReceiver::SetMinReceiverDelay(int desired_delay_ms) { CriticalSectionScoped cs(crit_sect_); if (desired_delay_ms < 0 || desired_delay_ms > kMaxReceiverDelayMs) { return -1; } max_video_delay_ms_ = desired_delay_ms + kMaxVideoDelayMs; // Initializing timing to the desired delay. timing_->set_min_playout_delay(desired_delay_ms); return 0; } int VCMReceiver::RenderBufferSizeMs() { uint32_t timestamp_start = 0u; uint32_t timestamp_end = 0u; // Render timestamps are computed just prior to decoding. Therefore this is // only an estimate based on frames' timestamps and current timing state. jitter_buffer_.RenderBufferSize(&timestamp_start, &timestamp_end); if (timestamp_start == timestamp_end) { return 0; } // Update timing. const int64_t now_ms = clock_->TimeInMilliseconds(); timing_->SetJitterDelay(jitter_buffer_.EstimatedJitterMs()); // Get render timestamps. uint32_t render_start = timing_->RenderTimeMs(timestamp_start, now_ms); uint32_t render_end = timing_->RenderTimeMs(timestamp_end, now_ms); return render_end - render_start; } void VCMReceiver::UpdateState(VCMReceiverState new_state) { CriticalSectionScoped cs(crit_sect_); assert(!(state_ == kPassive && new_state == kWaitForPrimaryDecode)); state_ = new_state; } void VCMReceiver::UpdateState(const VCMEncodedFrame& frame) { if (jitter_buffer_.nack_mode() == kNoNack) { // Dual decoder mode has not been enabled. return; } // Update the dual receiver state. if (frame.Complete() && frame.FrameType() == kVideoFrameKey) { UpdateState(kPassive); } if (State() == kWaitForPrimaryDecode && frame.Complete() && !frame.MissingFrame()) { UpdateState(kPassive); } if (frame.MissingFrame() || !frame.Complete()) { // State was corrupted, enable dual receiver. UpdateState(kReceiving); } } } // namespace webrtc <|endoftext|>
<commit_before>/* vim:expandtab:shiftwidth=2:tabstop=2:smarttab: * * Data Differential YATL (i.e. libtest) library * * Copyright (C) 2012 Data Differential, http://datadifferential.com/ * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * * The names of its contributors may not be used to endorse or * promote products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include <config.h> #include <libtest/common.h> #include <cassert> #include <cstdlib> #include <cstring> #include <ctime> #include <fnmatch.h> #include <iostream> #include <memory> #include <sys/stat.h> #include <sys/time.h> #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> #include <signal.h> #ifndef __INTEL_COMPILER #pragma GCC diagnostic ignored "-Wold-style-cast" #endif using namespace libtest; static void stats_print(Framework *frame) { if (frame->failed() == 0 and frame->success() == 0) { return; } Outn(); Out << "Collections\t\t\t\t\t" << frame->total(); Out << "\tFailed\t\t\t\t\t" << frame->failed(); Out << "\tSkipped\t\t\t\t\t" << frame->skipped(); Out << "\tSucceeded\t\t\t\t" << frame->success(); Outn(); Out << "Tests\t\t\t\t\t" << frame->sum_total(); Out << "\tFailed\t\t\t\t" << frame->sum_failed(); Out << "\tSkipped\t\t\t\t" << frame->sum_skipped(); Out << "\tSucceeded\t\t\t" << frame->sum_success(); } #include <getopt.h> #include <unistd.h> int main(int argc, char *argv[]) { bool opt_massive= false; unsigned long int opt_repeat= 1; // Run all tests once bool opt_quiet= false; std::string collection_to_run; std::string wildcard; /* Valgrind does not currently work reliably, or sometimes at all, on OSX - Fri Jun 15 11:24:07 EDT 2012 */ #if defined(TARGET_OS_OSX) && TARGET_OS_OSX if (valgrind_is_caller()) { return EXIT_SKIP; } #endif // Options parsing { enum long_option_t { OPT_LIBYATL_VERSION, OPT_LIBYATL_MATCH_COLLECTION, OPT_LIBYATL_MASSIVE, OPT_LIBYATL_QUIET, OPT_LIBYATL_MATCH_WILDCARD, OPT_LIBYATL_REPEAT }; static struct option long_options[]= { { "version", no_argument, NULL, OPT_LIBYATL_VERSION }, { "quiet", no_argument, NULL, OPT_LIBYATL_QUIET }, { "repeat", no_argument, NULL, OPT_LIBYATL_REPEAT }, { "collection", required_argument, NULL, OPT_LIBYATL_MATCH_COLLECTION }, { "wildcard", required_argument, NULL, OPT_LIBYATL_MATCH_WILDCARD }, { "massive", no_argument, NULL, OPT_LIBYATL_MASSIVE }, { 0, 0, 0, 0 } }; int option_index= 0; while (1) { int option_rv= getopt_long(argc, argv, "", long_options, &option_index); if (option_rv == -1) { break; } switch (option_rv) { case OPT_LIBYATL_VERSION: break; case OPT_LIBYATL_QUIET: opt_quiet= true; break; case OPT_LIBYATL_REPEAT: opt_repeat= strtoul(optarg, (char **) NULL, 10); break; case OPT_LIBYATL_MATCH_COLLECTION: collection_to_run= optarg; break; case OPT_LIBYATL_MATCH_WILDCARD: wildcard= optarg; break; case OPT_LIBYATL_MASSIVE: opt_massive= true; break; case '?': /* getopt_long already printed an error message. */ Error << "unknown option to getopt_long()"; exit(EXIT_FAILURE); default: break; } } } srandom((unsigned int)time(NULL)); if (bool(getenv("YATL_REPEAT")) and (strtoul(getenv("YATL_REPEAT"), (char **) NULL, 10) > 1)) { opt_repeat= strtoul(getenv("YATL_REPEAT"), (char **) NULL, 10); } if ((bool(getenv("YATL_QUIET")) and (strcmp(getenv("YATL_QUIET"), "0") == 0)) or opt_quiet) { opt_quiet= true; } else if (getenv("JENKINS_URL")) { if (bool(getenv("YATL_QUIET")) and (strcmp(getenv("YATL_QUIET"), "1") == 0)) { } else { opt_quiet= true; } } if (opt_quiet) { close(STDOUT_FILENO); } char buffer[1024]; if (getenv("LIBTEST_TMP")) { snprintf(buffer, sizeof(buffer), "%s", getenv("LIBTEST_TMP")); } else { snprintf(buffer, sizeof(buffer), "%s", LIBTEST_TEMP); } if (chdir(buffer) == -1) { char getcwd_buffer[1024]; char *dir= getcwd(getcwd_buffer, sizeof(getcwd_buffer)); Error << "Unable to chdir() from " << dir << " to " << buffer << " errno:" << strerror(errno); return EXIT_FAILURE; } if (libtest::libtool() == NULL) { Error << "Failed to locate libtool"; return EXIT_FAILURE; } if (getenv("YATL_COLLECTION_TO_RUN")) { if (strlen(getenv("YATL_COLLECTION_TO_RUN"))) { collection_to_run= getenv("YATL_COLLECTION_TO_RUN"); } } if (collection_to_run.compare("none") == 0) { return EXIT_SUCCESS; } if (collection_to_run.empty() == false) { Out << "Only testing " << collection_to_run; } int exit_code; try { do { exit_code= EXIT_SUCCESS; fatal_assert(sigignore(SIGPIPE) == 0); libtest::SignalThread signal; if (signal.setup() == false) { Error << "Failed to setup signals"; return EXIT_FAILURE; } std::auto_ptr<Framework> frame(new Framework(signal, collection_to_run, wildcard)); // Run create(), bail on error. { switch (frame->create()) { case TEST_SUCCESS: break; case TEST_SKIPPED: return EXIT_SKIP; case TEST_FAILURE: return EXIT_FAILURE; } } frame->exec(); if (signal.is_shutdown() == false) { signal.set_shutdown(SHUTDOWN_GRACEFUL); } shutdown_t status= signal.get_shutdown(); if (status == SHUTDOWN_FORCED) { Out << "Tests were aborted."; exit_code= EXIT_FAILURE; } else if (frame->failed()) { Out << "Some test failed."; exit_code= EXIT_FAILURE; } else if (frame->skipped() and frame->failed() and frame->success()) { Out << "Some tests were skipped."; } else if (frame->success() and (frame->failed() == 0)) { Out << "All tests completed successfully."; } stats_print(frame.get()); Outn(); // Generate a blank to break up the messages if make check/test has been run } while (exit_code == EXIT_SUCCESS and --opt_repeat); } catch (libtest::fatal& e) { std::cerr << e.what() << std::endl; exit_code= EXIT_FAILURE; } catch (libtest::disconnected& e) { std::cerr << "Unhandled disconnection occurred:" << e.what() << std::endl; exit_code= EXIT_FAILURE; } catch (std::exception& e) { std::cerr << e.what() << std::endl; exit_code= EXIT_FAILURE; } catch (...) { std::cerr << "Unknown exception halted execution." << std::endl; exit_code= EXIT_FAILURE; } return exit_code; } <commit_msg>Additional info on exit_code from main libtest.<commit_after>/* vim:expandtab:shiftwidth=2:tabstop=2:smarttab: * * Data Differential YATL (i.e. libtest) library * * Copyright (C) 2012 Data Differential, http://datadifferential.com/ * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * * The names of its contributors may not be used to endorse or * promote products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include <config.h> #include <libtest/common.h> #include <cassert> #include <cstdlib> #include <cstring> #include <ctime> #include <fnmatch.h> #include <iostream> #include <memory> #include <sys/stat.h> #include <sys/time.h> #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> #include <signal.h> #ifndef __INTEL_COMPILER #pragma GCC diagnostic ignored "-Wold-style-cast" #endif using namespace libtest; static void stats_print(Framework *frame) { if (frame->failed() == 0 and frame->success() == 0) { return; } Outn(); Out << "Collections\t\t\t\t\t" << frame->total(); Out << "\tFailed\t\t\t\t\t" << frame->failed(); Out << "\tSkipped\t\t\t\t\t" << frame->skipped(); Out << "\tSucceeded\t\t\t\t" << frame->success(); Outn(); Out << "Tests\t\t\t\t\t" << frame->sum_total(); Out << "\tFailed\t\t\t\t" << frame->sum_failed(); Out << "\tSkipped\t\t\t\t" << frame->sum_skipped(); Out << "\tSucceeded\t\t\t" << frame->sum_success(); } #include <getopt.h> #include <unistd.h> int main(int argc, char *argv[]) { bool opt_massive= false; unsigned long int opt_repeat= 1; // Run all tests once bool opt_quiet= false; std::string collection_to_run; std::string wildcard; /* Valgrind does not currently work reliably, or sometimes at all, on OSX - Fri Jun 15 11:24:07 EDT 2012 */ #if defined(TARGET_OS_OSX) && TARGET_OS_OSX if (valgrind_is_caller()) { return EXIT_SKIP; } #endif // Options parsing { enum long_option_t { OPT_LIBYATL_VERSION, OPT_LIBYATL_MATCH_COLLECTION, OPT_LIBYATL_MASSIVE, OPT_LIBYATL_QUIET, OPT_LIBYATL_MATCH_WILDCARD, OPT_LIBYATL_REPEAT }; static struct option long_options[]= { { "version", no_argument, NULL, OPT_LIBYATL_VERSION }, { "quiet", no_argument, NULL, OPT_LIBYATL_QUIET }, { "repeat", no_argument, NULL, OPT_LIBYATL_REPEAT }, { "collection", required_argument, NULL, OPT_LIBYATL_MATCH_COLLECTION }, { "wildcard", required_argument, NULL, OPT_LIBYATL_MATCH_WILDCARD }, { "massive", no_argument, NULL, OPT_LIBYATL_MASSIVE }, { 0, 0, 0, 0 } }; int option_index= 0; while (1) { int option_rv= getopt_long(argc, argv, "", long_options, &option_index); if (option_rv == -1) { break; } switch (option_rv) { case OPT_LIBYATL_VERSION: break; case OPT_LIBYATL_QUIET: opt_quiet= true; break; case OPT_LIBYATL_REPEAT: opt_repeat= strtoul(optarg, (char **) NULL, 10); break; case OPT_LIBYATL_MATCH_COLLECTION: collection_to_run= optarg; break; case OPT_LIBYATL_MATCH_WILDCARD: wildcard= optarg; break; case OPT_LIBYATL_MASSIVE: opt_massive= true; break; case '?': /* getopt_long already printed an error message. */ Error << "unknown option to getopt_long()"; exit(EXIT_FAILURE); default: break; } } } srandom((unsigned int)time(NULL)); if (bool(getenv("YATL_REPEAT")) and (strtoul(getenv("YATL_REPEAT"), (char **) NULL, 10) > 1)) { opt_repeat= strtoul(getenv("YATL_REPEAT"), (char **) NULL, 10); } if ((bool(getenv("YATL_QUIET")) and (strcmp(getenv("YATL_QUIET"), "0") == 0)) or opt_quiet) { opt_quiet= true; } else if (getenv("JENKINS_URL")) { if (bool(getenv("YATL_QUIET")) and (strcmp(getenv("YATL_QUIET"), "1") == 0)) { } else { opt_quiet= true; } } if (opt_quiet) { close(STDOUT_FILENO); } char buffer[1024]; if (getenv("LIBTEST_TMP")) { snprintf(buffer, sizeof(buffer), "%s", getenv("LIBTEST_TMP")); } else { snprintf(buffer, sizeof(buffer), "%s", LIBTEST_TEMP); } if (chdir(buffer) == -1) { char getcwd_buffer[1024]; char *dir= getcwd(getcwd_buffer, sizeof(getcwd_buffer)); Error << "Unable to chdir() from " << dir << " to " << buffer << " errno:" << strerror(errno); return EXIT_FAILURE; } if (libtest::libtool() == NULL) { Error << "Failed to locate libtool"; return EXIT_FAILURE; } if (getenv("YATL_COLLECTION_TO_RUN")) { if (strlen(getenv("YATL_COLLECTION_TO_RUN"))) { collection_to_run= getenv("YATL_COLLECTION_TO_RUN"); } } if (collection_to_run.compare("none") == 0) { return EXIT_SUCCESS; } if (collection_to_run.empty() == false) { Out << "Only testing " << collection_to_run; } int exit_code; try { do { exit_code= EXIT_SUCCESS; fatal_assert(sigignore(SIGPIPE) == 0); libtest::SignalThread signal; if (signal.setup() == false) { Error << "Failed to setup signals"; return EXIT_FAILURE; } std::auto_ptr<Framework> frame(new Framework(signal, collection_to_run, wildcard)); // Run create(), bail on error. { switch (frame->create()) { case TEST_SUCCESS: break; case TEST_SKIPPED: return EXIT_SKIP; case TEST_FAILURE: std::cerr << "frame->create()" << std::endl; return EXIT_FAILURE; } } frame->exec(); if (signal.is_shutdown() == false) { signal.set_shutdown(SHUTDOWN_GRACEFUL); } shutdown_t status= signal.get_shutdown(); if (status == SHUTDOWN_FORCED) { Out << "Tests were aborted."; exit_code= EXIT_FAILURE; } else if (frame->failed()) { Out << "Some test failed."; exit_code= EXIT_FAILURE; } else if (frame->skipped() and frame->failed() and frame->success()) { Out << "Some tests were skipped."; } else if (frame->success() and (frame->failed() == 0)) { Out << "All tests completed successfully."; } stats_print(frame.get()); Outn(); // Generate a blank to break up the messages if make check/test has been run } while (exit_code == EXIT_SUCCESS and --opt_repeat); } catch (libtest::fatal& e) { std::cerr << "FATAL:" << e.what() << std::endl; exit_code= EXIT_FAILURE; } catch (libtest::disconnected& e) { std::cerr << "Unhandled disconnection occurred:" << e.what() << std::endl; exit_code= EXIT_FAILURE; } catch (std::exception& e) { std::cerr << "std::exception:" << e.what() << std::endl; exit_code= EXIT_FAILURE; } catch (...) { std::cerr << "Unknown exception halted execution." << std::endl; exit_code= EXIT_FAILURE; } return exit_code; } <|endoftext|>
<commit_before>/******************************************************************************* * Copyright 2018 Intel Corporation * * 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 <functional> #include <memory> #include <typeindex> #include <typeinfo> #include <unordered_map> #include "cpu_nop_elimination.hpp" #include "ngraph/op/convert.hpp" #include "ngraph/op/pad.hpp" #include "ngraph/op/sum.hpp" #define TI(x) std::type_index(typeid(x)) #define HANDLER_DECL(x) \ static bool x(const std::shared_ptr<ngraph::Function>& function, \ const std::shared_ptr<ngraph::Node>& node) HANDLER_DECL(eliminate_pad) { auto pad = std::dynamic_pointer_cast<ngraph::op::Pad>(node); if (pad->get_input_shape(0) == pad->get_output_shape(0)) { function->replace_node(node, node->get_input_op(0)); return true; } return false; } HANDLER_DECL(eliminate_sum) { auto sum = std::dynamic_pointer_cast<ngraph::op::Sum>(node); if (sum->get_reduction_axes().empty()) { function->replace_node(node, node->get_input_op(0)); return true; } return false; } HANDLER_DECL(eliminate_convert) { auto convert = std::dynamic_pointer_cast<ngraph::op::Convert>(node); if (convert->get_convert_element_type() == convert->get_input_op(0)->get_element_type()) { function->replace_node(node, node->get_input_op(0)); return true; } return false; } static const std::unordered_map<std::type_index, std::function<bool(const std::shared_ptr<ngraph::Function>&, const std::shared_ptr<ngraph::Node>&)>> dispatcher{{TI(ngraph::op::Pad), &eliminate_pad}, {TI(ngraph::op::Sum), &eliminate_sum}, {TI(ngraph::op::Convert), &eliminate_convert}}; bool ngraph::runtime::cpu::pass::CPUNopElimination::run_on_function( std::shared_ptr<ngraph::Function> function) { bool clobbered = false; for (const auto& n : function->get_ops()) { // Work around a warning [-Wpotentially-evaluated-expression] const Node& node = *n; auto handler = dispatcher.find(TI(node)); if (handler != dispatcher.end()) { clobbered = handler->second(function, n) || clobbered; } } return clobbered; } <commit_msg>CPU: Eliminate slices (#849)<commit_after>/******************************************************************************* * Copyright 2018 Intel Corporation * * 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 <functional> #include <memory> #include <typeindex> #include <typeinfo> #include <unordered_map> #include "cpu_nop_elimination.hpp" #include "ngraph/op/convert.hpp" #include "ngraph/op/pad.hpp" #include "ngraph/op/slice.hpp" #include "ngraph/op/sum.hpp" #define TI(x) std::type_index(typeid(x)) #define HANDLER_DECL(x) \ static bool x(const std::shared_ptr<ngraph::Function>& function, \ const std::shared_ptr<ngraph::Node>& node) HANDLER_DECL(eliminate_pad) { auto pad = std::dynamic_pointer_cast<ngraph::op::Pad>(node); if (pad->get_input_shape(0) == pad->get_output_shape(0)) { function->replace_node(node, node->get_input_op(0)); return true; } return false; } HANDLER_DECL(eliminate_sum) { auto sum = std::dynamic_pointer_cast<ngraph::op::Sum>(node); if (sum->get_reduction_axes().empty()) { function->replace_node(node, node->get_input_op(0)); return true; } return false; } HANDLER_DECL(eliminate_convert) { auto convert = std::dynamic_pointer_cast<ngraph::op::Convert>(node); if (convert->get_convert_element_type() == convert->get_input_op(0)->get_element_type()) { function->replace_node(node, node->get_input_op(0)); return true; } return false; } HANDLER_DECL(eliminate_slice) { auto slice = std::dynamic_pointer_cast<ngraph::op::Slice>(node); if (slice->get_input_shape(0) == slice->get_output_shape(0)) { function->replace_node(node, node->get_input_op(0)); return true; } return false; } static const std::unordered_map<std::type_index, std::function<bool(const std::shared_ptr<ngraph::Function>&, const std::shared_ptr<ngraph::Node>&)>> dispatcher{{TI(ngraph::op::Pad), &eliminate_pad}, {TI(ngraph::op::Sum), &eliminate_sum}, {TI(ngraph::op::Convert), &eliminate_convert}, {TI(ngraph::op::Slice), &eliminate_slice}}; bool ngraph::runtime::cpu::pass::CPUNopElimination::run_on_function( std::shared_ptr<ngraph::Function> function) { bool clobbered = false; for (const auto& n : function->get_ops()) { // Work around a warning [-Wpotentially-evaluated-expression] const Node& node = *n; auto handler = dispatcher.find(TI(node)); if (handler != dispatcher.end()) { clobbered = handler->second(function, n) || clobbered; } } return clobbered; } <|endoftext|>
<commit_before>#include "WorldMapGenerator.h" #include <utility> #include <list> #include <tuple> #include "../maths/mathshelper.h" using namespace arma; using namespace maths; using namespace img; // MODULES ( dplacer ?) WorldMapGeneratorModule::WorldMapGeneratorModule(WorldMapGenerator * parent) : _parent(parent) { } cube & WorldMapGeneratorModule::reliefMap(WorldMap & map) const { return map._reliefMap; } std::mt19937 & WorldMapGeneratorModule::rng() const { return _parent->_rng; } // ----- ReliefMapGenerator::ReliefMapGenerator(WorldMapGenerator * parent) : WorldMapGeneratorModule(parent) { } // ----- const float CustomWorldRMGenerator::PIXEL_UNIT = 100; CustomWorldRMGenerator::CustomWorldRMGenerator(WorldMapGenerator * parent) : ReliefMapGenerator(parent) { } void CustomWorldRMGenerator::generate(WorldMap & map) const { cube relief = reliefMap(map); // Nombre de biomes gnrer. uint32_t size = relief.n_rows * relief.n_cols; uint32_t biomeCount = (uint32_t)(_biomeDensity * (float) size / PIXEL_UNIT); // -> Cration de la grille pour le placement des points de manire alatoire, // mais avec une distance minimum. // Calcul des dimensions de la grille float minDistance = PIXEL_UNIT / 2.0 * sqrt(_biomeDensity); uint32_t sliceCount = (uint32_t)((float)relief.n_rows / minDistance); float sliceSize = (float)relief.n_rows / (float)sliceCount; uint32_t caseCount = (uint32_t)((float)relief.n_cols / minDistance); float caseSize = (float)relief.n_cols / (float)caseCount; // Prparation de la grille typedef std::tuple<float, float, float, float> point; // pour plus de lisibilit std::vector<std::vector<point>> pointsMap; pointsMap.reserve(sliceCount); std::vector<std::pair<uint32_t, uint32_t>> grid; grid.reserve(size); for (int x = 0; x < sliceCount; x++) { pointsMap.emplace_back(); auto slice = pointsMap[x]; slice.reserve(caseCount); for (int y = 0; y < caseCount; y++) { grid.emplace_back(x, y); slice.emplace_back(-1, -1, 0, 0); } } // Gnration des points std::uniform_real_distribution<double> rand(0.0, 1.0); for (int i = 0; i < biomeCount; i++) { // Gnration des coordonnes des points uint32_t randIndex = (uint32_t)(rand(rng()) * grid.size()); std::pair<uint32_t, uint32_t> randPoint = grid.at(randIndex); grid.erase(grid.begin() + randIndex); uint32_t x = randPoint.first; uint32_t y = randPoint.second; // Calcul des limites dans lesquelles on peut avoir un point double limNegX = 0; double limPosX = sliceSize; double limNegY = 0; double limPosY = caseSize; if (x > 0) { auto negXCase = pointsMap[x - 1][y]; if (std::get<0>(negXCase) > 0) { limNegX = std::get<0>(negXCase); } } if (x < sliceCount - 1) { auto posXCase = pointsMap[x + 1][y]; if (std::get<0>(posXCase) > 0) { limPosX = std::get<0>(posXCase); } } if (y > 0) { auto negYCase = pointsMap[x][y - 1]; if (std::get<1>(negYCase) > 0) { limNegY = std::get<1>(negYCase); } } if (y < caseCount - 1) { auto posYCase = pointsMap[x][y + 1]; if (std::get<1>(posYCase) > 0) { limPosY = std::get<1>(posYCase); } } // partir des limites on peut dterminer la position random du point double randX = rand(rng()); double randY = rand(rng()); pointsMap[x][y] = std::make_tuple<float, float, float, float>( randX * (limPosX - limNegX) + limNegX + x * sliceSize, randY * (limPosY - limNegY) + limNegY + y * caseSize, 0, 0); // ET VOILA ! // Maintenant est-ce qu'on trouve les valeurs ici, ou est-ce qu'on attend ? // Est-ce qu'on spare cet algorithme du reste ? // Tant de question sans rponse... } // -> Interpolation des valeurs des points pour reconstituer une map } // WorldMapGenerator WorldMapGenerator::WorldMapGenerator(uint32_t sizeX, uint32_t sizeY) : _sizeX(sizeX), _sizeY(sizeY), _reliefMap(nullptr) { } WorldMapGenerator::~WorldMapGenerator() { } std::unique_ptr<WorldMap> WorldMapGenerator::generate() { std::unique_ptr<WorldMap> map = std::make_unique<WorldMap>(_sizeX, _sizeY); if (_reliefMap != nullptr) _reliefMap->generate(*map); return map; } <commit_msg>Reflexions supplémentaires sur la manière de mener le problème.<commit_after>#include "WorldMapGenerator.h" #include <utility> #include <list> #include <tuple> #include "../maths/mathshelper.h" using namespace arma; using namespace maths; using namespace img; // MODULES ( dplacer ?) WorldMapGeneratorModule::WorldMapGeneratorModule(WorldMapGenerator * parent) : _parent(parent) { } cube & WorldMapGeneratorModule::reliefMap(WorldMap & map) const { return map._reliefMap; } std::mt19937 & WorldMapGeneratorModule::rng() const { return _parent->_rng; } // ----- ReliefMapGenerator::ReliefMapGenerator(WorldMapGenerator * parent) : WorldMapGeneratorModule(parent) { } // ----- const float CustomWorldRMGenerator::PIXEL_UNIT = 100; CustomWorldRMGenerator::CustomWorldRMGenerator(WorldMapGenerator * parent) : ReliefMapGenerator(parent) { } void CustomWorldRMGenerator::generate(WorldMap & map) const { cube relief = reliefMap(map); // Nombre de biomes gnrer. uint32_t size = relief.n_rows * relief.n_cols; uint32_t biomeCount = (uint32_t)(_biomeDensity * (float) size / PIXEL_UNIT); // -> Cration de la grille pour le placement des points de manire alatoire, // mais avec une distance minimum. // Calcul des dimensions de la grille float minDistance = PIXEL_UNIT / 2.0 * sqrt(_biomeDensity); uint32_t sliceCount = (uint32_t)((float)relief.n_rows / minDistance); float sliceSize = (float)relief.n_rows / (float)sliceCount; uint32_t caseCount = (uint32_t)((float)relief.n_cols / minDistance); float caseSize = (float)relief.n_cols / (float)caseCount; // Prparation de la grille typedef std::tuple<float, float, float, float> point; // pour plus de lisibilit std::vector<std::vector<point>> pointsMap; pointsMap.reserve(sliceCount); std::vector<std::pair<uint32_t, uint32_t>> grid; grid.reserve(size); for (int x = 0; x < sliceCount; x++) { pointsMap.emplace_back(); auto slice = pointsMap[x]; slice.reserve(caseCount); for (int y = 0; y < caseCount; y++) { grid.emplace_back(x, y); slice.emplace_back(-1, -1, 0, 0); } } // Gnration des points std::uniform_real_distribution<double> rand(0.0, 1.0); for (int i = 0; i < biomeCount; i++) { // Gnration des coordonnes des points uint32_t randIndex = (uint32_t)(rand(rng()) * grid.size()); std::pair<uint32_t, uint32_t> randPoint = grid.at(randIndex); grid.erase(grid.begin() + randIndex); uint32_t x = randPoint.first; uint32_t y = randPoint.second; // Calcul des limites dans lesquelles on peut avoir un point double limNegX = 0; double limPosX = sliceSize; double limNegY = 0; double limPosY = caseSize; if (x > 0) { auto negXCase = pointsMap[x - 1][y]; if (std::get<0>(negXCase) > 0) { limNegX = std::get<0>(negXCase); } } if (x < sliceCount - 1) { auto posXCase = pointsMap[x + 1][y]; if (std::get<0>(posXCase) > 0) { limPosX = std::get<0>(posXCase); } } if (y > 0) { auto negYCase = pointsMap[x][y - 1]; if (std::get<1>(negYCase) > 0) { limNegY = std::get<1>(negYCase); } } if (y < caseCount - 1) { auto posYCase = pointsMap[x][y + 1]; if (std::get<1>(posYCase) > 0) { limPosY = std::get<1>(posYCase); } } // partir des limites on peut dterminer la position random du point double randX = rand(rng()); double randY = rand(rng()); float elevation = 0; float diff = 0; pointsMap[x][y] = std::tuple<float, float, float, float>( (float)(randX * (limPosX - limNegX) + limNegX + x * sliceSize), (float)(randY * (limPosY - limNegY) + limNegY + y * caseSize), elevation, diff); // ET VOILA ! // Maintenant est-ce qu'on trouve les valeurs ici, ou est-ce qu'on attend ? // Est-ce qu'on spare cet algorithme du reste ? // Tant de question sans rponse... } // -> Interpolation des valeurs des points pour reconstituer une map // https://en.wikipedia.org/wiki/Inverse_distance_weighting } // WorldMapGenerator WorldMapGenerator::WorldMapGenerator(uint32_t sizeX, uint32_t sizeY) : _sizeX(sizeX), _sizeY(sizeY), _reliefMap(nullptr) { } WorldMapGenerator::~WorldMapGenerator() { } std::unique_ptr<WorldMap> WorldMapGenerator::generate() { std::unique_ptr<WorldMap> map = std::make_unique<WorldMap>(_sizeX, _sizeY); if (_reliefMap != nullptr) _reliefMap->generate(*map); return map; } <|endoftext|>
<commit_before>#include <k52/optimization/params/double_parameters_array.h> #include <stdexcept> namespace k52 { namespace optimization { DoubleParametersArray::DoubleParametersArray(double min_value, double max_value, double desired_precision, size_t number_of_parameters) : sample_parameter_ (new DoubleParameter(min_value, min_value, max_value, desired_precision)), values_(number_of_parameters) { SetConstChromosomeSize(CountTotalChromosomeSize()); } DoubleParametersArray* DoubleParametersArray::Clone() const { DoubleParametersArray* clone = new DoubleParametersArray(); clone->values_ = values_; clone->sample_parameter_ = sample_parameter_ != NULL ? DoubleParameter::shared_ptr( sample_parameter_->Clone() ) : DoubleParameter::shared_ptr(); clone->SetConstChromosomeSize(CountTotalChromosomeSize()); return clone; } bool DoubleParametersArray::CheckConstraints() const { for(size_t i=0; i<values_.size(); i++) { //TODO //copypaste from DoubleParameter if(values_[i] < get_min_value() || values_[i] > get_max_value()) { return false; } } return true; } void DoubleParametersArray::SetChromosome(std::vector<bool>::iterator from, std::vector<bool>::iterator to) const { //TODO //copypaste from CompositeDiscreteParameters size_t chromosome_size = to - from; this->CheckForConstChromosomeSize(chromosome_size); std::vector<bool>::iterator current_from = from; size_t parameter_chromosome_size = sample_parameter_->GetChromosomeSize(); for(size_t i = 0; i < values_.size(); i++) { std::vector<bool>::iterator current_to = current_from + parameter_chromosome_size; sample_parameter_->SetValue(values_[i]); sample_parameter_->SetChromosome(current_from, current_to); current_from = current_to; } } void DoubleParametersArray::SetFromChromosome(std::vector<bool>::const_iterator from, std::vector<bool>::const_iterator to) { //TODO //copypaste from CompositeDiscreteParameters size_t chromosome_size = to - from; this->CheckForConstChromosomeSize(chromosome_size); std::vector<bool>::const_iterator current_from = from; size_t parameter_chromosome_size = sample_parameter_->GetChromosomeSize(); for(size_t i = 0; i < values_.size(); i++) { std::vector<bool>::const_iterator current_to = current_from + parameter_chromosome_size; sample_parameter_->SetFromChromosome(current_from, current_to); values_[i] = sample_parameter_->GetValue(); current_from = current_to; } } std::vector<double> DoubleParametersArray::GetValues() const { return values_; } double DoubleParametersArray::get_max_value() const { return sample_parameter_->get_max_value(); } double DoubleParametersArray::get_min_value() const { return sample_parameter_->get_min_value(); } size_t DoubleParametersArray::get_number_of_parameters() const { return values_.size(); } double DoubleParametersArray::get_actual_precision() const { return sample_parameter_->get_actual_precision(); } DoubleParametersArray::DoubleParametersArray() {} size_t DoubleParametersArray::CountTotalChromosomeSize() const { return sample_parameter_->GetChromosomeSize() * values_.size(); } }/* namespace optimization */ }/* namespace k52 */ <commit_msg>CheckConstaraints implemented using sample double parameter<commit_after>#include <k52/optimization/params/double_parameters_array.h> #include <stdexcept> namespace k52 { namespace optimization { DoubleParametersArray::DoubleParametersArray(double min_value, double max_value, double desired_precision, size_t number_of_parameters) : sample_parameter_ (new DoubleParameter(min_value, min_value, max_value, desired_precision)), values_(number_of_parameters) { SetConstChromosomeSize(CountTotalChromosomeSize()); } DoubleParametersArray* DoubleParametersArray::Clone() const { DoubleParametersArray* clone = new DoubleParametersArray(); clone->values_ = values_; clone->sample_parameter_ = sample_parameter_ != NULL ? DoubleParameter::shared_ptr( sample_parameter_->Clone() ) : DoubleParameter::shared_ptr(); clone->SetConstChromosomeSize(CountTotalChromosomeSize()); return clone; } bool DoubleParametersArray::CheckConstraints() const { for(size_t i=0; i<values_.size(); i++) { sample_parameter_->SetValue(values_[i]); if(!sample_parameter_->CheckConstraints()) { return false; } } return true; } void DoubleParametersArray::SetChromosome(std::vector<bool>::iterator from, std::vector<bool>::iterator to) const { //TODO //copypaste from CompositeDiscreteParameters size_t chromosome_size = to - from; this->CheckForConstChromosomeSize(chromosome_size); std::vector<bool>::iterator current_from = from; size_t parameter_chromosome_size = sample_parameter_->GetChromosomeSize(); for(size_t i = 0; i < values_.size(); i++) { std::vector<bool>::iterator current_to = current_from + parameter_chromosome_size; sample_parameter_->SetValue(values_[i]); sample_parameter_->SetChromosome(current_from, current_to); current_from = current_to; } } void DoubleParametersArray::SetFromChromosome(std::vector<bool>::const_iterator from, std::vector<bool>::const_iterator to) { //TODO //copypaste from CompositeDiscreteParameters size_t chromosome_size = to - from; this->CheckForConstChromosomeSize(chromosome_size); std::vector<bool>::const_iterator current_from = from; size_t parameter_chromosome_size = sample_parameter_->GetChromosomeSize(); for(size_t i = 0; i < values_.size(); i++) { std::vector<bool>::const_iterator current_to = current_from + parameter_chromosome_size; sample_parameter_->SetFromChromosome(current_from, current_to); values_[i] = sample_parameter_->GetValue(); current_from = current_to; } } std::vector<double> DoubleParametersArray::GetValues() const { return values_; } double DoubleParametersArray::get_max_value() const { return sample_parameter_->get_max_value(); } double DoubleParametersArray::get_min_value() const { return sample_parameter_->get_min_value(); } size_t DoubleParametersArray::get_number_of_parameters() const { return values_.size(); } double DoubleParametersArray::get_actual_precision() const { return sample_parameter_->get_actual_precision(); } DoubleParametersArray::DoubleParametersArray() {} size_t DoubleParametersArray::CountTotalChromosomeSize() const { return sample_parameter_->GetChromosomeSize() * values_.size(); } }/* namespace optimization */ }/* namespace k52 */ <|endoftext|>
<commit_before>// $Id$ // // You received this file as part of MCA2 // Modular Controller Architecture Version 2 // //Copyright (C) Forschungszentrum Informatik Karlsruhe // //This program is free software; you can redistribute it and/or //modify it under the terms of the GNU General Public License //as published by the Free Software Foundation; either version 2 //of the License, or (at your option) any later version. // //This program is distributed in the hope that it will be useful, //but WITHOUT ANY WARRANTY; without even the implied warranty of //MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //GNU General Public License for more details. // //You should have received a copy of the GNU General Public License //along with this program; if not, write to the Free Software //Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // // this is a -*- C++ -*- file //---------------------------------------------------------------------- //---------------------------------------------------------------------- #ifndef __XrdWin32_h__ #define __XrdWin32_h__ #include <errno.h> #include <stdio.h> #include <stdlib.h> #include <io.h> #include <time.h> #include <direct.h> #include <sys/types.h> #include <Winsock2.h> #ifndef POLLIN #define POLLIN 0x0001 /* There is data to read */ #define POLLPRI 0x0002 /* There is urgent data to read */ #define POLLOUT 0x0004 /* Writing now will not block */ #define POLLERR 0x0008 /* Error condition */ #define POLLHUP 0x0010 /* Hung up */ #define POLLNVAL 0x0020 /* Invalid request: fd not open */ #define POLLRDNORM 0x0001 #define POLLWRNORM 0x0002 #define POLLRDBAND 0x0000 struct pollfd { unsigned int fd; short events; short revents; }; #endif #define EMSGSIZE WSAEMSGSIZE #define EAFNOSUPPORT WSAEAFNOSUPPORT #define EWOULDBLOCK WSAEWOULDBLOCK #define ECONNRESET WSAECONNRESET #define EINPROGRESS WSAEINPROGRESS #define ENOBUFS WSAENOBUFS #define EPROTONOSUPPORT WSAEPROTONOSUPPORT #define ECONNREFUSED WSAECONNREFUSED #define EBADFD WSAENOTSOCK #define EOPNOTSUPP WSAEOPNOTSUPP #define ENETUNREACH WSAENETUNREACH #define EHOSTUNREACH WSAEHOSTUNREACH #define EHOSTDOWN WSAEHOSTDOWN #define EISCONN WSAEISCONN #define ECONNRESET WSAECONNRESET #define ECONNABORTED WSAECONNABORTED #define ESHUTDOWN WSAESHUTDOWN #ifndef ETIMEDOUT #define ETIMEDOUT WSAETIMEDOUT #endif #define ETXTBSY 26 #define WEXITSTATUS(w) (((w) >> 8) & 0xff) #define WIFEXITED(w) (((w) & 0xff) == 0) #define WTERMSIG(w) ((w) & 0x7f) #define WIFSIGNALED(w) (((w) & 0x7f) > 0 && (((w) & 0x7f) < 0x7f)) #ifndef S_ISDIR #define S_ISDIR(m) (((m)&(S_IFMT)) == (S_IFDIR)) #endif #ifndef S_ISREG #define S_ISREG(m) (((m)&(S_IFMT)) == (S_IFREG)) #endif #ifndef S_IXUSR #define S_IXUSR 00100 #endif #ifndef S_IRGRP #define S_IRGRP 00040 #endif #ifndef S_IXGRP #define S_IXGRP 00010 #endif #ifndef S_IROTH #define S_IROTH 00004 #endif #ifndef S_IXOTH #define S_IXOTH 00001 #endif #ifndef S_IRUSR #define S_IRUSR S_IREAD #endif #ifndef S_IWUSR #define S_IWUSR S_IWRITE #endif #ifndef S_IWGRP #define S_IWGRP 000020 #endif #ifndef S_IWOTH #define S_IWOTH 000002 #endif #ifndef S_IRWXU #define S_IRWXU 0000700 #endif #ifndef S_IRWXG #define S_IRWXG 0000070 #endif #ifndef S_ISFIFO # ifndef S_IFIFO # define S_IFIFO 0010000 # endif # define S_ISFIFO(m) ((m & S_IFMT) == S_IFIFO) #endif #ifndef S_IFSOCK #define S_IFSOCK 0140000 #endif #define _SC_PAGESIZE 1 #define F_GETFL 1 #define F_SETFL 2 #define F_GETFD 4 #define F_SETFD 8 #define FD_CLOEXEC 1 #define O_NDELAY 2 #define O_NONBLOCK 4 #define X_OK 1 #define W_OK 2 #define R_OK 4 #define RTLD_NOW 0x0001 #ifndef STDIN_FILENO #define STDIN_FILENO 0 #define STDOUT_FILENO 1 #define STDERR_FILENO 2 #endif #ifndef fsync #define fsync(a) _commit(a) #endif #ifndef socklen_t #define socklen_t int #endif #ifndef SOCKLEN_t #define SOCKLEN_t int #endif #ifndef snprintf #define snprintf _snprintf #endif #ifndef caddr_t typedef char* caddr_t; #endif #ifndef pid_t typedef int pid_t; #endif #ifndef mode_t typedef unsigned int mode_t; #endif #ifndef uint16_t typedef unsigned short uint16_t; #endif struct timezone { int tz_minuteswest; /* minutes west of Greenwich */ int tz_dsttime; /* type of dst correction */ }; inline int poll(struct pollfd *fds, unsigned int nfds, int timeout) { unsigned int max_fd = 0; unsigned int i; fd_set *open_fds, *read_fds, *write_fds, *except_fds; struct timeval tv = { timeout / 1000, (timeout % 1000) * 1000 }; for (i = 0; i < nfds; ++i) { if (fds[i].fd > max_fd) { max_fd = fds[i].fd; } } size_t fds_size = (max_fd + 1) * sizeof (fd_set); open_fds = (fd_set *) malloc (fds_size); read_fds = (fd_set *) malloc (fds_size); write_fds = (fd_set *) malloc (fds_size); except_fds = (fd_set *) malloc (fds_size); if (!open_fds || !read_fds || !write_fds || !except_fds) { return -1; } FD_ZERO(open_fds) ; FD_ZERO(read_fds) ; FD_ZERO(write_fds) ; FD_ZERO(except_fds) ; for ( i = 0; i < nfds; ++i) { FD_SET (fds[i].fd, open_fds); if (fds[i].events & POLLIN) FD_SET (fds[i].fd, read_fds); if (fds[i].events & POLLOUT) FD_SET (fds[i].fd, write_fds); if (fds[i].events & POLLPRI) FD_SET (fds[i].fd, except_fds); } // Sleep(1); int ret = select(max_fd + 1, read_fds, write_fds, except_fds, timeout < 0 ? NULL : &tv); for (i = 0; i < nfds; ++i) { if (!FD_ISSET (fds[i].fd, open_fds)) fds[i].revents = POLLNVAL; else if (ret < 0) fds[i].revents = POLLERR; else { fds[i].revents = 0; if (FD_ISSET (fds[i].fd, read_fds)) fds[i].revents |= POLLIN; if (FD_ISSET (fds[i].fd, write_fds)) fds[i].revents |= POLLOUT; if (FD_ISSET (fds[i].fd, except_fds)) fds[i].revents |= POLLPRI; } } free(open_fds); free(read_fds); free(write_fds); free(except_fds); return ret; } struct iovec { u_long iov_len; char FAR *iov_base; }; inline int lrint(double n) { return (int)n; }; extern void gethostbyname_r(const char *inetName, struct hostent *hent, char *buff, int buffsize, struct hostent **hp, int *rc); extern void gethostbyaddr_r(char *addr, size_t len, int type, struct hostent *hent, char *buff, size_t buffsize, struct hostent **hp, int *rc); extern int getservbyname_r(const char *servname, const char *servtype, struct servent *sent, char *buff, size_t buffsize, struct servent **sp); extern int gettimeofday(struct timeval * tp, struct timezone * tzp); extern void *dlopen(const char *libPath, int opt); extern BOOL dlclose(void *lib); extern void *dlsym(void *libHandle, const char *pname); extern char *dlerror(); extern pid_t fork(); extern const char *inet_ntop(int af, const void *src, char *dst, size_t size); extern int sysconf(int what); extern int fcntl(int fd, int cmd, long arg); extern int close(int fd); extern int writev(int sock, const struct iovec iov[], int nvecs); extern int posix_memalign (void **memptr, size_t alignment, size_t size); extern char *index(const char *str, int c); extern char *cuserid(char * s); #ifndef localtime_r #define localtime_r( _clock, _result ) \ ( *(_result) = *localtime( (_clock) ), \ (_result) ) #endif #define pipe(a) _pipe(a, 256, O_BINARY) #define rindex strrchr #define sleep(s) Sleep(s*1000) #define strtoll(a, b, c) _strtoi64(a, b, c) #define ntohll(x) (((_int64)(ntohl((int)((x << 32) >> 32))) << 32) | (unsigned int)ntohl(((int)(x >> 32)))) #define htonll(x) ntohll(x) #define random() rand() #define usleep(x) Sleep(x / 1000) #define lstat(a, b) stat(a, b) #define memalign(a, b) _aligned_malloc(b, a) struct sockaddr_un { unsigned short sun_family; char sun_path[128]; }; #define setpgid(x,y) #define fsync(a) _commit(a) #define ssize_t SSIZE_T #endif // __XrdWin32_h__ <commit_msg>From Bertrand: fix warnings in MSVC2010<commit_after>// $Id$ // // You received this file as part of MCA2 // Modular Controller Architecture Version 2 // //Copyright (C) Forschungszentrum Informatik Karlsruhe // //This program is free software; you can redistribute it and/or //modify it under the terms of the GNU General Public License //as published by the Free Software Foundation; either version 2 //of the License, or (at your option) any later version. // //This program is distributed in the hope that it will be useful, //but WITHOUT ANY WARRANTY; without even the implied warranty of //MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //GNU General Public License for more details. // //You should have received a copy of the GNU General Public License //along with this program; if not, write to the Free Software //Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // // this is a -*- C++ -*- file //---------------------------------------------------------------------- //---------------------------------------------------------------------- #ifndef __XrdWin32_h__ #define __XrdWin32_h__ #include <errno.h> #include <stdio.h> #include <stdlib.h> #include <io.h> #include <time.h> #include <direct.h> #include <sys/types.h> #include <Winsock2.h> #ifndef POLLIN #define POLLIN 0x0001 /* There is data to read */ #define POLLPRI 0x0002 /* There is urgent data to read */ #define POLLOUT 0x0004 /* Writing now will not block */ #define POLLERR 0x0008 /* Error condition */ #define POLLHUP 0x0010 /* Hung up */ #define POLLNVAL 0x0020 /* Invalid request: fd not open */ #define POLLRDNORM 0x0001 #define POLLWRNORM 0x0002 #define POLLRDBAND 0x0000 struct pollfd { unsigned int fd; short events; short revents; }; #endif #ifndef EMSGSIZE #define EMSGSIZE WSAEMSGSIZE #endif #ifndef EAFNOSUPPORT #define EAFNOSUPPORT WSAEAFNOSUPPORT #endif #ifndef EWOULDBLOCK #define EWOULDBLOCK WSAEWOULDBLOCK #endif #ifndef ECONNRESET #define ECONNRESET WSAECONNRESET #endif #ifndef EINPROGRESS #define EINPROGRESS WSAEINPROGRESS #endif #ifndef ENOBUFS #define ENOBUFS WSAENOBUFS #endif #ifndef EPROTONOSUPPORT #define EPROTONOSUPPORT WSAEPROTONOSUPPORT #endif #ifndef ECONNREFUSED #define ECONNREFUSED WSAECONNREFUSED #endif #ifndef EBADFD #define EBADFD WSAENOTSOCK #endif #ifndef EOPNOTSUPP #define EOPNOTSUPP WSAEOPNOTSUPP #endif #ifndef ENETUNREACH #define ENETUNREACH WSAENETUNREACH #endif #ifndef EHOSTUNREACH #define EHOSTUNREACH WSAEHOSTUNREACH #endif #ifndef EHOSTDOWN #define EHOSTDOWN WSAEHOSTDOWN #endif #ifndef EISCONN #define EISCONN WSAEISCONN #endif #ifndef ECONNRESET #define ECONNRESET WSAECONNRESET #endif #ifndef ECONNABORTED #define ECONNABORTED WSAECONNABORTED #endif #ifndef ESHUTDOWN #define ESHUTDOWN WSAESHUTDOWN #endif #ifndef ETIMEDOUT #define ETIMEDOUT WSAETIMEDOUT #endif #ifndef ETXTBSY #define ETXTBSY 26 #endif #define WEXITSTATUS(w) (((w) >> 8) & 0xff) #define WIFEXITED(w) (((w) & 0xff) == 0) #define WTERMSIG(w) ((w) & 0x7f) #define WIFSIGNALED(w) (((w) & 0x7f) > 0 && (((w) & 0x7f) < 0x7f)) #ifndef S_ISDIR #define S_ISDIR(m) (((m)&(S_IFMT)) == (S_IFDIR)) #endif #ifndef S_ISREG #define S_ISREG(m) (((m)&(S_IFMT)) == (S_IFREG)) #endif #ifndef S_IXUSR #define S_IXUSR 00100 #endif #ifndef S_IRGRP #define S_IRGRP 00040 #endif #ifndef S_IXGRP #define S_IXGRP 00010 #endif #ifndef S_IROTH #define S_IROTH 00004 #endif #ifndef S_IXOTH #define S_IXOTH 00001 #endif #ifndef S_IRUSR #define S_IRUSR S_IREAD #endif #ifndef S_IWUSR #define S_IWUSR S_IWRITE #endif #ifndef S_IWGRP #define S_IWGRP 000020 #endif #ifndef S_IWOTH #define S_IWOTH 000002 #endif #ifndef S_IRWXU #define S_IRWXU 0000700 #endif #ifndef S_IRWXG #define S_IRWXG 0000070 #endif #ifndef S_ISFIFO # ifndef S_IFIFO # define S_IFIFO 0010000 # endif # define S_ISFIFO(m) ((m & S_IFMT) == S_IFIFO) #endif #ifndef S_IFSOCK #define S_IFSOCK 0140000 #endif #define _SC_PAGESIZE 1 #define F_GETFL 1 #define F_SETFL 2 #define F_GETFD 4 #define F_SETFD 8 #define FD_CLOEXEC 1 #define O_NDELAY 2 #define O_NONBLOCK 4 #define X_OK 1 #define W_OK 2 #define R_OK 4 #define RTLD_NOW 0x0001 #ifndef STDIN_FILENO #define STDIN_FILENO 0 #define STDOUT_FILENO 1 #define STDERR_FILENO 2 #endif #ifndef fsync #define fsync(a) _commit(a) #endif #ifndef socklen_t #define socklen_t int #endif #ifndef SOCKLEN_t #define SOCKLEN_t int #endif #ifndef snprintf #define snprintf _snprintf #endif #ifndef caddr_t typedef char* caddr_t; #endif #ifndef pid_t typedef int pid_t; #endif #ifndef mode_t typedef unsigned int mode_t; #endif #ifndef uint16_t typedef unsigned short uint16_t; #endif struct timezone { int tz_minuteswest; /* minutes west of Greenwich */ int tz_dsttime; /* type of dst correction */ }; inline int poll(struct pollfd *fds, unsigned int nfds, int timeout) { unsigned int max_fd = 0; unsigned int i; fd_set *open_fds, *read_fds, *write_fds, *except_fds; struct timeval tv = { timeout / 1000, (timeout % 1000) * 1000 }; for (i = 0; i < nfds; ++i) { if (fds[i].fd > max_fd) { max_fd = fds[i].fd; } } size_t fds_size = (max_fd + 1) * sizeof (fd_set); open_fds = (fd_set *) malloc (fds_size); read_fds = (fd_set *) malloc (fds_size); write_fds = (fd_set *) malloc (fds_size); except_fds = (fd_set *) malloc (fds_size); if (!open_fds || !read_fds || !write_fds || !except_fds) { return -1; } FD_ZERO(open_fds) ; FD_ZERO(read_fds) ; FD_ZERO(write_fds) ; FD_ZERO(except_fds) ; for ( i = 0; i < nfds; ++i) { FD_SET (fds[i].fd, open_fds); if (fds[i].events & POLLIN) FD_SET (fds[i].fd, read_fds); if (fds[i].events & POLLOUT) FD_SET (fds[i].fd, write_fds); if (fds[i].events & POLLPRI) FD_SET (fds[i].fd, except_fds); } // Sleep(1); int ret = select(max_fd + 1, read_fds, write_fds, except_fds, timeout < 0 ? NULL : &tv); for (i = 0; i < nfds; ++i) { if (!FD_ISSET (fds[i].fd, open_fds)) fds[i].revents = POLLNVAL; else if (ret < 0) fds[i].revents = POLLERR; else { fds[i].revents = 0; if (FD_ISSET (fds[i].fd, read_fds)) fds[i].revents |= POLLIN; if (FD_ISSET (fds[i].fd, write_fds)) fds[i].revents |= POLLOUT; if (FD_ISSET (fds[i].fd, except_fds)) fds[i].revents |= POLLPRI; } } free(open_fds); free(read_fds); free(write_fds); free(except_fds); return ret; } struct iovec { u_long iov_len; char FAR *iov_base; }; inline int lrint(double n) { return (int)n; }; extern void gethostbyname_r(const char *inetName, struct hostent *hent, char *buff, int buffsize, struct hostent **hp, int *rc); extern void gethostbyaddr_r(char *addr, size_t len, int type, struct hostent *hent, char *buff, size_t buffsize, struct hostent **hp, int *rc); extern int getservbyname_r(const char *servname, const char *servtype, struct servent *sent, char *buff, size_t buffsize, struct servent **sp); extern int gettimeofday(struct timeval * tp, struct timezone * tzp); extern void *dlopen(const char *libPath, int opt); extern BOOL dlclose(void *lib); extern void *dlsym(void *libHandle, const char *pname); extern char *dlerror(); extern pid_t fork(); extern const char *inet_ntop(int af, const void *src, char *dst, size_t size); extern int sysconf(int what); extern int fcntl(int fd, int cmd, long arg); extern int close(int fd); extern int writev(int sock, const struct iovec iov[], int nvecs); extern int posix_memalign (void **memptr, size_t alignment, size_t size); extern char *index(const char *str, int c); extern char *cuserid(char * s); #ifndef localtime_r #define localtime_r( _clock, _result ) \ ( *(_result) = *localtime( (_clock) ), \ (_result) ) #endif #define pipe(a) _pipe(a, 256, O_BINARY) #define rindex strrchr #define sleep(s) Sleep(s*1000) #define strtoll(a, b, c) _strtoi64(a, b, c) #define ntohll(x) (((_int64)(ntohl((int)((x << 32) >> 32))) << 32) | (unsigned int)ntohl(((int)(x >> 32)))) #define htonll(x) ntohll(x) #define random() rand() #define usleep(x) Sleep(x / 1000) #define lstat(a, b) stat(a, b) #define memalign(a, b) _aligned_malloc(b, a) struct sockaddr_un { unsigned short sun_family; char sun_path[128]; }; #define setpgid(x,y) #define fsync(a) _commit(a) #define ssize_t SSIZE_T #endif // __XrdWin32_h__ <|endoftext|>
<commit_before>/* * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "voe_network_impl.h" #include "channel.h" #include "critical_section_wrapper.h" #include "trace.h" #include "voe_errors.h" #include "voice_engine_impl.h" namespace webrtc { VoENetwork* VoENetwork::GetInterface(VoiceEngine* voiceEngine) { if (NULL == voiceEngine) { return NULL; } VoiceEngineImpl* s = static_cast<VoiceEngineImpl*>(voiceEngine); s->AddRef(); return s; } VoENetworkImpl::VoENetworkImpl(voe::SharedData* shared) : _shared(shared) { WEBRTC_TRACE(kTraceMemory, kTraceVoice, VoEId(_shared->instance_id(), -1), "VoENetworkImpl() - ctor"); } VoENetworkImpl::~VoENetworkImpl() { WEBRTC_TRACE(kTraceMemory, kTraceVoice, VoEId(_shared->instance_id(), -1), "~VoENetworkImpl() - dtor"); } int VoENetworkImpl::RegisterExternalTransport(int channel, Transport& transport) { WEBRTC_TRACE(kTraceApiCall, kTraceVoice, VoEId(_shared->instance_id(), -1), "SetExternalTransport(channel=%d, transport=0x%x)", channel, &transport); if (!_shared->statistics().Initialized()) { _shared->SetLastError(VE_NOT_INITED, kTraceError); return -1; } voe::ScopedChannel sc(_shared->channel_manager(), channel); voe::Channel* channelPtr = sc.ChannelPtr(); if (channelPtr == NULL) { _shared->SetLastError(VE_CHANNEL_NOT_VALID, kTraceError, "SetExternalTransport() failed to locate channel"); return -1; } return channelPtr->RegisterExternalTransport(transport); } int VoENetworkImpl::DeRegisterExternalTransport(int channel) { WEBRTC_TRACE(kTraceApiCall, kTraceVoice, VoEId(_shared->instance_id(), -1), "DeRegisterExternalTransport(channel=%d)", channel); if (!_shared->statistics().Initialized()) { _shared->SetLastError(VE_NOT_INITED, kTraceError); return -1; } voe::ScopedChannel sc(_shared->channel_manager(), channel); voe::Channel* channelPtr = sc.ChannelPtr(); if (channelPtr == NULL) { _shared->SetLastError(VE_CHANNEL_NOT_VALID, kTraceError, "DeRegisterExternalTransport() failed to locate channel"); return -1; } return channelPtr->DeRegisterExternalTransport(); } int VoENetworkImpl::ReceivedRTPPacket(int channel, const void* data, unsigned int length) { WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_shared->instance_id(), -1), "ReceivedRTPPacket(channel=%d, length=%u)", channel, length); if (!_shared->statistics().Initialized()) { _shared->SetLastError(VE_NOT_INITED, kTraceError); return -1; } if ((length < 12) || (length > 807)) { _shared->SetLastError(VE_INVALID_PACKET, kTraceError, "ReceivedRTPPacket() invalid packet length"); return -1; } if (NULL == data) { _shared->SetLastError(VE_INVALID_ARGUMENT, kTraceError, "ReceivedRTPPacket() invalid data vector"); return -1; } voe::ScopedChannel sc(_shared->channel_manager(), channel); voe::Channel* channelPtr = sc.ChannelPtr(); if (channelPtr == NULL) { _shared->SetLastError(VE_CHANNEL_NOT_VALID, kTraceError, "ReceivedRTPPacket() failed to locate channel"); return -1; } if (!channelPtr->ExternalTransport()) { _shared->SetLastError(VE_INVALID_OPERATION, kTraceError, "ReceivedRTPPacket() external transport is not enabled"); return -1; } return channelPtr->ReceivedRTPPacket((const int8_t*) data, length); } int VoENetworkImpl::ReceivedRTCPPacket(int channel, const void* data, unsigned int length) { WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_shared->instance_id(), -1), "ReceivedRTCPPacket(channel=%d, length=%u)", channel, length); if (!_shared->statistics().Initialized()) { _shared->SetLastError(VE_NOT_INITED, kTraceError); return -1; } if (length < 4) { _shared->SetLastError(VE_INVALID_PACKET, kTraceError, "ReceivedRTCPPacket() invalid packet length"); return -1; } if (NULL == data) { _shared->SetLastError(VE_INVALID_ARGUMENT, kTraceError, "ReceivedRTCPPacket() invalid data vector"); return -1; } voe::ScopedChannel sc(_shared->channel_manager(), channel); voe::Channel* channelPtr = sc.ChannelPtr(); if (channelPtr == NULL) { _shared->SetLastError(VE_CHANNEL_NOT_VALID, kTraceError, "ReceivedRTCPPacket() failed to locate channel"); return -1; } if (!channelPtr->ExternalTransport()) { _shared->SetLastError(VE_INVALID_OPERATION, kTraceError, "ReceivedRTCPPacket() external transport is not enabled"); return -1; } return channelPtr->ReceivedRTCPPacket((const int8_t*) data, length); } int VoENetworkImpl::SetPacketTimeoutNotification(int channel, bool enable, int timeoutSeconds) { WEBRTC_TRACE(kTraceApiCall, kTraceVoice, VoEId(_shared->instance_id(), -1), "SetPacketTimeoutNotification(channel=%d, enable=%d, " "timeoutSeconds=%d)", channel, (int) enable, timeoutSeconds); if (!_shared->statistics().Initialized()) { _shared->SetLastError(VE_NOT_INITED, kTraceError); return -1; } if (enable && ((timeoutSeconds < kVoiceEngineMinPacketTimeoutSec) || (timeoutSeconds > kVoiceEngineMaxPacketTimeoutSec))) { _shared->SetLastError(VE_INVALID_ARGUMENT, kTraceError, "SetPacketTimeoutNotification() invalid timeout size"); return -1; } voe::ScopedChannel sc(_shared->channel_manager(), channel); voe::Channel* channelPtr = sc.ChannelPtr(); if (channelPtr == NULL) { _shared->SetLastError(VE_CHANNEL_NOT_VALID, kTraceError, "SetPacketTimeoutNotification() failed to locate channel"); return -1; } return channelPtr->SetPacketTimeoutNotification(enable, timeoutSeconds); } int VoENetworkImpl::GetPacketTimeoutNotification(int channel, bool& enabled, int& timeoutSeconds) { WEBRTC_TRACE(kTraceApiCall, kTraceVoice, VoEId(_shared->instance_id(), -1), "GetPacketTimeoutNotification(channel=%d, enabled=?," " timeoutSeconds=?)", channel); if (!_shared->statistics().Initialized()) { _shared->SetLastError(VE_NOT_INITED, kTraceError); return -1; } voe::ScopedChannel sc(_shared->channel_manager(), channel); voe::Channel* channelPtr = sc.ChannelPtr(); if (channelPtr == NULL) { _shared->SetLastError(VE_CHANNEL_NOT_VALID, kTraceError, "GetPacketTimeoutNotification() failed to locate channel"); return -1; } return channelPtr->GetPacketTimeoutNotification(enabled, timeoutSeconds); } int VoENetworkImpl::RegisterDeadOrAliveObserver(int channel, VoEConnectionObserver& observer) { WEBRTC_TRACE(kTraceApiCall, kTraceVoice, VoEId(_shared->instance_id(), -1), "RegisterDeadOrAliveObserver(channel=%d, observer=0x%x)", channel, &observer); if (!_shared->statistics().Initialized()) { _shared->SetLastError(VE_NOT_INITED, kTraceError); return -1; } voe::ScopedChannel sc(_shared->channel_manager(), channel); voe::Channel* channelPtr = sc.ChannelPtr(); if (channelPtr == NULL) { _shared->SetLastError(VE_CHANNEL_NOT_VALID, kTraceError, "RegisterDeadOrAliveObserver() failed to locate channel"); return -1; } return channelPtr->RegisterDeadOrAliveObserver(observer); } int VoENetworkImpl::DeRegisterDeadOrAliveObserver(int channel) { WEBRTC_TRACE(kTraceApiCall, kTraceVoice, VoEId(_shared->instance_id(), -1), "DeRegisterDeadOrAliveObserver(channel=%d)", channel); if (!_shared->statistics().Initialized()) { _shared->SetLastError(VE_NOT_INITED, kTraceError); return -1; } voe::ScopedChannel sc(_shared->channel_manager(), channel); voe::Channel* channelPtr = sc.ChannelPtr(); if (channelPtr == NULL) { _shared->SetLastError(VE_CHANNEL_NOT_VALID, kTraceError, "DeRegisterDeadOrAliveObserver() failed to locate channel"); return -1; } return channelPtr->DeRegisterDeadOrAliveObserver(); } int VoENetworkImpl::SetPeriodicDeadOrAliveStatus(int channel, bool enable, int sampleTimeSeconds) { WEBRTC_TRACE(kTraceApiCall, kTraceVoice, VoEId(_shared->instance_id(), -1), "SetPeriodicDeadOrAliveStatus(channel=%d, enable=%d," " sampleTimeSeconds=%d)", channel, enable, sampleTimeSeconds); if (!_shared->statistics().Initialized()) { _shared->SetLastError(VE_NOT_INITED, kTraceError); return -1; } if (enable && ((sampleTimeSeconds < kVoiceEngineMinSampleTimeSec) || (sampleTimeSeconds > kVoiceEngineMaxSampleTimeSec))) { _shared->SetLastError(VE_INVALID_ARGUMENT, kTraceError, "SetPeriodicDeadOrAliveStatus() invalid sample time"); return -1; } voe::ScopedChannel sc(_shared->channel_manager(), channel); voe::Channel* channelPtr = sc.ChannelPtr(); if (channelPtr == NULL) { _shared->SetLastError(VE_CHANNEL_NOT_VALID, kTraceError, "SetPeriodicDeadOrAliveStatus() failed to locate channel"); return -1; } return channelPtr->SetPeriodicDeadOrAliveStatus(enable, sampleTimeSeconds); } int VoENetworkImpl::GetPeriodicDeadOrAliveStatus(int channel, bool& enabled, int& sampleTimeSeconds) { WEBRTC_TRACE(kTraceApiCall, kTraceVoice, VoEId(_shared->instance_id(), -1), "GetPeriodicDeadOrAliveStatus(channel=%d, enabled=?," " sampleTimeSeconds=?)", channel); if (!_shared->statistics().Initialized()) { _shared->SetLastError(VE_NOT_INITED, kTraceError); return -1; } voe::ScopedChannel sc(_shared->channel_manager(), channel); voe::Channel* channelPtr = sc.ChannelPtr(); if (channelPtr == NULL) { _shared->SetLastError(VE_CHANNEL_NOT_VALID, kTraceError, "GetPeriodicDeadOrAliveStatus() failed to locate channel"); return -1; } return channelPtr->GetPeriodicDeadOrAliveStatus(enabled, sampleTimeSeconds); } } // namespace webrtc <commit_msg>Relax VoE's max packet length threshold.<commit_after>/* * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "webrtc/voice_engine/voe_network_impl.h" #include "webrtc/system_wrappers/interface/critical_section_wrapper.h" #include "webrtc/system_wrappers/interface/logging.h" #include "webrtc/system_wrappers/interface/trace.h" #include "webrtc/voice_engine/channel.h" #include "webrtc/voice_engine/include/voe_errors.h" #include "webrtc/voice_engine/voice_engine_impl.h" namespace webrtc { VoENetwork* VoENetwork::GetInterface(VoiceEngine* voiceEngine) { if (NULL == voiceEngine) { return NULL; } VoiceEngineImpl* s = static_cast<VoiceEngineImpl*>(voiceEngine); s->AddRef(); return s; } VoENetworkImpl::VoENetworkImpl(voe::SharedData* shared) : _shared(shared) { WEBRTC_TRACE(kTraceMemory, kTraceVoice, VoEId(_shared->instance_id(), -1), "VoENetworkImpl() - ctor"); } VoENetworkImpl::~VoENetworkImpl() { WEBRTC_TRACE(kTraceMemory, kTraceVoice, VoEId(_shared->instance_id(), -1), "~VoENetworkImpl() - dtor"); } int VoENetworkImpl::RegisterExternalTransport(int channel, Transport& transport) { WEBRTC_TRACE(kTraceApiCall, kTraceVoice, VoEId(_shared->instance_id(), -1), "SetExternalTransport(channel=%d, transport=0x%x)", channel, &transport); if (!_shared->statistics().Initialized()) { _shared->SetLastError(VE_NOT_INITED, kTraceError); return -1; } voe::ScopedChannel sc(_shared->channel_manager(), channel); voe::Channel* channelPtr = sc.ChannelPtr(); if (channelPtr == NULL) { _shared->SetLastError(VE_CHANNEL_NOT_VALID, kTraceError, "SetExternalTransport() failed to locate channel"); return -1; } return channelPtr->RegisterExternalTransport(transport); } int VoENetworkImpl::DeRegisterExternalTransport(int channel) { WEBRTC_TRACE(kTraceApiCall, kTraceVoice, VoEId(_shared->instance_id(), -1), "DeRegisterExternalTransport(channel=%d)", channel); if (!_shared->statistics().Initialized()) { _shared->SetLastError(VE_NOT_INITED, kTraceError); return -1; } voe::ScopedChannel sc(_shared->channel_manager(), channel); voe::Channel* channelPtr = sc.ChannelPtr(); if (channelPtr == NULL) { _shared->SetLastError(VE_CHANNEL_NOT_VALID, kTraceError, "DeRegisterExternalTransport() failed to locate channel"); return -1; } return channelPtr->DeRegisterExternalTransport(); } int VoENetworkImpl::ReceivedRTPPacket(int channel, const void* data, unsigned int length) { WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_shared->instance_id(), -1), "ReceivedRTPPacket(channel=%d, length=%u)", channel, length); if (!_shared->statistics().Initialized()) { _shared->SetLastError(VE_NOT_INITED, kTraceError); return -1; } // L16 at 32 kHz, stereo, 10 ms frames (+12 byte RTP header) -> 1292 bytes if ((length < 12) || (length > 1292)) { _shared->SetLastError(VE_INVALID_PACKET); LOG(LS_ERROR) << "Invalid packet length: " << length; return -1; } if (NULL == data) { _shared->SetLastError(VE_INVALID_ARGUMENT, kTraceError, "ReceivedRTPPacket() invalid data vector"); return -1; } voe::ScopedChannel sc(_shared->channel_manager(), channel); voe::Channel* channelPtr = sc.ChannelPtr(); if (channelPtr == NULL) { _shared->SetLastError(VE_CHANNEL_NOT_VALID, kTraceError, "ReceivedRTPPacket() failed to locate channel"); return -1; } if (!channelPtr->ExternalTransport()) { _shared->SetLastError(VE_INVALID_OPERATION, kTraceError, "ReceivedRTPPacket() external transport is not enabled"); return -1; } return channelPtr->ReceivedRTPPacket((const int8_t*) data, length); } int VoENetworkImpl::ReceivedRTCPPacket(int channel, const void* data, unsigned int length) { WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_shared->instance_id(), -1), "ReceivedRTCPPacket(channel=%d, length=%u)", channel, length); if (!_shared->statistics().Initialized()) { _shared->SetLastError(VE_NOT_INITED, kTraceError); return -1; } if (length < 4) { _shared->SetLastError(VE_INVALID_PACKET, kTraceError, "ReceivedRTCPPacket() invalid packet length"); return -1; } if (NULL == data) { _shared->SetLastError(VE_INVALID_ARGUMENT, kTraceError, "ReceivedRTCPPacket() invalid data vector"); return -1; } voe::ScopedChannel sc(_shared->channel_manager(), channel); voe::Channel* channelPtr = sc.ChannelPtr(); if (channelPtr == NULL) { _shared->SetLastError(VE_CHANNEL_NOT_VALID, kTraceError, "ReceivedRTCPPacket() failed to locate channel"); return -1; } if (!channelPtr->ExternalTransport()) { _shared->SetLastError(VE_INVALID_OPERATION, kTraceError, "ReceivedRTCPPacket() external transport is not enabled"); return -1; } return channelPtr->ReceivedRTCPPacket((const int8_t*) data, length); } int VoENetworkImpl::SetPacketTimeoutNotification(int channel, bool enable, int timeoutSeconds) { WEBRTC_TRACE(kTraceApiCall, kTraceVoice, VoEId(_shared->instance_id(), -1), "SetPacketTimeoutNotification(channel=%d, enable=%d, " "timeoutSeconds=%d)", channel, (int) enable, timeoutSeconds); if (!_shared->statistics().Initialized()) { _shared->SetLastError(VE_NOT_INITED, kTraceError); return -1; } if (enable && ((timeoutSeconds < kVoiceEngineMinPacketTimeoutSec) || (timeoutSeconds > kVoiceEngineMaxPacketTimeoutSec))) { _shared->SetLastError(VE_INVALID_ARGUMENT, kTraceError, "SetPacketTimeoutNotification() invalid timeout size"); return -1; } voe::ScopedChannel sc(_shared->channel_manager(), channel); voe::Channel* channelPtr = sc.ChannelPtr(); if (channelPtr == NULL) { _shared->SetLastError(VE_CHANNEL_NOT_VALID, kTraceError, "SetPacketTimeoutNotification() failed to locate channel"); return -1; } return channelPtr->SetPacketTimeoutNotification(enable, timeoutSeconds); } int VoENetworkImpl::GetPacketTimeoutNotification(int channel, bool& enabled, int& timeoutSeconds) { WEBRTC_TRACE(kTraceApiCall, kTraceVoice, VoEId(_shared->instance_id(), -1), "GetPacketTimeoutNotification(channel=%d, enabled=?," " timeoutSeconds=?)", channel); if (!_shared->statistics().Initialized()) { _shared->SetLastError(VE_NOT_INITED, kTraceError); return -1; } voe::ScopedChannel sc(_shared->channel_manager(), channel); voe::Channel* channelPtr = sc.ChannelPtr(); if (channelPtr == NULL) { _shared->SetLastError(VE_CHANNEL_NOT_VALID, kTraceError, "GetPacketTimeoutNotification() failed to locate channel"); return -1; } return channelPtr->GetPacketTimeoutNotification(enabled, timeoutSeconds); } int VoENetworkImpl::RegisterDeadOrAliveObserver(int channel, VoEConnectionObserver& observer) { WEBRTC_TRACE(kTraceApiCall, kTraceVoice, VoEId(_shared->instance_id(), -1), "RegisterDeadOrAliveObserver(channel=%d, observer=0x%x)", channel, &observer); if (!_shared->statistics().Initialized()) { _shared->SetLastError(VE_NOT_INITED, kTraceError); return -1; } voe::ScopedChannel sc(_shared->channel_manager(), channel); voe::Channel* channelPtr = sc.ChannelPtr(); if (channelPtr == NULL) { _shared->SetLastError(VE_CHANNEL_NOT_VALID, kTraceError, "RegisterDeadOrAliveObserver() failed to locate channel"); return -1; } return channelPtr->RegisterDeadOrAliveObserver(observer); } int VoENetworkImpl::DeRegisterDeadOrAliveObserver(int channel) { WEBRTC_TRACE(kTraceApiCall, kTraceVoice, VoEId(_shared->instance_id(), -1), "DeRegisterDeadOrAliveObserver(channel=%d)", channel); if (!_shared->statistics().Initialized()) { _shared->SetLastError(VE_NOT_INITED, kTraceError); return -1; } voe::ScopedChannel sc(_shared->channel_manager(), channel); voe::Channel* channelPtr = sc.ChannelPtr(); if (channelPtr == NULL) { _shared->SetLastError(VE_CHANNEL_NOT_VALID, kTraceError, "DeRegisterDeadOrAliveObserver() failed to locate channel"); return -1; } return channelPtr->DeRegisterDeadOrAliveObserver(); } int VoENetworkImpl::SetPeriodicDeadOrAliveStatus(int channel, bool enable, int sampleTimeSeconds) { WEBRTC_TRACE(kTraceApiCall, kTraceVoice, VoEId(_shared->instance_id(), -1), "SetPeriodicDeadOrAliveStatus(channel=%d, enable=%d," " sampleTimeSeconds=%d)", channel, enable, sampleTimeSeconds); if (!_shared->statistics().Initialized()) { _shared->SetLastError(VE_NOT_INITED, kTraceError); return -1; } if (enable && ((sampleTimeSeconds < kVoiceEngineMinSampleTimeSec) || (sampleTimeSeconds > kVoiceEngineMaxSampleTimeSec))) { _shared->SetLastError(VE_INVALID_ARGUMENT, kTraceError, "SetPeriodicDeadOrAliveStatus() invalid sample time"); return -1; } voe::ScopedChannel sc(_shared->channel_manager(), channel); voe::Channel* channelPtr = sc.ChannelPtr(); if (channelPtr == NULL) { _shared->SetLastError(VE_CHANNEL_NOT_VALID, kTraceError, "SetPeriodicDeadOrAliveStatus() failed to locate channel"); return -1; } return channelPtr->SetPeriodicDeadOrAliveStatus(enable, sampleTimeSeconds); } int VoENetworkImpl::GetPeriodicDeadOrAliveStatus(int channel, bool& enabled, int& sampleTimeSeconds) { WEBRTC_TRACE(kTraceApiCall, kTraceVoice, VoEId(_shared->instance_id(), -1), "GetPeriodicDeadOrAliveStatus(channel=%d, enabled=?," " sampleTimeSeconds=?)", channel); if (!_shared->statistics().Initialized()) { _shared->SetLastError(VE_NOT_INITED, kTraceError); return -1; } voe::ScopedChannel sc(_shared->channel_manager(), channel); voe::Channel* channelPtr = sc.ChannelPtr(); if (channelPtr == NULL) { _shared->SetLastError(VE_CHANNEL_NOT_VALID, kTraceError, "GetPeriodicDeadOrAliveStatus() failed to locate channel"); return -1; } return channelPtr->GetPeriodicDeadOrAliveStatus(enabled, sampleTimeSeconds); } } // namespace webrtc <|endoftext|>
<commit_before>/* ****************************************************************************** *\ Copyright (C) 2012-2017 Intel Corporation. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY INTEL CORPORATION "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL INTEL CORPORATION BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. File Name: mfx_win_reg_key.cpp \* ****************************************************************************** */ #if defined(_WIN32) || defined(_WIN64) || defined(__CYGWIN__) #include "mfx_win_reg_key.h" #include "mfx_dispatcher_log.h" #define TRACE_WINREG_ERROR(str, ...) DISPATCHER_LOG_ERROR((("[WINREG]: " str), __VA_ARGS__)) namespace MFX { WinRegKey::WinRegKey(void) { m_hKey = (HKEY) 0; } // WinRegKey::WinRegKey(void) WinRegKey::~WinRegKey(void) { Release(); } // WinRegKey::~WinRegKey(void) void WinRegKey::Release(void) { // close the opened key if (m_hKey) { RegCloseKey(m_hKey); } m_hKey = (HKEY) 0; } // void WinRegKey::Release(void) bool WinRegKey::Open(HKEY hRootKey, const wchar_t *pSubKey, REGSAM samDesired) { LONG lRes; HKEY hTemp; // // All operation are performed in this order by intention. // It makes possible to reopen the keys, using itself as a base. // // try to the open registry key lRes = RegOpenKeyExW(hRootKey, pSubKey, 0, samDesired, &hTemp); if (ERROR_SUCCESS != lRes) { DISPATCHER_LOG_OPERATION(SetLastError(lRes)); TRACE_WINREG_ERROR("Opening key \"%s\\%S\" : RegOpenKeyExW()==0x%x\n" , (HKEY_LOCAL_MACHINE == hRootKey) ? ("HKEY_LOCAL_MACHINE") : (HKEY_CURRENT_USER == hRootKey) ? ("HKEY_CURRENT_USER") : "UNSUPPORTED_KEY", pSubKey, GetLastError()); return false; } // release the object before initialization Release(); // save the handle m_hKey = hTemp; return true; } // bool WinRegKey::Open(HKEY hRootKey, const wchar_t *pSubKey, REGSAM samDesired) bool WinRegKey::Open(WinRegKey &rootKey, const wchar_t *pSubKey, REGSAM samDesired) { return Open(rootKey.m_hKey, pSubKey, samDesired); } // bool WinRegKey::Open(WinRegKey &rootKey, const wchar_t *pSubKey, REGSAM samDesired) bool WinRegKey::QueryValueSize(const wchar_t *pValueName, DWORD type, LPDWORD pcbData) { DWORD keyType = type; LONG lRes; // query the value lRes = RegQueryValueExW(m_hKey, pValueName, NULL, &keyType, 0, pcbData); if (ERROR_SUCCESS != lRes) { DISPATCHER_LOG_OPERATION(SetLastError(lRes)); TRACE_WINREG_ERROR("Querying \"%S\" : RegQueryValueExA()==0x%x\n", pValueName, GetLastError()); return false; } return true; } bool WinRegKey::Query(const wchar_t *pValueName, DWORD type, LPBYTE pData, LPDWORD pcbData) { DWORD keyType = type; LONG lRes; DWORD dstSize = (pcbData) ? (*pcbData) : (0); // query the value lRes = RegQueryValueExW(m_hKey, pValueName, NULL, &keyType, pData, pcbData); if (ERROR_SUCCESS != lRes) { DISPATCHER_LOG_OPERATION(SetLastError(lRes)); TRACE_WINREG_ERROR("Querying \"%S\" : RegQueryValueExA()==0x%x\n", pValueName, GetLastError()); return false; } // check the type if (keyType != type) { TRACE_WINREG_ERROR("Querying \"%S\" : expectedType=%d, returned=%d\n", pValueName, type, keyType); return false; } // terminate the string only if pointers not NULL if ((REG_SZ == type || REG_EXPAND_SZ == type) && NULL != pData && NULL != pcbData) { wchar_t *pString = (wchar_t *) pData; size_t NullEndingSizeBytes = sizeof(wchar_t); // size of string termination null character if (dstSize < NullEndingSizeBytes) { TRACE_WINREG_ERROR("Querying \"%S\" : buffer is too small for null-terminated string", pValueName); return false; } size_t maxStringLengthBytes = dstSize - NullEndingSizeBytes; size_t maxStringIndex = dstSize / sizeof(wchar_t) - 1; size_t lastIndex = (maxStringLengthBytes < *pcbData) ? (maxStringIndex) : (*pcbData) / sizeof(wchar_t); pString[lastIndex] = (wchar_t) 0; } else if(REG_MULTI_SZ == type && NULL != pData && NULL != pcbData) { wchar_t *pString = (wchar_t *) pData; size_t NullEndingSizeBytes = sizeof(wchar_t)*2; // size of string termination null characters if (dstSize < NullEndingSizeBytes) { TRACE_WINREG_ERROR("Querying \"%S\" : buffer is too small for multi-line null-terminated string", pValueName); return false; } size_t maxStringLengthBytes = dstSize - NullEndingSizeBytes; size_t maxStringIndex = dstSize / sizeof(wchar_t) - 1; size_t lastIndex = (maxStringLengthBytes < *pcbData) ? (maxStringIndex) : (*pcbData) / sizeof(wchar_t) + 1; // last 2 bytes should be 0 in case of REG_MULTI_SZ pString[lastIndex] = pString[lastIndex - 1] = (wchar_t) 0; } return true; } // bool WinRegKey::Query(const wchar_t *pValueName, DWORD type, LPBYTE pData, LPDWORD pcbData) bool WinRegKey::EnumValue(DWORD index, wchar_t *pValueName, LPDWORD pcchValueName, LPDWORD pType) { LONG lRes; // enum the values lRes = RegEnumValueW(m_hKey, index, pValueName, pcchValueName, 0, pType, NULL, NULL); if (ERROR_SUCCESS != lRes) { DISPATCHER_LOG_OPERATION(SetLastError(lRes)); return false; } return true; } // bool WinRegKey::EnumValue(DWORD index, wchar_t *pValueName, LPDWORD pcchValueName, LPDWORD pType) bool WinRegKey::EnumKey(DWORD index, wchar_t *pValueName, LPDWORD pcchValueName) { LONG lRes; // enum the keys lRes = RegEnumKeyExW(m_hKey, index, pValueName, pcchValueName, NULL, NULL, NULL, NULL); if (ERROR_SUCCESS != lRes) { DISPATCHER_LOG_OPERATION(SetLastError(lRes)); TRACE_WINREG_ERROR("EnumKey with index=%d: RegEnumKeyExW()==0x%x\n", index, GetLastError()); return false; } return true; } // bool WinRegKey::EnumKey(DWORD index, wchar_t *pValueName, LPDWORD pcchValueName) bool WinRegKey::QueryInfo(LPDWORD lpcSubkeys) { LONG lRes; lRes = RegQueryInfoKeyW(m_hKey, NULL, 0, 0, lpcSubkeys, 0, 0, 0, 0, 0, 0, 0); if (ERROR_SUCCESS != lRes) { TRACE_WINREG_ERROR("RegQueryInfoKeyW()==0x%x\n", lRes); return false; } return true; } //bool QueryInfo(LPDWORD lpcSubkeys); } // namespace MFX #endif // #if defined(_WIN32) || defined(_WIN64) || defined(__CYGWIN__) <commit_msg>do not call registry APIs if MEDIASDK_USE_REGISTRY is not set<commit_after>/* ****************************************************************************** *\ Copyright (C) 2012-2017 Intel Corporation. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY INTEL CORPORATION "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL INTEL CORPORATION BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. File Name: mfx_win_reg_key.cpp \* ****************************************************************************** */ #if defined(_WIN32) || defined(_WIN64) || defined(__CYGWIN__) #include "mfx_win_reg_key.h" #include "mfx_dispatcher_log.h" #define TRACE_WINREG_ERROR(str, ...) DISPATCHER_LOG_ERROR((("[WINREG]: " str), __VA_ARGS__)) namespace MFX { WinRegKey::WinRegKey(void) { m_hKey = (HKEY) 0; } // WinRegKey::WinRegKey(void) WinRegKey::~WinRegKey(void) { Release(); } // WinRegKey::~WinRegKey(void) void WinRegKey::Release(void) { // close the opened key if (m_hKey) { #if defined(MEDIASDK_USE_REGISTRY) || (!defined(MEDIASDK_UWP_LOADER) && !defined(MEDIASDK_UWP_PROCTABLE)) RegCloseKey(m_hKey); #endif } m_hKey = (HKEY) 0; } // void WinRegKey::Release(void) bool WinRegKey::Open(HKEY hRootKey, const wchar_t *pSubKey, REGSAM samDesired) { #if defined(MEDIASDK_USE_REGISTRY) || (!defined(MEDIASDK_UWP_LOADER) && !defined(MEDIASDK_UWP_PROCTABLE)) LONG lRes; HKEY hTemp; // // All operation are performed in this order by intention. // It makes possible to reopen the keys, using itself as a base. // // try to the open registry key lRes = RegOpenKeyExW(hRootKey, pSubKey, 0, samDesired, &hTemp); if (ERROR_SUCCESS != lRes) { DISPATCHER_LOG_OPERATION(SetLastError(lRes)); TRACE_WINREG_ERROR("Opening key \"%s\\%S\" : RegOpenKeyExW()==0x%x\n" , (HKEY_LOCAL_MACHINE == hRootKey) ? ("HKEY_LOCAL_MACHINE") : (HKEY_CURRENT_USER == hRootKey) ? ("HKEY_CURRENT_USER") : "UNSUPPORTED_KEY", pSubKey, GetLastError()); return false; } // release the object before initialization Release(); // save the handle m_hKey = hTemp; return true; #else return false; #endif } // bool WinRegKey::Open(HKEY hRootKey, const wchar_t *pSubKey, REGSAM samDesired) bool WinRegKey::Open(WinRegKey &rootKey, const wchar_t *pSubKey, REGSAM samDesired) { return Open(rootKey.m_hKey, pSubKey, samDesired); } // bool WinRegKey::Open(WinRegKey &rootKey, const wchar_t *pSubKey, REGSAM samDesired) bool WinRegKey::QueryValueSize(const wchar_t *pValueName, DWORD type, LPDWORD pcbData) { #if defined(MEDIASDK_USE_REGISTRY) || (!defined(MEDIASDK_UWP_LOADER) && !defined(MEDIASDK_UWP_PROCTABLE)) DWORD keyType = type; LONG lRes; // query the value lRes = RegQueryValueExW(m_hKey, pValueName, NULL, &keyType, 0, pcbData); if (ERROR_SUCCESS != lRes) { DISPATCHER_LOG_OPERATION(SetLastError(lRes)); TRACE_WINREG_ERROR("Querying \"%S\" : RegQueryValueExA()==0x%x\n", pValueName, GetLastError()); return false; } return true; #else return false; #endif } bool WinRegKey::Query(const wchar_t *pValueName, DWORD type, LPBYTE pData, LPDWORD pcbData) { #if defined(MEDIASDK_USE_REGISTRY) || (!defined(MEDIASDK_UWP_LOADER) && !defined(MEDIASDK_UWP_PROCTABLE)) DWORD keyType = type; LONG lRes; DWORD dstSize = (pcbData) ? (*pcbData) : (0); // query the value lRes = RegQueryValueExW(m_hKey, pValueName, NULL, &keyType, pData, pcbData); if (ERROR_SUCCESS != lRes) { DISPATCHER_LOG_OPERATION(SetLastError(lRes)); TRACE_WINREG_ERROR("Querying \"%S\" : RegQueryValueExA()==0x%x\n", pValueName, GetLastError()); return false; } // check the type if (keyType != type) { TRACE_WINREG_ERROR("Querying \"%S\" : expectedType=%d, returned=%d\n", pValueName, type, keyType); return false; } // terminate the string only if pointers not NULL if ((REG_SZ == type || REG_EXPAND_SZ == type) && NULL != pData && NULL != pcbData) { wchar_t *pString = (wchar_t *) pData; size_t NullEndingSizeBytes = sizeof(wchar_t); // size of string termination null character if (dstSize < NullEndingSizeBytes) { TRACE_WINREG_ERROR("Querying \"%S\" : buffer is too small for null-terminated string", pValueName); return false; } size_t maxStringLengthBytes = dstSize - NullEndingSizeBytes; size_t maxStringIndex = dstSize / sizeof(wchar_t) - 1; size_t lastIndex = (maxStringLengthBytes < *pcbData) ? (maxStringIndex) : (*pcbData) / sizeof(wchar_t); pString[lastIndex] = (wchar_t) 0; } else if(REG_MULTI_SZ == type && NULL != pData && NULL != pcbData) { wchar_t *pString = (wchar_t *) pData; size_t NullEndingSizeBytes = sizeof(wchar_t)*2; // size of string termination null characters if (dstSize < NullEndingSizeBytes) { TRACE_WINREG_ERROR("Querying \"%S\" : buffer is too small for multi-line null-terminated string", pValueName); return false; } size_t maxStringLengthBytes = dstSize - NullEndingSizeBytes; size_t maxStringIndex = dstSize / sizeof(wchar_t) - 1; size_t lastIndex = (maxStringLengthBytes < *pcbData) ? (maxStringIndex) : (*pcbData) / sizeof(wchar_t) + 1; // last 2 bytes should be 0 in case of REG_MULTI_SZ pString[lastIndex] = pString[lastIndex - 1] = (wchar_t) 0; } return true; #else return false; #endif } // bool WinRegKey::Query(const wchar_t *pValueName, DWORD type, LPBYTE pData, LPDWORD pcbData) bool WinRegKey::EnumValue(DWORD index, wchar_t *pValueName, LPDWORD pcchValueName, LPDWORD pType) { #if defined(MEDIASDK_USE_REGISTRY) || (!defined(MEDIASDK_UWP_LOADER) && !defined(MEDIASDK_UWP_PROCTABLE)) LONG lRes; // enum the values lRes = RegEnumValueW(m_hKey, index, pValueName, pcchValueName, 0, pType, NULL, NULL); if (ERROR_SUCCESS != lRes) { DISPATCHER_LOG_OPERATION(SetLastError(lRes)); return false; } return true; #else return false; #endif } // bool WinRegKey::EnumValue(DWORD index, wchar_t *pValueName, LPDWORD pcchValueName, LPDWORD pType) bool WinRegKey::EnumKey(DWORD index, wchar_t *pValueName, LPDWORD pcchValueName) { #if defined(MEDIASDK_USE_REGISTRY) || (!defined(MEDIASDK_UWP_LOADER) && !defined(MEDIASDK_UWP_PROCTABLE)) LONG lRes; // enum the keys lRes = RegEnumKeyExW(m_hKey, index, pValueName, pcchValueName, NULL, NULL, NULL, NULL); if (ERROR_SUCCESS != lRes) { DISPATCHER_LOG_OPERATION(SetLastError(lRes)); TRACE_WINREG_ERROR("EnumKey with index=%d: RegEnumKeyExW()==0x%x\n", index, GetLastError()); return false; } return true; #else return false; #endif } // bool WinRegKey::EnumKey(DWORD index, wchar_t *pValueName, LPDWORD pcchValueName) bool WinRegKey::QueryInfo(LPDWORD lpcSubkeys) { #if defined(MEDIASDK_USE_REGISTRY) || (!defined(MEDIASDK_UWP_LOADER) && !defined(MEDIASDK_UWP_PROCTABLE)) LONG lRes; lRes = RegQueryInfoKeyW(m_hKey, NULL, 0, 0, lpcSubkeys, 0, 0, 0, 0, 0, 0, 0); if (ERROR_SUCCESS != lRes) { TRACE_WINREG_ERROR("RegQueryInfoKeyW()==0x%x\n", lRes); return false; } return true; #else return false; #endif } //bool QueryInfo(LPDWORD lpcSubkeys); } // namespace MFX #endif // #if defined(_WIN32) || defined(_WIN64) || defined(__CYGWIN__) <|endoftext|>
<commit_before>// Copyright (c) 2020 by Robert Bosch GmbH. All rights reserved. // Copyright (c) 2020 - 2021 by Apex.AI Inc. 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. // // SPDX-License-Identifier: Apache-2.0 #ifndef IOX_POSH_GW_GATEWAY_GENERIC_INL #define IOX_POSH_GW_GATEWAY_GENERIC_INL #include "iceoryx_dust/cxx/file_reader.hpp" #include "iceoryx_posh/gateway/gateway_generic.hpp" #include "iceoryx_posh/internal/log/posh_logging.hpp" // ================================================== Public ================================================== // namespace iox { namespace gw { template <typename channel_t, typename gateway_t> inline GatewayGeneric<channel_t, gateway_t>::~GatewayGeneric() noexcept { shutdown(); } template <typename channel_t, typename gateway_t> inline void GatewayGeneric<channel_t, gateway_t>::runMultithreaded() noexcept { m_isRunning.store(true, std::memory_order_relaxed); m_discoveryThread = std::thread([this] { this->discoveryLoop(); }); m_forwardingThread = std::thread([this] { this->forwardingLoop(); }); } template <typename channel_t, typename gateway_t> inline void GatewayGeneric<channel_t, gateway_t>::shutdown() noexcept { if (m_isRunning.load(std::memory_order_relaxed)) { m_isRunning.store(false, std::memory_order_relaxed); m_discoveryThread.join(); m_forwardingThread.join(); } } template <typename channel_t, typename gateway_t> inline uint64_t GatewayGeneric<channel_t, gateway_t>::getNumberOfChannels() const noexcept { return m_channels->size(); } // ================================================== Protected ================================================== // template <typename channel_t, typename gateway_t> inline GatewayGeneric<channel_t, gateway_t>::GatewayGeneric(capro::Interfaces interface, units::Duration discoveryPeriod, units::Duration forwardingPeriod) noexcept : gateway_t(interface) , m_discoveryPeriod(discoveryPeriod) , m_forwardingPeriod(forwardingPeriod) { } template <typename channel_t, typename gateway_t> template <typename IceoryxPubSubOptions> inline cxx::expected<channel_t, GatewayError> GatewayGeneric<channel_t, gateway_t>::addChannel(const capro::ServiceDescription& service, const IceoryxPubSubOptions& options) noexcept { // Filter out wildcard services if (service.getServiceIDString() == capro::IdString_t(cxx::TruncateToCapacity, "*") || service.getInstanceIDString() == capro::IdString_t(cxx::TruncateToCapacity, "*") || service.getEventIDString() == capro::IdString_t(cxx::TruncateToCapacity, "*")) { return cxx::error<GatewayError>(GatewayError::UNSUPPORTED_SERVICE_TYPE); } // Return existing channel if one for the service already exists, otherwise create a new one auto existingChannel = findChannel(service); if (existingChannel.has_value()) { return cxx::success<channel_t>(existingChannel.value()); } else { auto result = channel_t::create({service.getServiceIDString(), service.getInstanceIDString(), service.getEventIDString(), {0U, 0U, 0U, 0U}, this->getInterface()}, options); if (result.has_error()) { return cxx::error<GatewayError>(GatewayError::UNSUCCESSFUL_CHANNEL_CREATION); } else { auto channel = result.value(); m_channels->push_back(channel); return cxx::success<channel_t>(channel); } } } template <typename channel_t, typename gateway_t> inline cxx::optional<channel_t> GatewayGeneric<channel_t, gateway_t>::findChannel(const iox::capro::ServiceDescription& service) const noexcept { auto guardedVector = this->m_channels.getScopeGuard(); auto channel = std::find_if(guardedVector->begin(), guardedVector->end(), [&service](const channel_t& channel) { return channel.getServiceDescription() == service; }); if (channel == guardedVector->end()) { return cxx::nullopt_t(); } else { return cxx::make_optional<channel_t>(*channel); } } template <typename channel_t, typename gateway_t> inline void GatewayGeneric<channel_t, gateway_t>::forEachChannel(const cxx::function_ref<void(channel_t&)> f) const noexcept { auto guardedVector = m_channels.getScopeGuard(); for (auto channel = guardedVector->begin(); channel != guardedVector->end(); ++channel) { f(*channel); } } template <typename channel_t, typename gateway_t> inline cxx::expected<GatewayError> GatewayGeneric<channel_t, gateway_t>::discardChannel(const capro::ServiceDescription& service) noexcept { auto guardedVector = this->m_channels.getScopeGuard(); auto channel = std::find_if(guardedVector->begin(), guardedVector->end(), [&service](const channel_t& channel) { return channel.getServiceDescription() == service; }); if (channel != guardedVector->end()) { guardedVector->erase(channel); return cxx::success<void>(); } else { return cxx::error<GatewayError>(GatewayError::NONEXISTANT_CHANNEL); } } // ================================================== Private ================================================== // template <typename channel_t, typename gateway_t> inline void GatewayGeneric<channel_t, gateway_t>::discoveryLoop() noexcept { while (m_isRunning.load(std::memory_order_relaxed)) { auto startTime = std::chrono::steady_clock::now(); capro::CaproMessage msg; while (this->getCaProMessage(msg)) { discover(msg); } std::this_thread::sleep_until(startTime + std::chrono::milliseconds(m_discoveryPeriod.toMilliseconds())); } } template <typename channel_t, typename gateway_t> inline void GatewayGeneric<channel_t, gateway_t>::forwardingLoop() noexcept { while (m_isRunning.load(std::memory_order_relaxed)) { auto startTime = std::chrono::steady_clock::now(); forEachChannel([this](channel_t channel) { this->forward(channel); }); std::this_thread::sleep_until(startTime + std::chrono::milliseconds(m_forwardingPeriod.toMilliseconds())); }; } } // namespace gw } // namespace iox #endif // IOX_POSH_GW_GATEWAY_GENERIC_INL <commit_msg>iox-#1666 Fix GatewayGeneric::shutdown & add copyright<commit_after>// Copyright (c) 2020 by Robert Bosch GmbH. All rights reserved. // Copyright (c) 2020 - 2021 by Apex.AI Inc. All rights reserved. // Copyright (c) 2022 by NXP. 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. // // SPDX-License-Identifier: Apache-2.0 #ifndef IOX_POSH_GW_GATEWAY_GENERIC_INL #define IOX_POSH_GW_GATEWAY_GENERIC_INL #include "iceoryx_dust/cxx/file_reader.hpp" #include "iceoryx_posh/gateway/gateway_generic.hpp" #include "iceoryx_posh/internal/log/posh_logging.hpp" // ================================================== Public ================================================== // namespace iox { namespace gw { template <typename channel_t, typename gateway_t> inline GatewayGeneric<channel_t, gateway_t>::~GatewayGeneric() noexcept { shutdown(); } template <typename channel_t, typename gateway_t> inline void GatewayGeneric<channel_t, gateway_t>::runMultithreaded() noexcept { m_isRunning.store(true); m_discoveryThread = std::thread([this] { this->discoveryLoop(); }); m_forwardingThread = std::thread([this] { this->forwardingLoop(); }); } template <typename channel_t, typename gateway_t> inline void GatewayGeneric<channel_t, gateway_t>::shutdown() noexcept { m_isRunning.store(false); if (m_discoveryThread.joinable()) { m_discoveryThread.join(); } if (m_forwardingThread.joinable()) { m_forwardingThread.join(); } } template <typename channel_t, typename gateway_t> inline uint64_t GatewayGeneric<channel_t, gateway_t>::getNumberOfChannels() const noexcept { return m_channels->size(); } // ================================================== Protected ================================================== // template <typename channel_t, typename gateway_t> inline GatewayGeneric<channel_t, gateway_t>::GatewayGeneric(capro::Interfaces interface, units::Duration discoveryPeriod, units::Duration forwardingPeriod) noexcept : gateway_t(interface) , m_discoveryPeriod(discoveryPeriod) , m_forwardingPeriod(forwardingPeriod) { } template <typename channel_t, typename gateway_t> template <typename IceoryxPubSubOptions> inline cxx::expected<channel_t, GatewayError> GatewayGeneric<channel_t, gateway_t>::addChannel(const capro::ServiceDescription& service, const IceoryxPubSubOptions& options) noexcept { // Filter out wildcard services if (service.getServiceIDString() == capro::IdString_t(cxx::TruncateToCapacity, "*") || service.getInstanceIDString() == capro::IdString_t(cxx::TruncateToCapacity, "*") || service.getEventIDString() == capro::IdString_t(cxx::TruncateToCapacity, "*")) { return cxx::error<GatewayError>(GatewayError::UNSUPPORTED_SERVICE_TYPE); } // Return existing channel if one for the service already exists, otherwise create a new one auto existingChannel = findChannel(service); if (existingChannel.has_value()) { return cxx::success<channel_t>(existingChannel.value()); } else { auto result = channel_t::create({service.getServiceIDString(), service.getInstanceIDString(), service.getEventIDString(), {0U, 0U, 0U, 0U}, this->getInterface()}, options); if (result.has_error()) { return cxx::error<GatewayError>(GatewayError::UNSUCCESSFUL_CHANNEL_CREATION); } else { auto channel = result.value(); m_channels->push_back(channel); return cxx::success<channel_t>(channel); } } } template <typename channel_t, typename gateway_t> inline cxx::optional<channel_t> GatewayGeneric<channel_t, gateway_t>::findChannel(const iox::capro::ServiceDescription& service) const noexcept { auto guardedVector = this->m_channels.getScopeGuard(); auto channel = std::find_if(guardedVector->begin(), guardedVector->end(), [&service](const channel_t& channel) { return channel.getServiceDescription() == service; }); if (channel == guardedVector->end()) { return cxx::nullopt_t(); } else { return cxx::make_optional<channel_t>(*channel); } } template <typename channel_t, typename gateway_t> inline void GatewayGeneric<channel_t, gateway_t>::forEachChannel(const cxx::function_ref<void(channel_t&)> f) const noexcept { auto guardedVector = m_channels.getScopeGuard(); for (auto channel = guardedVector->begin(); channel != guardedVector->end(); ++channel) { f(*channel); } } template <typename channel_t, typename gateway_t> inline cxx::expected<GatewayError> GatewayGeneric<channel_t, gateway_t>::discardChannel(const capro::ServiceDescription& service) noexcept { auto guardedVector = this->m_channels.getScopeGuard(); auto channel = std::find_if(guardedVector->begin(), guardedVector->end(), [&service](const channel_t& channel) { return channel.getServiceDescription() == service; }); if (channel != guardedVector->end()) { guardedVector->erase(channel); return cxx::success<void>(); } else { return cxx::error<GatewayError>(GatewayError::NONEXISTANT_CHANNEL); } } // ================================================== Private ================================================== // template <typename channel_t, typename gateway_t> inline void GatewayGeneric<channel_t, gateway_t>::discoveryLoop() noexcept { while (m_isRunning.load(std::memory_order_relaxed)) { auto startTime = std::chrono::steady_clock::now(); capro::CaproMessage msg; while (this->getCaProMessage(msg)) { discover(msg); } std::this_thread::sleep_until(startTime + std::chrono::milliseconds(m_discoveryPeriod.toMilliseconds())); } } template <typename channel_t, typename gateway_t> inline void GatewayGeneric<channel_t, gateway_t>::forwardingLoop() noexcept { while (m_isRunning.load(std::memory_order_relaxed)) { auto startTime = std::chrono::steady_clock::now(); forEachChannel([this](channel_t channel) { this->forward(channel); }); std::this_thread::sleep_until(startTime + std::chrono::milliseconds(m_forwardingPeriod.toMilliseconds())); }; } } // namespace gw } // namespace iox #endif // IOX_POSH_GW_GATEWAY_GENERIC_INL <|endoftext|>
<commit_before>#include <iostream> #include <vector> int regul(std::vector<int> v) { while (v.vector::back() == 0) { v.vector::pop_back(); } return 0; } class zzbar{ public: zzbar(int d, int n) { if (d > 1 && n <d) { deg = d; num = n; } } // set deg and num void set_dg(int d, int n) { deg = d; num = n; } // Function finding \alpha int alpha() { int alp, halfnum; halfnum = (1 + num) / 2; alp = deg - halfnum; return alp; } // Function finding \beta int beta() { int bet; bet = (1 + num) / 2; return bet; } // Function finding prefix int prefix() { int prefix; if (deg%2==0 && num==deg-1) { prefix = 3; // without prefix } else { if(num%2==1) prefix = 1; // prefix = Re if(num%2==0) prefix = 2; // prefix = Im } return prefix; } // Operator < comparing two monoms zzbar bool operator<(zzbar ob2) { bool answ; if (deg < ob2.deg) { answ = true; } else if (deg == ob2.deg && num > ob2.num) { answ = true; } else answ = false; return answ; } // Operator == comparing two monoms zzbar bool operator==(zzbar ob2) { bool answ; if (deg == ob2.deg && num == ob2.num) { answ = true; } else answ = false; return answ; } // Function printing monom zzbar void print_zzbar() { int alp, bet, pr; pr = prefix(); alp = alpha(); bet = beta(); if (pr == 1) { std::cout << "\\mathrm{Re}\\left("; } else if (pr == 2) { std::cout << "\\mathrm{Im}\\left("; } if (alp == 1) { std::cout << "z"; } else { std::cout << "z^{" << alp << "}"; } if (bet == 1) { std::cout << "\\bar{z}"; } else { std::cout << "\\bar{z}^{" << bet << "}"; } if(pr < 3) { std::cout << "\\right)"; } } private: int deg; // degree of monom z^{\alpha}\bar{z}^{\beta} int num; // numer of monom among all monoms degree deg }; class monom : public zzbar{ public: monom(int d, int n, std::vector<int> vec):zzbar(d, n) { degu = vec; } /* // Operator < comparing two monoms zzbar bool operator<(monom ob2) { bool answ; if (deg < ob2.deg) { answ = true; } else if (deg == ob2.deg && num > ob2.num) { answ = true; } else answ = false; return answ; } // Operator == comparing two monoms zzbar bool operator==(zzbar ob2) { bool answ; if (deg == ob2.deg && num == ob2.num) { if () { } else answ = false; } else answ = false; return answ; } */ // Function printing monom void print_monom() { int i, n = degu.vector::size(); print_zzbar(); for (i=0; i<n; ++i) { if (degu[i] > 1) { std::cout << "u_{" << i+1 << "}^{" << degu[i] << "}"; } else if (degu[i] == 1) { std::cout << "u_{" << i+1 << "}"; } } std::cout << "\n"; } private: std::vector<int> degu; }; int main() { std::vector<int> vect; vect.vector::push_back(1); vect.vector::push_back(7); vect.vector::push_back(4); vect.vector::push_back(0); vect.vector::push_back(12); vect.vector::push_back(0); vect.vector::push_back(0); vect.vector::push_back(0); vect.vector::push_back(0); vect.vector::push_back(0); monom mon(8,5,vect); mon.print_monom(); int i, j; // for (i=2; i<7; ++i) { // for (j=1; j<i; ++j) { // mon.set_dg(i, j); // mon.print_monom(); // } // } return 0; } <commit_msg>Final version of program<commit_after>#include <iostream> #include <vector> #include <cmath> #include <ctime> ////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////// zzbar ///////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////// class zzbar { public: zzbar(); zzbar(int d, int n); zzbar(const zzbar& copy); void set_dg(int d, int n); int alpha(); int beta(); int prefix(); int get_deg(); int get_num(); void print_zzbar(); bool operator<(zzbar ob2); bool operator==(zzbar ob2); protected: int deg; // degree of monom z^{\alpha}\bar{z}^{\beta} int num; // numer of monom among all monoms degree deg }; zzbar::zzbar() { deg = 2; num = 1; } zzbar::zzbar(int d, int n) { if (d > 1 && n < d) { deg = d; num = n; } } zzbar::zzbar(const zzbar& copy) { deg = copy.deg; num = copy.num; } // set deg and num void zzbar::set_dg(int d, int n) { deg = d; num = n; } // Function finding \alpha int zzbar::alpha() { int halfnum = (1 + num) / 2; int alp = deg - halfnum; return alp; } // Function finding \beta int zzbar::beta() { int bet = (1 + num) / 2; return bet; } // Function finding prefix int zzbar::prefix() { int prefix; if (deg%2 == 0 && num == deg-1) prefix = 3; // without prefix else { if(num%2 == 1) prefix = 1; // prefix = Re if(num%2 == 0) prefix = 2; // prefix = Im } return prefix; } int zzbar::get_deg() { return deg; } int zzbar::get_num() { return num; } // Operator < comparing two monoms zzbar bool zzbar::operator<(zzbar ob2) { bool answ = true; if (deg < ob2.deg) answ = true; else if (deg == ob2.deg && num > ob2.num) answ = true; else answ = false; return answ; } // Operator == comparing two monoms zzbar bool zzbar::operator==(zzbar ob2) { bool answ = true; if (deg == ob2.deg && num == ob2.num) { answ = true; } else answ = false; return answ; } // Function printing monom zzbar void zzbar::print_zzbar() { int pr = prefix(); int alp = alpha(); int bet = beta(); if (pr == 1) std::cout << "2\\mathrm{Re}\\left("; else if (pr == 2) std::cout << "2\\mathrm{Im}\\left("; if (alp == 1) std::cout << "z"; else std::cout << "z^{" << alp << "}"; if (bet == 1) std::cout << "\\bar{z}"; else std::cout << "\\bar{z}^{" << bet << "}"; if(pr < 3) std::cout << "\\right)"; } ////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////// monom ///////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////// class monom : public zzbar { public: monom(); monom(int d, int n, const std::vector<int> &vec); monom(int d, int n, const std::vector<int> &vec, const std::vector<int> &deg_wei); monom(const monom& copy); void set(int d, int n, const std::vector<int> &vec); void print_monom(); void set_index(int ind); void set_weight(int wei); void regul(); bool operator<(const monom &ob2) const; bool operator==(const monom &ob2) const; int get_index(); int get_weight(); int get_deguwei(const int i); void get_deguwei(std::vector<int> &vec); void get_degu(std::vector<int> &vec); int get_degusize(); private: int index; int weight; std::vector<int> degu; // degu = <g_1, ..., g_s>, where monom = zzbar * u_1^{g_1} * ... * u_s^{g_s} std::vector<int> degu_wei; // degu_wei = <w_0, w_1, ..., w_s>, where w_i = weight of cutting monom = zzbar * u_1^{g_1} * ... * u_s^{g_i} static bool less_vector(const std::vector<int> &v1, const std::vector<int> &v2); }; monom::monom() { deg = 2; num = 1; index = 1; weight = 2; degu_wei.push_back(2); } monom::monom(int d, int n, const std::vector<int> &vec) : zzbar(d, n) { degu = vec; while (!degu.empty() && degu.back() == 0) { degu.pop_back(); } index = 1; weight = 2; } monom::monom(int d, int n, const std::vector<int> &vec, const std::vector<int> &deg_wei) : zzbar(d, n) { degu = vec; while (!degu.empty() && degu.back() == 0) { degu.pop_back(); } degu_wei = deg_wei; index = 1; weight = 2; } monom::monom(const monom& copy) { deg = copy.deg; num = copy.num; index = copy.index; weight = copy.weight; degu = copy.degu; degu_wei = copy.degu_wei; } void monom::set(int d, int n, const std::vector<int> &vec) { degu = vec; while (!degu.empty() && degu.back() == 0) { degu.pop_back(); } index = 1; weight = 2; deg = d; num = n; } void monom::set_index(int ind) { index = ind; } void monom::set_weight(int wei) { weight = wei; } bool monom::less_vector(const std::vector<int> &v1, const std::vector<int> &v2) { bool answ = true; int i = 0; int flag = 0; int n = std::min(v1.size(), v2.size()); while (flag == 0 && i<n) { if (v1[i] < v2[i]) flag = 1; ++i; } if (flag == 1) answ = true; else answ = false; return answ; } void monom::regul() { while (!degu.empty() && degu.back() == 0) { degu.pop_back(); } int n = degu.size(); int m = degu_wei.size(); if(m > n+1) { int k = m-n-1; for(int i = 0; i < k; ++i) { degu_wei.pop_back(); } } } // Operator < comparing two monoms bool monom::operator<(const monom &ob2) const { bool answ = true; if (deg < ob2.deg) answ = true; else if (deg == ob2.deg && num > ob2.num) answ = true; else if (deg == ob2.deg && num == ob2.num && less_vector(degu, ob2.degu)) answ = true; else answ = false; return answ; } // Operator == comparing two monoms bool monom::operator==(const monom &ob2) const { bool answ = true; std::vector<int> vec_l = degu; std::vector<int> vec_r = ob2.degu; while (!vec_l.empty() && vec_l.back() == 0) { vec_l.pop_back(); } while (!vec_r.empty() && vec_r.back() == 0) { vec_r.pop_back(); } if (deg == ob2.deg && num == ob2.num && vec_r == vec_l) answ = true; else answ = false; return answ; } // Function printing monom void monom::print_monom() { int n = degu.size(); std::cout << "$$v_{" << index << "} = "; print_zzbar(); for (int i = 0; i < n; ++i) { if (degu[i] > 1) std::cout << "u_{" << i+1 << "}^{" << degu[i] << "}"; else if (degu[i] == 1) std::cout << "u_{" << i+1 << "}"; } std::cout << "$$"; std::cout << "\n"; } int monom::get_index() { return index; } int monom::get_weight() { return weight; } int monom::get_deguwei(int i) { if( i < degu_wei.size() && i >= 0) { return degu_wei[i]; } else { std::cout << "error. monom::get_deguwei. i >= degu_wei.size()"; return 0; } } void monom::get_deguwei(std::vector<int> &vec) { vec = degu_wei; } void monom::get_degu(std::vector<int> &vec) { vec = degu; } int monom::get_degusize() { return degu.size(); } ////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////// H_n //////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////// class H_n { public: H_n(); H_n(int n, const std::vector<int> &dim); int get_size(); void print_space(); void print_space(int i); monom get_space(int i); std::vector<monom> get_space(); private: int period_num; // number of period \in {2, 3, ...} std::vector<monom> space; // all monoms of weight period_num std::vector<int> dimensions; // dimensions of spaces CH_2, ... CH_{n-1} static int smartloop_inc (const std::vector<int> &weight, std::vector<int> &vec, int summa); void spacecreator(int n, const std::vector<int> &dim); }; H_n::H_n() { std::vector<int> dim; spacecreator(2, dim); } H_n::H_n(int n, const std::vector<int> &dim) { spacecreator(n, dim); } int H_n::get_size() { return space.size(); } void H_n::print_space() { for (int i = 0; i < space.size(); ++i) { space[i].print_monom(); } } monom H_n::get_space(int i) { if (space.size() > i) return space[i]; } std::vector<monom> H_n::get_space() { return space; } void H_n::print_space(int i) { if (i < space.size()) space[i].print_monom(); } void H_n::spacecreator(int n, const std::vector<int> &dim) { if( n-2 != dim.size() ) std::cout << "error. n-2 != dim.size()"; int i = 0; int flag = 0; int iwei = 0; int lim = (n-4) / 2; period_num = n; dimensions = dim; int sumdim = 0; for(i=0; i<=lim; ++i) { sumdim += dimensions[i]; } std::vector<int> weights; for(i = 0; i < sumdim; ++i) { flag = 0; iwei = 0; while (i+1 > flag) { flag += dimensions[iwei]; ++iwei; } weights.push_back(iwei+1); } //======== creation of vector space ======== std::vector<int> loopv(sumdim, 0); for(int ideg = period_num; ideg > 1; --ideg) { int diff = period_num - ideg; for(int inum = 1; inum < ideg; ++inum) { loopv.assign(sumdim, 0); int fl = 0; if (diff > 0) { fl = smartloop_inc(weights, loopv, diff); } while (fl == 0) { int sum = ideg; std::vector<int> deg_wei; deg_wei.push_back(sum); for (int ive = 0; ive < sumdim; ++ive) { sum += (loopv[ive] * weights[ive]); deg_wei.push_back(sum); } monom temp(ideg, inum, loopv, deg_wei); temp.set_weight(n); temp.regul(); space.push_back(temp); fl = smartloop_inc(weights, loopv, diff); } } } //========================================== } int H_n::smartloop_inc (const std::vector<int> &weight, std::vector<int> &vec, int summa) { if (weight.size() != vec.size()) std::cout << "error. weight.size != vec.size"; int end = 0; int n = weight.size(); if(n > 0) { int fl = 0; vec[0] += 1; while ( fl == 0 ) { int sum = 0; for(int i = 0; i < n; ++i) { sum += weight[i] * vec[i]; } if(sum < summa) vec[0] += 1; else if (sum == summa) fl = 1; else { int fl2 = 0; int ivec = 0; while (fl2 == 0 && ivec < n) { vec[ivec]==0 ? ++ivec : fl2=1; } if( ivec == n || ivec == n-1 ) { fl = 1; end = 1; } else { vec[ivec] = 0; vec[1+ivec] += 1; } } } } if(n == 0) end = 1; return end; } ////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////// CH_n ///////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////// class CH_n { public: CH_n(); CH_n(int n); void print_megaspace(); void print_info(); private: std::vector< std::vector<monom> > megaspace; std::vector<int> dim; int monom_index(const monom &mon); bool monom_check(const monom &mon); }; CH_n::CH_n() { H_n H; megaspace.push_back( H.get_space() ); } CH_n::CH_n(int n) { if(n < 2 ) std::cout << "error. n < 2"; int ind = 0; for(int i = 2; i < n+1; ++i) { H_n H(i, dim); dim.push_back(0); std::vector<monom> sp; for (int j = 0; j < H.get_size(); ++j) { if( monom_check( H.get_space(j) ) ) { ind++; dim[i-2] += 1; sp.push_back( H.get_space(j) ); sp.back().set_index(ind); } } megaspace.push_back( sp ); } } void CH_n::print_megaspace() { for(int i = 0; i < megaspace.size(); ++i) { std::cout << "$$========== period \\ " << i+2 << " ==========$$ \n"; for(int j = 0; j < megaspace[i].size(); ++j) { megaspace[i][j].print_monom(); } } } void CH_n::print_info() { std::cout << "\n"; for(int i = 0; i < megaspace.size(); ++i) { std::cout << "$$\\dim(CH_{" << i+2 << "}) = " << megaspace[i].size() << "$$ \n"; } std::cout << "\n"; for(int i = 0; i < megaspace.size(); ++i) { int max = 0; int jmax = 0; for(int j = 0; j < megaspace[i].size(); j++) { if( megaspace[i][j].get_degusize() > max ) { max = megaspace[i][j].get_degusize(); jmax = j; } } std::cout << "$$\\dim(U, \\ CH_{" << i+2 << "}) = " << max << ", \\ \\ \\text{for example}:$$ \n"; megaspace[i][jmax].print_monom(); } std::cout << "\n"; } int CH_n::monom_index(const monom &mon) { int ind = 0; monom mono(mon); std::vector<int> deg_u; mono.get_degu(deg_u); int wei = mono.get_deguwei( deg_u.size() ) - 2; int fl = 0; int i = 0; while( fl == 0 && i < megaspace[wei].size() ) { if(megaspace[wei][i] == mon) { ind = megaspace[wei][i].get_index(); fl = 1; } ++i; } return ind; } bool CH_n::monom_check(const monom &mon) { int answ = true; int fl = 0; monom mono(mon); std::vector<int> degu_w; mono.get_deguwei(degu_w); std::vector<int> deg_u; mono.get_degu(deg_u); if( 2*mono.get_deg() <= mono.get_weight() ) { int i = 0; int detailed_check = 0; std::vector<int> vec; while (fl == 0 && i < deg_u.size() ) { monom temp_mon(mono.get_deg(), mono.get_num(), vec, degu_w); vec.push_back(deg_u[i]); if(deg_u[i] > 0 && monom_index(temp_mon) <= i+1) { fl = 1; } ++i; } } if(fl == 0) answ = true; else answ = false; return answ; } ////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////// int main() { time_t sec1 = time(NULL); CH_n ch6(8); time_t sec2 = time(NULL); time_t dsec = sec2 - sec1; ch6.print_info(); ch6.print_megaspace(); std::cout << "Elapsed time: " << dsec << " sec" << std::endl; return 0; } <|endoftext|>
<commit_before>#pragma once #include "../std/vector.hpp" template <class T> class SimpleTree { typedef std::vector<SimpleTree<T> > internal_container_type; T m_value; internal_container_type m_siblings; public: SimpleTree(T const & value = T()) : m_value(value) { } /// @return reference is valid only up to the next tree structure modification T const & Value() const { return m_value; } /// @return reference is valid only up to the next tree structure modification T & Value() { return m_value; } /// @return reference is valid only up to the next tree structure modification T & AddAtDepth(int level, T const & value) { SimpleTree<T> * node = this; while (level-- > 0 && !node->m_siblings.empty()) node = &node->m_siblings.back(); return node->Add(value); } /// @return reference is valid only up to the next tree structure modification T & Add(T const & value) { m_siblings.push_back(SimpleTree(value)); return m_siblings.back().Value(); } /// Deletes all children and makes tree empty void Clear() { m_siblings.clear(); } bool operator<(SimpleTree<T> const & other) const { return Value() < other.Value(); } /// sorts siblings independently on each level by default void Sort(bool onlySiblings = false) { std::sort(m_siblings.begin(), m_siblings.end()); if (!onlySiblings) for (typename internal_container_type::iterator it = m_siblings.begin(); it != m_siblings.end(); ++it) it->Sort(false); } SimpleTree<T> const & operator[](size_t index) const { return m_siblings.at(index); } size_t SiblingsCount() const { return m_siblings.size(); } template <class TFunctor> void ForEachSibling(TFunctor & f) { for (typename internal_container_type::iterator it = m_siblings.begin(); it != m_siblings.end(); ++it) f(*it); } template <class TFunctor> void ForEachSibling(TFunctor & f) const { for (typename internal_container_type::const_iterator it = m_siblings.begin(); it != m_siblings.end(); ++it) f(*it); } template <class TFunctor> void ForEachChildren(TFunctor & f) { for (typename internal_container_type::iterator it = m_siblings.begin(); it != m_siblings.end(); ++it) { it->ForEachChildren(f); f(*it); } } template <class TFunctor> void ForEachChildren(TFunctor & f) const { for (typename internal_container_type::const_iterator it = m_siblings.begin(); it != m_siblings.end(); ++it) { it->ForEachChildren(f); f(*it); } } }; <commit_msg>Fixed missed include<commit_after>#pragma once #include "../std/vector.hpp" #include "../std/algorithm.hpp" template <class T> class SimpleTree { typedef std::vector<SimpleTree<T> > internal_container_type; T m_value; internal_container_type m_siblings; public: SimpleTree(T const & value = T()) : m_value(value) { } /// @return reference is valid only up to the next tree structure modification T const & Value() const { return m_value; } /// @return reference is valid only up to the next tree structure modification T & Value() { return m_value; } /// @return reference is valid only up to the next tree structure modification T & AddAtDepth(int level, T const & value) { SimpleTree<T> * node = this; while (level-- > 0 && !node->m_siblings.empty()) node = &node->m_siblings.back(); return node->Add(value); } /// @return reference is valid only up to the next tree structure modification T & Add(T const & value) { m_siblings.push_back(SimpleTree(value)); return m_siblings.back().Value(); } /// Deletes all children and makes tree empty void Clear() { m_siblings.clear(); } bool operator<(SimpleTree<T> const & other) const { return Value() < other.Value(); } /// sorts siblings independently on each level by default void Sort(bool onlySiblings = false) { std::sort(m_siblings.begin(), m_siblings.end()); if (!onlySiblings) for (typename internal_container_type::iterator it = m_siblings.begin(); it != m_siblings.end(); ++it) it->Sort(false); } SimpleTree<T> const & operator[](size_t index) const { return m_siblings.at(index); } size_t SiblingsCount() const { return m_siblings.size(); } template <class TFunctor> void ForEachSibling(TFunctor & f) { for (typename internal_container_type::iterator it = m_siblings.begin(); it != m_siblings.end(); ++it) f(*it); } template <class TFunctor> void ForEachSibling(TFunctor & f) const { for (typename internal_container_type::const_iterator it = m_siblings.begin(); it != m_siblings.end(); ++it) f(*it); } template <class TFunctor> void ForEachChildren(TFunctor & f) { for (typename internal_container_type::iterator it = m_siblings.begin(); it != m_siblings.end(); ++it) { it->ForEachChildren(f); f(*it); } } template <class TFunctor> void ForEachChildren(TFunctor & f) const { for (typename internal_container_type::const_iterator it = m_siblings.begin(); it != m_siblings.end(); ++it) { it->ForEachChildren(f); f(*it); } } }; <|endoftext|>
<commit_before> #include <s2sinputstream.h> #include <s2soutputstream.h> #include <virtualhost.h> #include <nanosoft/asyncdns.h> #include <iostream> using namespace std; /** * Конструктор потока */ S2SInputStream::S2SInputStream(XMPPServer *srv, int sock): XMPPStream(srv, sock) { } /** * Деструктор потока */ S2SInputStream::~S2SInputStream() { } /** * Событие: начало потока */ void S2SInputStream::onStartStream(const std::string &name, const attributes_t &attributes) { fprintf(stderr, "#%d new s2s stream\n", getWorkerId()); initXML(); startElement("stream:stream"); setAttribute("xmlns:stream", "http://etherx.jabber.org/streams"); setAttribute("xmlns", "jabber:server"); setAttribute("xmlns:db", "jabber:server:dialback"); setAttribute("id", id = "123456"); // Требования к id — непредсказуемость и уникальность setAttribute("xml:lang", "en"); flush(); } /** * Событие: конец потока */ void S2SInputStream::onEndStream() { fprintf(stderr, "#%d: [S2SInputStream: %d] end of stream\n", getWorkerId(), fd); terminate(); } /** * Обработчик станзы */ void S2SInputStream::onStanza(Stanza stanza) { fprintf(stderr, "#%d s2s-input stanza: %s\n", getWorkerId(), stanza->name().c_str()); if ( stanza->name() == "verify" ) onDBVerifyStanza(stanza); else if ( stanza->name() == "result" ) onDBResultStanza(stanza); else if ( state != authorized ) { fprintf(stderr, "#%d unexpected s2s-input stanza: %s\n", getWorkerId(), stanza->name().c_str()); Stanza error = Stanza::streamError("not-authoized"); sendStanza(error); delete error; terminate(); } else if ( stanza.from().hostname() != remote_host ) { fprintf(stderr, "#%d [s2s-input: %s] invalid from: %s\n", getWorkerId(), remote_host.c_str(), stanza->getAttribute("from").c_str()); Stanza error = Stanza::streamError("improper-addressing"); sendStanza(error); delete error; terminate(); } else { // доставить станзу по назначению XMPPDomain *vhost = server->getHostByName(stanza.to().hostname()); if ( ! vhost ) { fprintf(stderr, "#%d [s2s-input: %s] invalid to: %s\n", getWorkerId(), remote_host.c_str(), stanza->getAttribute("to").c_str()); Stanza error = Stanza::streamError("improper-addressing"); sendStanza(error); delete error; terminate(); } vhost->routeStanza(stanza); } } /** * Обработка <db:verify> */ void S2SInputStream::onDBVerifyStanza(Stanza stanza) { Stanza verify = new ATXmlTag("db:verify"); verify->setAttribute("from", stanza->getAttribute("to")); verify->setAttribute("to", stanza->getAttribute("from")); verify->setAttribute("type", "valid"); verify->setAttribute("id", stanza->getAttribute("id")); sendStanza(verify); delete verify; } /** * Резолвер s2s хоста, запись A (IPv4) */ static void on_s2s_a4(struct dns_ctx *ctx, struct dns_rr_a4 *result, void *data) { printf("on_s2s_a4\n"); if ( result ) for(int i = 0; i < result->dnsa4_nrr; i++) { char buf[40]; printf(" addr: %s\n", dns_ntop(AF_INET, &result->dnsa4_addr[i], buf, sizeof(buf))); } printf("\n"); } /** * Резолвер s2s хоста, запись SRV (_jabber._tcp) */ static void on_s2s_srv_jabber(struct dns_ctx *ctx, struct dns_rr_srv *result, void *data) { printf("on_s2s_srv_jabber\n"); if ( result ) for(int i = 0; i < result->dnssrv_nrr; i++) { char buf[40]; printf(" SRV priority: %d, weight: %d, port: %d, name: %s\n", result->dnssrv_srv[i].priority, result->dnssrv_srv[i].weight, result->dnssrv_srv[i].port, result->dnssrv_srv[i].name); } printf("\n"); } /** * Резолвер s2s хоста, запись SRV (_xmpp-server._tcp) */ static void on_srv_xmpp_server(struct dns_ctx *ctx, struct dns_rr_srv *result, void *data) { printf("on_srv_xmpp_server\n"); if ( result ) for(int i = 0; i < result->dnssrv_nrr; i++) { char buf[40]; printf(" SRV priority: %d, weight: %d, port: %d, name: %s\n", result->dnssrv_srv[i].priority, result->dnssrv_srv[i].weight, result->dnssrv_srv[i].port, result->dnssrv_srv[i].name); } printf("\n"); } /** * Резолвер s2s хоста, запись RBL */ static void on_s2s_rbl(struct dns_ctx *ctx, struct dns_rr_a4 *result, void *data) { printf("on_s2s_rbl\n"); if ( result ) { for(int i = 0; i < result->dnsa4_nrr; i++) { char buf[40]; printf(" addr: %s\n", dns_ntop(AF_INET, &result->dnsa4_addr[i], buf, sizeof(buf))); } } printf("\n"); } /** * Обработка <db:result> */ void S2SInputStream::onDBResultStanza(Stanza stanza) { string to = stanza->getAttribute("to"); string from = stanza->getAttribute("from"); cerr << "[s2s-input] db:result to: " << to << ", from: " << from << endl; // Шаг 1. проверка: "to" должен быть нашим виртуальным хостом XMPPDomain *host = server->getHostByName(to); if ( ! host || dynamic_cast<S2SOutputStream*>(host) ) { Stanza stanza = Stanza::streamError("host-unknown"); sendStanza(stanza); delete stanza; terminate(); return; } // Шаг 2. проверка "from" // // RFC 3920 не запрещает делать повторные коннекты (8.3.4). // // До завершения авторизации нужно поддерживать старое соединение, // пока не авторизуется новое. Но можно блокировать повторные // коннекты с ошибкой <not-authorized />, что мы и делаем. // // NOTE: В любом случае, логично блокировать попытки представиться // нашим хостом - мы сами к себе никогда не коннектимся. // Так что, если будете открывать повторные коннекты, то забудьте // блокировать попытки коннекта к самим себе. if ( server->getHostByName(from) ) { Stanza stanza = Stanza::streamError("not-authorized"); sendStanza(stanza); delete stanza; terminate(); return; } remote_host = from; // Шаг 3. резолвим DNS записи сервера // NOTE для оптимизации отправляем все DNS (асинхронные) запросы сразу server->adns->a4(from.c_str(), on_s2s_a4, this); server->adns->srv(from.c_str(), "jabber", "tcp", on_s2s_srv_jabber, this); server->adns->srv(from.c_str(), "xmpp-server", "tcp", on_srv_xmpp_server, this); // TODO извлекать список DNSBL из конфига server->adns->a4((from + ".dnsbl.jabber.ru").c_str(), on_s2s_rbl, this); // Шаг X. костыль - ответить сразу "authorized" state = authorized; Stanza result = new ATXmlTag("db:result"); result->setAttribute("to", from); result->setAttribute("from", to); result->setAttribute("type", "valid"); sendStanza(result); delete result; } /** * Сигнал завершения работы * * Сервер решил закрыть соединение, здесь ещё есть время * корректно попрощаться с пиром (peer). */ void S2SInputStream::onTerminate() { fprintf(stderr, "#%d: [S2SInputStream: %d] onTerminate\n", getWorkerId(), fd); // if ( state == authorized ) server->onOffline(this); mutex.lock(); endElement("stream:stream"); flush(); shutdown(WRITE); mutex.unlock(); } <commit_msg>ID on s2s<commit_after> #include <s2sinputstream.h> #include <s2soutputstream.h> #include <virtualhost.h> #include <functions.h> #include <nanosoft/asyncdns.h> #include <iostream> using namespace std; /** * Конструктор потока */ S2SInputStream::S2SInputStream(XMPPServer *srv, int sock): XMPPStream(srv, sock) { } /** * Деструктор потока */ S2SInputStream::~S2SInputStream() { } /** * Событие: начало потока */ void S2SInputStream::onStartStream(const std::string &name, const attributes_t &attributes) { fprintf(stderr, "#%d new s2s stream\n", getWorkerId()); initXML(); startElement("stream:stream"); setAttribute("xmlns:stream", "http://etherx.jabber.org/streams"); setAttribute("xmlns", "jabber:server"); setAttribute("xmlns:db", "jabber:server:dialback"); setAttribute("id", id = getUniqueId()); setAttribute("xml:lang", "en"); flush(); } /** * Событие: конец потока */ void S2SInputStream::onEndStream() { fprintf(stderr, "#%d: [S2SInputStream: %d] end of stream\n", getWorkerId(), fd); terminate(); } /** * Обработчик станзы */ void S2SInputStream::onStanza(Stanza stanza) { fprintf(stderr, "#%d s2s-input stanza: %s\n", getWorkerId(), stanza->name().c_str()); if ( stanza->name() == "verify" ) onDBVerifyStanza(stanza); else if ( stanza->name() == "result" ) onDBResultStanza(stanza); else if ( state != authorized ) { fprintf(stderr, "#%d unexpected s2s-input stanza: %s\n", getWorkerId(), stanza->name().c_str()); Stanza error = Stanza::streamError("not-authoized"); sendStanza(error); delete error; terminate(); } else if ( stanza.from().hostname() != remote_host ) { fprintf(stderr, "#%d [s2s-input: %s] invalid from: %s\n", getWorkerId(), remote_host.c_str(), stanza->getAttribute("from").c_str()); Stanza error = Stanza::streamError("improper-addressing"); sendStanza(error); delete error; terminate(); } else { // доставить станзу по назначению XMPPDomain *vhost = server->getHostByName(stanza.to().hostname()); if ( ! vhost ) { fprintf(stderr, "#%d [s2s-input: %s] invalid to: %s\n", getWorkerId(), remote_host.c_str(), stanza->getAttribute("to").c_str()); Stanza error = Stanza::streamError("improper-addressing"); sendStanza(error); delete error; terminate(); } vhost->routeStanza(stanza); } } /** * Обработка <db:verify> */ void S2SInputStream::onDBVerifyStanza(Stanza stanza) { Stanza verify = new ATXmlTag("db:verify"); verify->setAttribute("from", stanza->getAttribute("to")); verify->setAttribute("to", stanza->getAttribute("from")); verify->setAttribute("type", "valid"); verify->setAttribute("id", stanza->getAttribute("id")); sendStanza(verify); delete verify; } /** * Резолвер s2s хоста, запись A (IPv4) */ static void on_s2s_a4(struct dns_ctx *ctx, struct dns_rr_a4 *result, void *data) { printf("on_s2s_a4\n"); if ( result ) for(int i = 0; i < result->dnsa4_nrr; i++) { char buf[40]; printf(" addr: %s\n", dns_ntop(AF_INET, &result->dnsa4_addr[i], buf, sizeof(buf))); } printf("\n"); } /** * Резолвер s2s хоста, запись SRV (_jabber._tcp) */ static void on_s2s_srv_jabber(struct dns_ctx *ctx, struct dns_rr_srv *result, void *data) { printf("on_s2s_srv_jabber\n"); if ( result ) for(int i = 0; i < result->dnssrv_nrr; i++) { char buf[40]; printf(" SRV priority: %d, weight: %d, port: %d, name: %s\n", result->dnssrv_srv[i].priority, result->dnssrv_srv[i].weight, result->dnssrv_srv[i].port, result->dnssrv_srv[i].name); } printf("\n"); } /** * Резолвер s2s хоста, запись SRV (_xmpp-server._tcp) */ static void on_srv_xmpp_server(struct dns_ctx *ctx, struct dns_rr_srv *result, void *data) { printf("on_srv_xmpp_server\n"); if ( result ) for(int i = 0; i < result->dnssrv_nrr; i++) { char buf[40]; printf(" SRV priority: %d, weight: %d, port: %d, name: %s\n", result->dnssrv_srv[i].priority, result->dnssrv_srv[i].weight, result->dnssrv_srv[i].port, result->dnssrv_srv[i].name); } printf("\n"); } /** * Резолвер s2s хоста, запись RBL */ static void on_s2s_rbl(struct dns_ctx *ctx, struct dns_rr_a4 *result, void *data) { printf("on_s2s_rbl\n"); if ( result ) { for(int i = 0; i < result->dnsa4_nrr; i++) { char buf[40]; printf(" addr: %s\n", dns_ntop(AF_INET, &result->dnsa4_addr[i], buf, sizeof(buf))); } } printf("\n"); } /** * Обработка <db:result> */ void S2SInputStream::onDBResultStanza(Stanza stanza) { string to = stanza->getAttribute("to"); string from = stanza->getAttribute("from"); cerr << "[s2s-input] db:result to: " << to << ", from: " << from << endl; // Шаг 1. проверка: "to" должен быть нашим виртуальным хостом XMPPDomain *host = server->getHostByName(to); if ( ! host || dynamic_cast<S2SOutputStream*>(host) ) { Stanza stanza = Stanza::streamError("host-unknown"); sendStanza(stanza); delete stanza; terminate(); return; } // Шаг 2. проверка "from" // // RFC 3920 не запрещает делать повторные коннекты (8.3.4). // // До завершения авторизации нужно поддерживать старое соединение, // пока не авторизуется новое. Но можно блокировать повторные // коннекты с ошибкой <not-authorized />, что мы и делаем. // // NOTE: В любом случае, логично блокировать попытки представиться // нашим хостом - мы сами к себе никогда не коннектимся. // Так что, если будете открывать повторные коннекты, то забудьте // блокировать попытки коннекта к самим себе. if ( server->getHostByName(from) ) { Stanza stanza = Stanza::streamError("not-authorized"); sendStanza(stanza); delete stanza; terminate(); return; } remote_host = from; // Шаг 3. резолвим DNS записи сервера // NOTE для оптимизации отправляем все DNS (асинхронные) запросы сразу server->adns->a4(from.c_str(), on_s2s_a4, this); server->adns->srv(from.c_str(), "jabber", "tcp", on_s2s_srv_jabber, this); server->adns->srv(from.c_str(), "xmpp-server", "tcp", on_srv_xmpp_server, this); // TODO извлекать список DNSBL из конфига server->adns->a4((from + ".dnsbl.jabber.ru").c_str(), on_s2s_rbl, this); // Шаг X. костыль - ответить сразу "authorized" state = authorized; Stanza result = new ATXmlTag("db:result"); result->setAttribute("to", from); result->setAttribute("from", to); result->setAttribute("type", "valid"); sendStanza(result); delete result; } /** * Сигнал завершения работы * * Сервер решил закрыть соединение, здесь ещё есть время * корректно попрощаться с пиром (peer). */ void S2SInputStream::onTerminate() { fprintf(stderr, "#%d: [S2SInputStream: %d] onTerminate\n", getWorkerId(), fd); // if ( state == authorized ) server->onOffline(this); mutex.lock(); endElement("stream:stream"); flush(); shutdown(WRITE); mutex.unlock(); } <|endoftext|>
<commit_before>#include <iostream> #include <fstream> #include <vector> #include <string> #include <iterator> #include <ctime> #include <unordered_map> #include <algorithm> #include <cmath> #include <chrono> #include <iostream> #include <fstream> #include <string> #include <iterator> #include <unordered_map> #include <unordered_set> #include <set> #include <algorithm> #include <chrono> #include <map> #include <set> #include <ctype.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> using namespace std; char randomNucleotide(){ switch (rand() % 4){ case 0: return 'A'; case 1: return 'C'; case 2: return 'G'; case 3: return 'T'; } return 'A'; } string randomSequence(const uint length){ string result(length, 'A'); for(uint i(0); i < length; ++i){ result[i] = randomNucleotide(); } return result; } void insertion(uint rate, string& result){ uint dice(rand() % 100); if(dice < rate){ char newNucleotide(randomNucleotide()); result.push_back(newNucleotide); insertion(rate, result); } } string mutateSequence(const string& referenceSequence, uint maxMutRate=0, vector <double> ratioMutation={0.06,0.73,0.21}){ //~ string mutateSequence(const string& referenceSequence, uint maxMutRate=3, vector <double> ratioMutation={0.06,0.73,0.21}){ string result; result.reserve(5 * referenceSequence.size()); for(uint i(0); i < referenceSequence.size(); ++i){ uint mutRate(maxMutRate); //~ uint mutRate(rand() % maxMutRate); double substitutionRate(mutRate * ratioMutation[0]); double insertionRate(mutRate * ratioMutation[1]); double deletionRate(mutRate * ratioMutation[2]); uint dice(rand() % 100); if (dice <substitutionRate ){ //SUBSTITUTION char newNucleotide(randomNucleotide()); while(newNucleotide == referenceSequence[i]){ newNucleotide = randomNucleotide(); } result.push_back(newNucleotide); continue; } else if(dice < deletionRate+substitutionRate){ //DELETION uint dice2(rand() % 100); while (dice2 < deletionRate+substitutionRate){ // deletions larger than 1 ++i; dice2 = rand() % 100; } continue; } else if (dice < deletionRate + substitutionRate + insertionRate){ //INSERTION char newNucleotide(randomNucleotide()); result.push_back(referenceSequence[i]); result.push_back(newNucleotide); //~ --i; insertion(deletionRate + substitutionRate + insertionRate, result); // larger than 1 insertions continue; } else { //NO ERROR result.push_back(referenceSequence[i]); } } return result; } vector<string> generateAlternativeTranscriptReferences(uint transcriptNumber=1, uint totalExonNumber=1, uint exonNumber=1, uint sizeExons=200){ vector<string> result; vector<string> exonList; for(uint i(0); i < totalExonNumber; ++i){ exonList.push_back(randomSequence(sizeExons)); } string transcript; transcript.reserve(exonNumber*sizeExons); unordered_set<uint> selectedExons; uint dice1, transcriptExonNumber; for(uint i(0); i < transcriptNumber; ++i){ if (transcriptNumber > 1){ dice1 = (rand() % (totalExonNumber-3)); transcriptExonNumber = (dice1 + 3); } else { transcriptExonNumber = 0; } cout << transcriptExonNumber << endl; transcript = ""; selectedExons = {}; if (transcriptExonNumber > 0){ while(selectedExons.size() != transcriptExonNumber){ selectedExons.insert(rand() % totalExonNumber); } } else { selectedExons.insert(0); } for(uint ii(0); ii < totalExonNumber; ++ii){ if(selectedExons.count(ii) == 1){ transcript += exonList[ii]; } } result.push_back(transcript); } return result; } void generateReads(uint numberReads, uint referencesNumber=1, const string& outFileName="simulatedReads.fa", const string& refFileName="RefFile"){ ofstream out(outFileName); ofstream outRef(refFileName); vector<vector<string>> referenceList; for(uint i(0);i < referencesNumber; ++i){ referenceList.push_back(generateAlternativeTranscriptReferences()); for(uint ii(0); ii<referenceList[i].size(); ++ii){ outRef << ">referenceNumber:" << i << " alternativeNumber" << ii << " length"<< referenceList[i][ii].size() << endl; outRef << referenceList[i][ii] << endl; } } string refRead,realRead; for(uint i(0); i < numberReads; ++i){ uint dice1(rand() % referencesNumber); uint dice2(rand() % referenceList[dice1].size()); refRead = referenceList[dice1][dice2]; realRead = mutateSequence(refRead); out << ">referenceNumber:" << dice1 << " alternativeNumber" << dice2 << " length" << realRead.size() << endl; out << realRead << endl; } } int main(int argc, char ** argv){ srand (time(NULL)); auto startChrono = chrono::system_clock::now(); generateReads(100); auto end = chrono::system_clock::now(); auto waitedFor = end - startChrono; cout << "Time in ms : " << (chrono::duration_cast<chrono::milliseconds>(waitedFor).count()) << endl; return 0; } <commit_msg>some parameters as inputs of the tool<commit_after>#include <iostream> #include <fstream> #include <vector> #include <string> #include <iterator> #include <ctime> #include <unordered_map> #include <algorithm> #include <cmath> #include <chrono> #include <iostream> #include <fstream> #include <string> #include <iterator> #include <unordered_map> #include <unordered_set> #include <set> #include <algorithm> #include <chrono> #include <map> #include <set> #include <ctype.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> using namespace std; char randomNucleotide(){ switch (rand() % 4){ case 0: return 'A'; case 1: return 'C'; case 2: return 'G'; case 3: return 'T'; } return 'A'; } string randomSequence(const uint length){ string result(length, 'A'); for(uint i(0); i < length; ++i){ result[i] = randomNucleotide(); } return result; } void insertion(uint rate, string& result){ uint dice(rand() % 100); if(dice < rate){ char newNucleotide(randomNucleotide()); result.push_back(newNucleotide); insertion(rate, result); } } string mutateSequence(const string& referenceSequence, uint maxMutRate, vector <double> ratioMutation={0.06,0.73,0.21}){ //~ string mutateSequence(const string& referenceSequence, uint maxMutRate=3, vector <double> ratioMutation={0.06,0.73,0.21}){ string result; result.reserve(5 * referenceSequence.size()); for(uint i(0); i < referenceSequence.size(); ++i){ uint mutRate(maxMutRate); //~ uint mutRate(rand() % maxMutRate); double substitutionRate(mutRate * ratioMutation[0]); double insertionRate(mutRate * ratioMutation[1]); double deletionRate(mutRate * ratioMutation[2]); uint dice(rand() % 100); if (dice <substitutionRate ){ //SUBSTITUTION char newNucleotide(randomNucleotide()); while(newNucleotide == referenceSequence[i]){ newNucleotide = randomNucleotide(); } result.push_back(newNucleotide); continue; } else if(dice < deletionRate+substitutionRate){ //DELETION uint dice2(rand() % 100); while (dice2 < deletionRate+substitutionRate){ // deletions larger than 1 ++i; dice2 = rand() % 100; } continue; } else if (dice < deletionRate + substitutionRate + insertionRate){ //INSERTION char newNucleotide(randomNucleotide()); result.push_back(referenceSequence[i]); result.push_back(newNucleotide); //~ --i; insertion(deletionRate + substitutionRate + insertionRate, result); // larger than 1 insertions continue; } else { //NO ERROR result.push_back(referenceSequence[i]); } } return result; } vector<string> generateAlternativeTranscriptReferences(uint transcriptNumber=3, uint totalExonNumber=15, uint exonNumber=12, uint sizeExons=200){ vector<string> result; vector<string> exonList; for(uint i(0); i < totalExonNumber; ++i){ exonList.push_back(randomSequence(sizeExons)); } string transcript; transcript.reserve(exonNumber*sizeExons); unordered_set<uint> selectedExons; uint dice1, transcriptExonNumber; for(uint i(0); i < transcriptNumber; ++i){ if (transcriptNumber > 1){ dice1 = (rand() % (totalExonNumber-3)); transcriptExonNumber = (dice1 + 3); } else { transcriptExonNumber = 0; } cout << transcriptExonNumber << endl; transcript = ""; selectedExons = {}; if (transcriptExonNumber > 0){ while(selectedExons.size() != transcriptExonNumber){ selectedExons.insert(rand() % totalExonNumber); } } else { selectedExons.insert(0); } for(uint ii(0); ii < totalExonNumber; ++ii){ if(selectedExons.count(ii) == 1){ transcript += exonList[ii]; } } result.push_back(transcript); } return result; } void generateReads(uint numberReads, uint mutRate, uint referencesNumber, const string& outFileName="simulatedReads.fa", const string& refFileName="RefFile"){ ofstream out(outFileName); ofstream outRef(refFileName); vector<vector<string>> referenceList; for(uint i(0);i < referencesNumber; ++i){ referenceList.push_back(generateAlternativeTranscriptReferences()); for(uint ii(0); ii<referenceList[i].size(); ++ii){ outRef << ">referenceNumber:" << i << " alternativeNumber" << ii << " length"<< referenceList[i][ii].size() << endl; outRef << referenceList[i][ii] << endl; } } string refRead,realRead; for(uint i(0); i < numberReads; ++i){ uint dice1(rand() % referencesNumber); uint dice2(rand() % referenceList[dice1].size()); refRead = referenceList[dice1][dice2]; realRead = mutateSequence(refRead, mutRate); out << ">referenceNumber:" << dice1 << " alternativeNumber" << dice2 << " length" << realRead.size() << endl; out << realRead << endl; } } int main(int argc, char ** argv){ srand (time(NULL)); if (argc > 3){ auto startChrono = chrono::system_clock::now(); uint nbReads(stoi(argv[1])); uint mut(stoi(argv[2])); uint genes(stoi(argv[3])); generateReads(nbReads, mut, genes); auto end = chrono::system_clock::now(); auto waitedFor = end - startChrono; cout << "Time in ms : " << (chrono::duration_cast<chrono::milliseconds>(waitedFor).count()) << endl; } return 0; } <|endoftext|>
<commit_before>#include <iostream> #include <cstdlib> #include <string> #include "alphabet.h" using namespace std; string pwd; static const unsigned char MaxChars = 20; void checkPassword(string password) { cout << "checking " << password << endl; // TODO: generate sha hash, compare hashes if (password==pwd) { cout << "match [" << password << "]" << endl; exit(0); } } void brute(string baseString, int width, int position) { for(int i=0; i<SizeAlphabet; i++) { if (position+1 < width) { brute(baseString+alphabet[i], width, position+1); } checkPassword(baseString+alphabet[i]); } } int main() { cout << "Enter a string: " << endl; cin >> pwd; for(int i=1; i<=MaxChars; i++) { cout << "checking passwords with " << i << " characters..." << endl; brute(string(""),i,0); } return 1; } <commit_msg>rename main() to bruteInit()<commit_after>#include <iostream> #include <cstdlib> #include <string> #include "alphabet.h" using namespace std; string pwd; static const unsigned char MaxChars = 20; void checkPassword(string password) { cout << "checking " << password << endl; // TODO: generate sha hash, compare hashes if (password==pwd) { cout << "match [" << password << "]" << endl; exit(0); } } void brute(string baseString, int width, int position) { for(int i=0; i<SizeAlphabet; i++) { if (position+1 < width) { brute(baseString+alphabet[i], width, position+1); } checkPassword(baseString+alphabet[i]); } } int bruteInit() { cout << "Enter a string: " << endl; cin >> pwd; for(int i=1; i<=MaxChars; i++) { cout << "checking passwords with " << i << " characters..." << endl; brute(string(""),i,0); } return 1; } <|endoftext|>
<commit_before>#include "dsa_common.h" #include "link.h" #include <util/string.h> #include <boost/filesystem.hpp> #include <boost/program_options.hpp> #include <fstream> #include <regex> #include "core/client.h" #include "crypto/ecdh.h" #include "module/default/console_logger.h" #include "module/default/dummy_stream_acceptor.h" #include "module/default/simple_security_manager.h" #include "module/default/simple_session_manager.h" #include "network/tcp/stcp_client_connection.h" #include "network/tcp/tcp_client_connection.h" #include "network/tcp/tcp_server.h" #include "network/ws/ws_client_connection.h" #include "node/link_root.h" #include "stream/requester/incoming_invoke_stream.h" #include "stream/requester/incoming_set_stream.h" #include "util/app.h" #include "util/string.h" namespace opts = boost::program_options; namespace fs = boost::filesystem; namespace dsa { DsLink::DsLink(int argc, const char *argv[], const string_ &link_name, const string_ &version, const shared_ptr_<App> &app) { opts::options_description desc{"Options"}; desc.add_options()("help,h", "Help screen") // ("broker,b", opts::value<string_>()->default_value("127.0.0.1"), "Broker Url") // broker url ("log,l", opts::value<string_>()->default_value("info"), "Log Level [all,trace,debug,info,warn,error,fatal,none]") // log level ("token,t", opts::value<string_>()->default_value(""), "Token file path") // token ("thread", opts::value<size_t>()->default_value(1), "Number of thread") // custom name ("name,n", opts::value<string_>()->default_value(link_name), "Override Link Name") // custom name ("server-port", opts::value<uint16_t>()->default_value(0), "Tcp Server Port") // custom name ; opts::variables_map variables; try { opts::store(opts::parse_command_line(argc, argv, desc), variables); opts::notify(variables); } catch (std::exception &e) { LOG_FATAL( LOG << "Invalid input, please check available parameters with --help\n"); } // show help and exit if (variables.count("help")) { std::cout << desc << '\n'; exit(0); } own_app = false; _app = app; // If app object is already given, thread option is ignored in args if (_app.get() == nullptr) { parse_thread(variables["thread"].as<size_t>()); own_app = true; } strand.reset(new EditableStrand( get_app().new_strand(), std::unique_ptr<ECDH>(ECDH::from_file(".key")))); // TOKEN from file client_token = ""; auto client_token_path = variables["token"].as<string_>(); if (client_token_path.length() != 0) { try { client_token = string_from_file(client_token_path); } catch (std::exception &e) { LOG_FATAL(LOG << "Fatal loading token file " << client_token_path << " with error : " << e.what()); } } close_token = get_close_token_from_file(); parse_url(variables["broker"].as<string_>()); parse_name(variables["name"].as<string_>()); parse_log(variables["log"].as<string_>(), *strand); parse_server_port(variables["server-port"].as<uint16_t>()); LOG_TRACE(strand.get()->logger(), LOG << "DSLink initialized successfully"); } DsLink::~DsLink() {} App &DsLink::get_app() { return *_app; } void DsLink::destroy_impl() { // shared_ptr_<App> _app; // shared_ptr_<TcpServer> _tcp_server; // ref_<Client> _client; // // bool _running = false; // // OnConnectCallback _user_on_connect; if (_tcp_server != nullptr) { _tcp_server->destroy(); _tcp_server.reset(); } if (_client) { _client->destroy(); _client.reset(); } // child remove itself from array while (!_subscribe_mergers.empty()) { // If you dont create lvalue from it // gets heap usage after free error because // reference count drops zero in destroy auto p = _subscribe_mergers.begin()->second; p->destroy(); } // child remove itself from array while (!_list_mergers.empty()) { // If you dont create lvalue from it // gets heap usage after free error because // reference count drops zero in destroy auto p = _list_mergers.begin()->second; p->destroy(); } WrapperStrand::destroy_impl(); if (own_app) { _app->close(); } } void DsLink::parse_thread(size_t thread) { if (thread < 1) { thread = 1; } else if (thread > 16) { thread = 16; } _app.reset(new App(thread)); } void DsLink::parse_url(const string_ &url) { static std::regex url_regex( R"(^(ds://|dss://|ws://|wss://)?([^/:\[]+|\[[0-9A-Fa-f:]+\])(:\d+)?(/.*)?$)"); auto match = std::sregex_iterator(url.begin(), url.end(), url_regex); if (match == std::sregex_iterator()) { // match is a empty iterator LOG_FATAL(LOG << "Invalid Broker Url: " << url); } string_ protocol = (*match)[1].str(); if (protocol == "ws://" || protocol == "wss://") { if (protocol == "wss://") { secure = true; ws_port = 443; // default wss port } else { ws_port = 80; // default ws port } ws_host = (*match)[2].str(); if ((*match)[3].length() > 1) { ws_port = static_cast<uint16_t>( std::stoi(string_((*match)[3].first + 1, (*match)[3].second))); } ws_path = (*match)[4].str(); } else { if (protocol == "dss://") { secure = true; tcp_port = 4128; // default dss port } else { // "ds://" or blank tcp_port = 4120; // default ds port } tcp_host = (*match)[2].str(); if ((*match)[3].length() > 1) { tcp_port = static_cast<uint16_t>( std::stoi(string_((*match)[3].first + 1, (*match)[3].second))); } } } void DsLink::parse_log(const string_ &log, EditableStrand &config) { auto logger = std::unique_ptr<Logger>(new ConsoleLogger()); logger->level = Logger::parse(log); config.set_logger(std::move(logger)); } void DsLink::parse_name(const string_ &name) { dsid_prefix = name; } void DsLink::parse_server_port(uint16_t port) { tcp_server_port = port; } void DsLink::init_responder_raw(ref_<NodeModelBase> &&root_node) { strand->set_session_manager(make_ref_<SimpleSessionManager>(strand)); strand->set_security_manager(make_ref_<SimpleSecurityManager>()); strand->set_responder_model(std::move(root_node)); } void DsLink::init_responder(ref_<NodeModelBase> &&main_node) { _root = make_ref_<LinkRoot>(strand->get_ref(), get_ref()); if (main_node != nullptr) { _root->set_main(std::move(main_node)); } init_responder_raw(_root->get_ref()); } ref_<NodeModelBase> DsLink::add_to_main_node(const string_ &name, ref_<NodeModel> &&node) { return std::move(_root->add_to_main(name, std::move(node))); } void DsLink::remove_from_main_node(const string_ &name) { _root->remove_from_main(name); } void DsLink::connect(Client::OnConnectCallback &&on_connect, uint8_t callback_type) { if (_connected) { LOG_FATAL( LOG << "DsLink::connect(), Dslink is already requested for connection"); return; } _connected = true; strand->dispatch([ =, on_connect = std::move(on_connect) ]() mutable { if (tcp_server_port > 0) { _tcp_server = make_shared_<TcpServer>(*this); _tcp_server->start(); } if (tcp_port > 0) { if (secure) { static boost::asio::ssl::context context( boost::asio::ssl::context::sslv23); boost::system::error_code error; context.load_verify_file("certificate.pem", error); if (error) { LOG_FATAL(LOG << "Failed to verify cetificate"); } client_connection_maker = [ &context, dsid_prefix = dsid_prefix, tcp_host = tcp_host, tcp_port = tcp_port ](LinkStrandRef & strand, const string_ &previous_session_id, int32_t last_ack_id) { return make_shared_<StcpClientConnection>( strand, context, dsid_prefix, tcp_host, tcp_port); }; } else { client_connection_maker = [ dsid_prefix = dsid_prefix, tcp_host = tcp_host, tcp_port = tcp_port ](LinkStrandRef & strand, const string_ &previous_session_id, int32_t last_ack_id) { return make_shared_<TcpClientConnection>(strand, dsid_prefix, tcp_host, tcp_port); }; } } else if (ws_port > 0) { client_connection_maker = [ dsid_prefix = dsid_prefix, ws_host = ws_host, ws_port = ws_port ]( LinkStrandRef & strand, const string_ &previous_session_id, int32_t last_ack_id) { return make_shared_<WsClientConnection>(strand, dsid_prefix, ws_host, ws_port); }; } _client = make_ref_<Client>(*this); _client->connect(std::move(on_connect), callback_type); LOG_SYSTEM(strand.get()->logger(), LOG << "DsLink connection requested"); }); } void DsLink::run(Client::OnConnectCallback &&on_connect, uint8_t callback_type) { if (_running) { LOG_FATAL(LOG << "DsLink::run(), Dslink is already running"); return; } _running = true; if (!strand->is_responder_set()) { LOG_WARN(strand->logger(), LOG << "responder is not initialized"); _client->get_session().responder_enabled = false; strand->set_stream_acceptor(make_ref_<DummyStreamAcceptor>()); } if (!_connected) { connect(std::move(on_connect), callback_type); } else { LOG_SYSTEM(strand.get()->logger(), LOG << "DsLink on_connect callback " "ignored since it was connected " "before\n"); } LOG_SYSTEM(strand.get()->logger(), LOG << "DsLink running"); if (own_app) { _app->wait(); destroy(); } } // requester features ref_<IncomingSubscribeCache> DsLink::subscribe( const string_ &path, IncomingSubscribeCache::Callback &&callback, const SubscribeOptions &options) { if (_subscribe_mergers.count(path) == 0) { _subscribe_mergers[path] = make_ref_<SubscribeMerger>(get_ref(), path); } auto merger = _subscribe_mergers[path]; return merger->subscribe(std::move(callback), options); } ref_<IncomingListCache> DsLink::list(const string_ &path, IncomingListCache::Callback &&callback) { if (_list_mergers.count(path) == 0) { _list_mergers[path] = make_ref_<ListMerger>(get_ref(), path); } auto merger = _list_mergers[path]; return merger->list(std::move(callback)); } ref_<IncomingInvokeStream> DsLink::invoke( IncomingInvokeStreamCallback &&callback, ref_<const InvokeRequestMessage> &&message) { return _client->get_session().requester.invoke(std::move(callback), std::move(message)); } ref_<IncomingSetStream> DsLink::set(IncomingSetStreamCallback &&callback, ref_<const SetRequestMessage> &&message) { return _client->get_session().requester.set(std::move(callback), std::move(message)); } string_ DsLink::get_close_token() { return close_token; } } <commit_msg>fix VS compilation error<commit_after>#include "dsa_common.h" #include "link.h" #include <util/string.h> #include <boost/filesystem.hpp> #include <boost/program_options.hpp> #include <fstream> #include <regex> #include "core/client.h" #include "crypto/ecdh.h" #include "module/default/console_logger.h" #include "module/default/dummy_stream_acceptor.h" #include "module/default/simple_security_manager.h" #include "module/default/simple_session_manager.h" #include "network/tcp/stcp_client_connection.h" #include "network/tcp/tcp_client_connection.h" #include "network/tcp/tcp_server.h" #include "network/ws/ws_client_connection.h" #include "node/link_root.h" #include "stream/requester/incoming_invoke_stream.h" #include "stream/requester/incoming_set_stream.h" #include "util/app.h" #include "util/string.h" namespace opts = boost::program_options; namespace fs = boost::filesystem; namespace dsa { DsLink::DsLink(int argc, const char *argv[], const string_ &link_name, const string_ &version, const shared_ptr_<App> &app) { opts::options_description desc{"Options"}; desc.add_options()("help,h", "Help screen") // ("broker,b", opts::value<string_>()->default_value("127.0.0.1"), "Broker Url") // broker url ("log,l", opts::value<string_>()->default_value("info"), "Log Level [all,trace,debug,info,warn,error,fatal,none]") // log level ("token,t", opts::value<string_>()->default_value(""), "Token file path") // token ("thread", opts::value<size_t>()->default_value(1), "Number of thread") // custom name ("name,n", opts::value<string_>()->default_value(link_name), "Override Link Name") // custom name ("server-port", opts::value<uint16_t>()->default_value(0), "Tcp Server Port") // custom name ; opts::variables_map variables; try { opts::store(opts::parse_command_line(argc, argv, desc), variables); opts::notify(variables); } catch (std::exception &e) { LOG_FATAL( LOG << "Invalid input, please check available parameters with --help\n"); } // show help and exit if (variables.count("help")) { std::cout << desc << '\n'; exit(0); } own_app = false; _app = app; // If app object is already given, thread option is ignored in args if (_app.get() == nullptr) { parse_thread(variables["thread"].as<size_t>()); own_app = true; } strand.reset(new EditableStrand( get_app().new_strand(), std::unique_ptr<ECDH>(ECDH::from_file(".key")))); // TOKEN from file client_token = ""; auto client_token_path = variables["token"].as<string_>(); if (client_token_path.length() != 0) { try { client_token = string_from_file(client_token_path); } catch (std::exception &e) { LOG_FATAL(LOG << "Fatal loading token file " << client_token_path << " with error : " << e.what()); } } close_token = get_close_token_from_file(); parse_url(variables["broker"].as<string_>()); parse_name(variables["name"].as<string_>()); parse_log(variables["log"].as<string_>(), *strand); parse_server_port(variables["server-port"].as<uint16_t>()); LOG_TRACE(strand.get()->logger(), LOG << "DSLink initialized successfully"); } DsLink::~DsLink() {} App &DsLink::get_app() { return *_app; } void DsLink::destroy_impl() { // shared_ptr_<App> _app; // shared_ptr_<TcpServer> _tcp_server; // ref_<Client> _client; // // bool _running = false; // // OnConnectCallback _user_on_connect; if (_tcp_server != nullptr) { _tcp_server->destroy(); _tcp_server.reset(); } if (_client) { _client->destroy(); _client.reset(); } // child remove itself from array while (!_subscribe_mergers.empty()) { // If you dont create lvalue from it // gets heap usage after free error because // reference count drops zero in destroy auto p = _subscribe_mergers.begin()->second; p->destroy(); } // child remove itself from array while (!_list_mergers.empty()) { // If you dont create lvalue from it // gets heap usage after free error because // reference count drops zero in destroy auto p = _list_mergers.begin()->second; p->destroy(); } WrapperStrand::destroy_impl(); if (own_app) { _app->close(); } } void DsLink::parse_thread(size_t thread) { if (thread < 1) { thread = 1; } else if (thread > 16) { thread = 16; } _app.reset(new App(thread)); } void DsLink::parse_url(const string_ &url) { static std::regex url_regex( R"(^(ds://|dss://|ws://|wss://)?([^/:\[]+|\[[0-9A-Fa-f:]+\])(:\d+)?(/.*)?$)"); auto match = std::sregex_iterator(url.begin(), url.end(), url_regex); if (match == std::sregex_iterator()) { // match is a empty iterator LOG_FATAL(LOG << "Invalid Broker Url: " << url); } string_ protocol = (*match)[1].str(); if (protocol == "ws://" || protocol == "wss://") { if (protocol == "wss://") { secure = true; ws_port = 443; // default wss port } else { ws_port = 80; // default ws port } ws_host = (*match)[2].str(); if ((*match)[3].length() > 1) { ws_port = static_cast<uint16_t>( std::stoi(string_((*match)[3].first + 1, (*match)[3].second))); } ws_path = (*match)[4].str(); } else { if (protocol == "dss://") { secure = true; tcp_port = 4128; // default dss port } else { // "ds://" or blank tcp_port = 4120; // default ds port } tcp_host = (*match)[2].str(); if ((*match)[3].length() > 1) { tcp_port = static_cast<uint16_t>( std::stoi(string_((*match)[3].first + 1, (*match)[3].second))); } } } void DsLink::parse_log(const string_ &log, EditableStrand &config) { auto logger = std::unique_ptr<Logger>(new ConsoleLogger()); logger->level = Logger::parse(log); config.set_logger(std::move(logger)); } void DsLink::parse_name(const string_ &name) { dsid_prefix = name; } void DsLink::parse_server_port(uint16_t port) { tcp_server_port = port; } void DsLink::init_responder_raw(ref_<NodeModelBase> &&root_node) { strand->set_session_manager(make_ref_<SimpleSessionManager>(strand)); strand->set_security_manager(make_ref_<SimpleSecurityManager>()); strand->set_responder_model(std::move(root_node)); } void DsLink::init_responder(ref_<NodeModelBase> &&main_node) { _root = make_ref_<LinkRoot>(strand->get_ref(), get_ref()); if (main_node != nullptr) { _root->set_main(std::move(main_node)); } init_responder_raw(_root->get_ref()); } ref_<NodeModelBase> DsLink::add_to_main_node(const string_ &name, ref_<NodeModel> &&node) { return std::move(_root->add_to_main(name, std::move(node))); } void DsLink::remove_from_main_node(const string_ &name) { _root->remove_from_main(name); } void DsLink::connect(Client::OnConnectCallback &&on_connect, uint8_t callback_type) { if (_connected) { LOG_FATAL( LOG << "DsLink::connect(), Dslink is already requested for connection"); return; } _connected = true; strand->dispatch([ =, on_connect = std::move(on_connect) ]() mutable { if (tcp_server_port > 0) { _tcp_server = make_shared_<TcpServer>(*this); _tcp_server->start(); } if (tcp_port > 0) { if (secure) { static boost::asio::ssl::context context( boost::asio::ssl::context::sslv23); boost::system::error_code error; context.load_verify_file("certificate.pem", error); if (error) { LOG_FATAL(LOG << "Failed to verify cetificate"); } client_connection_maker = [ dsid_prefix = dsid_prefix, tcp_host = tcp_host, tcp_port = tcp_port ](LinkStrandRef & strand, const string_ &previous_session_id, int32_t last_ack_id) { return make_shared_<StcpClientConnection>( strand, context, dsid_prefix, tcp_host, tcp_port); }; } else { client_connection_maker = [ dsid_prefix = dsid_prefix, tcp_host = tcp_host, tcp_port = tcp_port ](LinkStrandRef & strand, const string_ &previous_session_id, int32_t last_ack_id) { return make_shared_<TcpClientConnection>(strand, dsid_prefix, tcp_host, tcp_port); }; } } else if (ws_port > 0) { client_connection_maker = [ dsid_prefix = dsid_prefix, ws_host = ws_host, ws_port = ws_port ]( LinkStrandRef & strand, const string_ &previous_session_id, int32_t last_ack_id) { return make_shared_<WsClientConnection>(strand, dsid_prefix, ws_host, ws_port); }; } _client = make_ref_<Client>(*this); _client->connect(std::move(on_connect), callback_type); LOG_SYSTEM(strand.get()->logger(), LOG << "DsLink connection requested"); }); } void DsLink::run(Client::OnConnectCallback &&on_connect, uint8_t callback_type) { if (_running) { LOG_FATAL(LOG << "DsLink::run(), Dslink is already running"); return; } _running = true; if (!strand->is_responder_set()) { LOG_WARN(strand->logger(), LOG << "responder is not initialized"); _client->get_session().responder_enabled = false; strand->set_stream_acceptor(make_ref_<DummyStreamAcceptor>()); } if (!_connected) { connect(std::move(on_connect), callback_type); } else { LOG_SYSTEM(strand.get()->logger(), LOG << "DsLink on_connect callback " "ignored since it was connected " "before\n"); } LOG_SYSTEM(strand.get()->logger(), LOG << "DsLink running"); if (own_app) { _app->wait(); destroy(); } } // requester features ref_<IncomingSubscribeCache> DsLink::subscribe( const string_ &path, IncomingSubscribeCache::Callback &&callback, const SubscribeOptions &options) { if (_subscribe_mergers.count(path) == 0) { _subscribe_mergers[path] = make_ref_<SubscribeMerger>(get_ref(), path); } auto merger = _subscribe_mergers[path]; return merger->subscribe(std::move(callback), options); } ref_<IncomingListCache> DsLink::list(const string_ &path, IncomingListCache::Callback &&callback) { if (_list_mergers.count(path) == 0) { _list_mergers[path] = make_ref_<ListMerger>(get_ref(), path); } auto merger = _list_mergers[path]; return merger->list(std::move(callback)); } ref_<IncomingInvokeStream> DsLink::invoke( IncomingInvokeStreamCallback &&callback, ref_<const InvokeRequestMessage> &&message) { return _client->get_session().requester.invoke(std::move(callback), std::move(message)); } ref_<IncomingSetStream> DsLink::set(IncomingSetStreamCallback &&callback, ref_<const SetRequestMessage> &&message) { return _client->get_session().requester.set(std::move(callback), std::move(message)); } string_ DsLink::get_close_token() { return close_token; } } <|endoftext|>
<commit_before>#include "mysql.h" #include <mysql/mysql.h> #include <cstring> #include <iostream> #include <stdexcept> // Prepared statement templates const char *query_add_snapshot = "INSERT INTO snapshot(reason) VALUES (?);"; const char *query_add_reason_malloc = "INSERT INTO reason_malloc(snapshot_id, address, size)" " VALUES(?, ?, ?);"; const char *query_add_reason_free = "INSERT INTO reason_free(snapshot_id, address) VALUES (?, ?);"; const char *query_add_reason_calloc = "INSERT INTO reason_calloc(snapshot_id, address, member, size)" " VALUES (?, ?, ?, ?);"; const char *query_add_reason_realloc = "INSERT INTO reason_realloc(snapshot_id, old_address, new_address, size)" " VALUES (?, ?, ?, ?);"; const char *query_add_memory_write = "INSERT INTO memory_write(snapshot_id, address, value) VALUES (?, ?, ?);"; const char *query_create_new_block = "INSERT INTO block(alloc_snapshot_id, address, size) VALUES (?, ?, ?);"; const char *query_free_block = "UPDATE block SET free_snapshot_id = ? WHERE address = ?" " AND free_snapshot_id = NULL"; // Raise an exception in the case of an error void fatal_error(MYSQL *db, int line) { std::cerr << "[FATAL] MySQL error at " << line << ": " << mysql_error(db) << std::endl; throw std::runtime_error(mysql_error(db)); } MySQL::MySQL( const char *host, const char *user, const char *password, const char *db) { // Init mysql if (mysql_library_init(0, NULL, NULL)) { std::cerr << "[FATAL] mysql_library_init failed" << std::endl; throw std::runtime_error("mysql_library_init failed"); } db_ = mysql_init(NULL); if (!mysql_real_connect(db_, host, user, password, db, 0, NULL, 0)) fatal_error(db_, __LINE__); // Initialize prepared statements add_snapshot_ = mysql_stmt_init(db_); add_reason_malloc_ = mysql_stmt_init(db_); add_reason_free_ = mysql_stmt_init(db_); add_reason_calloc_ = mysql_stmt_init(db_); add_reason_realloc_ = mysql_stmt_init(db_); add_memory_write_ = mysql_stmt_init(db_); create_new_block_ = mysql_stmt_init(db_); free_block_ = mysql_stmt_init(db_); if(!add_snapshot_ || mysql_stmt_prepare( add_snapshot_, query_add_snapshot, strlen(query_add_snapshot))) fatal_error(db_, __LINE__); if(!add_reason_malloc_ || mysql_stmt_prepare( add_reason_malloc_, query_add_reason_malloc, strlen(query_add_reason_malloc))) fatal_error(db_, __LINE__); if(!add_reason_free_ || mysql_stmt_prepare( add_reason_free_, query_add_reason_free, strlen(query_add_reason_free))) fatal_error(db_, __LINE__); if(!add_reason_calloc_ || mysql_stmt_prepare( add_reason_calloc_, query_add_reason_calloc, strlen(query_add_reason_calloc))) fatal_error(db_, __LINE__); if(!add_reason_realloc_ || mysql_stmt_prepare( add_reason_realloc_, query_add_reason_realloc, strlen(query_add_reason_realloc))) fatal_error(db_, __LINE__); if(!add_memory_write_ || mysql_stmt_prepare( add_memory_write_, query_add_memory_write, strlen(query_add_memory_write))) fatal_error(db_, __LINE__); if(!create_new_block_ || mysql_stmt_prepare( create_new_block_, query_create_new_block, strlen(query_create_new_block))) fatal_error(db_, __LINE__); if(!free_block_ || mysql_stmt_prepare( free_block_, query_free_block, strlen(query_free_block))) fatal_error(db_, __LINE__); } MySQL::~MySQL() { mysql_close(db_); mysql_stmt_close(add_snapshot_); mysql_stmt_close(add_reason_malloc_); mysql_stmt_close(add_reason_free_); mysql_stmt_close(add_reason_calloc_); mysql_stmt_close(add_reason_realloc_); mysql_stmt_close(add_memory_write_); } snapshot_t MySQL::addSnapshot(snapshot_reason::type_t type) { MYSQL_BIND bind; memset(&bind, 0, sizeof(MYSQL_BIND)); bind.buffer_type = MYSQL_TYPE_TINY; bind.buffer = (char*) &type; bind.buffer_length = sizeof(type); if (mysql_stmt_bind_param(add_snapshot_, &bind) || mysql_stmt_execute(add_snapshot_)) fatal_error(db_, __LINE__); return mysql_insert_id(db_); } void MySQL::addReasonMalloc(snapshot_t snapshot_id, void *mem, size_t size) { MYSQL_BIND bind[3]; memset(&bind, 0, sizeof(MYSQL_BIND)*3); // snapshot ID bind[0].buffer_type = MYSQL_TYPE_LONG; bind[0].buffer = &snapshot_id; bind[0].buffer_length = sizeof(snapshot_t); // memory pointer bind[1].buffer_type = MYSQL_TYPE_LONGLONG; bind[1].buffer = &mem; bind[1].buffer_length = sizeof(void*); // size bind[2].buffer_type = MYSQL_TYPE_LONG; bind[2].buffer = &size; bind[2].buffer_length = sizeof(size_t); if (mysql_stmt_bind_param(add_reason_malloc_, bind) || mysql_stmt_execute(add_reason_malloc_)) fatal_error(db_, __LINE__); // Create new block createNewBlock(snapshot_id, mem, size); } void MySQL::addReasonFree(snapshot_t snapshot_id, void *mem) { MYSQL_BIND bind[2]; memset(&bind, 0, sizeof(MYSQL_BIND)*2); // snapshot ID bind[0].buffer_type = MYSQL_TYPE_LONG; bind[0].buffer = &snapshot_id; bind[0].buffer_length = sizeof(snapshot_t); // memory pointer bind[1].buffer_type = MYSQL_TYPE_LONGLONG; bind[1].buffer = &mem; bind[1].buffer_length = sizeof(void*); if (mysql_stmt_bind_param(add_reason_free_, bind) || mysql_stmt_execute(add_reason_free_)) fatal_error(db_, __LINE__); // Free block if(mem) freeBlock(snapshot_id, mem); } void MySQL::addReasonCalloc( snapshot_t snapshot_id, void *mem, size_t nmemb, size_t size) { MYSQL_BIND bind[4]; memset(&bind, 0, sizeof(MYSQL_BIND)*4); // snapshot ID bind[0].buffer_type = MYSQL_TYPE_LONG; bind[0].buffer = &snapshot_id; bind[0].buffer_length = sizeof(snapshot_t); // memory pointer bind[1].buffer_type = MYSQL_TYPE_LONGLONG; bind[1].buffer = &mem; bind[1].buffer_length = sizeof(void*); // nmemb bind[2].buffer_type = MYSQL_TYPE_LONG; bind[2].buffer = &nmemb; bind[2].buffer_length = sizeof(size_t); // size bind[3].buffer_type = MYSQL_TYPE_LONG; bind[3].buffer = &size; bind[3].buffer_length = sizeof(size_t); if (mysql_stmt_bind_param(add_reason_calloc_, bind) || mysql_stmt_execute(add_reason_calloc_)) fatal_error(db_, __LINE__); // Create new block createNewBlock(snapshot_id, mem, nmemb * size); } void MySQL::addReasonRealloc( snapshot_t snapshot_id, void *old_mem, void *new_mem, size_t new_size) { MYSQL_BIND bind[4]; memset(&bind, 0, sizeof(MYSQL_BIND)*4); // snapshot ID bind[0].buffer_type = MYSQL_TYPE_LONG; bind[0].buffer = &snapshot_id; bind[0].buffer_length = sizeof(snapshot_t); // memory pointer bind[1].buffer_type = MYSQL_TYPE_LONGLONG; bind[1].buffer = &old_mem; bind[1].buffer_length = sizeof(void*); // nmemb bind[2].buffer_type = MYSQL_TYPE_LONGLONG; bind[2].buffer = &new_mem; bind[2].buffer_length = sizeof(void*); // size bind[3].buffer_type = MYSQL_TYPE_LONG; bind[3].buffer = &new_size; bind[3].buffer_length = sizeof(size_t); if (mysql_stmt_bind_param(add_reason_realloc_, bind) || mysql_stmt_execute(add_reason_realloc_)) fatal_error(db_, __LINE__); // Realloc has a special logic. If new_size is equal to zero, a free // is performed. // If old_mem is equal to zero, a malloc is performed. if (!new_size && old_mem) { freeBlock(snapshot_id, old_mem); } else if (new_size && !old_mem) { createNewBlock(snapshot_id, new_mem, new_size); } else { freeBlock(snapshot_id, old_mem); createNewBlock(snapshot_id, new_mem, new_size); } } void MySQL::addMemoryWrites( snapshot_t snapshot_id, const std::map<void *, unsigned char>& writes) { MYSQL_BIND bind[3]; char current_char; void* current_addr = NULL; memset(&bind, 0, sizeof(MYSQL_BIND)*3); // snapshot ID bind[0].buffer_type = MYSQL_TYPE_LONG; bind[0].buffer = &snapshot_id; bind[0].buffer_length = sizeof(snapshot_t); // address bind[1].buffer_type = MYSQL_TYPE_LONGLONG; bind[1].buffer = &current_addr; bind[1].buffer_length = sizeof(void*); // value bind[2].buffer_type = MYSQL_TYPE_BLOB; bind[2].buffer = &current_char; bind[2].buffer_length = 1; for (std::map<void *, unsigned char>::const_iterator it = writes.begin(); it != writes.end(); it++) { current_addr = it -> first; current_char = it -> second; if (mysql_stmt_bind_param(add_memory_write_, bind) || mysql_stmt_execute(add_memory_write_)) fatal_error(db_, __LINE__); } } void MySQL::createNewBlock(snapshot_t snapshot_id, void *address, size_t size) { MYSQL_BIND bind[3]; memset(&bind, 0, sizeof(MYSQL_BIND)*3); // snapshot ID bind[0].buffer_type = MYSQL_TYPE_LONG; bind[0].buffer = &snapshot_id; bind[0].buffer_length = sizeof(snapshot_t); // memory pointer bind[1].buffer_type = MYSQL_TYPE_LONGLONG; bind[1].buffer = &address; bind[1].buffer_length = sizeof(void*); // size bind[2].buffer_type = MYSQL_TYPE_LONG; bind[2].buffer = &size; bind[2].buffer_length = sizeof(size_t); if (mysql_stmt_bind_param(create_new_block_, bind) || mysql_stmt_execute(create_new_block_)) fatal_error(db_, __LINE__); } void MySQL::freeBlock(snapshot_t snapshot_id, void *address) { MYSQL_BIND bind[2]; memset(&bind, 0, sizeof(MYSQL_BIND)*2); // snapshot ID bind[0].buffer_type = MYSQL_TYPE_LONG; bind[0].buffer = &snapshot_id; bind[0].buffer_length = sizeof(snapshot_t); // memory pointer bind[1].buffer_type = MYSQL_TYPE_LONGLONG; bind[1].buffer = &address; bind[1].buffer_length = sizeof(void*); if (mysql_stmt_bind_param(free_block_, bind) || mysql_stmt_execute(free_block_)) fatal_error(db_, __LINE__); } <commit_msg>Fixed minor bug in MySQL query<commit_after>#include "mysql.h" #include <mysql/mysql.h> #include <cstring> #include <iostream> #include <stdexcept> // Prepared statement templates const char *query_add_snapshot = "INSERT INTO snapshot(reason) VALUES (?);"; const char *query_add_reason_malloc = "INSERT INTO reason_malloc(snapshot_id, address, size)" " VALUES(?, ?, ?);"; const char *query_add_reason_free = "INSERT INTO reason_free(snapshot_id, address) VALUES (?, ?);"; const char *query_add_reason_calloc = "INSERT INTO reason_calloc(snapshot_id, address, member, size)" " VALUES (?, ?, ?, ?);"; const char *query_add_reason_realloc = "INSERT INTO reason_realloc(snapshot_id, old_address, new_address, size)" " VALUES (?, ?, ?, ?);"; const char *query_add_memory_write = "INSERT INTO memory_write(snapshot_id, address, value) VALUES (?, ?, ?);"; const char *query_create_new_block = "INSERT INTO block(alloc_snapshot_id, address, size) VALUES (?, ?, ?);"; const char *query_free_block = "UPDATE block SET free_snapshot_id = ? WHERE address = ?" " AND free_snapshot_id IS NULL;"; // Raise an exception in the case of an error void fatal_error(MYSQL *db, int line) { std::cerr << "[FATAL] MySQL error at " << line << ": " << mysql_error(db) << std::endl; throw std::runtime_error(mysql_error(db)); } MySQL::MySQL( const char *host, const char *user, const char *password, const char *db) { // Init mysql if (mysql_library_init(0, NULL, NULL)) { std::cerr << "[FATAL] mysql_library_init failed" << std::endl; throw std::runtime_error("mysql_library_init failed"); } db_ = mysql_init(NULL); if (!mysql_real_connect(db_, host, user, password, db, 0, NULL, 0)) fatal_error(db_, __LINE__); // Initialize prepared statements add_snapshot_ = mysql_stmt_init(db_); add_reason_malloc_ = mysql_stmt_init(db_); add_reason_free_ = mysql_stmt_init(db_); add_reason_calloc_ = mysql_stmt_init(db_); add_reason_realloc_ = mysql_stmt_init(db_); add_memory_write_ = mysql_stmt_init(db_); create_new_block_ = mysql_stmt_init(db_); free_block_ = mysql_stmt_init(db_); if(!add_snapshot_ || mysql_stmt_prepare( add_snapshot_, query_add_snapshot, strlen(query_add_snapshot))) fatal_error(db_, __LINE__); if(!add_reason_malloc_ || mysql_stmt_prepare( add_reason_malloc_, query_add_reason_malloc, strlen(query_add_reason_malloc))) fatal_error(db_, __LINE__); if(!add_reason_free_ || mysql_stmt_prepare( add_reason_free_, query_add_reason_free, strlen(query_add_reason_free))) fatal_error(db_, __LINE__); if(!add_reason_calloc_ || mysql_stmt_prepare( add_reason_calloc_, query_add_reason_calloc, strlen(query_add_reason_calloc))) fatal_error(db_, __LINE__); if(!add_reason_realloc_ || mysql_stmt_prepare( add_reason_realloc_, query_add_reason_realloc, strlen(query_add_reason_realloc))) fatal_error(db_, __LINE__); if(!add_memory_write_ || mysql_stmt_prepare( add_memory_write_, query_add_memory_write, strlen(query_add_memory_write))) fatal_error(db_, __LINE__); if(!create_new_block_ || mysql_stmt_prepare( create_new_block_, query_create_new_block, strlen(query_create_new_block))) fatal_error(db_, __LINE__); if(!free_block_ || mysql_stmt_prepare( free_block_, query_free_block, strlen(query_free_block))) fatal_error(db_, __LINE__); } MySQL::~MySQL() { mysql_close(db_); mysql_stmt_close(add_snapshot_); mysql_stmt_close(add_reason_malloc_); mysql_stmt_close(add_reason_free_); mysql_stmt_close(add_reason_calloc_); mysql_stmt_close(add_reason_realloc_); mysql_stmt_close(add_memory_write_); } snapshot_t MySQL::addSnapshot(snapshot_reason::type_t type) { MYSQL_BIND bind; memset(&bind, 0, sizeof(MYSQL_BIND)); bind.buffer_type = MYSQL_TYPE_TINY; bind.buffer = (char*) &type; bind.buffer_length = sizeof(type); if (mysql_stmt_bind_param(add_snapshot_, &bind) || mysql_stmt_execute(add_snapshot_)) fatal_error(db_, __LINE__); return mysql_insert_id(db_); } void MySQL::addReasonMalloc(snapshot_t snapshot_id, void *mem, size_t size) { MYSQL_BIND bind[3]; memset(&bind, 0, sizeof(MYSQL_BIND)*3); // snapshot ID bind[0].buffer_type = MYSQL_TYPE_LONG; bind[0].buffer = &snapshot_id; bind[0].buffer_length = sizeof(snapshot_t); // memory pointer bind[1].buffer_type = MYSQL_TYPE_LONGLONG; bind[1].buffer = &mem; bind[1].buffer_length = sizeof(void*); // size bind[2].buffer_type = MYSQL_TYPE_LONG; bind[2].buffer = &size; bind[2].buffer_length = sizeof(size_t); if (mysql_stmt_bind_param(add_reason_malloc_, bind) || mysql_stmt_execute(add_reason_malloc_)) fatal_error(db_, __LINE__); // Create new block createNewBlock(snapshot_id, mem, size); } void MySQL::addReasonFree(snapshot_t snapshot_id, void *mem) { MYSQL_BIND bind[2]; memset(&bind, 0, sizeof(MYSQL_BIND)*2); // snapshot ID bind[0].buffer_type = MYSQL_TYPE_LONG; bind[0].buffer = &snapshot_id; bind[0].buffer_length = sizeof(snapshot_t); // memory pointer bind[1].buffer_type = MYSQL_TYPE_LONGLONG; bind[1].buffer = &mem; bind[1].buffer_length = sizeof(void*); if (mysql_stmt_bind_param(add_reason_free_, bind) || mysql_stmt_execute(add_reason_free_)) fatal_error(db_, __LINE__); // Free block if(mem) freeBlock(snapshot_id, mem); } void MySQL::addReasonCalloc( snapshot_t snapshot_id, void *mem, size_t nmemb, size_t size) { MYSQL_BIND bind[4]; memset(&bind, 0, sizeof(MYSQL_BIND)*4); // snapshot ID bind[0].buffer_type = MYSQL_TYPE_LONG; bind[0].buffer = &snapshot_id; bind[0].buffer_length = sizeof(snapshot_t); // memory pointer bind[1].buffer_type = MYSQL_TYPE_LONGLONG; bind[1].buffer = &mem; bind[1].buffer_length = sizeof(void*); // nmemb bind[2].buffer_type = MYSQL_TYPE_LONG; bind[2].buffer = &nmemb; bind[2].buffer_length = sizeof(size_t); // size bind[3].buffer_type = MYSQL_TYPE_LONG; bind[3].buffer = &size; bind[3].buffer_length = sizeof(size_t); if (mysql_stmt_bind_param(add_reason_calloc_, bind) || mysql_stmt_execute(add_reason_calloc_)) fatal_error(db_, __LINE__); // Create new block createNewBlock(snapshot_id, mem, nmemb * size); } void MySQL::addReasonRealloc( snapshot_t snapshot_id, void *old_mem, void *new_mem, size_t new_size) { MYSQL_BIND bind[4]; memset(&bind, 0, sizeof(MYSQL_BIND)*4); // snapshot ID bind[0].buffer_type = MYSQL_TYPE_LONG; bind[0].buffer = &snapshot_id; bind[0].buffer_length = sizeof(snapshot_t); // memory pointer bind[1].buffer_type = MYSQL_TYPE_LONGLONG; bind[1].buffer = &old_mem; bind[1].buffer_length = sizeof(void*); // nmemb bind[2].buffer_type = MYSQL_TYPE_LONGLONG; bind[2].buffer = &new_mem; bind[2].buffer_length = sizeof(void*); // size bind[3].buffer_type = MYSQL_TYPE_LONG; bind[3].buffer = &new_size; bind[3].buffer_length = sizeof(size_t); if (mysql_stmt_bind_param(add_reason_realloc_, bind) || mysql_stmt_execute(add_reason_realloc_)) fatal_error(db_, __LINE__); // Realloc has a special logic. If new_size is equal to zero, a free // is performed. // If old_mem is equal to zero, a malloc is performed. if (!new_size && old_mem) { freeBlock(snapshot_id, old_mem); } else if (new_size && !old_mem) { createNewBlock(snapshot_id, new_mem, new_size); } else { freeBlock(snapshot_id, old_mem); createNewBlock(snapshot_id, new_mem, new_size); } } void MySQL::addMemoryWrites( snapshot_t snapshot_id, const std::map<void *, unsigned char>& writes) { MYSQL_BIND bind[3]; char current_char; void* current_addr = NULL; memset(&bind, 0, sizeof(MYSQL_BIND)*3); // snapshot ID bind[0].buffer_type = MYSQL_TYPE_LONG; bind[0].buffer = &snapshot_id; bind[0].buffer_length = sizeof(snapshot_t); // address bind[1].buffer_type = MYSQL_TYPE_LONGLONG; bind[1].buffer = &current_addr; bind[1].buffer_length = sizeof(void*); // value bind[2].buffer_type = MYSQL_TYPE_BLOB; bind[2].buffer = &current_char; bind[2].buffer_length = 1; for (std::map<void *, unsigned char>::const_iterator it = writes.begin(); it != writes.end(); it++) { current_addr = it -> first; current_char = it -> second; if (mysql_stmt_bind_param(add_memory_write_, bind) || mysql_stmt_execute(add_memory_write_)) fatal_error(db_, __LINE__); } } void MySQL::createNewBlock(snapshot_t snapshot_id, void *address, size_t size) { MYSQL_BIND bind[3]; memset(&bind, 0, sizeof(MYSQL_BIND)*3); // snapshot ID bind[0].buffer_type = MYSQL_TYPE_LONG; bind[0].buffer = &snapshot_id; bind[0].buffer_length = sizeof(snapshot_t); // memory pointer bind[1].buffer_type = MYSQL_TYPE_LONGLONG; bind[1].buffer = &address; bind[1].buffer_length = sizeof(void*); // size bind[2].buffer_type = MYSQL_TYPE_LONG; bind[2].buffer = &size; bind[2].buffer_length = sizeof(size_t); if (mysql_stmt_bind_param(create_new_block_, bind) || mysql_stmt_execute(create_new_block_)) fatal_error(db_, __LINE__); } void MySQL::freeBlock(snapshot_t snapshot_id, void *address) { MYSQL_BIND bind[2]; memset(&bind, 0, sizeof(MYSQL_BIND)*2); // snapshot ID bind[0].buffer_type = MYSQL_TYPE_LONG; bind[0].buffer = &snapshot_id; bind[0].buffer_length = sizeof(snapshot_t); // memory pointer bind[1].buffer_type = MYSQL_TYPE_LONGLONG; bind[1].buffer = &address; bind[1].buffer_length = sizeof(void*); if (mysql_stmt_bind_param(free_block_, bind) || mysql_stmt_execute(free_block_)) fatal_error(db_, __LINE__); } <|endoftext|>
<commit_before>// // Copyright (c) 2015 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // EGLContextCompatibilityTest.cpp: // This test will try to use all combinations of context configs and // surface configs. If the configs are compatible, it checks that simple // rendering works, otherwise it checks an error is generated one MakeCurrent. #include <gtest/gtest.h> #include <vector> #include <EGL/egl.h> #include <EGL/eglext.h> #include "OSWindow.h" #include "test_utils/ANGLETest.h" #include "test_utils/angle_test_configs.h" using namespace angle; namespace { const EGLint contextAttribs[] = { EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE }; } class EGLContextCompatibilityTest : public ANGLETest { public: EGLContextCompatibilityTest() : mDisplay(0) { } void SetUp() override { PFNEGLGETPLATFORMDISPLAYEXTPROC eglGetPlatformDisplayEXT = reinterpret_cast<PFNEGLGETPLATFORMDISPLAYEXTPROC>(eglGetProcAddress("eglGetPlatformDisplayEXT")); ASSERT_TRUE(eglGetPlatformDisplayEXT != nullptr); EGLint dispattrs[] = { EGL_PLATFORM_ANGLE_TYPE_ANGLE, GetParam().getRenderer(), EGL_NONE }; mDisplay = eglGetPlatformDisplayEXT(EGL_PLATFORM_ANGLE_ANGLE, EGL_DEFAULT_DISPLAY, dispattrs); ASSERT_TRUE(mDisplay != EGL_NO_DISPLAY); ASSERT_TRUE(eglInitialize(mDisplay, nullptr, nullptr) == EGL_TRUE); int nConfigs = 0; ASSERT_TRUE(eglGetConfigs(mDisplay, nullptr, 0, &nConfigs) == EGL_TRUE); ASSERT_TRUE(nConfigs != 0); int nReturnedConfigs = 0; mConfigs.resize(nConfigs); ASSERT_TRUE(eglGetConfigs(mDisplay, mConfigs.data(), nConfigs, &nReturnedConfigs) == EGL_TRUE); ASSERT_TRUE(nConfigs == nReturnedConfigs); } void TearDown() override { eglMakeCurrent(mDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); eglTerminate(mDisplay); }; protected: bool areConfigsCompatible(EGLConfig c1, EGLConfig c2, EGLint surfaceBit) { EGLint colorBufferType1, colorBufferType2; EGLint red1, red2, green1, green2, blue1, blue2, alpha1, alpha2; EGLint depth1, depth2, stencil1, stencil2; EGLint surfaceType1, surfaceType2; eglGetConfigAttrib(mDisplay, c1, EGL_COLOR_BUFFER_TYPE, &colorBufferType1); eglGetConfigAttrib(mDisplay, c2, EGL_COLOR_BUFFER_TYPE, &colorBufferType2); eglGetConfigAttrib(mDisplay, c1, EGL_RED_SIZE, &red1); eglGetConfigAttrib(mDisplay, c2, EGL_RED_SIZE, &red2); eglGetConfigAttrib(mDisplay, c1, EGL_GREEN_SIZE, &green1); eglGetConfigAttrib(mDisplay, c2, EGL_GREEN_SIZE, &green2); eglGetConfigAttrib(mDisplay, c1, EGL_BLUE_SIZE, &blue1); eglGetConfigAttrib(mDisplay, c2, EGL_BLUE_SIZE, &blue2); eglGetConfigAttrib(mDisplay, c1, EGL_ALPHA_SIZE, &alpha1); eglGetConfigAttrib(mDisplay, c2, EGL_ALPHA_SIZE, &alpha2); eglGetConfigAttrib(mDisplay, c1, EGL_DEPTH_SIZE, &depth1); eglGetConfigAttrib(mDisplay, c2, EGL_DEPTH_SIZE, &depth2); eglGetConfigAttrib(mDisplay, c1, EGL_STENCIL_SIZE, &stencil1); eglGetConfigAttrib(mDisplay, c2, EGL_STENCIL_SIZE, &stencil2); eglGetConfigAttrib(mDisplay, c1, EGL_SURFACE_TYPE, &surfaceType1); eglGetConfigAttrib(mDisplay, c2, EGL_SURFACE_TYPE, &surfaceType2); return colorBufferType1 == colorBufferType2 && red1 == red2 && green1 == green2 && blue1 == blue2 && alpha1 == alpha2 && depth1 == depth2 && stencil1 == stencil2 && (surfaceType1 & surfaceBit) != 0 && (surfaceType2 & surfaceBit) != 0; } void testWindowCompatibility(EGLConfig windowConfig, EGLConfig contextConfig, bool compatible) const { OSWindow *osWindow = CreateOSWindow(); ASSERT_TRUE(osWindow != nullptr); osWindow->initialize("EGLContextCompatibilityTest", 500, 500); osWindow->setVisible(true); EGLContext context = eglCreateContext(mDisplay, contextConfig, EGL_NO_CONTEXT, contextAttribs); ASSERT_TRUE(context != EGL_NO_CONTEXT); EGLSurface window = eglCreateWindowSurface(mDisplay, windowConfig, osWindow->getNativeWindow(), nullptr); ASSERT_EGL_SUCCESS(); if (compatible) { testClearSurface(window, context); } else { testMakeCurrentFails(window, context); } eglDestroySurface(mDisplay, window); ASSERT_EGL_SUCCESS(); eglDestroyContext(mDisplay, context); ASSERT_EGL_SUCCESS(); SafeDelete(osWindow); } void testPbufferCompatibility(EGLConfig pbufferConfig, EGLConfig contextConfig, bool compatible) const { EGLContext context = eglCreateContext(mDisplay, contextConfig, EGL_NO_CONTEXT, contextAttribs); ASSERT_TRUE(context != EGL_NO_CONTEXT); const EGLint pBufferAttribs[] = { EGL_WIDTH, 500, EGL_HEIGHT, 500, EGL_NONE, }; EGLSurface pbuffer = eglCreatePbufferSurface(mDisplay, pbufferConfig, pBufferAttribs); ASSERT_TRUE(pbuffer != EGL_NO_SURFACE); if (compatible) { testClearSurface(pbuffer, context); } else { testMakeCurrentFails(pbuffer, context); } eglDestroySurface(mDisplay, pbuffer); ASSERT_EGL_SUCCESS(); eglDestroyContext(mDisplay, context); ASSERT_EGL_SUCCESS(); } std::vector<EGLConfig> mConfigs; EGLDisplay mDisplay; private: void testClearSurface(EGLSurface surface, EGLContext context) const { eglMakeCurrent(mDisplay, surface, surface, context); ASSERT_EGL_SUCCESS(); glViewport(0, 0, 500, 500); glClearColor(0.0f, 0.0f, 1.0f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); ASSERT_GL_NO_ERROR(); EXPECT_PIXEL_EQ(250, 250, 0, 0, 255, 255); eglMakeCurrent(mDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); ASSERT_EGL_SUCCESS(); } void testMakeCurrentFails(EGLSurface surface, EGLContext context) const { eglMakeCurrent(mDisplay, surface, surface, context); EXPECT_EGL_ERROR(EGL_BAD_MATCH); } }; // The test is split in several subtest so that simple cases // are tested separately. Also each surface types are not tested // together. // Basic test checking contexts and windows created with the // same config can render. TEST_P(EGLContextCompatibilityTest, WindowSameConfig) { // TODO(cwallez): figure out why this is broken on Linux/AMD. #ifdef ANGLE_PLATFORM_LINUX if (isAMD() && getPlatformRenderer() == EGL_PLATFORM_ANGLE_TYPE_OPENGL_ANGLE) { std::cout << "Test skipped on Linux AMD on OpenGL." << std::endl; return; } #endif for (size_t i = 0; i < mConfigs.size(); i++) { EGLConfig config = mConfigs[i]; EGLint surfaceType; eglGetConfigAttrib(mDisplay, config, EGL_SURFACE_TYPE, &surfaceType); ASSERT_EGL_SUCCESS(); if ((surfaceType & EGL_WINDOW_BIT) != 0) { testWindowCompatibility(config, config, true); } } } // Basic test checking contexts and pbuffers created with the // same config can render. TEST_P(EGLContextCompatibilityTest, PbufferSameConfig) { // TODO(cwallez): figure out why this is broken on Linux/AMD. #ifdef ANGLE_PLATFORM_LINUX if (isAMD() && getPlatformRenderer() == EGL_PLATFORM_ANGLE_TYPE_OPENGL_ANGLE) { std::cout << "Test skipped on Linux AMD on OpenGL." << std::endl; return; } #endif for (size_t i = 0; i < mConfigs.size(); i++) { EGLConfig config = mConfigs[i]; EGLint surfaceType; eglGetConfigAttrib(mDisplay, config, EGL_SURFACE_TYPE, &surfaceType); ASSERT_EGL_SUCCESS(); if ((surfaceType & EGL_PBUFFER_BIT) != 0) { testPbufferCompatibility(config, config, true); } } } // Check that a context rendering to a window with a different // config works or errors according to the EGL compatibility rules TEST_P(EGLContextCompatibilityTest, WindowDifferentConfig) { // TODO(cwallez): figure out why this is broken on Linux/AMD. #ifdef ANGLE_PLATFORM_LINUX if (isAMD() && getPlatformRenderer() == EGL_PLATFORM_ANGLE_TYPE_OPENGL_ANGLE) { std::cout << "Test skipped on Linux AMD on OpenGL." << std::endl; return; } #endif for (size_t i = 0; i < mConfigs.size(); i++) { EGLConfig config1 = mConfigs[i]; EGLint surfaceType; eglGetConfigAttrib(mDisplay, config1, EGL_SURFACE_TYPE, &surfaceType); ASSERT_EGL_SUCCESS(); if ((surfaceType & EGL_WINDOW_BIT) == 0) { continue; } for (size_t j = 0; j < mConfigs.size(); j++) { EGLConfig config2 = mConfigs[j]; testPbufferCompatibility(config1, config2, areConfigsCompatible(config1, config2, EGL_WINDOW_BIT)); } } } // Check that a context rendering to a pbuffer with a different // config works or errors according to the EGL compatibility rules TEST_P(EGLContextCompatibilityTest, PbufferDifferentConfig) { // TODO(cwallez): figure out why this is broken on Linux/AMD. #ifdef ANGLE_PLATFORM_LINUX if (isAMD() && getPlatformRenderer() == EGL_PLATFORM_ANGLE_TYPE_OPENGL_ANGLE) { std::cout << "Test skipped on Linux AMD on OpenGL." << std::endl; return; } #endif for (size_t i = 0; i < mConfigs.size(); i++) { EGLConfig config1 = mConfigs[i]; EGLint surfaceType; eglGetConfigAttrib(mDisplay, config1, EGL_SURFACE_TYPE, &surfaceType); ASSERT_EGL_SUCCESS(); if ((surfaceType & EGL_PBUFFER_BIT) == 0) { continue; } for (size_t j = 0; j < mConfigs.size(); j++) { EGLConfig config2 = mConfigs[j]; testPbufferCompatibility(config1, config2, areConfigsCompatible(config1, config2, EGL_PBUFFER_BIT)); } } } ANGLE_INSTANTIATE_TEST(EGLContextCompatibilityTest, ES2_D3D9(), ES2_D3D11(), ES2_OPENGL()); <commit_msg>EGLContextCompatibilityTest: check for suppression only when a context is bound.<commit_after>// // Copyright (c) 2015 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // EGLContextCompatibilityTest.cpp: // This test will try to use all combinations of context configs and // surface configs. If the configs are compatible, it checks that simple // rendering works, otherwise it checks an error is generated one MakeCurrent. #include <gtest/gtest.h> #include <vector> #include <EGL/egl.h> #include <EGL/eglext.h> #include "OSWindow.h" #include "test_utils/ANGLETest.h" #include "test_utils/angle_test_configs.h" using namespace angle; namespace { const EGLint contextAttribs[] = { EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE }; } class EGLContextCompatibilityTest : public ANGLETest { public: EGLContextCompatibilityTest() : mDisplay(0) { } void SetUp() override { PFNEGLGETPLATFORMDISPLAYEXTPROC eglGetPlatformDisplayEXT = reinterpret_cast<PFNEGLGETPLATFORMDISPLAYEXTPROC>(eglGetProcAddress("eglGetPlatformDisplayEXT")); ASSERT_TRUE(eglGetPlatformDisplayEXT != nullptr); EGLint dispattrs[] = { EGL_PLATFORM_ANGLE_TYPE_ANGLE, GetParam().getRenderer(), EGL_NONE }; mDisplay = eglGetPlatformDisplayEXT(EGL_PLATFORM_ANGLE_ANGLE, EGL_DEFAULT_DISPLAY, dispattrs); ASSERT_TRUE(mDisplay != EGL_NO_DISPLAY); ASSERT_TRUE(eglInitialize(mDisplay, nullptr, nullptr) == EGL_TRUE); int nConfigs = 0; ASSERT_TRUE(eglGetConfigs(mDisplay, nullptr, 0, &nConfigs) == EGL_TRUE); ASSERT_TRUE(nConfigs != 0); int nReturnedConfigs = 0; mConfigs.resize(nConfigs); ASSERT_TRUE(eglGetConfigs(mDisplay, mConfigs.data(), nConfigs, &nReturnedConfigs) == EGL_TRUE); ASSERT_TRUE(nConfigs == nReturnedConfigs); } void TearDown() override { eglMakeCurrent(mDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); eglTerminate(mDisplay); }; protected: bool areConfigsCompatible(EGLConfig c1, EGLConfig c2, EGLint surfaceBit) { EGLint colorBufferType1, colorBufferType2; EGLint red1, red2, green1, green2, blue1, blue2, alpha1, alpha2; EGLint depth1, depth2, stencil1, stencil2; EGLint surfaceType1, surfaceType2; eglGetConfigAttrib(mDisplay, c1, EGL_COLOR_BUFFER_TYPE, &colorBufferType1); eglGetConfigAttrib(mDisplay, c2, EGL_COLOR_BUFFER_TYPE, &colorBufferType2); eglGetConfigAttrib(mDisplay, c1, EGL_RED_SIZE, &red1); eglGetConfigAttrib(mDisplay, c2, EGL_RED_SIZE, &red2); eglGetConfigAttrib(mDisplay, c1, EGL_GREEN_SIZE, &green1); eglGetConfigAttrib(mDisplay, c2, EGL_GREEN_SIZE, &green2); eglGetConfigAttrib(mDisplay, c1, EGL_BLUE_SIZE, &blue1); eglGetConfigAttrib(mDisplay, c2, EGL_BLUE_SIZE, &blue2); eglGetConfigAttrib(mDisplay, c1, EGL_ALPHA_SIZE, &alpha1); eglGetConfigAttrib(mDisplay, c2, EGL_ALPHA_SIZE, &alpha2); eglGetConfigAttrib(mDisplay, c1, EGL_DEPTH_SIZE, &depth1); eglGetConfigAttrib(mDisplay, c2, EGL_DEPTH_SIZE, &depth2); eglGetConfigAttrib(mDisplay, c1, EGL_STENCIL_SIZE, &stencil1); eglGetConfigAttrib(mDisplay, c2, EGL_STENCIL_SIZE, &stencil2); eglGetConfigAttrib(mDisplay, c1, EGL_SURFACE_TYPE, &surfaceType1); eglGetConfigAttrib(mDisplay, c2, EGL_SURFACE_TYPE, &surfaceType2); return colorBufferType1 == colorBufferType2 && red1 == red2 && green1 == green2 && blue1 == blue2 && alpha1 == alpha2 && depth1 == depth2 && stencil1 == stencil2 && (surfaceType1 & surfaceBit) != 0 && (surfaceType2 & surfaceBit) != 0; } void testWindowCompatibility(EGLConfig windowConfig, EGLConfig contextConfig, bool compatible) const { OSWindow *osWindow = CreateOSWindow(); ASSERT_TRUE(osWindow != nullptr); osWindow->initialize("EGLContextCompatibilityTest", 500, 500); osWindow->setVisible(true); EGLContext context = eglCreateContext(mDisplay, contextConfig, EGL_NO_CONTEXT, contextAttribs); ASSERT_TRUE(context != EGL_NO_CONTEXT); EGLSurface window = eglCreateWindowSurface(mDisplay, windowConfig, osWindow->getNativeWindow(), nullptr); ASSERT_EGL_SUCCESS(); if (compatible) { testClearSurface(window, context); } else { testMakeCurrentFails(window, context); } eglDestroySurface(mDisplay, window); ASSERT_EGL_SUCCESS(); eglDestroyContext(mDisplay, context); ASSERT_EGL_SUCCESS(); SafeDelete(osWindow); } void testPbufferCompatibility(EGLConfig pbufferConfig, EGLConfig contextConfig, bool compatible) const { EGLContext context = eglCreateContext(mDisplay, contextConfig, EGL_NO_CONTEXT, contextAttribs); ASSERT_TRUE(context != EGL_NO_CONTEXT); const EGLint pBufferAttribs[] = { EGL_WIDTH, 500, EGL_HEIGHT, 500, EGL_NONE, }; EGLSurface pbuffer = eglCreatePbufferSurface(mDisplay, pbufferConfig, pBufferAttribs); ASSERT_TRUE(pbuffer != EGL_NO_SURFACE); if (compatible) { testClearSurface(pbuffer, context); } else { testMakeCurrentFails(pbuffer, context); } eglDestroySurface(mDisplay, pbuffer); ASSERT_EGL_SUCCESS(); eglDestroyContext(mDisplay, context); ASSERT_EGL_SUCCESS(); } std::vector<EGLConfig> mConfigs; EGLDisplay mDisplay; private: void testClearSurface(EGLSurface surface, EGLContext context) const { eglMakeCurrent(mDisplay, surface, surface, context); ASSERT_EGL_SUCCESS(); #ifdef ANGLE_PLATFORM_LINUX // TODO(cwallez): figure out why this is broken on Linux/AMD. if (isAMD() && getPlatformRenderer() == EGL_PLATFORM_ANGLE_TYPE_OPENGL_ANGLE) { eglMakeCurrent(mDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); return; } #endif glViewport(0, 0, 500, 500); glClearColor(0.0f, 0.0f, 1.0f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); ASSERT_GL_NO_ERROR(); EXPECT_PIXEL_EQ(250, 250, 0, 0, 255, 255); eglMakeCurrent(mDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); ASSERT_EGL_SUCCESS(); } void testMakeCurrentFails(EGLSurface surface, EGLContext context) const { eglMakeCurrent(mDisplay, surface, surface, context); EXPECT_EGL_ERROR(EGL_BAD_MATCH); } }; // The test is split in several subtest so that simple cases // are tested separately. Also each surface types are not tested // together. // Basic test checking contexts and windows created with the // same config can render. TEST_P(EGLContextCompatibilityTest, WindowSameConfig) { for (size_t i = 0; i < mConfigs.size(); i++) { EGLConfig config = mConfigs[i]; EGLint surfaceType; eglGetConfigAttrib(mDisplay, config, EGL_SURFACE_TYPE, &surfaceType); ASSERT_EGL_SUCCESS(); if ((surfaceType & EGL_WINDOW_BIT) != 0) { testWindowCompatibility(config, config, true); } } } // Basic test checking contexts and pbuffers created with the // same config can render. TEST_P(EGLContextCompatibilityTest, PbufferSameConfig) { for (size_t i = 0; i < mConfigs.size(); i++) { EGLConfig config = mConfigs[i]; EGLint surfaceType; eglGetConfigAttrib(mDisplay, config, EGL_SURFACE_TYPE, &surfaceType); ASSERT_EGL_SUCCESS(); if ((surfaceType & EGL_PBUFFER_BIT) != 0) { testPbufferCompatibility(config, config, true); } } } // Check that a context rendering to a window with a different // config works or errors according to the EGL compatibility rules TEST_P(EGLContextCompatibilityTest, WindowDifferentConfig) { for (size_t i = 0; i < mConfigs.size(); i++) { EGLConfig config1 = mConfigs[i]; EGLint surfaceType; eglGetConfigAttrib(mDisplay, config1, EGL_SURFACE_TYPE, &surfaceType); ASSERT_EGL_SUCCESS(); if ((surfaceType & EGL_WINDOW_BIT) == 0) { continue; } for (size_t j = 0; j < mConfigs.size(); j++) { EGLConfig config2 = mConfigs[j]; testPbufferCompatibility(config1, config2, areConfigsCompatible(config1, config2, EGL_WINDOW_BIT)); } } } // Check that a context rendering to a pbuffer with a different // config works or errors according to the EGL compatibility rules TEST_P(EGLContextCompatibilityTest, PbufferDifferentConfig) { for (size_t i = 0; i < mConfigs.size(); i++) { EGLConfig config1 = mConfigs[i]; EGLint surfaceType; eglGetConfigAttrib(mDisplay, config1, EGL_SURFACE_TYPE, &surfaceType); ASSERT_EGL_SUCCESS(); if ((surfaceType & EGL_PBUFFER_BIT) == 0) { continue; } for (size_t j = 0; j < mConfigs.size(); j++) { EGLConfig config2 = mConfigs[j]; testPbufferCompatibility(config1, config2, areConfigsCompatible(config1, config2, EGL_PBUFFER_BIT)); } } } ANGLE_INSTANTIATE_TEST(EGLContextCompatibilityTest, ES2_D3D9(), ES2_D3D11(), ES2_OPENGL()); <|endoftext|>
<commit_before>/* * Copyright (C) 2006 Apple Computer, Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "core/platform/image-decoders/gif/GIFImageDecoder.h" #include <limits> #include "core/platform/PlatformInstrumentation.h" #include "core/platform/image-decoders/gif/GIFImageReader.h" #include "wtf/NotFound.h" #include "wtf/PassOwnPtr.h" namespace WebCore { GIFImageDecoder::GIFImageDecoder(ImageSource::AlphaOption alphaOption, ImageSource::GammaAndColorProfileOption gammaAndColorProfileOption) : ImageDecoder(alphaOption, gammaAndColorProfileOption) , m_repetitionCount(cAnimationLoopOnce) { } GIFImageDecoder::~GIFImageDecoder() { } void GIFImageDecoder::setData(SharedBuffer* data, bool allDataReceived) { if (failed()) return; ImageDecoder::setData(data, allDataReceived); if (m_reader) m_reader->setData(data); } bool GIFImageDecoder::isSizeAvailable() { if (!ImageDecoder::isSizeAvailable()) parse(GIFSizeQuery); return ImageDecoder::isSizeAvailable(); } size_t GIFImageDecoder::frameCount() { parse(GIFFrameCountQuery); return m_frameBufferCache.size(); } int GIFImageDecoder::repetitionCount() const { // This value can arrive at any point in the image data stream. Most GIFs // in the wild declare it near the beginning of the file, so it usually is // set by the time we've decoded the size, but (depending on the GIF and the // packets sent back by the webserver) not always. If the reader hasn't // seen a loop count yet, it will return cLoopCountNotSeen, in which case we // should default to looping once (the initial value for // |m_repetitionCount|). // // There are some additional wrinkles here. First, ImageSource::clear() // may destroy the reader, making the result from the reader _less_ // authoritative on future calls if the recreated reader hasn't seen the // loop count. We don't need to special-case this because in this case the // new reader will once again return cLoopCountNotSeen, and we won't // overwrite the cached correct value. // // Second, a GIF might never set a loop count at all, in which case we // should continue to treat it as a "loop once" animation. We don't need // special code here either, because in this case we'll never change // |m_repetitionCount| from its default value. // // Third, we use the same GIFImageReader for counting frames and we might // see the loop count and then encounter a decoding error which happens // later in the stream. It is also possible that no frames are in the // stream. In these cases we should just loop once. if (failed() || (m_reader && (!m_reader->imagesCount()))) m_repetitionCount = cAnimationLoopOnce; else if (m_reader && m_reader->loopCount() != cLoopCountNotSeen) m_repetitionCount = m_reader->loopCount(); return m_repetitionCount; } ImageFrame* GIFImageDecoder::frameBufferAtIndex(size_t index) { if (index >= frameCount()) return 0; ImageFrame& frame = m_frameBufferCache[index]; if (frame.status() != ImageFrame::FrameComplete) { PlatformInstrumentation::willDecodeImage("GIF"); decode(index); PlatformInstrumentation::didDecodeImage(); } return &frame; } bool GIFImageDecoder::frameIsCompleteAtIndex(size_t index) const { return m_reader && (index < m_reader->imagesCount()) && m_reader->frameContext(index)->isComplete(); } float GIFImageDecoder::frameDurationAtIndex(size_t index) const { return (m_reader && (index < m_reader->imagesCount()) && m_reader->frameContext(index)->isHeaderDefined()) ? m_reader->frameContext(index)->delayTime : 0; } bool GIFImageDecoder::setFailed() { m_reader.clear(); return ImageDecoder::setFailed(); } bool GIFImageDecoder::haveDecodedRow(size_t frameIndex, const Vector<unsigned char>& rowBuffer, size_t width, size_t rowNumber, unsigned repeatCount, bool writeTransparentPixels) { const GIFFrameContext* frameContext = m_reader->frameContext(frameIndex); // The pixel data and coordinates supplied to us are relative to the frame's // origin within the entire image size, i.e. // (frameContext->xOffset, frameContext->yOffset). There is no guarantee // that width == (size().width() - frameContext->xOffset), so // we must ensure we don't run off the end of either the source data or the // row's X-coordinates. int xBegin = frameContext->xOffset; int yBegin = frameContext->yOffset + rowNumber; int xEnd = std::min(static_cast<int>(frameContext->xOffset + width), size().width()); int yEnd = std::min(static_cast<int>(frameContext->yOffset + rowNumber + repeatCount), size().height()); if (rowBuffer.isEmpty() || (xBegin < 0) || (yBegin < 0) || (xEnd <= xBegin) || (yEnd <= yBegin)) return true; // Get the colormap. const unsigned char* colorMap; unsigned colorMapSize; if (frameContext->isLocalColormapDefined) { colorMap = m_reader->localColormap(frameContext); colorMapSize = m_reader->localColormapSize(frameContext); } else { colorMap = m_reader->globalColormap(); colorMapSize = m_reader->globalColormapSize(); } if (!colorMap) return true; // Initialize the frame if necessary. ImageFrame& buffer = m_frameBufferCache[frameIndex]; if ((buffer.status() == ImageFrame::FrameEmpty) && !initFrameBuffer(frameIndex)) return false; ImageFrame::PixelData* currentAddress = buffer.getAddr(xBegin, yBegin); // Write one row's worth of data into the frame. for (int x = xBegin; x < xEnd; ++x) { const unsigned char sourceValue = rowBuffer[x - frameContext->xOffset]; if ((!frameContext->isTransparent || (sourceValue != frameContext->tpixel)) && (sourceValue < colorMapSize)) { const size_t colorIndex = static_cast<size_t>(sourceValue) * 3; buffer.setRGBA(currentAddress, colorMap[colorIndex], colorMap[colorIndex + 1], colorMap[colorIndex + 2], 255); } else { m_currentBufferSawAlpha = true; // We may or may not need to write transparent pixels to the buffer. // If we're compositing against a previous image, it's wrong, and if // we're writing atop a cleared, fully transparent buffer, it's // unnecessary; but if we're decoding an interlaced gif and // displaying it "Haeberli"-style, we must write these for passes // beyond the first, or the initial passes will "show through" the // later ones. if (writeTransparentPixels) buffer.setRGBA(currentAddress, 0, 0, 0, 0); } ++currentAddress; } // Tell the frame to copy the row data if need be. if (repeatCount > 1) buffer.copyRowNTimes(xBegin, xEnd, yBegin, yEnd); return true; } bool GIFImageDecoder::parseCompleted() const { return m_reader && m_reader->parseCompleted(); } bool GIFImageDecoder::frameComplete(size_t frameIndex) { // Initialize the frame if necessary. Some GIFs insert do-nothing frames, // in which case we never reach haveDecodedRow() before getting here. ImageFrame& buffer = m_frameBufferCache[frameIndex]; if ((buffer.status() == ImageFrame::FrameEmpty) && !initFrameBuffer(frameIndex)) return false; // initFrameBuffer() has already called setFailed(). buffer.setStatus(ImageFrame::FrameComplete); if (!m_currentBufferSawAlpha) { // The whole frame was non-transparent, so it's possible that the entire // resulting buffer was non-transparent, and we can setHasAlpha(false). if (buffer.originalFrameRect().contains(IntRect(IntPoint(), size()))) { buffer.setHasAlpha(false); buffer.setRequiredPreviousFrameIndex(notFound); } else if (buffer.requiredPreviousFrameIndex() != notFound) { // Tricky case. This frame does not have alpha only if everywhere // outside its rect doesn't have alpha. To know whether this is // true, we check the start state of the frame -- if it doesn't have // alpha, we're safe. const ImageFrame* prevBuffer = &m_frameBufferCache[buffer.requiredPreviousFrameIndex()]; ASSERT(prevBuffer->disposalMethod() != ImageFrame::DisposeOverwritePrevious); // Now, if we're at a DisposeNotSpecified or DisposeKeep frame, then // we can say we have no alpha if that frame had no alpha. But // since in initFrameBuffer() we already copied that frame's alpha // state into the current frame's, we need do nothing at all here. // // The only remaining case is a DisposeOverwriteBgcolor frame. If // it had no alpha, and its rect is contained in the current frame's // rect, we know the current frame has no alpha. if ((prevBuffer->disposalMethod() == ImageFrame::DisposeOverwriteBgcolor) && !prevBuffer->hasAlpha() && buffer.originalFrameRect().contains(prevBuffer->originalFrameRect())) buffer.setHasAlpha(false); } } return true; } void GIFImageDecoder::clearFrameBuffer(size_t frameIndex) { if (m_reader && m_frameBufferCache[frameIndex].status() == ImageFrame::FramePartial) { // Reset the state of the partial frame in the reader so that the frame // can be decoded again when requested. m_reader->clearDecodeState(frameIndex); } ImageDecoder::clearFrameBuffer(frameIndex); } void GIFImageDecoder::parse(GIFParseQuery query) { if (failed()) return; if (!m_reader) { m_reader = adoptPtr(new GIFImageReader(this)); m_reader->setData(m_data); } if (!m_reader->parse(query)) { setFailed(); return; } const size_t oldSize = m_frameBufferCache.size(); m_frameBufferCache.resize(m_reader->imagesCount()); for (size_t i = oldSize; i < m_reader->imagesCount(); ++i) { ImageFrame& buffer = m_frameBufferCache[i]; const GIFFrameContext* frameContext = m_reader->frameContext(i); buffer.setPremultiplyAlpha(m_premultiplyAlpha); buffer.setRequiredPreviousFrameIndex(findRequiredPreviousFrame(i)); buffer.setDuration(frameContext->delayTime); buffer.setDisposalMethod(frameContext->disposalMethod); // Initialize the frame rect in our buffer. IntRect frameRect(frameContext->xOffset, frameContext->yOffset, frameContext->width, frameContext->height); // Make sure the frameRect doesn't extend outside the buffer. if (frameRect.maxX() > size().width()) frameRect.setWidth(size().width() - frameContext->xOffset); if (frameRect.maxY() > size().height()) frameRect.setHeight(size().height() - frameContext->yOffset); buffer.setOriginalFrameRect(frameRect); } } void GIFImageDecoder::decode(size_t frameIndex) { parse(GIFFrameCountQuery); if (failed()) return; Vector<size_t> framesToDecode; size_t frameToDecode = frameIndex; do { framesToDecode.append(frameToDecode); frameToDecode = m_frameBufferCache[frameToDecode].requiredPreviousFrameIndex(); } while (frameToDecode != notFound && m_frameBufferCache[frameToDecode].status() != ImageFrame::FrameComplete); // The |rend| variable is needed by some compilers that can't correctly // select from const and non-const versions of overloaded functions. // Can remove the variable if Android compiler can compile // 'iter != framesToDecode.rend()'. Vector<size_t>::const_reverse_iterator rend = framesToDecode.rend(); for (Vector<size_t>::const_reverse_iterator iter = framesToDecode.rbegin(); iter != rend; ++iter) { size_t frameIndex = *iter; if (!m_reader->decode(frameIndex)) { setFailed(); return; } // We need more data to continue decoding. if (m_frameBufferCache[frameIndex].status() != ImageFrame::FrameComplete) break; } // It is also a fatal error if all data is received and we have decoded all // frames available but the file is truncated. if (frameIndex >= m_frameBufferCache.size() - 1 && isAllDataReceived() && m_reader && !m_reader->parseCompleted()) setFailed(); } bool GIFImageDecoder::initFrameBuffer(size_t frameIndex) { // Initialize the frame rect in our buffer. const GIFFrameContext* frameContext = m_reader->frameContext(frameIndex); ImageFrame* const buffer = &m_frameBufferCache[frameIndex]; size_t requiredPreviousFrameIndex = buffer->requiredPreviousFrameIndex(); if (requiredPreviousFrameIndex == notFound) { // This frame doesn't rely on any previous data. if (!buffer->setSize(size().width(), size().height())) return setFailed(); } else { const ImageFrame* prevBuffer = &m_frameBufferCache[requiredPreviousFrameIndex]; ASSERT(prevBuffer->status() == ImageFrame::FrameComplete); // Preserve the last frame as the starting state for this frame. if (!buffer->copyBitmapData(*prevBuffer)) return setFailed(); if (prevBuffer->disposalMethod() == ImageFrame::DisposeOverwriteBgcolor) { // We want to clear the previous frame to transparent, without // affecting pixels in the image outside of the frame. const IntRect& prevRect = prevBuffer->originalFrameRect(); ASSERT(!prevRect.contains(IntRect(IntPoint(), size()))); for (int y = prevRect.y(); y < prevRect.maxY(); ++y) { for (int x = prevRect.x(); x < prevRect.maxX(); ++x) buffer->setRGBA(x, y, 0, 0, 0, 0); } if ((prevRect.width() > 0) && (prevRect.height() > 0)) buffer->setHasAlpha(true); } } // Update our status to be partially complete. buffer->setStatus(ImageFrame::FramePartial); // Reset the alpha pixel tracker for this frame. m_currentBufferSawAlpha = false; return true; } } // namespace WebCore <commit_msg>GIFDecoder: Use index in place of iterator in vector iteration<commit_after>/* * Copyright (C) 2006 Apple Computer, Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "core/platform/image-decoders/gif/GIFImageDecoder.h" #include <limits> #include "core/platform/PlatformInstrumentation.h" #include "core/platform/image-decoders/gif/GIFImageReader.h" #include "wtf/NotFound.h" #include "wtf/PassOwnPtr.h" namespace WebCore { GIFImageDecoder::GIFImageDecoder(ImageSource::AlphaOption alphaOption, ImageSource::GammaAndColorProfileOption gammaAndColorProfileOption) : ImageDecoder(alphaOption, gammaAndColorProfileOption) , m_repetitionCount(cAnimationLoopOnce) { } GIFImageDecoder::~GIFImageDecoder() { } void GIFImageDecoder::setData(SharedBuffer* data, bool allDataReceived) { if (failed()) return; ImageDecoder::setData(data, allDataReceived); if (m_reader) m_reader->setData(data); } bool GIFImageDecoder::isSizeAvailable() { if (!ImageDecoder::isSizeAvailable()) parse(GIFSizeQuery); return ImageDecoder::isSizeAvailable(); } size_t GIFImageDecoder::frameCount() { parse(GIFFrameCountQuery); return m_frameBufferCache.size(); } int GIFImageDecoder::repetitionCount() const { // This value can arrive at any point in the image data stream. Most GIFs // in the wild declare it near the beginning of the file, so it usually is // set by the time we've decoded the size, but (depending on the GIF and the // packets sent back by the webserver) not always. If the reader hasn't // seen a loop count yet, it will return cLoopCountNotSeen, in which case we // should default to looping once (the initial value for // |m_repetitionCount|). // // There are some additional wrinkles here. First, ImageSource::clear() // may destroy the reader, making the result from the reader _less_ // authoritative on future calls if the recreated reader hasn't seen the // loop count. We don't need to special-case this because in this case the // new reader will once again return cLoopCountNotSeen, and we won't // overwrite the cached correct value. // // Second, a GIF might never set a loop count at all, in which case we // should continue to treat it as a "loop once" animation. We don't need // special code here either, because in this case we'll never change // |m_repetitionCount| from its default value. // // Third, we use the same GIFImageReader for counting frames and we might // see the loop count and then encounter a decoding error which happens // later in the stream. It is also possible that no frames are in the // stream. In these cases we should just loop once. if (failed() || (m_reader && (!m_reader->imagesCount()))) m_repetitionCount = cAnimationLoopOnce; else if (m_reader && m_reader->loopCount() != cLoopCountNotSeen) m_repetitionCount = m_reader->loopCount(); return m_repetitionCount; } ImageFrame* GIFImageDecoder::frameBufferAtIndex(size_t index) { if (index >= frameCount()) return 0; ImageFrame& frame = m_frameBufferCache[index]; if (frame.status() != ImageFrame::FrameComplete) { PlatformInstrumentation::willDecodeImage("GIF"); decode(index); PlatformInstrumentation::didDecodeImage(); } return &frame; } bool GIFImageDecoder::frameIsCompleteAtIndex(size_t index) const { return m_reader && (index < m_reader->imagesCount()) && m_reader->frameContext(index)->isComplete(); } float GIFImageDecoder::frameDurationAtIndex(size_t index) const { return (m_reader && (index < m_reader->imagesCount()) && m_reader->frameContext(index)->isHeaderDefined()) ? m_reader->frameContext(index)->delayTime : 0; } bool GIFImageDecoder::setFailed() { m_reader.clear(); return ImageDecoder::setFailed(); } bool GIFImageDecoder::haveDecodedRow(size_t frameIndex, const Vector<unsigned char>& rowBuffer, size_t width, size_t rowNumber, unsigned repeatCount, bool writeTransparentPixels) { const GIFFrameContext* frameContext = m_reader->frameContext(frameIndex); // The pixel data and coordinates supplied to us are relative to the frame's // origin within the entire image size, i.e. // (frameContext->xOffset, frameContext->yOffset). There is no guarantee // that width == (size().width() - frameContext->xOffset), so // we must ensure we don't run off the end of either the source data or the // row's X-coordinates. int xBegin = frameContext->xOffset; int yBegin = frameContext->yOffset + rowNumber; int xEnd = std::min(static_cast<int>(frameContext->xOffset + width), size().width()); int yEnd = std::min(static_cast<int>(frameContext->yOffset + rowNumber + repeatCount), size().height()); if (rowBuffer.isEmpty() || (xBegin < 0) || (yBegin < 0) || (xEnd <= xBegin) || (yEnd <= yBegin)) return true; // Get the colormap. const unsigned char* colorMap; unsigned colorMapSize; if (frameContext->isLocalColormapDefined) { colorMap = m_reader->localColormap(frameContext); colorMapSize = m_reader->localColormapSize(frameContext); } else { colorMap = m_reader->globalColormap(); colorMapSize = m_reader->globalColormapSize(); } if (!colorMap) return true; // Initialize the frame if necessary. ImageFrame& buffer = m_frameBufferCache[frameIndex]; if ((buffer.status() == ImageFrame::FrameEmpty) && !initFrameBuffer(frameIndex)) return false; ImageFrame::PixelData* currentAddress = buffer.getAddr(xBegin, yBegin); // Write one row's worth of data into the frame. for (int x = xBegin; x < xEnd; ++x) { const unsigned char sourceValue = rowBuffer[x - frameContext->xOffset]; if ((!frameContext->isTransparent || (sourceValue != frameContext->tpixel)) && (sourceValue < colorMapSize)) { const size_t colorIndex = static_cast<size_t>(sourceValue) * 3; buffer.setRGBA(currentAddress, colorMap[colorIndex], colorMap[colorIndex + 1], colorMap[colorIndex + 2], 255); } else { m_currentBufferSawAlpha = true; // We may or may not need to write transparent pixels to the buffer. // If we're compositing against a previous image, it's wrong, and if // we're writing atop a cleared, fully transparent buffer, it's // unnecessary; but if we're decoding an interlaced gif and // displaying it "Haeberli"-style, we must write these for passes // beyond the first, or the initial passes will "show through" the // later ones. if (writeTransparentPixels) buffer.setRGBA(currentAddress, 0, 0, 0, 0); } ++currentAddress; } // Tell the frame to copy the row data if need be. if (repeatCount > 1) buffer.copyRowNTimes(xBegin, xEnd, yBegin, yEnd); return true; } bool GIFImageDecoder::parseCompleted() const { return m_reader && m_reader->parseCompleted(); } bool GIFImageDecoder::frameComplete(size_t frameIndex) { // Initialize the frame if necessary. Some GIFs insert do-nothing frames, // in which case we never reach haveDecodedRow() before getting here. ImageFrame& buffer = m_frameBufferCache[frameIndex]; if ((buffer.status() == ImageFrame::FrameEmpty) && !initFrameBuffer(frameIndex)) return false; // initFrameBuffer() has already called setFailed(). buffer.setStatus(ImageFrame::FrameComplete); if (!m_currentBufferSawAlpha) { // The whole frame was non-transparent, so it's possible that the entire // resulting buffer was non-transparent, and we can setHasAlpha(false). if (buffer.originalFrameRect().contains(IntRect(IntPoint(), size()))) { buffer.setHasAlpha(false); buffer.setRequiredPreviousFrameIndex(notFound); } else if (buffer.requiredPreviousFrameIndex() != notFound) { // Tricky case. This frame does not have alpha only if everywhere // outside its rect doesn't have alpha. To know whether this is // true, we check the start state of the frame -- if it doesn't have // alpha, we're safe. const ImageFrame* prevBuffer = &m_frameBufferCache[buffer.requiredPreviousFrameIndex()]; ASSERT(prevBuffer->disposalMethod() != ImageFrame::DisposeOverwritePrevious); // Now, if we're at a DisposeNotSpecified or DisposeKeep frame, then // we can say we have no alpha if that frame had no alpha. But // since in initFrameBuffer() we already copied that frame's alpha // state into the current frame's, we need do nothing at all here. // // The only remaining case is a DisposeOverwriteBgcolor frame. If // it had no alpha, and its rect is contained in the current frame's // rect, we know the current frame has no alpha. if ((prevBuffer->disposalMethod() == ImageFrame::DisposeOverwriteBgcolor) && !prevBuffer->hasAlpha() && buffer.originalFrameRect().contains(prevBuffer->originalFrameRect())) buffer.setHasAlpha(false); } } return true; } void GIFImageDecoder::clearFrameBuffer(size_t frameIndex) { if (m_reader && m_frameBufferCache[frameIndex].status() == ImageFrame::FramePartial) { // Reset the state of the partial frame in the reader so that the frame // can be decoded again when requested. m_reader->clearDecodeState(frameIndex); } ImageDecoder::clearFrameBuffer(frameIndex); } void GIFImageDecoder::parse(GIFParseQuery query) { if (failed()) return; if (!m_reader) { m_reader = adoptPtr(new GIFImageReader(this)); m_reader->setData(m_data); } if (!m_reader->parse(query)) { setFailed(); return; } const size_t oldSize = m_frameBufferCache.size(); m_frameBufferCache.resize(m_reader->imagesCount()); for (size_t i = oldSize; i < m_reader->imagesCount(); ++i) { ImageFrame& buffer = m_frameBufferCache[i]; const GIFFrameContext* frameContext = m_reader->frameContext(i); buffer.setPremultiplyAlpha(m_premultiplyAlpha); buffer.setRequiredPreviousFrameIndex(findRequiredPreviousFrame(i)); buffer.setDuration(frameContext->delayTime); buffer.setDisposalMethod(frameContext->disposalMethod); // Initialize the frame rect in our buffer. IntRect frameRect(frameContext->xOffset, frameContext->yOffset, frameContext->width, frameContext->height); // Make sure the frameRect doesn't extend outside the buffer. if (frameRect.maxX() > size().width()) frameRect.setWidth(size().width() - frameContext->xOffset); if (frameRect.maxY() > size().height()) frameRect.setHeight(size().height() - frameContext->yOffset); buffer.setOriginalFrameRect(frameRect); } } void GIFImageDecoder::decode(size_t frameIndex) { parse(GIFFrameCountQuery); if (failed()) return; Vector<size_t> framesToDecode; size_t frameToDecode = frameIndex; do { framesToDecode.append(frameToDecode); frameToDecode = m_frameBufferCache[frameToDecode].requiredPreviousFrameIndex(); } while (frameToDecode != notFound && m_frameBufferCache[frameToDecode].status() != ImageFrame::FrameComplete); for (size_t i = framesToDecode.size(); i > 0; --i) { size_t frameIndex = framesToDecode[i - 1]; if (!m_reader->decode(frameIndex)) { setFailed(); return; } // We need more data to continue decoding. if (m_frameBufferCache[frameIndex].status() != ImageFrame::FrameComplete) break; } // It is also a fatal error if all data is received and we have decoded all // frames available but the file is truncated. if (frameIndex >= m_frameBufferCache.size() - 1 && isAllDataReceived() && m_reader && !m_reader->parseCompleted()) setFailed(); } bool GIFImageDecoder::initFrameBuffer(size_t frameIndex) { // Initialize the frame rect in our buffer. const GIFFrameContext* frameContext = m_reader->frameContext(frameIndex); ImageFrame* const buffer = &m_frameBufferCache[frameIndex]; size_t requiredPreviousFrameIndex = buffer->requiredPreviousFrameIndex(); if (requiredPreviousFrameIndex == notFound) { // This frame doesn't rely on any previous data. if (!buffer->setSize(size().width(), size().height())) return setFailed(); } else { const ImageFrame* prevBuffer = &m_frameBufferCache[requiredPreviousFrameIndex]; ASSERT(prevBuffer->status() == ImageFrame::FrameComplete); // Preserve the last frame as the starting state for this frame. if (!buffer->copyBitmapData(*prevBuffer)) return setFailed(); if (prevBuffer->disposalMethod() == ImageFrame::DisposeOverwriteBgcolor) { // We want to clear the previous frame to transparent, without // affecting pixels in the image outside of the frame. const IntRect& prevRect = prevBuffer->originalFrameRect(); ASSERT(!prevRect.contains(IntRect(IntPoint(), size()))); for (int y = prevRect.y(); y < prevRect.maxY(); ++y) { for (int x = prevRect.x(); x < prevRect.maxX(); ++x) buffer->setRGBA(x, y, 0, 0, 0, 0); } if ((prevRect.width() > 0) && (prevRect.height() > 0)) buffer->setHasAlpha(true); } } // Update our status to be partially complete. buffer->setStatus(ImageFrame::FramePartial); // Reset the alpha pixel tracker for this frame. m_currentBufferSawAlpha = false; return true; } } // namespace WebCore <|endoftext|>
<commit_before>#include <iostream> #include <iomanip> #include <string> #include <memory> #include <map> #include <algorithm> #include <Lexer.hpp> #include <Parser.hpp> #include <Visitors.hpp> #include <Checker.hpp> #include <ExprStmt.hpp> #include <RefExpr.hpp> #include <IdRef.hpp> using namespace std; void PrintResult(string varname, double val, bool suppressed) { if (!suppressed) { cout << varname << " =" << endl << endl; cout << " " << val << endl << endl; } } int main() { string input_line; auto id_table = make_shared<map<string, double>>(); (*id_table)["ans"] = 0; cout << "miniMAT: It's like MATLAB, but smaller." << endl; cout << "Copyright (C) 2014 Federico Menozzi" << endl; cout << endl; while (true) { cout << ">>> "; getline(cin, input_line); if (cin.eof()) { cout << endl; break; } if (input_line == "quit" || input_line == "exit") { break; } else if (input_line == "") { continue; } else if (input_line == "who") { for (auto var : *id_table) cout << var.first << endl; cout << endl; continue; } else if (input_line == "whos") { // Find longest var name (for formatting) auto w = max_element(begin(*id_table), end(*id_table), [](pair<string, double> p1, pair<string, double> p2) { return p1.first.size() < p2.first.size(); })->first.size(); for (auto var : *id_table) cout << setw(w) << var.first << " = " << var.second << endl; cout << endl; continue; } auto reporter = make_shared<miniMAT::reporter::ErrorReporter>(); miniMAT::lexer::Lexer lexer(input_line, reporter); miniMAT::parser::Parser parser(lexer, reporter); auto ast = parser.Parse(); if (reporter->HasErrors()) { reporter->ReportErrors(); cout << endl; continue; } miniMAT::checker::Checker checker(id_table, reporter); ast = checker.check(ast); if (reporter->HasErrors()) { reporter->ReportErrors(); cout << endl; } else { double ans = ast->VisitEvaluate(id_table); if (ast->GetClassName() == "ExprStmt") { auto exprstmt = dynamic_pointer_cast<miniMAT::ast::ExprStmt>(ast); if (exprstmt->expr->GetClassName() == "RefExpr") { auto refexpr = dynamic_pointer_cast<miniMAT::ast::RefExpr>(exprstmt->expr); auto varname = dynamic_pointer_cast<miniMAT::ast::IdRef>(refexpr->ref)->id->GetSpelling(); PrintResult(varname, id_table->at(varname), parser.SuppressedOutput()); } else { (*id_table)["ans"] = ans; PrintResult("ans", ans, parser.SuppressedOutput()); } } else if (ast->GetClassName() == "AssignStmt") { auto assign_stmt = dynamic_pointer_cast<miniMAT::ast::AssignStmt>(ast); if (assign_stmt->ref->GetClassName() == "IdRef") { auto idref = dynamic_pointer_cast<miniMAT::ast::IdRef>(assign_stmt->ref); auto varname = idref->id->GetSpelling(); auto val = assign_stmt->val; PrintResult(varname, val, parser.SuppressedOutput()); } } } } return 0; } <commit_msg>Just a wee bit of cleanup<commit_after>#include <iostream> #include <iomanip> #include <string> #include <memory> #include <map> #include <algorithm> #include <Lexer.hpp> #include <Parser.hpp> #include <Visitors.hpp> #include <Checker.hpp> #include <ExprStmt.hpp> #include <RefExpr.hpp> #include <IdRef.hpp> using namespace std; void PrintResult(string varname, double val, bool suppressed) { if (!suppressed) { cout << varname << " =" << endl << endl; cout << " " << val << endl << endl; } } int main() { string input_line; auto id_table = make_shared<map<string, double>>(); (*id_table)["ans"] = 0; cout << "miniMAT: It's like MATLAB, but smaller." << endl; cout << "Copyright (C) 2014 Federico Menozzi" << endl; cout << endl; while (true) { cout << ">>> "; getline(cin, input_line); if (cin.eof()) { cout << endl; break; } if (input_line == "quit" || input_line == "exit") { break; } else if (input_line == "") { continue; } else if (input_line == "who") { for (auto var : *id_table) cout << var.first << endl; cout << endl; continue; } else if (input_line == "whos") { // Find longest var name (for formatting) auto vars = *id_table; auto w = max_element(begin(vars), end(vars), [](pair<string, double> p1, pair<string, double> p2) { return p1.first.size() < p2.first.size(); })->first.size(); cout << endl; for (auto var : vars) cout << setw(w) << var.first << " = " << var.second << endl; cout << endl; continue; } auto reporter = make_shared<miniMAT::reporter::ErrorReporter>(); miniMAT::lexer::Lexer lexer(input_line, reporter); miniMAT::parser::Parser parser(lexer, reporter); auto ast = parser.Parse(); if (reporter->HasErrors()) { reporter->ReportErrors(); cout << endl; continue; } miniMAT::checker::Checker checker(id_table, reporter); ast = checker.check(ast); if (reporter->HasErrors()) { reporter->ReportErrors(); cout << endl; } else { double ans = ast->VisitEvaluate(id_table); if (ast->GetClassName() == "ExprStmt") { auto exprstmt = dynamic_pointer_cast<miniMAT::ast::ExprStmt>(ast); if (exprstmt->expr->GetClassName() == "RefExpr") { auto refexpr = dynamic_pointer_cast<miniMAT::ast::RefExpr>(exprstmt->expr); auto varname = dynamic_pointer_cast<miniMAT::ast::IdRef>(refexpr->ref)->id->GetSpelling(); PrintResult(varname, id_table->at(varname), parser.SuppressedOutput()); } else { (*id_table)["ans"] = ans; PrintResult("ans", ans, parser.SuppressedOutput()); } } else if (ast->GetClassName() == "AssignStmt") { auto assign_stmt = dynamic_pointer_cast<miniMAT::ast::AssignStmt>(ast); if (assign_stmt->ref->GetClassName() == "IdRef") { auto idref = dynamic_pointer_cast<miniMAT::ast::IdRef>(assign_stmt->ref); auto varname = idref->id->GetSpelling(); auto val = assign_stmt->val; PrintResult(varname, val, parser.SuppressedOutput()); } } } } return 0; } <|endoftext|>
<commit_before>/* listener.cc Mathieu Stefani, 12 August 2015 */ #include <pistache/listener.h> #include <pistache/peer.h> #include <pistache/common.h> #include <pistache/os.h> #include <pistache/transport.h> #include <pistache/errors.h> #include <sys/socket.h> #include <netinet/in.h> #include <netinet/tcp.h> #include <arpa/inet.h> #include <sys/types.h> #include <ifaddrs.h> #include <netdb.h> #include <sys/epoll.h> #include <sys/timerfd.h> #include <chrono> #include <memory> #include <vector> #include <cerrno> #include <signal.h> namespace Pistache { namespace Tcp { namespace { volatile sig_atomic_t g_listen_fd = -1; void closeListener() { if (g_listen_fd != -1) { ::close(g_listen_fd); g_listen_fd = -1; } } void handle_sigint(int) { closeListener(); } } void setSocketOptions(Fd fd, Flags<Options> options) { if (options.hasFlag(Options::ReuseAddr)) { int one = 1; TRY(::setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof (one))); } if (options.hasFlag(Options::Linger)) { struct linger opt; opt.l_onoff = 1; opt.l_linger = 1; TRY(::setsockopt(fd, SOL_SOCKET, SO_LINGER, &opt, sizeof (opt))); } if (options.hasFlag(Options::FastOpen)) { int hint = 5; TRY(::setsockopt(fd, SOL_TCP, TCP_FASTOPEN, &hint, sizeof (hint))); } if (options.hasFlag(Options::NoDelay)) { int one = 1; TRY(::setsockopt(fd, SOL_TCP, TCP_NODELAY, &one, sizeof (one))); } } Listener::Listener() : addr_() , listen_fd(-1) , backlog_(Const::MaxBacklog) , shutdownFd() , poller() , options_() , workers_(Const::DefaultWorkers) , reactor_() , transportKey() { } Listener::Listener(const Address& address) : addr_(address) , listen_fd(-1) , backlog_(Const::MaxBacklog) , shutdownFd() , poller() , options_() , workers_(Const::DefaultWorkers) , reactor_() , transportKey() { } Listener::~Listener() { if (isBound()) shutdown(); if (acceptThread.joinable()) acceptThread.join(); } void Listener::init( size_t workers, Flags<Options> options, int backlog) { if (workers > hardware_concurrency()) { // Log::warning() << "More workers than available cores" } options_ = options; backlog_ = backlog; if (options_.hasFlag(Options::InstallSignalHandler)) { if (signal(SIGINT, handle_sigint) == SIG_ERR) { throw std::runtime_error("Could not install signal handler"); } } workers_ = workers; } void Listener::setHandler(const std::shared_ptr<Handler>& handler) { handler_ = handler; } void Listener::pinWorker(size_t worker, const CpuSet& set) { UNUSED(worker) UNUSED(set) #if 0 if (ioGroup.empty()) { throw std::domain_error("Invalid operation, did you call init() before ?"); } if (worker > ioGroup.size()) { throw std::invalid_argument("Trying to pin invalid worker"); } auto &wrk = ioGroup[worker]; wrk->pin(set); #endif } bool Listener::systemSupportsIpv6(){ struct ifaddrs *ifaddr, *ifa; int family, n; bool supportsIpv6 = false; if (getifaddrs(&ifaddr) == -1) { throw std::runtime_error("Call to getifaddrs() failed"); } for (ifa = ifaddr, n = 0; ifa != NULL; ifa = ifa->ifa_next, n++) { if (ifa->ifa_addr == NULL) continue; family = ifa->ifa_addr->sa_family; if (family == AF_INET6) continue; } freeifaddrs(ifaddr); return supportsIpv6; } void Listener::bind() { bind(addr_); } void Listener::bind(const Address& address) { if (!handler_) throw std::runtime_error("Call setHandler before calling bind()"); addr_ = address; struct addrinfo hints; hints.ai_family = address.family(); hints.ai_socktype = SOCK_STREAM; hints.ai_flags = AI_PASSIVE; hints.ai_protocol = 0; const auto& host = addr_.host(); const auto& port = addr_.port().toString(); struct addrinfo *addrs; TRY(::getaddrinfo(host.c_str(), port.c_str(), &hints, &addrs)); int fd = -1; addrinfo *addr; for (addr = addrs; addr; addr = addr->ai_next) { fd = ::socket(addr->ai_family, addr->ai_socktype, addr->ai_protocol); if (fd < 0) continue; setSocketOptions(fd, options_); if (::bind(fd, addr->ai_addr, addr->ai_addrlen) < 0) { close(fd); continue; } TRY(::listen(fd, backlog_)); break; } // At this point, it is still possible that we couldn't bind any socket. If it is the case, the previous // loop would have exited naturally and addr will be null. if (addr == nullptr) { throw std::runtime_error(strerror(errno)); } make_non_blocking(fd); poller.addFd(fd, Polling::NotifyOn::Read, Polling::Tag(fd)); listen_fd = fd; g_listen_fd = fd; transport_ = std::make_shared<Transport>(handler_); reactor_.init(Aio::AsyncContext(workers_)); transportKey = reactor_.addHandler(transport_); } bool Listener::isBound() const { return listen_fd != -1; } // Return actual TCP port Listener is on, or 0 on error / no port. // Notes: // 1) Default constructor for 'Port()' sets value to 0. // 2) Socket is created inside 'Listener::run()', which is called from // 'Endpoint::serve()' and 'Endpoint::serveThreaded()'. So getting the // port is only useful if you attempt to do so from a _different_ thread // than the one running 'Listener::run()'. So for a traditional single- // threaded program this method is of little value. Port Listener::getPort() const { if (listen_fd == -1) { return Port(); } struct sockaddr_in sock_addr = {0}; socklen_t addrlen = sizeof(sock_addr); auto sock_addr_alias = reinterpret_cast<struct sockaddr*>(&sock_addr); if (-1 == getsockname(listen_fd, sock_addr_alias, &addrlen)) { return Port(); } return Port(ntohs(sock_addr.sin_port)); } void Listener::run() { reactor_.run(); for (;;) { std::vector<Polling::Event> events; int ready_fds = poller.poll(events, 128, std::chrono::milliseconds(-1)); if (ready_fds == -1) { if (errno == EINTR && g_listen_fd == -1) return; throw Error::system("Polling"); } for (const auto& event: events) { if (event.tag == shutdownFd.tag()) return; if (event.flags.hasFlag(Polling::NotifyOn::Read)) { auto fd = event.tag.value(); if (static_cast<ssize_t>(fd) == listen_fd) { try { handleNewConnection(); } catch (SocketError& ex) { std::cerr << "Server: " << ex.what() << std::endl; } catch (ServerError& ex) { std::cerr << "Server: " << ex.what() << std::endl; throw; } } } } } } void Listener::runThreaded() { shutdownFd.bind(poller); acceptThread = std::thread([=]() { this->run(); }); } void Listener::shutdown() { if (shutdownFd.isBound()) shutdownFd.notify(); reactor_.shutdown(); } Async::Promise<Listener::Load> Listener::requestLoad(const Listener::Load& old) { auto handlers = reactor_.handlers(transportKey); std::vector<Async::Promise<rusage>> loads; for (const auto& handler: handlers) { auto transport = std::static_pointer_cast<Transport>(handler); loads.push_back(transport->load()); } return Async::whenAll(std::begin(loads), std::end(loads)).then([=](const std::vector<rusage>& usages) { Load res; res.raw = usages; if (old.raw.empty()) { res.global = 0.0; for (size_t i = 0; i < handlers.size(); ++i) res.workers.push_back(0.0); } else { auto totalElapsed = [](rusage usage) { return (usage.ru_stime.tv_sec * 1e6 + usage.ru_stime.tv_usec) + (usage.ru_utime.tv_sec * 1e6 + usage.ru_utime.tv_usec); }; auto now = std::chrono::system_clock::now(); auto diff = now - old.tick; auto tick = std::chrono::duration_cast<std::chrono::microseconds>(diff); res.tick = now; for (size_t i = 0; i < usages.size(); ++i) { auto last = old.raw[i]; const auto& usage = usages[i]; auto nowElapsed = totalElapsed(usage); auto timeElapsed = nowElapsed - totalElapsed(last); auto loadPct = (timeElapsed * 100.0) / tick.count(); res.workers.push_back(loadPct); res.global += loadPct; } res.global /= usages.size(); } return res; }, Async::Throw); } Address Listener::address() const { return addr_; } Options Listener::options() const { return options_; } void Listener::handleNewConnection() { struct sockaddr_in peer_addr; socklen_t peer_addr_len = sizeof(peer_addr); int client_fd = ::accept(listen_fd, (struct sockaddr *)&peer_addr, &peer_addr_len); if (client_fd < 0) { if (errno == EBADF || errno == ENOTSOCK) throw ServerError(strerror(errno)); else throw SocketError(strerror(errno)); } make_non_blocking(client_fd); auto peer = std::make_shared<Peer>(Address::fromUnix((struct sockaddr *)&peer_addr)); peer->associateFd(client_fd); dispatchPeer(peer); } void Listener::dispatchPeer(const std::shared_ptr<Peer>& peer) { auto handlers = reactor_.handlers(transportKey); auto idx = peer->fd() % handlers.size(); auto transport = std::static_pointer_cast<Transport>(handlers[idx]); transport->handleNewPeer(peer); } } // namespace Tcp } // namespace Pistache <commit_msg>Corrected silly mistake where boolean wasn't set<commit_after>/* listener.cc Mathieu Stefani, 12 August 2015 */ #include <pistache/listener.h> #include <pistache/peer.h> #include <pistache/common.h> #include <pistache/os.h> #include <pistache/transport.h> #include <pistache/errors.h> #include <sys/socket.h> #include <netinet/in.h> #include <netinet/tcp.h> #include <arpa/inet.h> #include <sys/types.h> #include <ifaddrs.h> #include <netdb.h> #include <sys/epoll.h> #include <sys/timerfd.h> #include <chrono> #include <memory> #include <vector> #include <cerrno> #include <signal.h> namespace Pistache { namespace Tcp { namespace { volatile sig_atomic_t g_listen_fd = -1; void closeListener() { if (g_listen_fd != -1) { ::close(g_listen_fd); g_listen_fd = -1; } } void handle_sigint(int) { closeListener(); } } void setSocketOptions(Fd fd, Flags<Options> options) { if (options.hasFlag(Options::ReuseAddr)) { int one = 1; TRY(::setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof (one))); } if (options.hasFlag(Options::Linger)) { struct linger opt; opt.l_onoff = 1; opt.l_linger = 1; TRY(::setsockopt(fd, SOL_SOCKET, SO_LINGER, &opt, sizeof (opt))); } if (options.hasFlag(Options::FastOpen)) { int hint = 5; TRY(::setsockopt(fd, SOL_TCP, TCP_FASTOPEN, &hint, sizeof (hint))); } if (options.hasFlag(Options::NoDelay)) { int one = 1; TRY(::setsockopt(fd, SOL_TCP, TCP_NODELAY, &one, sizeof (one))); } } Listener::Listener() : addr_() , listen_fd(-1) , backlog_(Const::MaxBacklog) , shutdownFd() , poller() , options_() , workers_(Const::DefaultWorkers) , reactor_() , transportKey() { } Listener::Listener(const Address& address) : addr_(address) , listen_fd(-1) , backlog_(Const::MaxBacklog) , shutdownFd() , poller() , options_() , workers_(Const::DefaultWorkers) , reactor_() , transportKey() { } Listener::~Listener() { if (isBound()) shutdown(); if (acceptThread.joinable()) acceptThread.join(); } void Listener::init( size_t workers, Flags<Options> options, int backlog) { if (workers > hardware_concurrency()) { // Log::warning() << "More workers than available cores" } options_ = options; backlog_ = backlog; if (options_.hasFlag(Options::InstallSignalHandler)) { if (signal(SIGINT, handle_sigint) == SIG_ERR) { throw std::runtime_error("Could not install signal handler"); } } workers_ = workers; } void Listener::setHandler(const std::shared_ptr<Handler>& handler) { handler_ = handler; } void Listener::pinWorker(size_t worker, const CpuSet& set) { UNUSED(worker) UNUSED(set) #if 0 if (ioGroup.empty()) { throw std::domain_error("Invalid operation, did you call init() before ?"); } if (worker > ioGroup.size()) { throw std::invalid_argument("Trying to pin invalid worker"); } auto &wrk = ioGroup[worker]; wrk->pin(set); #endif } bool Listener::systemSupportsIpv6(){ struct ifaddrs *ifaddr, *ifa; int family, n; bool supportsIpv6 = false; if (getifaddrs(&ifaddr) == -1) { throw std::runtime_error("Call to getifaddrs() failed"); } for (ifa = ifaddr, n = 0; ifa != NULL; ifa = ifa->ifa_next, n++) { if (ifa->ifa_addr == NULL) continue; family = ifa->ifa_addr->sa_family; if (family == AF_INET6) { supportsIpv6 = true; continue; } } freeifaddrs(ifaddr); return supportsIpv6; } void Listener::bind() { bind(addr_); } void Listener::bind(const Address& address) { if (!handler_) throw std::runtime_error("Call setHandler before calling bind()"); addr_ = address; struct addrinfo hints; hints.ai_family = address.family(); hints.ai_socktype = SOCK_STREAM; hints.ai_flags = AI_PASSIVE; hints.ai_protocol = 0; const auto& host = addr_.host(); const auto& port = addr_.port().toString(); struct addrinfo *addrs; TRY(::getaddrinfo(host.c_str(), port.c_str(), &hints, &addrs)); int fd = -1; addrinfo *addr; for (addr = addrs; addr; addr = addr->ai_next) { fd = ::socket(addr->ai_family, addr->ai_socktype, addr->ai_protocol); if (fd < 0) continue; setSocketOptions(fd, options_); if (::bind(fd, addr->ai_addr, addr->ai_addrlen) < 0) { close(fd); continue; } TRY(::listen(fd, backlog_)); break; } // At this point, it is still possible that we couldn't bind any socket. If it is the case, the previous // loop would have exited naturally and addr will be null. if (addr == nullptr) { throw std::runtime_error(strerror(errno)); } make_non_blocking(fd); poller.addFd(fd, Polling::NotifyOn::Read, Polling::Tag(fd)); listen_fd = fd; g_listen_fd = fd; transport_ = std::make_shared<Transport>(handler_); reactor_.init(Aio::AsyncContext(workers_)); transportKey = reactor_.addHandler(transport_); } bool Listener::isBound() const { return listen_fd != -1; } // Return actual TCP port Listener is on, or 0 on error / no port. // Notes: // 1) Default constructor for 'Port()' sets value to 0. // 2) Socket is created inside 'Listener::run()', which is called from // 'Endpoint::serve()' and 'Endpoint::serveThreaded()'. So getting the // port is only useful if you attempt to do so from a _different_ thread // than the one running 'Listener::run()'. So for a traditional single- // threaded program this method is of little value. Port Listener::getPort() const { if (listen_fd == -1) { return Port(); } struct sockaddr_in sock_addr = {0}; socklen_t addrlen = sizeof(sock_addr); auto sock_addr_alias = reinterpret_cast<struct sockaddr*>(&sock_addr); if (-1 == getsockname(listen_fd, sock_addr_alias, &addrlen)) { return Port(); } return Port(ntohs(sock_addr.sin_port)); } void Listener::run() { reactor_.run(); for (;;) { std::vector<Polling::Event> events; int ready_fds = poller.poll(events, 128, std::chrono::milliseconds(-1)); if (ready_fds == -1) { if (errno == EINTR && g_listen_fd == -1) return; throw Error::system("Polling"); } for (const auto& event: events) { if (event.tag == shutdownFd.tag()) return; if (event.flags.hasFlag(Polling::NotifyOn::Read)) { auto fd = event.tag.value(); if (static_cast<ssize_t>(fd) == listen_fd) { try { handleNewConnection(); } catch (SocketError& ex) { std::cerr << "Server: " << ex.what() << std::endl; } catch (ServerError& ex) { std::cerr << "Server: " << ex.what() << std::endl; throw; } } } } } } void Listener::runThreaded() { shutdownFd.bind(poller); acceptThread = std::thread([=]() { this->run(); }); } void Listener::shutdown() { if (shutdownFd.isBound()) shutdownFd.notify(); reactor_.shutdown(); } Async::Promise<Listener::Load> Listener::requestLoad(const Listener::Load& old) { auto handlers = reactor_.handlers(transportKey); std::vector<Async::Promise<rusage>> loads; for (const auto& handler: handlers) { auto transport = std::static_pointer_cast<Transport>(handler); loads.push_back(transport->load()); } return Async::whenAll(std::begin(loads), std::end(loads)).then([=](const std::vector<rusage>& usages) { Load res; res.raw = usages; if (old.raw.empty()) { res.global = 0.0; for (size_t i = 0; i < handlers.size(); ++i) res.workers.push_back(0.0); } else { auto totalElapsed = [](rusage usage) { return (usage.ru_stime.tv_sec * 1e6 + usage.ru_stime.tv_usec) + (usage.ru_utime.tv_sec * 1e6 + usage.ru_utime.tv_usec); }; auto now = std::chrono::system_clock::now(); auto diff = now - old.tick; auto tick = std::chrono::duration_cast<std::chrono::microseconds>(diff); res.tick = now; for (size_t i = 0; i < usages.size(); ++i) { auto last = old.raw[i]; const auto& usage = usages[i]; auto nowElapsed = totalElapsed(usage); auto timeElapsed = nowElapsed - totalElapsed(last); auto loadPct = (timeElapsed * 100.0) / tick.count(); res.workers.push_back(loadPct); res.global += loadPct; } res.global /= usages.size(); } return res; }, Async::Throw); } Address Listener::address() const { return addr_; } Options Listener::options() const { return options_; } void Listener::handleNewConnection() { struct sockaddr_in peer_addr; socklen_t peer_addr_len = sizeof(peer_addr); int client_fd = ::accept(listen_fd, (struct sockaddr *)&peer_addr, &peer_addr_len); if (client_fd < 0) { if (errno == EBADF || errno == ENOTSOCK) throw ServerError(strerror(errno)); else throw SocketError(strerror(errno)); } make_non_blocking(client_fd); auto peer = std::make_shared<Peer>(Address::fromUnix((struct sockaddr *)&peer_addr)); peer->associateFd(client_fd); dispatchPeer(peer); } void Listener::dispatchPeer(const std::shared_ptr<Peer>& peer) { auto handlers = reactor_.handlers(transportKey); auto idx = peer->fd() % handlers.size(); auto transport = std::static_pointer_cast<Transport>(handlers[idx]); transport->handleNewPeer(peer); } } // namespace Tcp } // namespace Pistache <|endoftext|>
<commit_before>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkConjugateGradientOptimizerTest.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 2000 National Library of Medicine All rights reserved. See COPYRIGHT.txt for copyright details. =========================================================================*/ #include <itkConjugateGradientOptimizer.h> #include <vnl/vnl_vector.h> #include <vnl/vnl_matrix.h> typedef vnl_matrix<double> MatrixType; typedef vnl_vector<double> VectorType; /** * The objectif function is the quadratic form: * * 1/2 x^T A x - b^T x * * Where A is represented as an itkMatrix and * b is represented as a itkVector * * The system in this example is: * * | 3 2 ||x| | 2| |0| * | 2 6 ||y| + |-8| = |0| * * * the solution is the vector | 2 -2 | * */ class CostFunction { public: enum { SpaceDimension=2 }; CostFunction():m_A(2,2),m_b(2) { m_A[0][0] = 3; m_A[0][1] = 2; m_A[1][0] = 2; m_A[1][1] = 6; m_b[0] = 2; m_b[1] = -8; } double GetValue( const VectorType & v ) { std::cout << "GetValue( " << v << " ) = "; VectorType Av = m_A * v; double val = ( inner_product<double>( Av , v ) )/2.0; val -= inner_product< double >( m_b , v ); std::cout << val << std::endl; return val; } VectorType GetDerivative( const VectorType & v ) { std::cout << "GetDerivative( " << v << " ) = "; VectorType grad = m_A * v - m_b; std::cout << grad << std::endl; return grad; } private: MatrixType m_A; VectorType m_b; }; int main() { typedef itk::ConjugateGradientOptimizer< CostFunction > OptimizerType; typedef OptimizerType::InternalOptimizerType vnlOptimizerType; // Declaration of a itkOptimizer OptimizerType::Pointer itkOptimizer = OptimizerType::New(); // Declaration of the CostFunction adaptor CostFunction costFunction; itkOptimizer->SetCostFunction( &costFunction ); const double F_Tolerance = 1e-3; // Function value tolerance const double G_Tolerance = 1e-4; // Gradient magnitude tolerance const double X_Tolerance = 1e-8; // Search space tolerance const double Epsilon_Function = 1e-10; // Step const int Max_Iterations = 100; // Maximum number of iterations vnlOptimizerType & vnlOptimizer = itkOptimizer->GetOptimizer(); vnlOptimizer.set_f_tolerance( F_Tolerance ); vnlOptimizer.set_g_tolerance( G_Tolerance ); vnlOptimizer.set_x_tolerance( X_Tolerance ); vnlOptimizer.set_epsilon_function( Epsilon_Function ); vnlOptimizer.set_max_function_evals( Max_Iterations ); vnlOptimizer.set_trace( true ); // activate print out per iteration vnlOptimizer.set_verbose( true ); // activate verbose mode vnlOptimizer.set_check_derivatives( 3 ); VectorType initialValue(2); // constructor requires vector size initialValue[0] = 100; // We start not so far from | 2 -2 | initialValue[1] = -100; itkOptimizer->StartOptimization( initialValue ); std::cout << "End condition = " << vnlOptimizer.get_failure_code() << std::endl; std::cout << "Number of iters = " << vnlOptimizer.get_num_iterations() << std::endl; std::cout << "Number of evals = " << vnlOptimizer.get_num_evaluations() << std::endl; return 0; } <commit_msg>ENH: Print out of the final solution added<commit_after>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkConjugateGradientOptimizerTest.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 2000 National Library of Medicine All rights reserved. See COPYRIGHT.txt for copyright details. =========================================================================*/ #include <itkConjugateGradientOptimizer.h> #include <vnl/vnl_vector.h> #include <vnl/vnl_matrix.h> typedef vnl_matrix<double> MatrixType; typedef vnl_vector<double> VectorType; /** * The objectif function is the quadratic form: * * 1/2 x^T A x - b^T x * * Where A is represented as an itkMatrix and * b is represented as a itkVector * * The system in this example is: * * | 3 2 ||x| | 2| |0| * | 2 6 ||y| + |-8| = |0| * * * the solution is the vector | 2 -2 | * */ class CostFunction { public: enum { SpaceDimension=2 }; CostFunction():m_A(2,2),m_b(2) { m_A[0][0] = 3; m_A[0][1] = 2; m_A[1][0] = 2; m_A[1][1] = 6; m_b[0] = 2; m_b[1] = -8; } double GetValue( const VectorType & v ) { std::cout << "GetValue( " << v << " ) = "; VectorType Av = m_A * v; double val = ( inner_product<double>( Av , v ) )/2.0; val -= inner_product< double >( m_b , v ); std::cout << val << std::endl; return val; } VectorType GetDerivative( const VectorType & v ) { std::cout << "GetDerivative( " << v << " ) = "; VectorType grad = m_A * v - m_b; std::cout << grad << std::endl; return grad; } private: MatrixType m_A; VectorType m_b; }; int main() { typedef itk::ConjugateGradientOptimizer< CostFunction > OptimizerType; typedef OptimizerType::InternalOptimizerType vnlOptimizerType; // Declaration of a itkOptimizer OptimizerType::Pointer itkOptimizer = OptimizerType::New(); // Declaration of the CostFunction adaptor CostFunction costFunction; itkOptimizer->SetCostFunction( &costFunction ); const double F_Tolerance = 1e-3; // Function value tolerance const double G_Tolerance = 1e-4; // Gradient magnitude tolerance const double X_Tolerance = 1e-8; // Search space tolerance const double Epsilon_Function = 1e-10; // Step const int Max_Iterations = 100; // Maximum number of iterations vnlOptimizerType & vnlOptimizer = itkOptimizer->GetOptimizer(); vnlOptimizer.set_f_tolerance( F_Tolerance ); vnlOptimizer.set_g_tolerance( G_Tolerance ); vnlOptimizer.set_x_tolerance( X_Tolerance ); vnlOptimizer.set_epsilon_function( Epsilon_Function ); vnlOptimizer.set_max_function_evals( Max_Iterations ); vnlOptimizer.set_trace( true ); // activate print out per iteration vnlOptimizer.set_verbose( true ); // activate verbose mode vnlOptimizer.set_check_derivatives( 3 ); VectorType initialValue(2); // constructor requires vector size initialValue[0] = 100; // We start not so far from | 2 -2 | initialValue[1] = -100; itkOptimizer->StartOptimization( initialValue ); std::cout << "End condition = " << vnlOptimizer.get_failure_code() << std::endl; std::cout << "Number of iters = " << vnlOptimizer.get_num_iterations() << std::endl; std::cout << "Number of evals = " << vnlOptimizer.get_num_evaluations() << std::endl; std::cout << std::endl; std::cout << "Solution = " << initialValue << std::endl; return 0; } <|endoftext|>
<commit_before>/****************************************************************************** * This file is part of the Gluon Development Platform * Copyright (c) 2010-2011 Arjen Hiemstra <ahiemstra@heimr.nl> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "mainwindow.h" #include <unistd.h> #include <KDE/KSplashScreen> #include <KDE/KApplication> #include <KDE/KAboutData> #include <QString> #include <KDE/KCmdLineArgs> #include <KDE/KStandardDirs> #include <QtDeclarative/QDeclarativeContext> #include <QtDeclarative/QDeclarativeView> #include <core/gluon_global.h> #include "aboutdata.h" #include <QDebug> int main( int argc, char** argv ) { KAboutData aboutData = GluonCreator::aboutData(); KCmdLineArgs::init( argc, argv, &aboutData ); KCmdLineOptions options; options.add( "+project", ki18n( "Project to open" ) ); KCmdLineArgs::addCmdLineOptions( options ); KApplication app; KCmdLineArgs* args = KCmdLineArgs::parsedArgs(); //Create and show a splashscreen KSplashScreen splash( QPixmap( KGlobal::dirs()->locate( "appdata", "gluon-creator-splash.png" ) ) ); splash.show(); app.processEvents(); //Create the main window GluonCreator::MainWindow* window = new GluonCreator::MainWindow( args->count() > 0 ? args->arg( 0 ) : QString() ); window->show(); splash.finish( window ); kapp->setActiveWindow(window); app.exec(); } <commit_msg>creator: Remove the splash screen since we now have a proper welcome dialog<commit_after>/****************************************************************************** * This file is part of the Gluon Development Platform * Copyright (c) 2010-2011 Arjen Hiemstra <ahiemstra@heimr.nl> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "mainwindow.h" #include <unistd.h> #include <KDE/KSplashScreen> #include <KDE/KApplication> #include <KDE/KAboutData> #include <QString> #include <KDE/KCmdLineArgs> #include <KDE/KStandardDirs> #include <QtDeclarative/QDeclarativeContext> #include <QtDeclarative/QDeclarativeView> #include <core/gluon_global.h> #include "aboutdata.h" #include <QDebug> int main( int argc, char** argv ) { KAboutData aboutData = GluonCreator::aboutData(); KCmdLineArgs::init( argc, argv, &aboutData ); KCmdLineOptions options; options.add( "+project", ki18n( "Project to open" ) ); KCmdLineArgs::addCmdLineOptions( options ); KApplication app; KCmdLineArgs* args = KCmdLineArgs::parsedArgs(); //Create the main window GluonCreator::MainWindow* window = new GluonCreator::MainWindow( args->count() > 0 ? args->arg( 0 ) : QString() ); window->show(); kapp->setActiveWindow(window); app.exec(); } <|endoftext|>
<commit_before>//---------------------------------------------------------------------------- // // "Copyright Centre National d'Etudes Spatiales" // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // //---------------------------------------------------------------------------- // $Id$ #include <otb/HermiteInterpolator.h> #include <string> #include <cassert> #include <cmath> namespace ossimplugins { HermiteInterpolator::HermiteInterpolator(): theNPointsAvailable(0), theXValues(NULL), theYValues(NULL), thedYValues(NULL), prodC(NULL), sumC(NULL), isComputed(false) { } HermiteInterpolator::HermiteInterpolator(int nbrPoints, double* x, double* y, double* dy): theNPointsAvailable(nbrPoints), isComputed(false) { if(x != NULL) { theXValues = new double[theNPointsAvailable]; for (int i=0;i<theNPointsAvailable;i++) { theXValues[i] = x[i]; } } else { theXValues = NULL; } if(y != NULL) { theYValues = new double[theNPointsAvailable]; for (int i=0;i<theNPointsAvailable;i++) { theYValues[i] = y[i]; } } else { theYValues = NULL; } if(dy != NULL) { thedYValues = new double[theNPointsAvailable]; for (int i=0;i<theNPointsAvailable;i++) { thedYValues[i] = dy[i]; } } else { thedYValues = NULL; } for (int i = 1 ; i < theNPointsAvailable ; i++) { /** * @todo Verifier que l'interpolateur n'ai pas besoin ques les abscisses soitent strictement croissantes */ /* * Les abscisses ne sont pas croissantes */ // if (theXValues[i] <= theXValues[i-1]) // std::cerr << "WARNING: Hermite interpolation assumes increasing x values" << std::endl; assert(theXValues[i] > theXValues[i-1]); } } HermiteInterpolator::~HermiteInterpolator() { Clear(); } HermiteInterpolator::HermiteInterpolator(const HermiteInterpolator& rhs): theNPointsAvailable(rhs.theNPointsAvailable), isComputed(false) { if(rhs.theXValues != NULL) { theXValues = new double[theNPointsAvailable]; for (int i=0;i<theNPointsAvailable;i++) { theXValues[i] = rhs.theXValues[i]; } } else { theXValues = NULL; } if(rhs.theYValues != NULL) { theYValues = new double[theNPointsAvailable]; for (int i=0;i<theNPointsAvailable;i++) { theYValues[i] = rhs.theYValues[i]; } } else { theYValues = NULL; } if(rhs.thedYValues != NULL) { thedYValues = new double[theNPointsAvailable]; for (int i=0;i<theNPointsAvailable;i++) { thedYValues[i] = rhs.thedYValues[i]; } } else { thedYValues = NULL; } } HermiteInterpolator& HermiteInterpolator::operator =(const HermiteInterpolator& rhs) { Clear(); theNPointsAvailable = rhs.theNPointsAvailable; isComputed = false; if(rhs.theXValues != NULL) { theXValues = new double[theNPointsAvailable]; for (int i=0;i<theNPointsAvailable;i++) { theXValues[i] = rhs.theXValues[i]; } } else { theXValues = NULL; } if(rhs.theYValues != NULL) { theYValues = new double[theNPointsAvailable]; for (int i=0;i<theNPointsAvailable;i++) { theYValues[i] = rhs.theYValues[i]; } } else { theYValues = NULL; } if(rhs.thedYValues != NULL) { thedYValues = new double[theNPointsAvailable]; for (int i=0;i<theNPointsAvailable;i++) { thedYValues[i] = rhs.thedYValues[i]; } } else { thedYValues = NULL; } return *this; } // Interpolation method for the value and the derivative int HermiteInterpolator::Interpolate(double x, double& y, double& dy) const { //NOTE assume that x is increasing // Not enough points to interpolate if (theNPointsAvailable < 2) return -1; y = 0.0; dy = 0.0; double epsilon = 0.0000000000001; //Precompute useful value if they are not available if (!isComputed) { Precompute(); } for (int i = 0; i < theNPointsAvailable; i++) { double si = 0.0; double hi = 1.0; double ui = 0; //derivative computation double r = x - theXValues[i]; // check if the point is on the list if ( std::abs(r/x) < epsilon ) { y = theYValues[i]; dy = thedYValues[i]; return 0; } for (int j = 0; j < theNPointsAvailable; j++) { if (j != i) { hi = hi * (x - theXValues[j]); ui = ui + 1 / (x - theXValues[j]);//derivative computation } } hi *= prodC[i]; si = sumC[i]; double f = 1.0 - 2.0 * r * si; y += (theYValues[i] * f + thedYValues[i] * r) * hi * hi; ui *= hi;//derivative computation double fp = 2.0 * hi * (ui * (1.0 - 2.0 * si * r) - hi * si);//derivative computation double d = hi * (hi + 2.0 * r * ui);//derivative computation dy += fp * theYValues[i] + d * thedYValues[i];//derivative computation } return 0; } // Interpolation method for the value only // this is about 5 times faster and should be used when time // is a constraint. int HermiteInterpolator::Interpolate(double x, double& y) const { //NOTE assume that x is increasing // Not enough points to interpolate if (theNPointsAvailable < 2) return -1; y = 0.0; //Precompute useful value if they are not available if (!isComputed) { Precompute(); } for (int i = 0; i < theNPointsAvailable; i++) { double si = 0.0; double hi = 1.0; double r = x - theXValues[i]; for (int j = 0; j < theNPointsAvailable; j++) { if (j != i) { hi = hi * (x - theXValues[j]); } } hi *= prodC[i]; si = sumC[i]; double f = 1.0 - 2.0 * r * si; y += (theYValues[i] * f + thedYValues[i] * r) * hi * hi; } return 0; } int HermiteInterpolator::Precompute() const { prodC = new double[theNPointsAvailable]; sumC= new double[theNPointsAvailable]; for (int i = 0; i < theNPointsAvailable; i++) { prodC[i] = 1; sumC[i] = 0; for (int j = 0; j < theNPointsAvailable; j++) { if (j != i) { double v = 1.0 / (theXValues[i] - theXValues[j]); prodC[i] *= v; sumC[i] += v; } } } isComputed = true; return 0; } void HermiteInterpolator::Clear() { if (theXValues != NULL) { delete[] theXValues; theXValues = NULL; } if (theYValues != NULL) { delete[] theYValues; theYValues = NULL; } if (thedYValues != NULL) { delete[] thedYValues; thedYValues = NULL; } if (prodC != NULL) { delete[] prodC; prodC = NULL; } if (sumC != NULL) { delete[] sumC; prodC = NULL; } isComputed = false; theNPointsAvailable = 0; } } <commit_msg>BUG: fix Asar limit case<commit_after>//---------------------------------------------------------------------------- // // "Copyright Centre National d'Etudes Spatiales" // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // //---------------------------------------------------------------------------- // $Id$ #include <otb/HermiteInterpolator.h> #include <string> #include <cassert> #include <cmath> namespace ossimplugins { HermiteInterpolator::HermiteInterpolator(): theNPointsAvailable(0), theXValues(NULL), theYValues(NULL), thedYValues(NULL), prodC(NULL), sumC(NULL), isComputed(false) { } HermiteInterpolator::HermiteInterpolator(int nbrPoints, double* x, double* y, double* dy): theNPointsAvailable(nbrPoints), isComputed(false) { if(x != NULL) { theXValues = new double[theNPointsAvailable]; for (int i=0;i<theNPointsAvailable;i++) { theXValues[i] = x[i]; } } else { theXValues = NULL; } if(y != NULL) { theYValues = new double[theNPointsAvailable]; for (int i=0;i<theNPointsAvailable;i++) { theYValues[i] = y[i]; } } else { theYValues = NULL; } if(dy != NULL) { thedYValues = new double[theNPointsAvailable]; for (int i=0;i<theNPointsAvailable;i++) { thedYValues[i] = dy[i]; } } else { thedYValues = NULL; } for (int i = 1 ; i < theNPointsAvailable ; i++) { /** * @todo Verifier que l'interpolateur n'ai pas besoin ques les abscisses soitent strictement croissantes */ /* * Les abscisses ne sont pas croissantes */ // if (theXValues[i] <= theXValues[i-1]) // std::cerr << "WARNING: Hermite interpolation assumes increasing x values" << std::endl; assert(theXValues[i] > theXValues[i-1]); } } HermiteInterpolator::~HermiteInterpolator() { Clear(); } HermiteInterpolator::HermiteInterpolator(const HermiteInterpolator& rhs): theNPointsAvailable(rhs.theNPointsAvailable), isComputed(false) { if(rhs.theXValues != NULL) { theXValues = new double[theNPointsAvailable]; for (int i=0;i<theNPointsAvailable;i++) { theXValues[i] = rhs.theXValues[i]; } } else { theXValues = NULL; } if(rhs.theYValues != NULL) { theYValues = new double[theNPointsAvailable]; for (int i=0;i<theNPointsAvailable;i++) { theYValues[i] = rhs.theYValues[i]; } } else { theYValues = NULL; } if(rhs.thedYValues != NULL) { thedYValues = new double[theNPointsAvailable]; for (int i=0;i<theNPointsAvailable;i++) { thedYValues[i] = rhs.thedYValues[i]; } } else { thedYValues = NULL; } } HermiteInterpolator& HermiteInterpolator::operator =(const HermiteInterpolator& rhs) { Clear(); theNPointsAvailable = rhs.theNPointsAvailable; isComputed = false; if(rhs.theXValues != NULL) { theXValues = new double[theNPointsAvailable]; for (int i=0;i<theNPointsAvailable;i++) { theXValues[i] = rhs.theXValues[i]; } } else { theXValues = NULL; } if(rhs.theYValues != NULL) { theYValues = new double[theNPointsAvailable]; for (int i=0;i<theNPointsAvailable;i++) { theYValues[i] = rhs.theYValues[i]; } } else { theYValues = NULL; } if(rhs.thedYValues != NULL) { thedYValues = new double[theNPointsAvailable]; for (int i=0;i<theNPointsAvailable;i++) { thedYValues[i] = rhs.thedYValues[i]; } } else { thedYValues = NULL; } return *this; } // Interpolation method for the value and the derivative int HermiteInterpolator::Interpolate(double x, double& y, double& dy) const { //NOTE assume that x is increasing // Not enough points to interpolate if (theNPointsAvailable < 2) return -1; y = 0.0; dy = 0.0; double epsilon = 0.0000000000001; //Precompute useful value if they are not available if (!isComputed) { Precompute(); } for (int i = 0; i < theNPointsAvailable; i++) { double si = 0.0; double hi = 1.0; double ui = 0; //derivative computation double r = x - theXValues[i]; // check if the point is on the list if ( std::abs(r) < epsilon ) { y = theYValues[i]; dy = thedYValues[i]; return 0; } for (int j = 0; j < theNPointsAvailable; j++) { if (j != i) { hi = hi * (x - theXValues[j]); ui = ui + 1 / (x - theXValues[j]);//derivative computation } } hi *= prodC[i]; si = sumC[i]; double f = 1.0 - 2.0 * r * si; y += (theYValues[i] * f + thedYValues[i] * r) * hi * hi; ui *= hi;//derivative computation double fp = 2.0 * hi * (ui * (1.0 - 2.0 * si * r) - hi * si);//derivative computation double d = hi * (hi + 2.0 * r * ui);//derivative computation dy += fp * theYValues[i] + d * thedYValues[i];//derivative computation } return 0; } // Interpolation method for the value only // this is about 5 times faster and should be used when time // is a constraint. int HermiteInterpolator::Interpolate(double x, double& y) const { //NOTE assume that x is increasing // Not enough points to interpolate if (theNPointsAvailable < 2) return -1; y = 0.0; //Precompute useful value if they are not available if (!isComputed) { Precompute(); } for (int i = 0; i < theNPointsAvailable; i++) { double si = 0.0; double hi = 1.0; double r = x - theXValues[i]; for (int j = 0; j < theNPointsAvailable; j++) { if (j != i) { hi = hi * (x - theXValues[j]); } } hi *= prodC[i]; si = sumC[i]; double f = 1.0 - 2.0 * r * si; y += (theYValues[i] * f + thedYValues[i] * r) * hi * hi; } return 0; } int HermiteInterpolator::Precompute() const { prodC = new double[theNPointsAvailable]; sumC= new double[theNPointsAvailable]; for (int i = 0; i < theNPointsAvailable; i++) { prodC[i] = 1; sumC[i] = 0; for (int j = 0; j < theNPointsAvailable; j++) { if (j != i) { double v = 1.0 / (theXValues[i] - theXValues[j]); prodC[i] *= v; sumC[i] += v; } } } isComputed = true; return 0; } void HermiteInterpolator::Clear() { if (theXValues != NULL) { delete[] theXValues; theXValues = NULL; } if (theYValues != NULL) { delete[] theYValues; theYValues = NULL; } if (thedYValues != NULL) { delete[] thedYValues; thedYValues = NULL; } if (prodC != NULL) { delete[] prodC; prodC = NULL; } if (sumC != NULL) { delete[] sumC; prodC = NULL; } isComputed = false; theNPointsAvailable = 0; } } <|endoftext|>
<commit_before>/************************************************************************* > File Name: CardLoader.cpp > Project Name: Hearthstone++ > Author: Chan-Ho Chris Ohk > Purpose: Card loader that loads data from cards.json. > Created Time: 2017/08/13 > Copyright (c) 2017, Chan-Ho Chris Ohk *************************************************************************/ #include <Enums/StringToEnums.h> #include <Loaders/CardLoader.h> #include <Models/Entities/Enchantment.h> #include <Models/Entities/Hero.h> #include <Models/Entities/HeroPower.h> #include <Models/Entities/Minion.h> #include <Models/Entities/Spell.h> #include <Models/Entities/Weapon.h> #include <fstream> namespace Hearthstonepp { std::vector<Card*> CardLoader::Load() const { // Read card data from JSON file std::ifstream cardFile(RESOURCES_DIR "cards.json"); json j; if (!cardFile.is_open()) { throw std::runtime_error("Can't open cards.json"); } cardFile >> j; std::vector<Card*> cards; cards.reserve(j.size()); for (auto& card : j) { const std::string id = std::move(card["id"].get<std::string>()); const Rarity rarity = card["rarity"].is_null() ? Rarity::FREE : std::move(ConverterFromStringToRarity.at(card["rarity"].get<std::string>())); const Faction faction = card["faction"].is_null() ? Faction::NEUTRAL : std::move(ConverterFromStringToFaction.at(card["faction"].get<std::string>())); const CardSet cardSet = card["set"].is_null() ? CardSet::NONE : std::move(ConverterFromStringToCardSet.at(card["set"].get<std::string>())); const CardClass cardClass = card["cardClass"].is_null() ? CardClass::NEUTRAL : std::move(ConverterFromStringToCardClass.at(card["cardClass"].get<std::string>())); const CardType cardType = card["type"].is_null() ? CardType::INVALID : std::move(ConverterFromStringToCardType.at(card["type"].get<std::string>())); const Race race = card["race"].is_null() ? Race::INVALID : std::move(ConverterFromStringToRace.at(card["race"].get<std::string>())); const std::string name = card["name"].is_null() ? "" : std::move(card["name"]["enUS"].get<std::string>()); const std::string text = card["text"].is_null() ? "" : std::move(card["text"]["enUS"].get<std::string>()); const bool collectible = card["collectible"].is_null() ? false : card["collectible"].get<bool>(); const int cost = card["cost"].is_null() ? -1 : card["cost"].get<int>(); const int attack = card["attack"].is_null() ? -1 : card["attack"].get<int>(); const int health = card["health"].is_null() ? -1 : card["health"].get<int>(); const int durability = card["durability"].is_null() ? -1 : card["durability"].get<int>(); std::vector<GameTag> mechanics; for (auto& mechanic : card["mechanics"]) { mechanics.emplace_back(std::move(ConverterFromStringToGameTag.at(mechanic.get<std::string>()))); } std::map<PlayReq, int> playRequirements; for (auto iter = card["playRequirements"].begin(); iter != card["playRequirements"].end(); ++iter) { playRequirements.try_emplace(std::move(ConverterFromStringToPlayReq.at(iter.key())), iter.value().get<int>()); } std::vector<std::string> entourages; for (auto& entourage : card["entourage"]) { entourages.emplace_back(std::move(entourage.get<std::string>())); } Card* c; switch (cardType) { case CardType::HERO: c = new Hero( id, rarity, faction, cardSet, cardClass, cardType, race, name, text, collectible, cost, attack, health, durability, mechanics, playRequirements, entourages); break; case CardType::MINION: c = new Minion( id, rarity, faction, cardSet, cardClass, cardType, race, name, text, collectible, cost, attack, health, durability, mechanics, playRequirements, entourages); break; case CardType::SPELL: c = new Spell( id, rarity, faction, cardSet, cardClass, cardType, race, name, text, collectible, cost, attack, health, durability, mechanics, playRequirements, entourages); break; case CardType::ENCHANTMENT: c = new Enchantment( id, rarity, faction, cardSet, cardClass, cardType, race, name, text, collectible, cost, attack, health, durability, mechanics, playRequirements, entourages); break; case CardType::WEAPON: c = new Weapon( id, rarity, faction, cardSet, cardClass, cardType, race, name, text, collectible, cost, attack, health, durability, mechanics, playRequirements, entourages); break; case CardType::HERO_POWER: c = new HeroPower( id, rarity, faction, cardSet, cardClass, cardType, race, name, text, collectible, cost, attack, health, durability, mechanics, playRequirements, entourages); break; default: // TODO: Log invalid card type break; } cards.emplace_back(c); } cardFile.close(); return cards; } }<commit_msg>Update CardLoader.cpp - Remove std::move for copy elision<commit_after>/************************************************************************* > File Name: CardLoader.cpp > Project Name: Hearthstone++ > Author: Chan-Ho Chris Ohk > Purpose: Card loader that loads data from cards.json. > Created Time: 2017/08/13 > Copyright (c) 2017, Chan-Ho Chris Ohk *************************************************************************/ #include <Enums/StringToEnums.h> #include <Loaders/CardLoader.h> #include <Models/Entities/Enchantment.h> #include <Models/Entities/Hero.h> #include <Models/Entities/HeroPower.h> #include <Models/Entities/Minion.h> #include <Models/Entities/Spell.h> #include <Models/Entities/Weapon.h> #include <fstream> namespace Hearthstonepp { std::vector<Card*> CardLoader::Load() const { // Read card data from JSON file std::ifstream cardFile(RESOURCES_DIR "cards.json"); json j; if (!cardFile.is_open()) { throw std::runtime_error("Can't open cards.json"); } cardFile >> j; std::vector<Card*> cards; cards.reserve(j.size()); for (auto& card : j) { const std::string id = card["id"].get<std::string>(); const Rarity rarity = card["rarity"].is_null() ? Rarity::FREE : std::move(ConverterFromStringToRarity.at(card["rarity"].get<std::string>())); const Faction faction = card["faction"].is_null() ? Faction::NEUTRAL : std::move(ConverterFromStringToFaction.at(card["faction"].get<std::string>())); const CardSet cardSet = card["set"].is_null() ? CardSet::NONE : std::move(ConverterFromStringToCardSet.at(card["set"].get<std::string>())); const CardClass cardClass = card["cardClass"].is_null() ? CardClass::NEUTRAL : std::move(ConverterFromStringToCardClass.at(card["cardClass"].get<std::string>())); const CardType cardType = card["type"].is_null() ? CardType::INVALID : std::move(ConverterFromStringToCardType.at(card["type"].get<std::string>())); const Race race = card["race"].is_null() ? Race::INVALID : std::move(ConverterFromStringToRace.at(card["race"].get<std::string>())); const std::string name = card["name"].is_null() ? "" : card["name"]["enUS"].get<std::string>(); const std::string text = card["text"].is_null() ? "" : card["text"]["enUS"].get<std::string>(); const bool collectible = card["collectible"].is_null() ? false : card["collectible"].get<bool>(); const int cost = card["cost"].is_null() ? -1 : card["cost"].get<int>(); const int attack = card["attack"].is_null() ? -1 : card["attack"].get<int>(); const int health = card["health"].is_null() ? -1 : card["health"].get<int>(); const int durability = card["durability"].is_null() ? -1 : card["durability"].get<int>(); std::vector<GameTag> mechanics; for (auto& mechanic : card["mechanics"]) { mechanics.emplace_back(std::move(ConverterFromStringToGameTag.at(mechanic.get<std::string>()))); } std::map<PlayReq, int> playRequirements; for (auto iter = card["playRequirements"].begin(); iter != card["playRequirements"].end(); ++iter) { playRequirements.try_emplace(std::move(ConverterFromStringToPlayReq.at(iter.key())), iter.value().get<int>()); } std::vector<std::string> entourages; for (auto& entourage : card["entourage"]) { entourages.emplace_back(entourage.get<std::string>()); } Card* c; switch (cardType) { case CardType::HERO: c = new Hero( id, rarity, faction, cardSet, cardClass, cardType, race, name, text, collectible, cost, attack, health, durability, mechanics, playRequirements, entourages); break; case CardType::MINION: c = new Minion( id, rarity, faction, cardSet, cardClass, cardType, race, name, text, collectible, cost, attack, health, durability, mechanics, playRequirements, entourages); break; case CardType::SPELL: c = new Spell( id, rarity, faction, cardSet, cardClass, cardType, race, name, text, collectible, cost, attack, health, durability, mechanics, playRequirements, entourages); break; case CardType::ENCHANTMENT: c = new Enchantment( id, rarity, faction, cardSet, cardClass, cardType, race, name, text, collectible, cost, attack, health, durability, mechanics, playRequirements, entourages); break; case CardType::WEAPON: c = new Weapon( id, rarity, faction, cardSet, cardClass, cardType, race, name, text, collectible, cost, attack, health, durability, mechanics, playRequirements, entourages); break; case CardType::HERO_POWER: c = new HeroPower( id, rarity, faction, cardSet, cardClass, cardType, race, name, text, collectible, cost, attack, health, durability, mechanics, playRequirements, entourages); break; default: // TODO: Log invalid card type break; } cards.emplace_back(c); } cardFile.close(); return cards; } }<|endoftext|>
<commit_before>#include <algorithm> #include <map> #include <iostream> #include "google/protobuf/descriptor.h" #include "vtrc-rpc-lowlevel.pb.h" #include "vtrc-rpc-options.pb.h" #include "vtrc-rpc-channel.h" #include "vtrc-protocol-layer.h" #include "vtrc-exception.h" #include "vtrc-bind.h" namespace vtrc { namespace common { namespace gpb = google::protobuf; namespace { void default_error_cb( const rpc_channel::lowlevel_unit_type &llu ) { throw vtrc::common::exception( llu.error( ).code( ), llu.error( ).category( ), llu.error( ).additional( ) ); } void default_chan_error_cb( const char *message ) { throw vtrc::common::exception( rpc::errors::ERR_CHANNEL, message ); } rpc_channel::proto_error_cb_type get_default_error_cb( ) { return vtrc::bind( default_error_cb, vtrc::placeholders::_1 ); } rpc_channel::channel_error_cb_type get_default_chan_error_cb( ) { return vtrc::bind( default_chan_error_cb, vtrc::placeholders::_1 ); } } struct rpc_channel::impl { unsigned direct_type_; unsigned callback_type_; std::string data_; rpc_channel::proto_error_cb_type error_cb_; rpc_channel::channel_error_cb_type chan_error_cb_; impl( unsigned direct_call_type, unsigned callback_type ) :direct_type_(direct_call_type) ,callback_type_(callback_type) ,error_cb_(get_default_error_cb( )) ,chan_error_cb_(get_default_chan_error_cb( )) { } }; rpc_channel::rpc_channel(unsigned direct_call_type, unsigned callback_type) :impl_(new impl(direct_call_type, callback_type)) { } rpc_channel::~rpc_channel( ) { delete impl_; } rpc_channel::lowlevel_unit_sptr rpc_channel::create_lowlevel( const gpb::MethodDescriptor *method, const gpb::Message *request, gpb::Message *response) { lowlevel_unit_sptr llu(vtrc::make_shared<lowlevel_unit_type>( )); const std::string &serv_name(method->service( )->full_name( )); const std::string &meth_name(method->name( )); llu->mutable_call( )->set_service_id( serv_name ); llu->mutable_call( )->set_method_id( meth_name ); if( request ) { llu->set_request( request->SerializeAsString( ) ); } if( !response ) { llu->mutable_opt( )->set_accept_response( false ); } return llu; } rpc_channel::lowlevel_unit_sptr rpc_channel::make_lowlevel( const google::protobuf::MethodDescriptor* method, const google::protobuf::Message* request, google::protobuf::Message* response ) { rpc_channel::lowlevel_unit_sptr res = create_lowlevel( method, request, response ); return res; } rpc_channel::lowlevel_unit_sptr rpc_channel::raw_call( rpc_channel::lowlevel_unit_sptr /*llu*/, lowlevel_closure_type /*callbacks*/ ) { ;;; /// nothing to do here return rpc_channel::lowlevel_unit_sptr( ); } void rpc_channel::set_channel_data( const std::string &data ) { impl_->data_ = data; } const std::string &rpc_channel::channel_data( ) { return impl_->data_; } bool can_accept_callbacks( const common::call_context *cc ) { #if 1 /// yeap. we always set it up rpc::lowlevel_unit const *llu = cc->get_lowlevel_message( ); return llu->opt( ).wait( ) && llu->opt( ).accept_callbacks( ); #else rpc::options const *opts = cc->get_call_options( ); rpc::lowlevel_unit const *llu = cc->get_lowlevel_message( ); bool accept_callbacks = llu->opt( ).has_accept_callbacks( ) ? llu->opt( ).accept_callbacks( ) : opts->accept_callbacks( ); bool wait = llu->opt( ).has_wait( ) ? llu->opt( ).wait( ) : opts->wait( ); return wait && accept_callbacks; #endif } void rpc_channel::configure_message( common::connection_iface_sptr c, unsigned mess_type, lowlevel_unit_type &llu ) const { const common::call_context *cc(common::call_context::get(c)); llu.set_id(c->get_protocol( ).next_index( )); if( mess_type == impl_->callback_type_ ) { if( cc && can_accept_callbacks( cc ) ) { llu.mutable_info( )->set_message_type( mess_type ); llu.set_target_id( cc->get_lowlevel_message( )->id( ) ); } else { llu.mutable_info( )->set_message_type( impl_->direct_type_ ); } } else { llu.mutable_info( )->set_message_type( mess_type ); } } rpc_channel::lowlevel_unit_sptr rpc_channel::call_and_wait_raw ( google::protobuf::uint64 call_id, lowlevel_unit_type &llu, common::connection_iface_sptr &cl, lowlevel_closure_type events, const rpc::options *call_opt ) const { cl->get_protocol( ).call_rpc_method( call_id, llu ); const unsigned mess_type( llu.info( ).message_type( ) ); bool wait = true; lowlevel_unit_sptr top (vtrc::make_shared<lowlevel_unit_type>( )); if( !events ) { llu.mutable_opt( )->set_accept_callbacks( false ); } while( wait ) { top->Clear( ); cl->get_protocol( ).read_slot_for( call_id, top, call_opt->timeout( ) ); if( top->error( ).code( ) != rpc::errors::ERR_NO_ERROR ) { wait = false; } else if( top->info( ).message_type( ) != mess_type ) { if( events ) { events( *top ); } } else { wait = false; } } cl->get_protocol( ).erase_slot( call_id ); return top; } const rpc_channel::proto_error_cb_type & rpc_channel::get_proto_error_callback( ) const { return impl_->error_cb_; } void rpc_channel::set_proto_error_callback( const rpc_channel::proto_error_cb_type &value ) { if( value ) { impl_->error_cb_ = value; } else { impl_->error_cb_ = get_default_error_cb( ); } } const rpc_channel::channel_error_cb_type & rpc_channel::get_channel_error_callback( ) const { return impl_->chan_error_cb_; } void rpc_channel::set_channel_error_callback( const rpc_channel::channel_error_cb_type &value ) { if( value ) { impl_->chan_error_cb_ = value; } else { impl_->chan_error_cb_ = get_default_chan_error_cb( ); } } bool rpc_channel::call_and_wait( google::protobuf::uint64 call_id, const lowlevel_unit_type &llu, google::protobuf::Message *response, connection_iface_sptr &cl, const rpc::options *call_opt ) const { cl->get_protocol( ).call_rpc_method( call_id, llu ); const unsigned mess_type(llu.info( ).message_type( )); bool wait = true; lowlevel_unit_sptr top (vtrc::make_shared<lowlevel_unit_type>( )); while( wait ) { top->Clear( ); cl->get_protocol( ).read_slot_for( call_id, top, call_opt->timeout( ) ); if( top->error( ).code( ) != rpc::errors::ERR_NO_ERROR ) { cl->get_protocol( ).erase_slot( call_id ); impl_->error_cb_( *top ); // throw vtrc::common::exception( top->error( ).code( ), // top->error( ).category( ), // top->error( ).additional( ) ); return false; } /// from client: call, insertion_call /// from server: event, callback if( top->info( ).message_type( ) != mess_type ) { cl->get_protocol( ).make_local_call( top ); } else { if( response ) { response->ParseFromString( top->response( ) ); } wait = false; } } cl->get_protocol( ).erase_slot( call_id ); return true; } protocol_layer &rpc_channel::get_protocol(connection_iface &cl) { return cl.get_protocol( ); } void rpc_channel::CallMethod( const gpb::MethodDescriptor *method, gpb::RpcController *controller, const gpb::Message *request, gpb::Message *response, gpb::Closure *done) { lowlevel_unit_sptr llu( create_lowlevel( method, request, response ) ); if( !impl_->data_.empty( ) ) { llu->set_channel_data( impl_->data_ ); } send_message( *llu, method, controller, request, response, done ); } }} <commit_msg>errors<commit_after>#include <algorithm> #include <map> #include <iostream> #include "google/protobuf/descriptor.h" #include "vtrc-rpc-lowlevel.pb.h" #include "vtrc-rpc-options.pb.h" #include "vtrc-rpc-channel.h" #include "vtrc-protocol-layer.h" #include "vtrc-exception.h" #include "vtrc-bind.h" namespace vtrc { namespace common { namespace gpb = google::protobuf; namespace ph = vtrc::placeholders; namespace { void default_error_cb( const rpc_channel::lowlevel_unit_type &llu ) { throw vtrc::common::exception( llu.error( ).code( ), llu.error( ).category( ), llu.error( ).additional( ) ); } void default_chan_error_cb( const char *message ) { throw vtrc::common::exception( rpc::errors::ERR_CHANNEL, message ); } rpc_channel::proto_error_cb_type get_default_error_cb( ) { return vtrc::bind( default_error_cb, ph::_1 ); } rpc_channel::channel_error_cb_type get_default_chan_error_cb( ) { return vtrc::bind( default_chan_error_cb, ph::_1 ); } } struct rpc_channel::impl { unsigned direct_type_; unsigned callback_type_; std::string data_; rpc_channel::proto_error_cb_type error_cb_; rpc_channel::channel_error_cb_type chan_error_cb_; impl( unsigned direct_call_type, unsigned callback_type ) :direct_type_(direct_call_type) ,callback_type_(callback_type) ,error_cb_(get_default_error_cb( )) ,chan_error_cb_(get_default_chan_error_cb( )) { } }; rpc_channel::rpc_channel(unsigned direct_call_type, unsigned callback_type) :impl_(new impl(direct_call_type, callback_type)) { } rpc_channel::~rpc_channel( ) { delete impl_; } rpc_channel::lowlevel_unit_sptr rpc_channel::create_lowlevel( const gpb::MethodDescriptor *method, const gpb::Message *request, gpb::Message *response) { lowlevel_unit_sptr llu(vtrc::make_shared<lowlevel_unit_type>( )); const std::string &serv_name(method->service( )->full_name( )); const std::string &meth_name(method->name( )); llu->mutable_call( )->set_service_id( serv_name ); llu->mutable_call( )->set_method_id( meth_name ); if( request ) { llu->set_request( request->SerializeAsString( ) ); } if( !response ) { llu->mutable_opt( )->set_accept_response( false ); } return llu; } rpc_channel::lowlevel_unit_sptr rpc_channel::make_lowlevel( const google::protobuf::MethodDescriptor* method, const google::protobuf::Message* request, google::protobuf::Message* response ) { rpc_channel::lowlevel_unit_sptr res = create_lowlevel( method, request, response ); return res; } rpc_channel::lowlevel_unit_sptr rpc_channel::raw_call( rpc_channel::lowlevel_unit_sptr /*llu*/, lowlevel_closure_type /*callbacks*/ ) { ;;; /// nothing to do here return rpc_channel::lowlevel_unit_sptr( ); } void rpc_channel::set_channel_data( const std::string &data ) { impl_->data_ = data; } const std::string &rpc_channel::channel_data( ) { return impl_->data_; } bool can_accept_callbacks( const common::call_context *cc ) { #if 1 /// yeap. we always set it up rpc::lowlevel_unit const *llu = cc->get_lowlevel_message( ); return llu->opt( ).wait( ) && llu->opt( ).accept_callbacks( ); #else rpc::options const *opts = cc->get_call_options( ); rpc::lowlevel_unit const *llu = cc->get_lowlevel_message( ); bool accept_callbacks = llu->opt( ).has_accept_callbacks( ) ? llu->opt( ).accept_callbacks( ) : opts->accept_callbacks( ); bool wait = llu->opt( ).has_wait( ) ? llu->opt( ).wait( ) : opts->wait( ); return wait && accept_callbacks; #endif } void rpc_channel::configure_message( common::connection_iface_sptr c, unsigned mess_type, lowlevel_unit_type &llu ) const { const common::call_context *cc(common::call_context::get(c)); llu.set_id(c->get_protocol( ).next_index( )); if( mess_type == impl_->callback_type_ ) { if( cc && can_accept_callbacks( cc ) ) { llu.mutable_info( )->set_message_type( mess_type ); llu.set_target_id( cc->get_lowlevel_message( )->id( ) ); } else { llu.mutable_info( )->set_message_type( impl_->direct_type_ ); } } else { llu.mutable_info( )->set_message_type( mess_type ); } } rpc_channel::lowlevel_unit_sptr rpc_channel::call_and_wait_raw ( google::protobuf::uint64 call_id, lowlevel_unit_type &llu, common::connection_iface_sptr &cl, lowlevel_closure_type events, const rpc::options *call_opt ) const { cl->get_protocol( ).call_rpc_method( call_id, llu ); const unsigned mess_type( llu.info( ).message_type( ) ); bool wait = true; lowlevel_unit_sptr top (vtrc::make_shared<lowlevel_unit_type>( )); if( !events ) { llu.mutable_opt( )->set_accept_callbacks( false ); } while( wait ) { top->Clear( ); cl->get_protocol( ).read_slot_for( call_id, top, call_opt->timeout( ) ); if( top->error( ).code( ) != rpc::errors::ERR_NO_ERROR ) { wait = false; } else if( top->info( ).message_type( ) != mess_type ) { if( events ) { events( *top ); } } else { wait = false; } } cl->get_protocol( ).erase_slot( call_id ); return top; } const rpc_channel::proto_error_cb_type & rpc_channel::get_proto_error_callback( ) const { return impl_->error_cb_; } void rpc_channel::set_proto_error_callback( const rpc_channel::proto_error_cb_type &value ) { if( value ) { impl_->error_cb_ = value; } else { impl_->error_cb_ = get_default_error_cb( ); } } const rpc_channel::channel_error_cb_type & rpc_channel::get_channel_error_callback( ) const { return impl_->chan_error_cb_; } void rpc_channel::set_channel_error_callback( const rpc_channel::channel_error_cb_type &value ) { if( value ) { impl_->chan_error_cb_ = value; } else { impl_->chan_error_cb_ = get_default_chan_error_cb( ); } } bool rpc_channel::call_and_wait( google::protobuf::uint64 call_id, const lowlevel_unit_type &llu, google::protobuf::Message *response, connection_iface_sptr &cl, const rpc::options *call_opt ) const { cl->get_protocol( ).call_rpc_method( call_id, llu ); const unsigned mess_type(llu.info( ).message_type( )); bool wait = true; lowlevel_unit_sptr top (vtrc::make_shared<lowlevel_unit_type>( )); while( wait ) { top->Clear( ); cl->get_protocol( ).read_slot_for( call_id, top, call_opt->timeout( ) ); if( top->error( ).code( ) != rpc::errors::ERR_NO_ERROR ) { cl->get_protocol( ).erase_slot( call_id ); impl_->error_cb_( *top ); // throw vtrc::common::exception( top->error( ).code( ), // top->error( ).category( ), // top->error( ).additional( ) ); return false; } /// from client: call, insertion_call /// from server: event, callback if( top->info( ).message_type( ) != mess_type ) { cl->get_protocol( ).make_local_call( top ); } else { if( response ) { response->ParseFromString( top->response( ) ); } wait = false; } } cl->get_protocol( ).erase_slot( call_id ); return true; } protocol_layer &rpc_channel::get_protocol(connection_iface &cl) { return cl.get_protocol( ); } void rpc_channel::CallMethod( const gpb::MethodDescriptor *method, gpb::RpcController *controller, const gpb::Message *request, gpb::Message *response, gpb::Closure *done) { lowlevel_unit_sptr llu( create_lowlevel( method, request, response ) ); if( !impl_->data_.empty( ) ) { llu->set_channel_data( impl_->data_ ); } send_message( *llu, method, controller, request, response, done ); } }} <|endoftext|>
<commit_before>#include "Globals.h" #include "App.h" #include "ModuleInput.h" #include "ModuleCamera3D.h" #include "EditorUI.h" #include "Game.h" #include "ModuleWindow.h" #include "Cursor.h" #include "imgui.h" ModuleCamera3D::ModuleCamera3D(bool start_enabled) : Module(start_enabled) { SetName("Camera3D"); CalculateViewMatrix(); // Normalized vectors that define the direction of X, Y and Z X = vec3(1.0f, 0.0f, 0.0f); Y = vec3(0.0f, 1.0f, 0.0f); Z = vec3(0.0f, 0.0f, 1.0f); // Position of the camera X, Y and Z Position = vec3(0.0f, 0.0f, 0.0f); // Reference point in which is rotating from Reference = vec3(0.0f, 0.0f, 0.0f); } ModuleCamera3D::~ModuleCamera3D() {} bool ModuleCamera3D::Awake() { bool ret = true; LOG_OUTPUT("Loading Camera3D"); return ret; } // ----------------------------------------------------------------- bool ModuleCamera3D::Start() { bool ret = true; LOG_OUTPUT("Setting up the camera"); camera_speed = 20.0f; wheel_speed = 5.0f; mouse_sensitivity = 0.25f; return ret; } // ----------------------------------------------------------------- bool ModuleCamera3D::CleanUp() { LOG_OUTPUT("Cleaning camera"); return true; } // ----------------------------------------------------------------- bool ModuleCamera3D::Update() { bool ret = true; float speed = camera_speed * App->GetDT(); if (App->input->GetKeyRepeat(SDL_SCANCODE_LSHIFT)) speed = camera_speed/2 * App->GetDT(); if (App->input->GetKeyRepeat(SDL_SCANCODE_R)) MoveUp(speed); if (App->input->GetKeyRepeat(SDL_SCANCODE_F)) MoveDown(speed); if (IsMouseInsideWindow()) { mouse_movement = true; } // Mouse motion ---------------- if (mouse_movement) { if (App->input->GetMouseWheel() == 1) { MoveFront(wheel_speed); } else if (App->input->GetMouseWheel() == -1) { MoveBack(wheel_speed); } else if (App->input->GetMouseButton(SDL_BUTTON_RIGHT) == KEY_REPEAT) { App->window->GetCursor()->Hand(); if (App->input->GetKeyRepeat(SDL_SCANCODE_W)) MoveFront(speed); if (App->input->GetKeyRepeat(SDL_SCANCODE_S)) MoveBack(speed); if (App->input->GetKeyRepeat(SDL_SCANCODE_A)) MoveLeft(speed); if (App->input->GetKeyRepeat(SDL_SCANCODE_D)) MoveRight(speed); if (App->input->GetKeyRepeat(SDL_SCANCODE_LALT) || App->input->GetKeyRepeat(SDL_SCANCODE_RALT)) { Orbit(vec3(0, 0, 0), App->input->GetMouseXMotion(), App->input->GetMouseYMotion()); App->window->GetCursor()->SizeAll(); } else { Rotate(App->input->GetMouseXMotion(), App->input->GetMouseYMotion()); } } else { mouse_movement = false; } } // Recalculate matrix ------------- //LOG_OUTPUT("X:%f, %f, %f Y:%f, %f, %f Z:%f, %f, %f ", X.x, X.y, X.z, Y.x, Y.y, Y.z, Z.x, Z.y, Z.z); LOG_OUTPUT("5. %f %f %f", X.x, X.y, X.z); CalculateViewMatrix(); LOG_OUTPUT("6. %f %f %f", X.x, X.y, X.z); return ret; } // ----------------------------------------------------------------- void ModuleCamera3D::Look(const vec3 &Position, const vec3 &Reference, bool RotateAroundReference) { this->Position = Position; this->Reference = Reference; Z = normalize(Position - Reference); X = normalize(cross(vec3(0.0f, 1.0f, 0.0f), Z)); Y = cross(Z, X); if (!RotateAroundReference) { this->Reference = this->Position; this->Position += Z * 0.05f; } CalculateViewMatrix(); } // ----------------------------------------------------------------- void ModuleCamera3D::LookAt(const vec3 &Spot) { Reference = Spot; Z = normalize(Position - Reference); X = normalize(cross(vec3(0.0f, 1.0f, 0.0f), Z)); Y = cross(Z, X); CalculateViewMatrix(); } // ----------------------------------------------------------------- void ModuleCamera3D::Move(const vec3 &Movement) { Position += Movement; Reference += Movement; CalculateViewMatrix(); } // ----------------------------------------------------------------- float* ModuleCamera3D::GetViewMatrix() { return &ViewMatrix; } // ----------------------------------------------------------------- void ModuleCamera3D::CalculateViewMatrix() { ViewMatrix = mat4x4(X.x, Y.x, Z.x, 0.0f, X.y, Y.y, Z.y, 0.0f, X.z, Y.z, Z.z, 0.0f, -dot(X, Position), -dot(Y, Position), -dot(Z, Position), 1.0f); ViewMatrixInverse = inverse(ViewMatrix); } void ModuleCamera3D::MoveFront(float speed) { vec3 newPos(0, 0, 0); newPos -= Z * speed; Position += newPos; Reference += newPos; } void ModuleCamera3D::MoveBack(float speed) { vec3 newPos(0, 0, 0); newPos += Z * speed; Position += newPos; Reference += newPos; } void ModuleCamera3D::MoveLeft(float speed) { vec3 newPos(0, 0, 0); newPos -= X * speed; Position += newPos; Reference += newPos; } void ModuleCamera3D::MoveRight(float speed) { vec3 newPos(0, 0, 0); newPos += X * speed; Position += newPos; Reference += newPos; } void ModuleCamera3D::MoveUp(float speed) { vec3 newPos(0, 0, 0); newPos.y += speed; Position += newPos; Reference += newPos; } void ModuleCamera3D::MoveDown(float speed) { vec3 newPos(0, 0, 0); newPos.y -= speed; Position += newPos; Reference += newPos; } void ModuleCamera3D::Orbit(vec3 orbit_center, float motion_x, float motion_y) { Reference = orbit_center; int dx = -motion_x; int dy = -motion_y; Position -= Reference; if (dx != 0) { float DeltaX = (float)dx * mouse_sensitivity; // Rotate arround the y axis X = rotate(X, DeltaX, vec3(0.0f, 1.0f, 0.0f)); Y = rotate(Y, DeltaX, vec3(0.0f, 1.0f, 0.0f)); Z = rotate(Z, DeltaX, vec3(0.0f, 1.0f, 0.0f)); } if (dy != 0) { float DeltaY = (float)dy * mouse_sensitivity; // Rotate arround the X direction Y = rotate(Y, DeltaY, X); Z = rotate(Z, DeltaY, X); } Position = Reference + Z * length(Position); } void ModuleCamera3D::Rotate(float motion_x, float motion_y) { Reference = Position; int dx = -motion_x; int dy = -motion_y; Position -= Reference; if (dx != 0) { float DeltaX = (float)dx * mouse_sensitivity; X = rotate(X, DeltaX, vec3(0.0f, 1.0f, 0.0f)); Y = rotate(Y, DeltaX, vec3(0.0f, 1.0f, 0.0f)); Z = rotate(Z, DeltaX, vec3(0.0f, 1.0f, 0.0f)); } if (dy != 0) { float DeltaY = (float)dy * mouse_sensitivity; Y = rotate(Y, DeltaY, X); Z = rotate(Z, DeltaY, X); } Position = Reference + Z * length(Position); } bool ModuleCamera3D::IsMouseInsideWindow() const { return PointInRect(float2(App->input->GetMouseX(), App->input->GetMouseY()), App->editorUI->GameRect()); } <commit_msg>Cleaned log<commit_after>#include "Globals.h" #include "App.h" #include "ModuleInput.h" #include "ModuleCamera3D.h" #include "EditorUI.h" #include "Game.h" #include "ModuleWindow.h" #include "Cursor.h" #include "imgui.h" ModuleCamera3D::ModuleCamera3D(bool start_enabled) : Module(start_enabled) { SetName("Camera3D"); CalculateViewMatrix(); // Normalized vectors that define the direction of X, Y and Z X = vec3(1.0f, 0.0f, 0.0f); Y = vec3(0.0f, 1.0f, 0.0f); Z = vec3(0.0f, 0.0f, 1.0f); // Position of the camera X, Y and Z Position = vec3(0.0f, 0.0f, 0.0f); // Reference point in which is rotating from Reference = vec3(0.0f, 0.0f, 0.0f); } ModuleCamera3D::~ModuleCamera3D() {} bool ModuleCamera3D::Awake() { bool ret = true; LOG_OUTPUT("Loading Camera3D"); return ret; } // ----------------------------------------------------------------- bool ModuleCamera3D::Start() { bool ret = true; LOG_OUTPUT("Setting up the camera"); camera_speed = 20.0f; wheel_speed = 5.0f; mouse_sensitivity = 0.25f; return ret; } // ----------------------------------------------------------------- bool ModuleCamera3D::CleanUp() { LOG_OUTPUT("Cleaning camera"); return true; } // ----------------------------------------------------------------- bool ModuleCamera3D::Update() { bool ret = true; float speed = camera_speed * App->GetDT(); if (App->input->GetKeyRepeat(SDL_SCANCODE_LSHIFT)) speed = camera_speed/2 * App->GetDT(); if (App->input->GetKeyRepeat(SDL_SCANCODE_R)) MoveUp(speed); if (App->input->GetKeyRepeat(SDL_SCANCODE_F)) MoveDown(speed); if (IsMouseInsideWindow()) { mouse_movement = true; } // Mouse motion ---------------- if (mouse_movement) { if (App->input->GetMouseWheel() == 1) { MoveFront(wheel_speed); } else if (App->input->GetMouseWheel() == -1) { MoveBack(wheel_speed); } else if (App->input->GetMouseButton(SDL_BUTTON_RIGHT) == KEY_REPEAT) { App->window->GetCursor()->Hand(); if (App->input->GetKeyRepeat(SDL_SCANCODE_W)) MoveFront(speed); if (App->input->GetKeyRepeat(SDL_SCANCODE_S)) MoveBack(speed); if (App->input->GetKeyRepeat(SDL_SCANCODE_A)) MoveLeft(speed); if (App->input->GetKeyRepeat(SDL_SCANCODE_D)) MoveRight(speed); if (App->input->GetKeyRepeat(SDL_SCANCODE_LALT) || App->input->GetKeyRepeat(SDL_SCANCODE_RALT)) { Orbit(vec3(0, 0, 0), App->input->GetMouseXMotion(), App->input->GetMouseYMotion()); App->window->GetCursor()->SizeAll(); } else { Rotate(App->input->GetMouseXMotion(), App->input->GetMouseYMotion()); } } else { mouse_movement = false; } } // Recalculate matrix ------------- CalculateViewMatrix(); return ret; } // ----------------------------------------------------------------- void ModuleCamera3D::Look(const vec3 &Position, const vec3 &Reference, bool RotateAroundReference) { this->Position = Position; this->Reference = Reference; Z = normalize(Position - Reference); X = normalize(cross(vec3(0.0f, 1.0f, 0.0f), Z)); Y = cross(Z, X); if (!RotateAroundReference) { this->Reference = this->Position; this->Position += Z * 0.05f; } CalculateViewMatrix(); } // ----------------------------------------------------------------- void ModuleCamera3D::LookAt(const vec3 &Spot) { Reference = Spot; Z = normalize(Position - Reference); X = normalize(cross(vec3(0.0f, 1.0f, 0.0f), Z)); Y = cross(Z, X); CalculateViewMatrix(); } // ----------------------------------------------------------------- void ModuleCamera3D::Move(const vec3 &Movement) { Position += Movement; Reference += Movement; CalculateViewMatrix(); } // ----------------------------------------------------------------- float* ModuleCamera3D::GetViewMatrix() { return &ViewMatrix; } // ----------------------------------------------------------------- void ModuleCamera3D::CalculateViewMatrix() { ViewMatrix = mat4x4(X.x, Y.x, Z.x, 0.0f, X.y, Y.y, Z.y, 0.0f, X.z, Y.z, Z.z, 0.0f, -dot(X, Position), -dot(Y, Position), -dot(Z, Position), 1.0f); ViewMatrixInverse = inverse(ViewMatrix); } void ModuleCamera3D::MoveFront(float speed) { vec3 newPos(0, 0, 0); newPos -= Z * speed; Position += newPos; Reference += newPos; } void ModuleCamera3D::MoveBack(float speed) { vec3 newPos(0, 0, 0); newPos += Z * speed; Position += newPos; Reference += newPos; } void ModuleCamera3D::MoveLeft(float speed) { vec3 newPos(0, 0, 0); newPos -= X * speed; Position += newPos; Reference += newPos; } void ModuleCamera3D::MoveRight(float speed) { vec3 newPos(0, 0, 0); newPos += X * speed; Position += newPos; Reference += newPos; } void ModuleCamera3D::MoveUp(float speed) { vec3 newPos(0, 0, 0); newPos.y += speed; Position += newPos; Reference += newPos; } void ModuleCamera3D::MoveDown(float speed) { vec3 newPos(0, 0, 0); newPos.y -= speed; Position += newPos; Reference += newPos; } void ModuleCamera3D::Orbit(vec3 orbit_center, float motion_x, float motion_y) { Reference = orbit_center; int dx = -motion_x; int dy = -motion_y; Position -= Reference; if (dx != 0) { float DeltaX = (float)dx * mouse_sensitivity; // Rotate arround the y axis X = rotate(X, DeltaX, vec3(0.0f, 1.0f, 0.0f)); Y = rotate(Y, DeltaX, vec3(0.0f, 1.0f, 0.0f)); Z = rotate(Z, DeltaX, vec3(0.0f, 1.0f, 0.0f)); } if (dy != 0) { float DeltaY = (float)dy * mouse_sensitivity; // Rotate arround the X direction Y = rotate(Y, DeltaY, X); Z = rotate(Z, DeltaY, X); } Position = Reference + Z * length(Position); } void ModuleCamera3D::Rotate(float motion_x, float motion_y) { Reference = Position; int dx = -motion_x; int dy = -motion_y; Position -= Reference; if (dx != 0) { float DeltaX = (float)dx * mouse_sensitivity; X = rotate(X, DeltaX, vec3(0.0f, 1.0f, 0.0f)); Y = rotate(Y, DeltaX, vec3(0.0f, 1.0f, 0.0f)); Z = rotate(Z, DeltaX, vec3(0.0f, 1.0f, 0.0f)); } if (dy != 0) { float DeltaY = (float)dy * mouse_sensitivity; Y = rotate(Y, DeltaY, X); Z = rotate(Z, DeltaY, X); } Position = Reference + Z * length(Position); } bool ModuleCamera3D::IsMouseInsideWindow() const { return PointInRect(float2(App->input->GetMouseX(), App->input->GetMouseY()), App->editorUI->GameRect()); } <|endoftext|>
<commit_before>/* * The Apache Software License, Version 1.1 * * * Copyright (c) 1999 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xalan" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ #include <cassert> #include <fstream> #include <iostream> #include <strstream> #if !defined(NDEBUG) && defined(_MSC_VER) #include <crtdbg.h> #endif //These came from the debug test. #include <cstdio> #include <ctime> #include <string> #include <string.h> #include <vector> #include <util/PlatformUtils.hpp> #include <PlatformSupport/DOMStringHelper.hpp> #include <PlatformSupport/XalanFileOutputStream.hpp> #include <PlatformSupport/XalanOutputStreamPrintWriter.hpp> #include <XercesParserLiaison/XercesDOMSupport.hpp> #include <XPath/XObjectFactoryDefault.hpp> #include <XPath/XPathSupportDefault.hpp> #include <XPath/XPathFactoryDefault.hpp> #include <XSLT/StylesheetConstructionContextDefault.hpp> #include <XSLT/StylesheetExecutionContextDefault.hpp> #include <XSLT/StylesheetRoot.hpp> #include <XSLT/XSLTEngineImpl.hpp> #include <XSLT/XSLTInit.hpp> #include <XSLT/XSLTInputSource.hpp> #include <XSLT/XSLTProcessorEnvSupportDefault.hpp> #include <XSLT/XSLTResultTarget.hpp> #include <XercesParserLiaison/XercesParserLiaison.hpp> #include <XMLFileReporter.hpp> //This is here for the threads. #define WIN32_LEAN_AND_MEAN #include <windows.h> #include <winbase.h> #define THREADFUNCTIONRETURN DWORD WINAPI #if !defined(XALAN_NO_NAMESPACES) using std::cerr; using std::cout; using std::cin; using std::endl; using std::ifstream; using std::ios_base; using std::ostrstream; using std::string; #endif // This is here for memory leak testing. #if defined(_DEBUG) #include <crtdbg.h> #endif const char* xslStylesheets[] = { "v:\\xsl-test\\perf\\basic\\basic-all_well", "v:\\xsl-test\\perf\\basic\\basic-datetranscode", "v:\\xsl-test\\perf\\basic\\basic-dict2", "v:\\xsl-test\\perf\\basic\\basic-Fischer-Euwe", //"v:\\xsl-test\\perf\\basic\\basic-queens", "v:\\xsl-test\\perf\\large\\large-all_well", //"v:\\xsl-test\\perf\\large\\large-evans_large", "v:\\xsl-test\\perf\\nodes\\nodes-fancy_xml_tree_viewer_34", "v:\\xsl-test\\perf\\nodes\\nodes-showtree-19991008", "v:\\xsl-test\\perf\\sort\\sort-big", "v:\\xsl-test\\perf\\xpath\\xpath-evans_small", "v:\\xsl-test\\perf\\xpath\\xpath-evans_tiny", 0 }; const char* outputDir = "d:\\xslt-results\\perf\\test\\"; // Used to hold compiled stylesheet, and source document. XalanNode* glbSourceXML[sizeof(xslStylesheets) / sizeof(const char*)]; StylesheetRoot* glbStylesheetRoot[sizeof(xslStylesheets) / sizeof(const char*)]; void outputMessage(int iter) { cout << "\n" << "Starting Iteration: " << iter << '\0'; } int main( int argc, const char* argv []) { XMLFileReporter theXMLFileReporter; theXMLFileReporter.setFileName("testfile.txt"); theXMLFileReporter.initialize(); theXMLFileReporter.logTestFileInit("CConformanceTest - Iterates over all conf test dirs and validates outputs USING Xalan-C"); theXMLFileReporter.logTestFileClose("xxx", "pass"); theXMLFileReporter.close(); assert(sizeof(glbStylesheetRoot) == sizeof(glbSourceXML)); #if !defined(NDEBUG) && defined(_MSC_VER) _CrtSetDbgFlag(_CrtSetDbgFlag(_CRTDBG_REPORT_FLAG) | _CRTDBG_LEAK_CHECK_DF); _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE); _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR); #endif if (argc > 2) { cerr << "Usage: perf" << endl << endl; } else { int iterCount = 1; if (argc == 2) { iterCount = atoi(argv[1]); } try { // Call the static initializers... XMLPlatformUtils::Initialize(); { XSLTInit theInit; const XalanDOMString XSLSuffix(".xsl"); const XalanDOMString XMLSuffix(".xml"); const XalanDOMString outputSuffix(".out"); // Create the necessary support objects to instantiate a processor. XercesDOMSupport csDOMSupport; XercesParserLiaison csParserLiaison(csDOMSupport); XPathSupportDefault csXPathSupport(csDOMSupport); XSLTProcessorEnvSupportDefault csXSLTProcessorEnvSupport; XObjectFactoryDefault csXObjectFactory; XPathFactoryDefault csXPathFactory; // Create a processor for stylesheet compilation and connect to // ProcessorEnvSupport object XSLTEngineImpl csProcessor( csParserLiaison, csXPathSupport, csXSLTProcessorEnvSupport, csDOMSupport, csXObjectFactory, csXPathFactory); csXSLTProcessorEnvSupport.setProcessor(&csProcessor); // Create separate factory support object, so the stylesheet's // factory-created XPath instance are independent from processor's. XPathFactoryDefault ssXPathFactory; // Create a stylesheet construction context, using the // stylesheet's factory support objects. StylesheetConstructionContextDefault csConstructionContext( csProcessor, csXSLTProcessorEnvSupport, ssXPathFactory); for(int i = 0; xslStylesheets[i] != 0; i++) { const XalanDOMString theXSLfile(XalanDOMString(xslStylesheets[i]) + XSLSuffix); const XalanDOMString theXMLfile(XalanDOMString(xslStylesheets[i]) + XMLSuffix); cout << "Now compiling Stylesheet: " << xslStylesheets[i] << endl; //Generate the XML and XSL input objects. XSLTInputSource csStylesheetSourceXSL(c_wstr(theXSLfile)); XSLTInputSource csSourceXML(c_wstr(theXMLfile)); // Ask the processor to create a compiled stylesheet (StylesheetRoot) for the // specified input XSL. We don't have to delete it, since it is owned by the // StylesheetConstructionContext instance. {const double startTime = clock(); //cout << "Clock before Compliation: " << startTime << endl; glbStylesheetRoot[i] = csProcessor.processStylesheet(csStylesheetSourceXSL, csConstructionContext); const double endTime = clock(); //cout << "Clock after Compliation: " << endTime << endl; cout << "Compliation took: " << endTime - startTime << endl; } assert(glbStylesheetRoot[i] != 0); // Have the processor create a compiled SourceDocument for the specified // input XML. glbSourceXML[i] = csProcessor.getSourceTreeFromInput(csSourceXML); assert(glbSourceXML[i] != 0); } for(int ii = 0; xslStylesheets[ii] != 0; ii++) { cout << endl << "Testing: " << xslStylesheets[ii] << endl; // The execution context uses the same factory support objects as // the processor, since those objects have the same lifetime as // other objects created as a result of the execution. StylesheetExecutionContextDefault psExecutionContext( csProcessor, csXSLTProcessorEnvSupport, csXPathSupport, csXObjectFactory); const XalanDOMString outputfile(//XalanDOMString(outputDir) + XalanDOMString(xslStylesheets[ii]) + outputSuffix); //Generate the XML input and output objects. XSLTInputSource csSourceXML(glbSourceXML[ii]); XSLTResultTarget theResultTarget(outputfile); // Set the stylesheet to be the compiled stylesheet. Then do the transform. const double singleStart = clock(); //cout << "Clock before single transform: " << singleStart << endl; csProcessor.setStylesheetRoot(glbStylesheetRoot[ii]); csProcessor.process(csSourceXML, theResultTarget,psExecutionContext); psExecutionContext.reset(); const double singleEnd = clock(); //cout << "Clock after single transform: " << singleEnd << endl; cout << "Single Transform time: " << singleEnd - singleStart << endl; const double startTime = clock(); //cout << endl << "Clock before transforms: " << startTime << endl; for(int j = 0; j < iterCount; ++j) { csProcessor.setStylesheetRoot(glbStylesheetRoot[ii]); csProcessor.process(csSourceXML, theResultTarget,psExecutionContext); psExecutionContext.reset(); } const double endTime = clock(); //cout << "Clock after transforms: " << endTime << endl; //cout << "Total clock ticks: " << endTime - startTime << endl; const double millis = ((endTime - startTime) / CLOCKS_PER_SEC) * 1000.0; //cout << "Milliseconds: " << millis << endl; cout << "Averaged: " << millis / iterCount << " for " << iterCount << " iterations" << endl; } } XMLPlatformUtils::Terminate(); } catch(...) { cerr << "Exception caught!!!" << endl << endl; } } return 0; } <commit_msg>Major overhaul. Don't compile all the stylesheets beforehand. Now just do one at a time.<commit_after>/* * The Apache Software License, Version 1.1 * * * Copyright (c) 1999 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xalan" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ #include <cassert> #include <fstream> #include <iostream> #include <strstream> #if !defined(NDEBUG) && defined(_MSC_VER) #include <crtdbg.h> #endif //These came from the debug test. #include <cstdio> #include <ctime> #include <string> #include <string.h> #include <vector> #include <util/PlatformUtils.hpp> #include <PlatformSupport/DOMStringHelper.hpp> #include <PlatformSupport/XalanFileOutputStream.hpp> #include <PlatformSupport/XalanOutputStreamPrintWriter.hpp> #include <XercesParserLiaison/XercesDOMSupport.hpp> #include <XercesParserLiaison/XercesParserLiaison.hpp> #include <XPath/XObjectFactoryDefault.hpp> #include <XPath/XPathSupportDefault.hpp> #include <XPath/XPathFactoryDefault.hpp> #include <XSLT/StylesheetConstructionContextDefault.hpp> #include <XSLT/StylesheetExecutionContextDefault.hpp> #include <XSLT/StylesheetRoot.hpp> #include <XSLT/XSLTEngineImpl.hpp> #include <XSLT/XSLTInit.hpp> #include <XSLT/XSLTInputSource.hpp> #include <XSLT/XSLTProcessorEnvSupportDefault.hpp> #include <XSLT/XSLTResultTarget.hpp> #include <XMLFileReporter.hpp> //This is here for the threads. #define WIN32_LEAN_AND_MEAN #include <windows.h> #include <winbase.h> #define THREADFUNCTIONRETURN DWORD WINAPI #if !defined(XALAN_NO_NAMESPACES) using std::cerr; using std::cout; using std::cin; using std::endl; using std::ifstream; using std::ios_base; using std::ostrstream; using std::string; #endif // This is here for memory leak testing. #if defined(_DEBUG) #include <crtdbg.h> #endif const char* xslStylesheets[] = { "v:\\xsl-test\\perf\\basic\\basic-all_well", //"v:\\xsl-test\\perf\\basic\\basic-datetranscode", //"v:\\xsl-test\\perf\\basic\\basic-dict2", //"v:\\xsl-test\\perf\\basic\\basic-Fischer-Euwe", //"v:\\xsl-test\\perf\\basic\\basic-queens", "v:\\xsl-test\\perf\\large\\large-all_well", //"v:\\xsl-test\\perf\\large\\large-evans_large", //"v:\\xsl-test\\perf\\nodes\\nodes-fancy_xml_tree_viewer_34", //"v:\\xsl-test\\perf\\nodes\\nodes-showtree-19991008", //"v:\\xsl-test\\perf\\sort\\sort-big", //"v:\\xsl-test\\perf\\xpath\\xpath-evans_small", //"v:\\xsl-test\\perf\\xpath\\xpath-evans_tiny", 0 }; const char* outputDir = "d:\\xslt-results\\perf\\test\\"; // Used to hold compiled stylesheet, and source document. XalanNode* glbSourceXML; StylesheetRoot* glbStylesheetRoot; void outputMessage(int iter) { cout << "\n" << "Starting Iteration: " << iter << '\0'; } int main( int argc, const char* argv []) { XMLFileReporter theXMLFileReporter; theXMLFileReporter.setFileName("testfile.txt"); theXMLFileReporter.initialize(); theXMLFileReporter.logTestFileInit("CConformanceTest - Iterates over all conf test dirs and validates outputs USING Xalan-C"); theXMLFileReporter.logTestFileClose("xxx", "pass"); theXMLFileReporter.close(); #if !defined(NDEBUG) && defined(_MSC_VER) _CrtSetDbgFlag(_CrtSetDbgFlag(_CRTDBG_REPORT_FLAG) | _CRTDBG_LEAK_CHECK_DF); _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE); _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR); #endif if (argc > 2) { cerr << "Usage: perf" << endl << endl; } else { int iterCount = 1; if (argc == 2) { iterCount = atoi(argv[1]); } try { // Call the static initializers... and define file suffixes XMLPlatformUtils::Initialize(); const XalanDOMString XSLSuffix(".xsl"); const XalanDOMString XMLSuffix(".xml"); const XalanDOMString outputSuffix(".out"); { XSLTInit theInit; for(int i = 0; xslStylesheets[i] != 0; i++) { // Create the necessary support objects to instantiate a processor. XercesDOMSupport csDOMSupport; XercesParserLiaison csParserLiaison(csDOMSupport); XPathSupportDefault csXPathSupport(csDOMSupport); XSLTProcessorEnvSupportDefault csXSLTProcessorEnvSupport; XObjectFactoryDefault csXObjectFactory; XPathFactoryDefault csXPathFactory; // Create a processor for stylesheet compilation and connect to // ProcessorEnvSupport object XSLTEngineImpl csProcessor( csParserLiaison, csXPathSupport, csXSLTProcessorEnvSupport, csDOMSupport, csXObjectFactory, csXPathFactory); csXSLTProcessorEnvSupport.setProcessor(&csProcessor); // Create separate factory support object, so the stylesheet's // factory-created XPath instance are independent from processor's. XPathFactoryDefault ssXPathFactory; // Create a stylesheet construction context, using the // stylesheet's factory support objects. StylesheetConstructionContextDefault csConstructionContext( csProcessor, csXSLTProcessorEnvSupport, ssXPathFactory); const XalanDOMString theXSLfile(XalanDOMString(xslStylesheets[i]) + XSLSuffix); const XalanDOMString theXMLfile(XalanDOMString(xslStylesheets[i]) + XMLSuffix); cout << endl << "Compiling: " << xslStylesheets[i] << endl; //Generate the XML and XSL input objects. XSLTInputSource csStylesheetSourceXSL(c_wstr(theXSLfile)); XSLTInputSource csSourceXML(c_wstr(theXMLfile)); // Ask the processor to create a compiled stylesheet (StylesheetRoot) for the // specified input XSL. We don't have to delete it, since it is owned by the // StylesheetConstructionContext instance. const double startTime = clock(); glbStylesheetRoot= csProcessor.processStylesheet(csStylesheetSourceXSL, csConstructionContext); const double endTime = clock(); cout << "Compliation took: " << endTime - startTime << endl; assert(glbStylesheetRoot != 0); // Have the processor create a compiled SourceDocument for the specified // input XML. glbSourceXML = csProcessor.getSourceTreeFromInput(csSourceXML); assert(glbSourceXML != 0); //cout << endl << "Testing: " << xslStylesheets[i] << endl; // The execution context uses the same factory support objects as // the processor, since those objects have the same lifetime as // other objects created as a result of the execution. StylesheetExecutionContextDefault psExecutionContext( csProcessor, csXSLTProcessorEnvSupport, csXPathSupport, csXObjectFactory); const XalanDOMString outputfile(//XalanDOMString(outputDir) + XalanDOMString(xslStylesheets[i]) + outputSuffix); //Generate the XML input and output objects. //XSLTInputSource csSourceXML(glbSourceXML); XSLTResultTarget theResultTarget(outputfile); // Set the stylesheet to be the compiled stylesheet. Then do the transform. csProcessor.setStylesheetRoot(glbStylesheetRoot); const double singleStart = clock(); csProcessor.process(csSourceXML, theResultTarget,psExecutionContext); const double singleEnd = clock(); psExecutionContext.reset(); cout << "Single Transform time: " << singleEnd - singleStart << endl; /* const double startTime = clock(); //cout << endl << "Clock before transforms: " << startTime << endl; for(int j = 0; j < iterCount; ++j) { csProcessor.setStylesheetRoot(glbStylesheetRoot); csProcessor.process(csSourceXML, theResultTarget,psExecutionContext); psExecutionContext.reset(); } const double endTime = clock(); //cout << "Clock after transforms: " << endTime << endl; //cout << "Total clock ticks: " << endTime - startTime << endl; const double millis = ((endTime - startTime) / CLOCKS_PER_SEC) * 1000.0; //cout << "Milliseconds: " << millis << endl; cout << "Averaged: " << millis / iterCount << " for " << iterCount << " iterations" << endl; */ } } XMLPlatformUtils::Terminate(); } catch(...) { cerr << "Exception caught!!!" << endl << endl; } } return 0; } <|endoftext|>
<commit_before>/******************************************************************************* * c7a/api/size.hpp * * Part of Project c7a. * * Copyright (C) 2015 Matthias Stumpp <mstumpp@gmail.com> * * This file has no license. Only Chuck Norris can compile it. ******************************************************************************/ #pragma once #ifndef C7A_API_SIZE_HEADER #define C7A_API_SIZE_HEADER #include <c7a/api/action_node.hpp> #include <c7a/core/stage_builder.hpp> #include <c7a/net/collective_communication.hpp> #include <c7a/net/flow_control_channel.hpp> #include <c7a/net/flow_control_manager.hpp> #include <c7a/net/group.hpp> #include <string> namespace c7a { namespace api { //! \addtogroup api Interface //! \{ template <typename ValueType, typename ParentStack> class SizeNode : public ActionNode { static const bool debug = false; using Super = ActionNode; using Super::context_; using Super::parents; using Super::result_file_; using ParentInput = typename ParentStack::Input; public: SizeNode(Context& ctx, const std::shared_ptr<DIANode<ParentInput> >& parent, const ParentStack& parent_stack) : ActionNode(ctx, { parent }, "Size"), parent_(parent) { // Hook PreOp(s) auto pre_op_fn = [=](const ValueType&) { ++local_size_; }; lop_chain_ = parent_stack.push(pre_op_fn).emit(); parent_->RegisterChild(lop_chain_); } virtual ~SizeNode() { parent_->UnregisterChild(lop_chain_); } //! Executes the size operation. void Execute() override { this->StartExecutionTimer(); MainOp(); this->StopExecutionTimer(); } /*! * Returns result of global size. * \return result */ auto result() { return global_size_; } /*! * Returns "[SizeNode]" as a string. * \return "[SizeNode]" */ std::string ToString() override { return "[SizeNode] Id:" + result_file_.ToString(); } private: // Local size to be used. size_t local_size_ = 0; // Global size resulting from all reduce. size_t global_size_ = 0; std::shared_ptr<DIANode<ParentInput> > parent_; common::delegate<void(ParentInput)> lop_chain_; void PreOp() { } void MainOp() { // get the number of elements that are stored on this worker LOG1 << "MainOp processing, sum: " << local_size_; net::FlowControlChannel& channel = context_.flow_control_channel(); // process the reduce, default argument is SumOp. global_size_ = channel.AllReduce(local_size_); } void PostOp() { } }; template <typename ValueType, typename Stack> size_t DIARef<ValueType, Stack>::Size() const { using SizeResultNode = SizeNode<ValueType, Stack>; auto shared_node = std::make_shared<SizeResultNode>(node_->context(), node_, stack_); core::StageBuilder().RunScope(shared_node.get()); return shared_node.get()->result(); } //! \} } // namespace api } // namespace c7a #endif // !C7A_API_SIZE_HEADER /******************************************************************************/ <commit_msg>remove LOG1 in size.hpp .. please do not commit LOG1 :c<commit_after>/******************************************************************************* * c7a/api/size.hpp * * Part of Project c7a. * * Copyright (C) 2015 Matthias Stumpp <mstumpp@gmail.com> * * This file has no license. Only Chuck Norris can compile it. ******************************************************************************/ #pragma once #ifndef C7A_API_SIZE_HEADER #define C7A_API_SIZE_HEADER #include <c7a/api/action_node.hpp> #include <c7a/core/stage_builder.hpp> #include <c7a/net/collective_communication.hpp> #include <c7a/net/flow_control_channel.hpp> #include <c7a/net/flow_control_manager.hpp> #include <c7a/net/group.hpp> #include <string> namespace c7a { namespace api { //! \addtogroup api Interface //! \{ template <typename ValueType, typename ParentStack> class SizeNode : public ActionNode { static const bool debug = false; using Super = ActionNode; using Super::context_; using Super::parents; using Super::result_file_; using ParentInput = typename ParentStack::Input; public: SizeNode(Context& ctx, const std::shared_ptr<DIANode<ParentInput> >& parent, const ParentStack& parent_stack) : ActionNode(ctx, { parent }, "Size"), parent_(parent) { // Hook PreOp(s) auto pre_op_fn = [=](const ValueType&) { ++local_size_; }; lop_chain_ = parent_stack.push(pre_op_fn).emit(); parent_->RegisterChild(lop_chain_); } virtual ~SizeNode() { parent_->UnregisterChild(lop_chain_); } //! Executes the size operation. void Execute() override { this->StartExecutionTimer(); MainOp(); this->StopExecutionTimer(); } /*! * Returns result of global size. * \return result */ auto result() { return global_size_; } /*! * Returns "[SizeNode]" as a string. * \return "[SizeNode]" */ std::string ToString() override { return "[SizeNode] Id:" + result_file_.ToString(); } private: // Local size to be used. size_t local_size_ = 0; // Global size resulting from all reduce. size_t global_size_ = 0; std::shared_ptr<DIANode<ParentInput> > parent_; common::delegate<void(ParentInput)> lop_chain_; void PreOp() { } void MainOp() { // get the number of elements that are stored on this worker LOG << "MainOp processing, sum: " << local_size_; net::FlowControlChannel& channel = context_.flow_control_channel(); // process the reduce, default argument is SumOp. global_size_ = channel.AllReduce(local_size_); } void PostOp() { } }; template <typename ValueType, typename Stack> size_t DIARef<ValueType, Stack>::Size() const { using SizeResultNode = SizeNode<ValueType, Stack>; auto shared_node = std::make_shared<SizeResultNode>(node_->context(), node_, stack_); core::StageBuilder().RunScope(shared_node.get()); return shared_node.get()->result(); } //! \} } // namespace api } // namespace c7a #endif // !C7A_API_SIZE_HEADER /******************************************************************************/ <|endoftext|>
<commit_before>#include "timeentryeditorwidget.h" #include "ui_timeentryeditorwidget.h" #include <QMessageBox> #include "toggl_api.h" TimeEntryEditorWidget::TimeEntryEditorWidget(QWidget *parent) : QWidget(parent), ui(new Ui::TimeEntryEditorWidget), guid(""), timeEntryAutocompleteNeedsUpdate(false), projectAutocompleteNeedsUpdate(false), workspaceSelectNeedsUpdate(false), clientSelectNeedsUpdate(false) { ui->setupUi(this); setVisible(false); ui->addNewProject->setText("<a href=\"#add_new_project\">Add new project</a>"); connect(TogglApi::instance, SIGNAL(displayLogin(bool,uint64_t)), this, SLOT(displayLogin(bool,uint64_t))); connect(TogglApi::instance, SIGNAL(displayTimeEntryList(bool,QVector<TimeEntryView*>)), this, SLOT(displayTimeEntryList(bool,QVector<TimeEntryView*>))); connect(TogglApi::instance, SIGNAL(displayTimeEntryEditor(bool,TimeEntryView*,QString)), this, SLOT(displayTimeEntryEditor(bool,TimeEntryView*,QString))); connect(TogglApi::instance, SIGNAL(displayTags(QVector<GenericView*>)), this, SLOT(displayTags(QVector<GenericView*>))); connect(TogglApi::instance, SIGNAL(displayWorkspaceSelect(QVector<GenericView*>)), this, SLOT(displayWorkspaceSelect(QVector<GenericView*>))); connect(TogglApi::instance, SIGNAL(displayProjectAutocomplete(QVector<AutocompleteView*>)), this, SLOT(displayProjectAutocomplete(QVector<AutocompleteView*>))); connect(TogglApi::instance, SIGNAL(displayTimeEntryAutocomplete(QVector<AutocompleteView*>)), this, SLOT(displayTimeEntryAutocomplete(QVector<AutocompleteView*>))); connect(TogglApi::instance, SIGNAL(displayClientSelect(QVector<GenericView*>)), this, SLOT(displayClientSelect(QVector<GenericView*>))); } TimeEntryEditorWidget::~TimeEntryEditorWidget() { delete ui; } void TimeEntryEditorWidget::displayTags( QVector<GenericView*> tags) { } void TimeEntryEditorWidget::displayClientSelect( QVector<GenericView *> list) { clientSelectUpdate = list; clientSelectNeedsUpdate = true; if (ui->newProjectClient->hasFocus()) { return; } u_int64_t workspaceID = 0; QVariant data = ui->newProjectWorkspace->currentData(); if (data.canConvert<GenericView *>()) { GenericView *view = data.value<GenericView *>(); workspaceID = view->ID; } ui->newProjectClient->clear(); ui->newProjectClient->addItem(""); foreach(GenericView *view, clientSelectUpdate) { if (workspaceID && workspaceID != view->WID) { continue; } ui->newProjectClient->addItem(view->Name, QVariant::fromValue(view)); } clientSelectNeedsUpdate = false; } void TimeEntryEditorWidget::displayTimeEntryAutocomplete( QVector<AutocompleteView *> list) { timeEntryAutocompleteUpdate = list; timeEntryAutocompleteNeedsUpdate = true; if (ui->description->hasFocus()) { return; } ui->description->clear(); ui->description->addItem(""); foreach(AutocompleteView *view, timeEntryAutocompleteUpdate) { ui->description->addItem(view->Text, QVariant::fromValue(view)); } timeEntryAutocompleteNeedsUpdate = false; } void TimeEntryEditorWidget::displayProjectAutocomplete( QVector<AutocompleteView *> list) { projectAutocompleteUpdate = list; projectAutocompleteNeedsUpdate = true; if (ui->project->hasFocus()) { return; } ui->project->clear(); ui->project->addItem(""); foreach(AutocompleteView *view, projectAutocompleteUpdate) { ui->project->addItem(view->Text, QVariant::fromValue(view)); } projectAutocompleteNeedsUpdate = false; } void TimeEntryEditorWidget::displayWorkspaceSelect( QVector<GenericView *> list) { workspaceSelectUpdate = list; workspaceSelectNeedsUpdate = true; if (ui->newProjectWorkspace->hasFocus()) { return; } ui->newProjectWorkspace->clear(); foreach(GenericView *view, workspaceSelectUpdate) { ui->newProjectWorkspace->addItem(view->Name, QVariant::fromValue(view)); } workspaceSelectNeedsUpdate = false; } void TimeEntryEditorWidget::displayLogin( const bool open, const uint64_t user_id) { if (open || !user_id) { setVisible(false); } } void TimeEntryEditorWidget::displayTimeEntryList( const bool open, QVector<TimeEntryView *> list) { if (open) { setVisible(false); } } void TimeEntryEditorWidget::displayTimeEntryEditor( const bool open, TimeEntryView *view, const QString focused_field_name) { if (open) { ui->timeDetails->setVisible(false); ui->timeOverview->setVisible(true); ui->newProject->setVisible(false); ui->addNewProject->setVisible(true); setVisible(true); } guid = view->GUID; ui->description->setEditText(view->Description); ui->project->setEditText(view->ProjectAndTaskLabel); ui->start->setText(view->StartTimeString); ui->stop->setText(view->EndTimeString); ui->duration->setText(view->Duration); ui->billable->setChecked(view->Billable); ui->timeOverview->setText("<a href=\"#view_time_details\">" + view->timeOverview() + "</a>"); ui->lastUpdate->setVisible(view->UpdatedAt); ui->lastUpdate->setText(view->lastUpdate()); } void TimeEntryEditorWidget::on_doneButton_clicked() { TogglApi::instance->viewTimeEntryList(); } void TimeEntryEditorWidget::on_deleteButton_clicked() { if (QMessageBox::Ok == QMessageBox(QMessageBox::Question, "Delete this time entry?", "Deleted time entries cannot be restored.", QMessageBox::Ok|QMessageBox::Cancel).exec()) { TogglApi::instance->deleteTimeEntry(guid); } } void TimeEntryEditorWidget::on_addNewProject_linkActivated(const QString &link) { ui->addNewProject->setVisible(false); ui->newProject->setVisible(true); ui->newProjectName->setFocus(); } void TimeEntryEditorWidget::on_timeOverview_linkActivated(const QString &link) { ui->timeOverview->setVisible(false); ui->timeDetails->setVisible(true); } void TimeEntryEditorWidget::on_newProjectWorkspace_currentIndexChanged(int index) { displayClientSelect(clientSelectUpdate); } <commit_msg>Edit form improvemenets (linux)<commit_after>#include "timeentryeditorwidget.h" #include "ui_timeentryeditorwidget.h" #include <QMessageBox> #include "toggl_api.h" TimeEntryEditorWidget::TimeEntryEditorWidget(QWidget *parent) : QWidget(parent), ui(new Ui::TimeEntryEditorWidget), guid(""), timeEntryAutocompleteNeedsUpdate(false), projectAutocompleteNeedsUpdate(false), workspaceSelectNeedsUpdate(false), clientSelectNeedsUpdate(false) { ui->setupUi(this); setVisible(false); ui->addNewProject->setText("<a href=\"#add_new_project\">Add new project</a>"); connect(TogglApi::instance, SIGNAL(displayLogin(bool,uint64_t)), this, SLOT(displayLogin(bool,uint64_t))); connect(TogglApi::instance, SIGNAL(displayTimeEntryList(bool,QVector<TimeEntryView*>)), this, SLOT(displayTimeEntryList(bool,QVector<TimeEntryView*>))); connect(TogglApi::instance, SIGNAL(displayTimeEntryEditor(bool,TimeEntryView*,QString)), this, SLOT(displayTimeEntryEditor(bool,TimeEntryView*,QString))); connect(TogglApi::instance, SIGNAL(displayTags(QVector<GenericView*>)), this, SLOT(displayTags(QVector<GenericView*>))); connect(TogglApi::instance, SIGNAL(displayWorkspaceSelect(QVector<GenericView*>)), this, SLOT(displayWorkspaceSelect(QVector<GenericView*>))); connect(TogglApi::instance, SIGNAL(displayProjectAutocomplete(QVector<AutocompleteView*>)), this, SLOT(displayProjectAutocomplete(QVector<AutocompleteView*>))); connect(TogglApi::instance, SIGNAL(displayTimeEntryAutocomplete(QVector<AutocompleteView*>)), this, SLOT(displayTimeEntryAutocomplete(QVector<AutocompleteView*>))); connect(TogglApi::instance, SIGNAL(displayClientSelect(QVector<GenericView*>)), this, SLOT(displayClientSelect(QVector<GenericView*>))); } TimeEntryEditorWidget::~TimeEntryEditorWidget() { delete ui; } void TimeEntryEditorWidget::displayTags( QVector<GenericView*> tags) { } void TimeEntryEditorWidget::displayClientSelect( QVector<GenericView *> list) { clientSelectUpdate = list; clientSelectNeedsUpdate = true; if (ui->newProjectClient->hasFocus()) { return; } u_int64_t workspaceID = 0; QVariant data = ui->newProjectWorkspace->currentData(); if (data.canConvert<GenericView *>()) { GenericView *view = data.value<GenericView *>(); workspaceID = view->ID; } ui->newProjectClient->clear(); ui->newProjectClient->addItem(""); foreach(GenericView *view, clientSelectUpdate) { if (workspaceID && workspaceID != view->WID) { continue; } ui->newProjectClient->addItem(view->Name, QVariant::fromValue(view)); } clientSelectNeedsUpdate = false; } void TimeEntryEditorWidget::displayTimeEntryAutocomplete( QVector<AutocompleteView *> list) { timeEntryAutocompleteUpdate = list; timeEntryAutocompleteNeedsUpdate = true; if (ui->description->hasFocus()) { return; } ui->description->clear(); ui->description->addItem(""); foreach(AutocompleteView *view, timeEntryAutocompleteUpdate) { ui->description->addItem(view->Text, QVariant::fromValue(view)); } timeEntryAutocompleteNeedsUpdate = false; } void TimeEntryEditorWidget::displayProjectAutocomplete( QVector<AutocompleteView *> list) { projectAutocompleteUpdate = list; projectAutocompleteNeedsUpdate = true; if (ui->project->hasFocus()) { return; } ui->project->clear(); ui->project->addItem(""); foreach(AutocompleteView *view, projectAutocompleteUpdate) { ui->project->addItem(view->Text, QVariant::fromValue(view)); } projectAutocompleteNeedsUpdate = false; } void TimeEntryEditorWidget::displayWorkspaceSelect( QVector<GenericView *> list) { workspaceSelectUpdate = list; workspaceSelectNeedsUpdate = true; if (ui->newProjectWorkspace->hasFocus()) { return; } ui->newProjectWorkspace->clear(); foreach(GenericView *view, workspaceSelectUpdate) { ui->newProjectWorkspace->addItem(view->Name, QVariant::fromValue(view)); } workspaceSelectNeedsUpdate = false; } void TimeEntryEditorWidget::displayLogin( const bool open, const uint64_t user_id) { if (open || !user_id) { setVisible(false); } } void TimeEntryEditorWidget::displayTimeEntryList( const bool open, QVector<TimeEntryView *> list) { if (open) { setVisible(false); } } void TimeEntryEditorWidget::displayTimeEntryEditor( const bool open, TimeEntryView *view, const QString focused_field_name) { if (open) { ui->timeDetails->setVisible(false); ui->timeOverview->setVisible(true); ui->newProject->setVisible(false); ui->addNewProject->setVisible(true); setVisible(true); } guid = view->GUID; ui->description->setEditText(view->Description); ui->project->setEditText(view->ProjectAndTaskLabel); ui->start->setText(view->StartTimeString); ui->stop->setText(view->EndTimeString); ui->dateEdit->setDateTime(QDateTime::fromTime_t(view->Started)); ui->duration->setText(view->Duration); ui->billable->setChecked(view->Billable); ui->timeOverview->setText("<a href=\"#view_time_details\">" + view->timeOverview() + "</a>"); ui->lastUpdate->setVisible(view->UpdatedAt); ui->lastUpdate->setText(view->lastUpdate()); } void TimeEntryEditorWidget::on_doneButton_clicked() { TogglApi::instance->viewTimeEntryList(); } void TimeEntryEditorWidget::on_deleteButton_clicked() { if (QMessageBox::Ok == QMessageBox(QMessageBox::Question, "Delete this time entry?", "Deleted time entries cannot be restored.", QMessageBox::Ok|QMessageBox::Cancel).exec()) { TogglApi::instance->deleteTimeEntry(guid); } } void TimeEntryEditorWidget::on_addNewProject_linkActivated(const QString &link) { ui->addNewProject->setVisible(false); ui->newProject->setVisible(true); ui->newProjectName->setFocus(); } void TimeEntryEditorWidget::on_timeOverview_linkActivated(const QString &link) { ui->timeOverview->setVisible(false); ui->timeDetails->setVisible(true); ui->duration->setFocus(); } void TimeEntryEditorWidget::on_newProjectWorkspace_currentIndexChanged(int index) { displayClientSelect(clientSelectUpdate); } <|endoftext|>
<commit_before>/* */ #include "lineFollowing.h" using namespace std; using namespace cv; ControlMovements lineFollowingControl() { line_main(); return ControlMovements(); } void line_main() { // printf("Hello, this is Caleb\n"); VideoCapture cap("../../tests/videos/top_down_4.m4v"); if (!cap.isOpened()) // check if we succeeded return; namedWindow("edges", CV_WINDOW_NORMAL); // Mat edges; for (; ;) { Mat mask; Mat frame, hsv; cap >> frame; // get a new frame from camera cvtColor(frame, hsv, CV_BGR2HSV); double minH = 30; double minS = 0; double minV = 240; double maxH = 80; double maxS = 70; double maxV = 255; cv::Scalar lower(minH, minS, minV); cv::Scalar upper(maxH, maxS, maxV); cv::inRange(hsv, lower, upper, mask); // bitwise_and(frame, frame, frame, mask); erode(mask, mask, Mat(), Point(-1, -1), 5); medianBlur(mask, mask, 5); medianBlur(mask, mask, 5); medianBlur(mask, mask, 5); vector<Vec4i> lines; HoughLines(mask, lines, 1, CV_PI / 180.0, 10); printf("Adding in %d lines\n", (int) lines.size()); for (size_t i = 0; i < lines.size(); i++) { float rho = lines[i][0], theta = lines[i][1]; Point pt1, pt2; double a = cos(theta), b = sin(theta); double x0 = a * rho, y0 = b * rho; pt1.x = cvRound(x0 + 1000 * (-b)); pt1.y = cvRound(y0 + 1000 * (a)); pt2.x = cvRound(x0 - 1000 * (-b)); pt2.y = cvRound(y0 - 1000 * (a)); line(frame, pt1, pt2, Scalar(0, 0, 255), 3, CV_AA); } // if (lines.size() < 1) continue; imshow("edges", mask); if (waitKey(30) >= 0) break; } // the camera will be deinitialized automatically in VideoCapture destructor return; } <commit_msg>messing with erode<commit_after>/* */ #include "lineFollowing.h" using namespace std; using namespace cv; ControlMovements lineFollowingControl() { line_main(); return ControlMovements(); } void line_main() { // printf("Hello, this is Caleb\n"); VideoCapture cap("../../tests/videos/top_down_4.m4v"); if (!cap.isOpened()) // check if we succeeded return; namedWindow("edges", CV_WINDOW_NORMAL); // Mat edges; for (; ;) { Mat mask; Mat frame, hsv; cap >> frame; // get a new frame from camera cvtColor(frame, hsv, CV_BGR2HSV); double minH = 30; double minS = 0; double minV = 240; double maxH = 80; double maxS = 70; double maxV = 255; cv::Scalar lower(minH, minS, minV); cv::Scalar upper(maxH, maxS, maxV); cv::inRange(hsv, lower, upper, mask); // bitwise_and(frame, frame, frame, mask); // erode(mask, mask, Mat(), Point(-1, -1), 5); // medianBlur(mask, mask, 5); // medianBlur(mask, mask, 5); // medianBlur(mask, mask, 5); vector<Vec2f> lines; HoughLines(mask, lines, 1, CV_PI/180, 100, 0, 0 ); printf("Adding in %d lines\n", (int) lines.size()); for (size_t i = 0; i < lines.size(); i++) { float rho = lines[i][0], theta = lines[i][1]; Point pt1, pt2; double a = cos(theta), b = sin(theta); double x0 = a * rho, y0 = b * rho; pt1.x = cvRound(x0 + 1000 * (-b)); pt1.y = cvRound(y0 + 1000 * (a)); pt2.x = cvRound(x0 - 1000 * (-b)); pt2.y = cvRound(y0 - 1000 * (a)); line(frame, pt1, pt2, Scalar(0, 0, 255), 3, CV_AA); } // if (lines.size() < 1) continue; imshow("edges", mask); if (waitKey(30) >= 0) break; } // the camera will be deinitialized automatically in VideoCapture destructor return; } <|endoftext|>
<commit_before>/* */ #include "lineFollowing.h" using namespace std; using namespace cv; ControlMovements lineFollowingControl() { line_main(); return ControlMovements(); } void line_main() { // printf("Hello, this is Caleb\n"); VideoCapture cap("../../tests/videos/top_down_4.m4v"); if (!cap.isOpened()) // check if we succeeded return; namedWindow("edges", CV_WINDOW_NORMAL); // Mat edges; for (; ;) { Mat mask; Mat frame, hsv; cap >> frame; // get a new frame from camera cvtColor(frame, hsv, CV_BGR2HSV); double minH = 30; double minS = 0; double minV = 240; double maxH = 80; double maxS = 70; double maxV = 255; cv::Scalar lower(minH, minS, minV); cv::Scalar upper(maxH, maxS, maxV); cv::inRange(hsv, lower, upper, mask); // bitwise_and(frame, frame, frame, mask); resize(mask, mask, Size(), .2, .2); vector <Vec4i> lines; HoughLinesP(mask, lines, 1, CV_PI / 180.0, 10, 100, 10); printf("Adding in %d lines\n", (int) lines.size()); for (size_t i = 0; i < lines.size(); i++) { Vec4i l = lines[i]; line(frame, Point(l[0], l[1]), Point(l[2], l[3]), Scalar(0, 0, 255), 3, CV_AA); // break; } // if (lines.size() < 1) continue; imshow("edges", frame); if (waitKey(30) >= 0) break; } // the camera will be deinitialized automatically in VideoCapture destructor return; } <commit_msg>size changes<commit_after>/* */ #include "lineFollowing.h" using namespace std; using namespace cv; ControlMovements lineFollowingControl() { line_main(); return ControlMovements(); } void line_main() { // printf("Hello, this is Caleb\n"); VideoCapture cap("../../tests/videos/top_down_4.m4v"); if (!cap.isOpened()) // check if we succeeded return; namedWindow("edges", CV_WINDOW_NORMAL); // Mat edges; for (; ;) { Mat mask; Mat frame, hsv; cap >> frame; // get a new frame from camera resize(frame, frame, Size(), .2, .2); cvtColor(frame, hsv, CV_BGR2HSV); double minH = 30; double minS = 0; double minV = 240; double maxH = 80; double maxS = 70; double maxV = 255; cv::Scalar lower(minH, minS, minV); cv::Scalar upper(maxH, maxS, maxV); cv::inRange(hsv, lower, upper, mask); // bitwise_and(frame, frame, frame, mask); vector <Vec4i> lines; HoughLinesP(mask, lines, 1, CV_PI / 180.0, 10, 100, 10); printf("Adding in %d lines\n", (int) lines.size()); for (size_t i = 0; i < lines.size(); i++) { Vec4i l = lines[i]; line(frame, Point(l[0], l[1]), Point(l[2], l[3]), Scalar(0, 0, 255), 3, CV_AA); // break; } // if (lines.size() < 1) continue; imshow("edges", frame); if (waitKey(30) >= 0) break; } // the camera will be deinitialized automatically in VideoCapture destructor return; } <|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 "liblocationwrapper_p.h" using namespace std; QTM_BEGIN_NAMESPACE Q_GLOBAL_STATIC(LiblocationWrapper, LocationEngine) LiblocationWrapper *LiblocationWrapper::instance() { return LocationEngine(); } LiblocationWrapper::~LiblocationWrapper() { if (locationDevice) g_object_unref(locationDevice); if (locationControl) g_object_unref(locationControl); } bool LiblocationWrapper::inited() { int retval = false; if (!(locationState & LiblocationWrapper::Inited)) { g_type_init(); locationControl = location_gpsd_control_get_default(); if (locationControl) { g_object_set(G_OBJECT(locationControl), "preferred-method", LOCATION_METHOD_USER_SELECTED, "preferred-interval", LOCATION_INTERVAL_1S, NULL); locationDevice = (LocationGPSDevice*)g_object_new(LOCATION_TYPE_GPS_DEVICE, NULL); if (locationDevice) { errorHandlerId = g_signal_connect(G_OBJECT(locationControl), "error-verbose", G_CALLBACK(&locationError), static_cast<void*>(this)); posChangedId = g_signal_connect(G_OBJECT(locationDevice), "changed", G_CALLBACK(&locationChanged), static_cast<void*>(this)); locationState = LiblocationWrapper::Inited; retval = true; startcounter = 0; } } } else { retval = true; } return retval; } void LiblocationWrapper::locationError(LocationGPSDevice *device, gint errorCode, gpointer data) { Q_UNUSED(device); QString locationError; switch (errorCode) { case LOCATION_ERROR_USER_REJECTED_DIALOG: locationError = "User didn't enable requested methods"; break; case LOCATION_ERROR_USER_REJECTED_SETTINGS: locationError = "User changed settings, which disabled location."; break; case LOCATION_ERROR_BT_GPS_NOT_AVAILABLE: locationError = "Problems with BT GPS"; break; case LOCATION_ERROR_METHOD_NOT_ALLOWED_IN_OFFLINE_MODE: locationError = "Requested method is not allowed in offline mode"; break; case LOCATION_ERROR_SYSTEM: locationError = "System error."; break; default: locationError = "Unknown error."; } qDebug() << "Location error:" << locationError; LiblocationWrapper *object; object = (LiblocationWrapper *)data; emit object->error(); } void LiblocationWrapper::locationChanged(LocationGPSDevice *device, gpointer data) { QGeoPositionInfo posInfo; QGeoCoordinate coordinate; QGeoSatelliteInfo satInfo; int satellitesInUseCount = 0; LiblocationWrapper *object; if (!data || !device) { return; } object = (LiblocationWrapper *)data; if (device) { if (device->fix) { if (device->fix->fields & LOCATION_GPS_DEVICE_TIME_SET) { posInfo.setTimestamp(QDateTime::fromTime_t(device->fix->time)); } if (device->fix->fields & LOCATION_GPS_DEVICE_LATLONG_SET) { coordinate.setLatitude(device->fix->latitude); coordinate.setLongitude(device->fix->longitude); posInfo.setAttribute(QGeoPositionInfo::HorizontalAccuracy, device->fix->eph * 100); device->fix->eph / 100.0); posInfo.setAttribute(QGeoPositionInfo::VerticalAccuracy, device->fix->epv); } if (device->fix->fields & LOCATION_GPS_DEVICE_ALTITUDE_SET) { coordinate.setAltitude(device->fix->altitude); } if (device->fix->fields & LOCATION_GPS_DEVICE_SPEED_SET) { posInfo.setAttribute(QGeoPositionInfo::GroundSpeed, device->fix->speed); } if (device->fix->fields & LOCATION_GPS_DEVICE_CLIMB_SET) { posInfo.setAttribute(QGeoPositionInfo::VerticalSpeed, device->fix->climb); } if (device->fix->fields & LOCATION_GPS_DEVICE_TRACK_SET) { posInfo.setAttribute(QGeoPositionInfo::Direction, device->fix->track); } } if (device->satellites_in_view) { QList<QGeoSatelliteInfo> satsInView; QList<QGeoSatelliteInfo> satsInUse; unsigned int i; for (i=0;i<device->satellites->len;i++) { LocationGPSDeviceSatellite *satData = (LocationGPSDeviceSatellite *)g_ptr_array_index(device->satellites, i); satInfo.setSignalStrength(satData->signal_strength); satInfo.setPrnNumber(satData->prn); satInfo.setAttribute(QGeoSatelliteInfo::Elevation, satData->elevation); satInfo.setAttribute(QGeoSatelliteInfo::Azimuth, satData->azimuth); satsInView.append(satInfo); if (satData->in_use) { satellitesInUseCount++; satsInUse.append(satInfo); } } if (!satsInView.isEmpty()) object->satellitesInViewUpdated(satsInView); if (!satsInUse.isEmpty()) object->satellitesInUseUpdated(satsInUse); } } posInfo.setCoordinate(coordinate); if ((device->fix->fields & LOCATION_GPS_DEVICE_TIME_SET) && ((device->fix->mode == LOCATION_GPS_DEVICE_MODE_3D) || (device->fix->mode == LOCATION_GPS_DEVICE_MODE_2D))) { object->setLocation(posInfo, true); } else { object->setLocation(posInfo, false); } } void LiblocationWrapper::setLocation(const QGeoPositionInfo &update, bool locationValid) { validLastSatUpdate = locationValid; lastSatUpdate = update; } QGeoPositionInfo LiblocationWrapper::position() { return lastSatUpdate; } bool LiblocationWrapper::fixIsValid() { return validLastSatUpdate; } QGeoPositionInfo LiblocationWrapper::lastKnownPosition(bool fromSatellitePositioningMethodsOnly) const { QGeoPositionInfo posInfo; QGeoCoordinate coordinate; double time; double latitude; double longitude; double altitude; double speed; double track; double climb; GConfItem lastKnownPositionTime("/system/nokia/location/lastknown/time"); GConfItem lastKnownPositionLatitude("/system/nokia/location/lastknown/latitude"); GConfItem lastKnownPositionLongitude("/system/nokia/location/lastknown/longitude"); GConfItem lastKnownPositionAltitude("/system/nokia/location/lastknown/altitude"); GConfItem lastKnownPositionSpeed("/system/nokia/location/lastknown/speed"); GConfItem lastKnownPositionTrack("/system/nokia/location/lastknown/track"); GConfItem lastKnownPositionClimb("/system/nokia/location/lastknown/climb"); if (validLastSatUpdate) return lastSatUpdate; if (!fromSatellitePositioningMethodsOnly) if (validLastUpdate) return lastUpdate; time = lastKnownPositionTime.value().toDouble(); latitude = lastKnownPositionLatitude.value().toDouble(); longitude = lastKnownPositionLongitude.value().toDouble(); altitude = lastKnownPositionAltitude.value().toDouble(); speed = lastKnownPositionSpeed.value().toDouble(); track = lastKnownPositionTrack.value().toDouble(); climb = lastKnownPositionClimb.value().toDouble(); if (longitude && latitude) { coordinate.setLongitude(longitude); coordinate.setLatitude(latitude); if (altitude) { coordinate.setAltitude(altitude); } posInfo.setCoordinate(coordinate); } if (speed) { posInfo.setAttribute(QGeoPositionInfo::GroundSpeed, speed); } if (track) { posInfo.setAttribute(QGeoPositionInfo::Direction, track); } if (climb) { posInfo.setAttribute(QGeoPositionInfo::VerticalSpeed, climb); } // Only positions with time (3D) are provided. if (time) { posInfo.setTimestamp(QDateTime::fromTime_t(time)); return posInfo; } return QGeoPositionInfo(); } void LiblocationWrapper::satellitesInViewUpdated(const QList<QGeoSatelliteInfo> &satellites) { satsInView = satellites; } void LiblocationWrapper::satellitesInUseUpdated(const QList<QGeoSatelliteInfo> &satellites) { satsInUse = satellites; } QList<QGeoSatelliteInfo> LiblocationWrapper::satellitesInView() { return satsInView; } QList<QGeoSatelliteInfo> LiblocationWrapper::satellitesInUse() { return satsInUse; } void LiblocationWrapper::start() { startcounter++; if ((locationState & LiblocationWrapper::Inited) && !(locationState & LiblocationWrapper::Started)) { if (!errorHandlerId) { errorHandlerId = g_signal_connect(G_OBJECT(locationControl), "error-verbose", G_CALLBACK(&locationError), static_cast<void*>(this)); } if (!posChangedId) { posChangedId = g_signal_connect(G_OBJECT(locationDevice), "changed", G_CALLBACK(&locationChanged), static_cast<void*>(this)); } location_gpsd_control_start(locationControl); locationState |= LiblocationWrapper::Started; locationState &= ~LiblocationWrapper::Stopped; } } void LiblocationWrapper::stop() { startcounter--; if (startcounter > 0) return; if ((locationState & (LiblocationWrapper::Started | LiblocationWrapper::Inited)) && !(locationState & LiblocationWrapper::Stopped)) { if (errorHandlerId) g_signal_handler_disconnect(G_OBJECT(locationControl), errorHandlerId); if (posChangedId) g_signal_handler_disconnect(G_OBJECT(locationDevice), posChangedId); errorHandlerId = 0; posChangedId = 0; startcounter = 0; location_gpsd_control_stop(locationControl); locationState &= ~LiblocationWrapper::Started; locationState |= LiblocationWrapper::Stopped; } } bool LiblocationWrapper::isActive() { if (locationState & LiblocationWrapper::Started) return true; else return false; } #include "moc_liblocationwrapper_p.cpp" QTM_END_NAMESPACE <commit_msg>Attempt fo fix failed merge.<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 "liblocationwrapper_p.h" using namespace std; QTM_BEGIN_NAMESPACE Q_GLOBAL_STATIC(LiblocationWrapper, LocationEngine) LiblocationWrapper *LiblocationWrapper::instance() { return LocationEngine(); } LiblocationWrapper::~LiblocationWrapper() { if (locationDevice) g_object_unref(locationDevice); if (locationControl) g_object_unref(locationControl); } bool LiblocationWrapper::inited() { int retval = false; if (!(locationState & LiblocationWrapper::Inited)) { g_type_init(); locationControl = location_gpsd_control_get_default(); if (locationControl) { g_object_set(G_OBJECT(locationControl), "preferred-method", LOCATION_METHOD_USER_SELECTED, "preferred-interval", LOCATION_INTERVAL_1S, NULL); locationDevice = (LocationGPSDevice*)g_object_new(LOCATION_TYPE_GPS_DEVICE, NULL); if (locationDevice) { errorHandlerId = g_signal_connect(G_OBJECT(locationControl), "error-verbose", G_CALLBACK(&locationError), static_cast<void*>(this)); posChangedId = g_signal_connect(G_OBJECT(locationDevice), "changed", G_CALLBACK(&locationChanged), static_cast<void*>(this)); locationState = LiblocationWrapper::Inited; retval = true; startcounter = 0; } } } else { retval = true; } return retval; } void LiblocationWrapper::locationError(LocationGPSDevice *device, gint errorCode, gpointer data) { Q_UNUSED(device); QString locationError; switch (errorCode) { case LOCATION_ERROR_USER_REJECTED_DIALOG: locationError = "User didn't enable requested methods"; break; case LOCATION_ERROR_USER_REJECTED_SETTINGS: locationError = "User changed settings, which disabled location."; break; case LOCATION_ERROR_BT_GPS_NOT_AVAILABLE: locationError = "Problems with BT GPS"; break; case LOCATION_ERROR_METHOD_NOT_ALLOWED_IN_OFFLINE_MODE: locationError = "Requested method is not allowed in offline mode"; break; case LOCATION_ERROR_SYSTEM: locationError = "System error."; break; default: locationError = "Unknown error."; } qDebug() << "Location error:" << locationError; LiblocationWrapper *object; object = (LiblocationWrapper *)data; emit object->error(); } void LiblocationWrapper::locationChanged(LocationGPSDevice *device, gpointer data) { QGeoPositionInfo posInfo; QGeoCoordinate coordinate; QGeoSatelliteInfo satInfo; int satellitesInUseCount = 0; LiblocationWrapper *object; if (!data || !device) { return; } object = (LiblocationWrapper *)data; if (device) { if (device->fix) { if (device->fix->fields & LOCATION_GPS_DEVICE_TIME_SET) { posInfo.setTimestamp(QDateTime::fromTime_t(device->fix->time)); } if (device->fix->fields & LOCATION_GPS_DEVICE_LATLONG_SET) { coordinate.setLatitude(device->fix->latitude); coordinate.setLongitude(device->fix->longitude); posInfo.setAttribute(QGeoPositionInfo::HorizontalAccuracy, device->fix->eph / 100.0); posInfo.setAttribute(QGeoPositionInfo::VerticalAccuracy, device->fix->epv); } if (device->fix->fields & LOCATION_GPS_DEVICE_ALTITUDE_SET) { coordinate.setAltitude(device->fix->altitude); } if (device->fix->fields & LOCATION_GPS_DEVICE_SPEED_SET) { posInfo.setAttribute(QGeoPositionInfo::GroundSpeed, device->fix->speed); } if (device->fix->fields & LOCATION_GPS_DEVICE_CLIMB_SET) { posInfo.setAttribute(QGeoPositionInfo::VerticalSpeed, device->fix->climb); } if (device->fix->fields & LOCATION_GPS_DEVICE_TRACK_SET) { posInfo.setAttribute(QGeoPositionInfo::Direction, device->fix->track); } } if (device->satellites_in_view) { QList<QGeoSatelliteInfo> satsInView; QList<QGeoSatelliteInfo> satsInUse; unsigned int i; for (i=0;i<device->satellites->len;i++) { LocationGPSDeviceSatellite *satData = (LocationGPSDeviceSatellite *)g_ptr_array_index(device->satellites, i); satInfo.setSignalStrength(satData->signal_strength); satInfo.setPrnNumber(satData->prn); satInfo.setAttribute(QGeoSatelliteInfo::Elevation, satData->elevation); satInfo.setAttribute(QGeoSatelliteInfo::Azimuth, satData->azimuth); satsInView.append(satInfo); if (satData->in_use) { satellitesInUseCount++; satsInUse.append(satInfo); } } if (!satsInView.isEmpty()) object->satellitesInViewUpdated(satsInView); if (!satsInUse.isEmpty()) object->satellitesInUseUpdated(satsInUse); } } posInfo.setCoordinate(coordinate); if ((device->fix->fields & LOCATION_GPS_DEVICE_TIME_SET) && ((device->fix->mode == LOCATION_GPS_DEVICE_MODE_3D) || (device->fix->mode == LOCATION_GPS_DEVICE_MODE_2D))) { object->setLocation(posInfo, true); } else { object->setLocation(posInfo, false); } } void LiblocationWrapper::setLocation(const QGeoPositionInfo &update, bool locationValid) { validLastSatUpdate = locationValid; lastSatUpdate = update; } QGeoPositionInfo LiblocationWrapper::position() { return lastSatUpdate; } bool LiblocationWrapper::fixIsValid() { return validLastSatUpdate; } QGeoPositionInfo LiblocationWrapper::lastKnownPosition(bool fromSatellitePositioningMethodsOnly) const { QGeoPositionInfo posInfo; QGeoCoordinate coordinate; double time; double latitude; double longitude; double altitude; double speed; double track; double climb; GConfItem lastKnownPositionTime("/system/nokia/location/lastknown/time"); GConfItem lastKnownPositionLatitude("/system/nokia/location/lastknown/latitude"); GConfItem lastKnownPositionLongitude("/system/nokia/location/lastknown/longitude"); GConfItem lastKnownPositionAltitude("/system/nokia/location/lastknown/altitude"); GConfItem lastKnownPositionSpeed("/system/nokia/location/lastknown/speed"); GConfItem lastKnownPositionTrack("/system/nokia/location/lastknown/track"); GConfItem lastKnownPositionClimb("/system/nokia/location/lastknown/climb"); if (validLastSatUpdate) return lastSatUpdate; if (!fromSatellitePositioningMethodsOnly) if (validLastUpdate) return lastUpdate; time = lastKnownPositionTime.value().toDouble(); latitude = lastKnownPositionLatitude.value().toDouble(); longitude = lastKnownPositionLongitude.value().toDouble(); altitude = lastKnownPositionAltitude.value().toDouble(); speed = lastKnownPositionSpeed.value().toDouble(); track = lastKnownPositionTrack.value().toDouble(); climb = lastKnownPositionClimb.value().toDouble(); if (longitude && latitude) { coordinate.setLongitude(longitude); coordinate.setLatitude(latitude); if (altitude) { coordinate.setAltitude(altitude); } posInfo.setCoordinate(coordinate); } if (speed) { posInfo.setAttribute(QGeoPositionInfo::GroundSpeed, speed); } if (track) { posInfo.setAttribute(QGeoPositionInfo::Direction, track); } if (climb) { posInfo.setAttribute(QGeoPositionInfo::VerticalSpeed, climb); } // Only positions with time (3D) are provided. if (time) { posInfo.setTimestamp(QDateTime::fromTime_t(time)); return posInfo; } return QGeoPositionInfo(); } void LiblocationWrapper::satellitesInViewUpdated(const QList<QGeoSatelliteInfo> &satellites) { satsInView = satellites; } void LiblocationWrapper::satellitesInUseUpdated(const QList<QGeoSatelliteInfo> &satellites) { satsInUse = satellites; } QList<QGeoSatelliteInfo> LiblocationWrapper::satellitesInView() { return satsInView; } QList<QGeoSatelliteInfo> LiblocationWrapper::satellitesInUse() { return satsInUse; } void LiblocationWrapper::start() { startcounter++; if ((locationState & LiblocationWrapper::Inited) && !(locationState & LiblocationWrapper::Started)) { if (!errorHandlerId) { errorHandlerId = g_signal_connect(G_OBJECT(locationControl), "error-verbose", G_CALLBACK(&locationError), static_cast<void*>(this)); } if (!posChangedId) { posChangedId = g_signal_connect(G_OBJECT(locationDevice), "changed", G_CALLBACK(&locationChanged), static_cast<void*>(this)); } location_gpsd_control_start(locationControl); locationState |= LiblocationWrapper::Started; locationState &= ~LiblocationWrapper::Stopped; } } void LiblocationWrapper::stop() { startcounter--; if (startcounter > 0) return; if ((locationState & (LiblocationWrapper::Started | LiblocationWrapper::Inited)) && !(locationState & LiblocationWrapper::Stopped)) { if (errorHandlerId) g_signal_handler_disconnect(G_OBJECT(locationControl), errorHandlerId); if (posChangedId) g_signal_handler_disconnect(G_OBJECT(locationDevice), posChangedId); errorHandlerId = 0; posChangedId = 0; startcounter = 0; location_gpsd_control_stop(locationControl); locationState &= ~LiblocationWrapper::Started; locationState |= LiblocationWrapper::Stopped; } } bool LiblocationWrapper::isActive() { if (locationState & LiblocationWrapper::Started) return true; else return false; } #include "moc_liblocationwrapper_p.cpp" QTM_END_NAMESPACE <|endoftext|>
<commit_before>// Copyright (c) 2015, Karsten Heinze <karsten.heinze@sidenotes.de> // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef SESAME_VERSION_HPP #define SESAME_VERSION_HPP #include <cstdint> namespace sesame { const uint32_t VERSION_MAJOR = 0; const uint32_t VERSION_MINOR = 1; const uint32_t VERSION_BUGFIX = 2; namespace { static const String getVersionString() { StringStream s; s << "Sesame "; s << VERSION_MAJOR << "." << VERSION_MINOR << "." << VERSION_BUGFIX; s << " - Copyright (c), 2015 Karsten Heinze"; return s.str(); } } static const String VERSION_STRING( getVersionString() ); } #endif <commit_msg>adjusted version<commit_after>// Copyright (c) 2015, Karsten Heinze <karsten.heinze@sidenotes.de> // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef SESAME_VERSION_HPP #define SESAME_VERSION_HPP #include <cstdint> namespace sesame { const uint32_t VERSION_MAJOR = 0; const uint32_t VERSION_MINOR = 1; const uint32_t VERSION_BUGFIX = 3; namespace { static const String getVersionString() { StringStream s; s << "Sesame "; s << VERSION_MAJOR << "." << VERSION_MINOR << "." << VERSION_BUGFIX; s << " - Copyright (c), 2015 Karsten Heinze"; return s.str(); } } static const String VERSION_STRING( getVersionString() ); } #endif <|endoftext|>
<commit_before>/** * @copyright * ==================================================================== * Copyright (c) 2003 CollabNet. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://subversion.tigris.org/license-1.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * * This software consists of voluntary contributions made by many * individuals. For exact contribution history, see the revision * history and logs, available at http://subversion.tigris.org/. * ==================================================================== * @endcopyright * * @file Revision.cpp * @brief Implementation of the class Revision */ #include "Revision.h" #include "org_tigris_subversion_javahl_Revision_Kind.h" #include "JNIUtil.h" ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// const svn_opt_revision_kind Revision::START = svn_opt_revision_unspecified; const svn_opt_revision_kind Revision::HEAD = svn_opt_revision_head; Revision::Revision (const svn_opt_revision_kind kind) { m_revision.kind = kind; m_revision.value.number = 0; } Revision::Revision(jobject jthis, bool headIfUnspecified, bool oneIfUnspecified) { if(jthis == NULL) { m_revision.kind = svn_opt_revision_unspecified; m_revision.value.number = 0; } else { JNIEnv *env = JNIUtil::getEnv(); static jfieldID fid = 0; if(fid == 0) { jclass clazz = env->FindClass(JAVA_PACKAGE"/Revision"); if(JNIUtil::isJavaExceptionThrown()) { return; } fid = env->GetFieldID(clazz, "revKind", "I"); if(JNIUtil::isJavaExceptionThrown()) { return; } env->DeleteLocalRef(clazz); if(JNIUtil::isJavaExceptionThrown()) { return; } } jint jKind = env->GetIntField(jthis, fid); if(JNIUtil::isJavaExceptionThrown()) { return; } m_revision.value.number = 0; switch(jKind) { case org_tigris_subversion_javahl_Revision_Kind_unspecified: m_revision.kind = svn_opt_revision_unspecified; break; case org_tigris_subversion_javahl_Revision_Kind_number: m_revision.kind = svn_opt_revision_number; { static jfieldID fidNum = 0; if(fidNum == 0) { jclass clazz = env->FindClass(JAVA_PACKAGE"/Revision$Number"); if(JNIUtil::isJavaExceptionThrown()) { return; } fidNum = env->GetFieldID(clazz, "revNumber", "J"); if(JNIUtil::isJavaExceptionThrown()) { return; } env->DeleteLocalRef(clazz); if(JNIUtil::isJavaExceptionThrown()) { return; } } jlong jNumber = env->GetLongField(jthis, fidNum); m_revision.value.number = jNumber; } break; case org_tigris_subversion_javahl_Revision_Kind_date: m_revision.kind = svn_opt_revision_date; { static jfieldID fidDate = 0; if(fidDate == 0) { jclass clazz = env->FindClass(JAVA_PACKAGE"/Revision$DateSpec"); if(JNIUtil::isJavaExceptionThrown()) { return; } fidDate = env->GetFieldID(clazz, "revDate", "Ljava/util/Date;"); if(JNIUtil::isJavaExceptionThrown()) { return; } env->DeleteLocalRef(clazz); if(JNIUtil::isJavaExceptionThrown()) { return; } } jobject jDate = env->GetObjectField(jthis, fidDate); if(JNIUtil::isJavaExceptionThrown()) { return; } static jmethodID mid = 0; if(mid == 0) { jclass clazz = env->FindClass("java/util/Date"); if(JNIUtil::isJavaExceptionThrown()) { return; } fid = env->GetFieldID(clazz, "getTime", "()J"); if(JNIUtil::isJavaExceptionThrown()) { return; } env->DeleteLocalRef(clazz); if(JNIUtil::isJavaExceptionThrown()) { return; } } jlong jMillSec = env->CallLongMethod(jDate, mid); if(JNIUtil::isJavaExceptionThrown()) { return; } env->DeleteLocalRef(jDate); if(JNIUtil::isJavaExceptionThrown()) { return; } m_revision.value.date = jMillSec * 1000; } break; case org_tigris_subversion_javahl_Revision_Kind_committed: m_revision.kind = svn_opt_revision_committed; break; case org_tigris_subversion_javahl_Revision_Kind_previous: m_revision.kind = svn_opt_revision_previous; break; case org_tigris_subversion_javahl_Revision_Kind_base: m_revision.kind = svn_opt_revision_base; break; case org_tigris_subversion_javahl_Revision_Kind_working: m_revision.kind = svn_opt_revision_working; break; case org_tigris_subversion_javahl_Revision_Kind_head: m_revision.kind = svn_opt_revision_head; break; } } if(headIfUnspecified && m_revision.kind == svn_opt_revision_unspecified) m_revision.kind = svn_opt_revision_head; else if(oneIfUnspecified && m_revision.kind == svn_opt_revision_unspecified) { m_revision.kind = svn_opt_revision_number; m_revision.value.number = 1; } } Revision::~Revision() { } const svn_opt_revision_t *Revision::revision () const { return &m_revision; } <commit_msg> * Revision.cpp (Revision::Revision) Passing a Revision.DateSpec in javahl failed with java.lang.NoSuchFieldError because java.util.Date.getTime() was searched as a field when it is a method.<commit_after>/** * @copyright * ==================================================================== * Copyright (c) 2003 CollabNet. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://subversion.tigris.org/license-1.html. * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * * This software consists of voluntary contributions made by many * individuals. For exact contribution history, see the revision * history and logs, available at http://subversion.tigris.org/. * ==================================================================== * @endcopyright * * @file Revision.cpp * @brief Implementation of the class Revision */ #include "Revision.h" #include "org_tigris_subversion_javahl_Revision_Kind.h" #include "JNIUtil.h" ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// const svn_opt_revision_kind Revision::START = svn_opt_revision_unspecified; const svn_opt_revision_kind Revision::HEAD = svn_opt_revision_head; Revision::Revision (const svn_opt_revision_kind kind) { m_revision.kind = kind; m_revision.value.number = 0; } Revision::Revision(jobject jthis, bool headIfUnspecified, bool oneIfUnspecified) { if(jthis == NULL) { m_revision.kind = svn_opt_revision_unspecified; m_revision.value.number = 0; } else { JNIEnv *env = JNIUtil::getEnv(); static jfieldID fid = 0; if(fid == 0) { jclass clazz = env->FindClass(JAVA_PACKAGE"/Revision"); if(JNIUtil::isJavaExceptionThrown()) { return; } fid = env->GetFieldID(clazz, "revKind", "I"); if(JNIUtil::isJavaExceptionThrown()) { return; } env->DeleteLocalRef(clazz); if(JNIUtil::isJavaExceptionThrown()) { return; } } jint jKind = env->GetIntField(jthis, fid); if(JNIUtil::isJavaExceptionThrown()) { return; } m_revision.value.number = 0; switch(jKind) { case org_tigris_subversion_javahl_Revision_Kind_unspecified: m_revision.kind = svn_opt_revision_unspecified; break; case org_tigris_subversion_javahl_Revision_Kind_number: m_revision.kind = svn_opt_revision_number; { static jfieldID fidNum = 0; if(fidNum == 0) { jclass clazz = env->FindClass(JAVA_PACKAGE"/Revision$Number"); if(JNIUtil::isJavaExceptionThrown()) { return; } fidNum = env->GetFieldID(clazz, "revNumber", "J"); if(JNIUtil::isJavaExceptionThrown()) { return; } env->DeleteLocalRef(clazz); if(JNIUtil::isJavaExceptionThrown()) { return; } } jlong jNumber = env->GetLongField(jthis, fidNum); m_revision.value.number = jNumber; } break; case org_tigris_subversion_javahl_Revision_Kind_date: m_revision.kind = svn_opt_revision_date; { static jfieldID fidDate = 0; if(fidDate == 0) { jclass clazz = env->FindClass(JAVA_PACKAGE"/Revision$DateSpec"); if(JNIUtil::isJavaExceptionThrown()) { return; } fidDate = env->GetFieldID(clazz, "revDate", "Ljava/util/Date;"); if(JNIUtil::isJavaExceptionThrown()) { return; } env->DeleteLocalRef(clazz); if(JNIUtil::isJavaExceptionThrown()) { return; } } jobject jDate = env->GetObjectField(jthis, fidDate); if(JNIUtil::isJavaExceptionThrown()) { return; } static jmethodID mid = 0; if(mid == 0) { jclass clazz = env->FindClass("java/util/Date"); if(JNIUtil::isJavaExceptionThrown()) { return; } mid = env->GetMethodID(clazz, "getTime", "()J"); if(JNIUtil::isJavaExceptionThrown()) { return; } env->DeleteLocalRef(clazz); if(JNIUtil::isJavaExceptionThrown()) { return; } } jlong jMillSec = env->CallLongMethod(jDate, mid); if(JNIUtil::isJavaExceptionThrown()) { return; } env->DeleteLocalRef(jDate); if(JNIUtil::isJavaExceptionThrown()) { return; } m_revision.value.date = jMillSec * 1000; } break; case org_tigris_subversion_javahl_Revision_Kind_committed: m_revision.kind = svn_opt_revision_committed; break; case org_tigris_subversion_javahl_Revision_Kind_previous: m_revision.kind = svn_opt_revision_previous; break; case org_tigris_subversion_javahl_Revision_Kind_base: m_revision.kind = svn_opt_revision_base; break; case org_tigris_subversion_javahl_Revision_Kind_working: m_revision.kind = svn_opt_revision_working; break; case org_tigris_subversion_javahl_Revision_Kind_head: m_revision.kind = svn_opt_revision_head; break; } } if(headIfUnspecified && m_revision.kind == svn_opt_revision_unspecified) m_revision.kind = svn_opt_revision_head; else if(oneIfUnspecified && m_revision.kind == svn_opt_revision_unspecified) { m_revision.kind = svn_opt_revision_number; m_revision.value.number = 1; } } Revision::~Revision() { } const svn_opt_revision_t *Revision::revision () const { return &m_revision; } <|endoftext|>
<commit_before>/*********************************************************************************************************************** * * * SPLASH build system v0.2 * * * * Copyright (c) 2016 Andrew D. Zonenberg * * All rights reserved. * * * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the * * following conditions are met: * * * * * Redistributions of source code must retain the above copyright notice, this list of conditions, and the * * following disclaimer. * * * * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the * * following disclaimer in the documentation and/or other materials provided with the distribution. * * * * * Neither the name of the author nor the names of any contributors may be used to endorse or promote products * * derived from this software without specific prior written permission. * * * * THIS SOFTWARE IS PROVIDED BY THE AUTHORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL * * THE AUTHORS BE HELD LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * * POSSIBILITY OF SUCH DAMAGE. * * * ***********************************************************************************************************************/ #include "splashdev.h" using namespace std; void ShowUsage(); void ShowVersion(); /** @brief Program entry point */ int main(int argc, char* argv[]) { string source_dir; string ctl_server; LogSink::Severity console_verbosity = LogSink::NOTICE; //Parse command-line arguments for(int i=1; i<argc; i++) { string s(argv[i]); //Let the logger eat its args first if(ParseLoggerArguments(i, argc, argv, console_verbosity)) continue; else if(s == "--help") { ShowUsage(); return 0; } else if(s == "--version") { ShowVersion(); return 0; } //Last two args without switches are source dir and control server. //TODO: mandatory arguments to introduce these? else if(source_dir == "") source_dir = argv[i]; else ctl_server = argv[i]; } //Set up logging g_log_sinks.emplace(g_log_sinks.begin(), new STDLogSink(console_verbosity)); //Print header if(console_verbosity >= LogSink::NOTICE) { ShowVersion(); printf("\n"); } //Open the source directory and start an inotify watcher on it and all subdirectories source_dir = CanonicalizePath(source_dir); int hnotify = inotify_init(); if(hnotify < 0) LogFatal("Couldn't start inotify\n"); LogNotice("Running on directory: %s\n", source_dir.c_str()); WatchDirRecursively(hnotify, source_dir); //TODO: signal handler so we can quit gracefully //Main event loop size_t buflen = 8192; char ebuf[buflen]; while(1) { //Get the event size_t len = read(hnotify, ebuf, buflen); if(len <= 0) break; size_t offset = 0; while(offset < len) { inotify_event* evt = reinterpret_cast<inotify_event*>(ebuf + offset); //Skip events without a filename, or hidden files if( (evt->len != 0) && (evt->name[0] != '.') ) WatchedFileChanged(evt->mask, CanonicalizePath(source_dir + "/" + evt->name)); //Go on to the next one offset += sizeof(inotify_event) + evt->len; } } //Done close(hnotify); return 0; } /** @brief Add watches to a directory *and* all subdirectories */ void WatchDirRecursively(int hnotify, string dir) { LogDebug(" Recursively watching directory %s\n", dir.c_str()); //Watch changes to the directory if(0 > inotify_add_watch( hnotify, dir.c_str(), IN_CREATE | IN_DELETE | IN_MODIFY | IN_MOVED_FROM | IN_MOVED_TO | IN_DELETE_SELF)) { LogFatal("Failed to watch directory %s\n", dir.c_str()); } //Look for any subdirs and watch them vector<string> subdirs; FindSubdirs(dir, subdirs); for(auto s : subdirs) WatchDirRecursively(hnotify, s); } void ShowVersion() { printf( "SPLASH build system developer daemon by Andrew D. Zonenberg.\n" "\n" "License: 3-clause BSD\n" "This is free software: you are free to change and redistribute it.\n" "There is NO WARRANTY, to the extent permitted by law.\n"); } void ShowUsage() { printf("Usage: splashdev srcdir ctlserver\n"); exit(0); } <commit_msg>splashdev: Rephrased log message<commit_after>/*********************************************************************************************************************** * * * SPLASH build system v0.2 * * * * Copyright (c) 2016 Andrew D. Zonenberg * * All rights reserved. * * * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the * * following conditions are met: * * * * * Redistributions of source code must retain the above copyright notice, this list of conditions, and the * * following disclaimer. * * * * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the * * following disclaimer in the documentation and/or other materials provided with the distribution. * * * * * Neither the name of the author nor the names of any contributors may be used to endorse or promote products * * derived from this software without specific prior written permission. * * * * THIS SOFTWARE IS PROVIDED BY THE AUTHORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL * * THE AUTHORS BE HELD LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * * POSSIBILITY OF SUCH DAMAGE. * * * ***********************************************************************************************************************/ #include "splashdev.h" using namespace std; void ShowUsage(); void ShowVersion(); /** @brief Program entry point */ int main(int argc, char* argv[]) { string source_dir; string ctl_server; LogSink::Severity console_verbosity = LogSink::NOTICE; //Parse command-line arguments for(int i=1; i<argc; i++) { string s(argv[i]); //Let the logger eat its args first if(ParseLoggerArguments(i, argc, argv, console_verbosity)) continue; else if(s == "--help") { ShowUsage(); return 0; } else if(s == "--version") { ShowVersion(); return 0; } //Last two args without switches are source dir and control server. //TODO: mandatory arguments to introduce these? else if(source_dir == "") source_dir = argv[i]; else ctl_server = argv[i]; } //Set up logging g_log_sinks.emplace(g_log_sinks.begin(), new STDLogSink(console_verbosity)); //Print header if(console_verbosity >= LogSink::NOTICE) { ShowVersion(); printf("\n"); } //Open the source directory and start an inotify watcher on it and all subdirectories source_dir = CanonicalizePath(source_dir); int hnotify = inotify_init(); if(hnotify < 0) LogFatal("Couldn't start inotify\n"); LogNotice("Working copy root directory: %s\n", source_dir.c_str()); WatchDirRecursively(hnotify, source_dir); //TODO: signal handler so we can quit gracefully //Main event loop size_t buflen = 8192; char ebuf[buflen]; while(1) { //Get the event size_t len = read(hnotify, ebuf, buflen); if(len <= 0) break; size_t offset = 0; while(offset < len) { inotify_event* evt = reinterpret_cast<inotify_event*>(ebuf + offset); //Skip events without a filename, or hidden files if( (evt->len != 0) && (evt->name[0] != '.') ) WatchedFileChanged(evt->mask, CanonicalizePath(source_dir + "/" + evt->name)); //Go on to the next one offset += sizeof(inotify_event) + evt->len; } } //Done close(hnotify); return 0; } /** @brief Add watches to a directory *and* all subdirectories */ void WatchDirRecursively(int hnotify, string dir) { LogDebug(" Recursively watching directory %s\n", dir.c_str()); //Watch changes to the directory if(0 > inotify_add_watch( hnotify, dir.c_str(), IN_CREATE | IN_DELETE | IN_MODIFY | IN_MOVED_FROM | IN_MOVED_TO | IN_DELETE_SELF)) { LogFatal("Failed to watch directory %s\n", dir.c_str()); } //Look for any subdirs and watch them vector<string> subdirs; FindSubdirs(dir, subdirs); for(auto s : subdirs) WatchDirRecursively(hnotify, s); } void ShowVersion() { printf( "SPLASH build system developer daemon by Andrew D. Zonenberg.\n" "\n" "License: 3-clause BSD\n" "This is free software: you are free to change and redistribute it.\n" "There is NO WARRANTY, to the extent permitted by law.\n"); } void ShowUsage() { printf("Usage: splashdev srcdir ctlserver\n"); exit(0); } <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/sys/vfs/vfs_main.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2010,2020 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #include <string.h> #include <errno.h> #include <sys/msg.h> #include <sys/vfs.h> #include <sys/task.h> #include <sys/sync.h> #include <util/locked/list.H> #include <kernel/console.H> // TODO : Remove this. const char* VFS_ROOT = "/"; const char* VFS_ROOT_BIN = "/bin/"; const char* VFS_ROOT_DATA = "/data/"; const char* VFS_ROOT_MSG = "/msg/"; const char* VFS_ROOT_MSG_VFS = "/msg/vfs"; const char* VFS_ROOT_MSG_MBOX = "/msg/mbox"; const char* VFS_ROOT_MSG_MCTP_IN = "/msg/mctpin"; const char* VFS_ROOT_MSG_MCTP_OUT = "/msg/mctpout"; const char* VFS_ROOT_MSG_PLDM_REQ_IN = "/msg/pldmreqin"; const char* VFS_ROOT_MSG_PLDM_RSP_IN = "/msg/pldmrspin"; const char* VFS_ROOT_MSG_PLDM_REQ_OUT= "/msg/pldrreqout"; void vfs_module_init(); struct VfsPath { char key[64]; bool operator!=(VfsPath& r) { return 0 != strcmp(key, r.key); }; }; struct VfsEntry { typedef VfsPath key_type; key_type key; msg_q_t msg_q; VfsEntry* next; VfsEntry* prev; }; void* vfs_main(void* i_barrier) { // Detach this task from the parent task_detach(); barrier_t * barrier = (barrier_t *)i_barrier; // Create message queue, register with kernel. msg_q_t vfsMsgQ = msg_q_create(); msg_q_register(vfsMsgQ, VFS_ROOT); printk("done.\n"); // Initalize modules. vfs_module_init(); // Signal with sys/init to continue on. barrier_wait(barrier); Util::Locked::List<VfsEntry, VfsEntry::key_type> vfsContents; while(1) { msg_t* msg = msg_wait(vfsMsgQ); switch(msg->type) { case VFS_MSG_REGISTER_MSGQ: { VfsEntry* e = new VfsEntry(); strcpy(e->key.key, (char*) msg->extra_data); e->msg_q = (msg_q_t) msg->data[0]; vfsContents.insert(e); printkd("VFS: Registering %p as %s\n", e->msg_q, e->key.key); msg_respond(vfsMsgQ, msg); } break; case VFS_MSG_REMOVE_MSGQ: { VfsEntry::key_type k; strcpy(k.key, (char*) msg->extra_data); VfsEntry* e = vfsContents.find(k); if(NULL != e) { msg->data[0] = 0; //(uint64_t) e->msg_q; printkd("VFS: Removing msg queue %s\n",e->key.key); vfsContents.erase(e); delete e; } else { msg->data[0] = (uint64_t) (-ENXIO); } msg_respond(vfsMsgQ, msg); } break; case VFS_MSG_RESOLVE_MSGQ: { VfsEntry::key_type k; strcpy(k.key, (char*) msg->extra_data); VfsEntry* e = vfsContents.find(k); if (NULL == e) msg->data[0] = (uint64_t) NULL; else msg->data[0] = (uint64_t) e->msg_q; msg_respond(vfsMsgQ, msg); } break; case VFS_MSG_EXEC: { printkd("VFS: Got exec request of %s\n", (const char*)msg->data[0]); VfsSystemModule* module = vfs_find_module(VFS_MODULES, (const char *) msg->data[0]); void* fnptr = vfs_start_entrypoint(module); // child == -ENOENT means module not found in base image // so send a message to VFS_MSG queue to look in the // extended image VFS_MSG queue will handle the // msg_respond() if( fnptr == reinterpret_cast<void*>(-ENOENT) ) // forward msg to usr vfs { VfsEntry::key_type k; strcpy(k.key, VFS_ROOT_MSG_VFS); VfsEntry* e = vfsContents.find(k); if(e != NULL) { msg_t* emsg = msg_allocate(); emsg->type = msg->type; emsg->data[0] = (uint64_t) msg; emsg->data[1] = (uint64_t) vfsMsgQ; msg_send(e->msg_q, emsg); // send async msg } else // Can't find VFS_MSG queue - not started yet { msg->data[0] = (uint64_t) fnptr; msg_respond(vfsMsgQ, msg); } } else // send back child (or errno) { msg->data[0] = (uint64_t) fnptr; msg_respond(vfsMsgQ, msg); } } break; default: msg_free(msg); break; } } // end while(1) return NULL; } // ---------------------------------------------------------------------------- void* vfs_start_entrypoint(VfsSystemModule * i_module) { void* ptr = reinterpret_cast<void*>(-ENOENT); if(i_module != NULL) { if (i_module->start == NULL) { // module has no start() routine ptr = reinterpret_cast<void*>(-ENOEXEC); } else { ptr = reinterpret_cast<void*>(i_module->start); } } return ptr; } <commit_msg>Update vfs_main.C<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/sys/vfs/vfs_main.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2010,2021 */ /* [+] International Business Machines Corp. */ /* [+] dongshijiang */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #include <string.h> #include <errno.h> #include <sys/msg.h> #include <sys/vfs.h> #include <sys/task.h> #include <sys/sync.h> #include <util/locked/list.H> #include <kernel/console.H> // TODO : Remove this. const char* VFS_ROOT = "/"; const char* VFS_ROOT_BIN = "/bin/"; const char* VFS_ROOT_DATA = "/data/"; const char* VFS_ROOT_MSG = "/msg/"; const char* VFS_ROOT_MSG_VFS = "/msg/vfs"; const char* VFS_ROOT_MSG_MBOX = "/msg/mbox"; const char* VFS_ROOT_MSG_MCTP_IN = "/msg/mctpin"; const char* VFS_ROOT_MSG_MCTP_OUT = "/msg/mctpout"; const char* VFS_ROOT_MSG_PLDM_REQ_IN = "/msg/pldmreqin"; const char* VFS_ROOT_MSG_PLDM_RSP_IN = "/msg/pldmrspin"; const char* VFS_ROOT_MSG_PLDM_REQ_OUT= "/msg/pldmreqout"; void vfs_module_init(); struct VfsPath { char key[64]; bool operator!=(VfsPath& r) { return 0 != strcmp(key, r.key); }; }; struct VfsEntry { typedef VfsPath key_type; key_type key; msg_q_t msg_q; VfsEntry* next; VfsEntry* prev; }; void* vfs_main(void* i_barrier) { // Detach this task from the parent task_detach(); barrier_t * barrier = (barrier_t *)i_barrier; // Create message queue, register with kernel. msg_q_t vfsMsgQ = msg_q_create(); msg_q_register(vfsMsgQ, VFS_ROOT); printk("done.\n"); // Initalize modules. vfs_module_init(); // Signal with sys/init to continue on. barrier_wait(barrier); Util::Locked::List<VfsEntry, VfsEntry::key_type> vfsContents; while(1) { msg_t* msg = msg_wait(vfsMsgQ); switch(msg->type) { case VFS_MSG_REGISTER_MSGQ: { VfsEntry* e = new VfsEntry(); strcpy(e->key.key, (char*) msg->extra_data); e->msg_q = (msg_q_t) msg->data[0]; vfsContents.insert(e); printkd("VFS: Registering %p as %s\n", e->msg_q, e->key.key); msg_respond(vfsMsgQ, msg); } break; case VFS_MSG_REMOVE_MSGQ: { VfsEntry::key_type k; strcpy(k.key, (char*) msg->extra_data); VfsEntry* e = vfsContents.find(k); if(NULL != e) { msg->data[0] = 0; //(uint64_t) e->msg_q; printkd("VFS: Removing msg queue %s\n",e->key.key); vfsContents.erase(e); delete e; } else { msg->data[0] = (uint64_t) (-ENXIO); } msg_respond(vfsMsgQ, msg); } break; case VFS_MSG_RESOLVE_MSGQ: { VfsEntry::key_type k; strcpy(k.key, (char*) msg->extra_data); VfsEntry* e = vfsContents.find(k); if (NULL == e) msg->data[0] = (uint64_t) NULL; else msg->data[0] = (uint64_t) e->msg_q; msg_respond(vfsMsgQ, msg); } break; case VFS_MSG_EXEC: { printkd("VFS: Got exec request of %s\n", (const char*)msg->data[0]); VfsSystemModule* module = vfs_find_module(VFS_MODULES, (const char *) msg->data[0]); void* fnptr = vfs_start_entrypoint(module); // child == -ENOENT means module not found in base image // so send a message to VFS_MSG queue to look in the // extended image VFS_MSG queue will handle the // msg_respond() if( fnptr == reinterpret_cast<void*>(-ENOENT) ) // forward msg to usr vfs { VfsEntry::key_type k; strcpy(k.key, VFS_ROOT_MSG_VFS); VfsEntry* e = vfsContents.find(k); if(e != NULL) { msg_t* emsg = msg_allocate(); emsg->type = msg->type; emsg->data[0] = (uint64_t) msg; emsg->data[1] = (uint64_t) vfsMsgQ; msg_send(e->msg_q, emsg); // send async msg } else // Can't find VFS_MSG queue - not started yet { msg->data[0] = (uint64_t) fnptr; msg_respond(vfsMsgQ, msg); } } else // send back child (or errno) { msg->data[0] = (uint64_t) fnptr; msg_respond(vfsMsgQ, msg); } } break; default: msg_free(msg); break; } } // end while(1) return NULL; } // ---------------------------------------------------------------------------- void* vfs_start_entrypoint(VfsSystemModule * i_module) { void* ptr = reinterpret_cast<void*>(-ENOENT); if(i_module != NULL) { if (i_module->start == NULL) { // module has no start() routine ptr = reinterpret_cast<void*>(-ENOEXEC); } else { ptr = reinterpret_cast<void*>(i_module->start); } } return ptr; } <|endoftext|>
<commit_before>#include "globals.h" #include "syscalls.h" #define LINUX_FUTEX_WAIT 0 #define LINUX_FUTEX_WAKE 1 #define LINUX_FUTEX_FD 2 #define LINUX_FUTEX_REQUEUE 3 #define LINUX_FUTEX_CMP_REQUEUE 4 #define LINUX_FUTEX_WAKE_OP 5 #define LINUX_FUTEX_LOCK_PI 6 #define LINUX_FUTEX_UNLOCK_PI 7 #define LINUX_FUTEX_TRYLOCK_PI 8 #define LINUX_FUTEX_WAIT_BITSET 9 #define LINUX_FUTEX_WAKE_BITSET 10 #define LINUX_FUTEX_PRIVATE_FLAG 128 #define LINUX_FUTEX_CMD_MASK ~LINUX_FUTEX_PRIVATE_FLAG #define LINUX_FUTEX_WAIT_PRIVATE (LINUX_FUTEX_WAIT | LINUX_FUTEX_PRIVATE_FLAG) #define LINUX_FUTEX_WAKE_PRIVATE (LINUX_FUTEX_WAKE | LINUX_FUTEX_PRIVATE_FLAG) #define LINUX_FUTEX_REQUEUE_PRIVATE (LINUX_FUTEX_REQUEUE | LINUX_FUTEX_PRIVATE_FLAG) #define LINUX_FUTEX_CMP_REQUEUE_PRIVATE (LINUX_FUTEX_CMP_REQUEUE | LINUX_FUTEX_PRIVATE_FLAG) #define LINUX_FUTEX_WAKE_OP_PRIVATE (LINUX_FUTEX_WAKE_OP | LINUX_FUTEX_PRIVATE_FLAG) #define LINUX_FUTEX_LOCK_PI_PRIVATE (LINUX_FUTEX_LOCK_PI | LINUX_FUTEX_PRIVATE_FLAG) #define LINUX_FUTEX_UNLOCK_PI_PRIVATE (LINUX_FUTEX_UNLOCK_PI | LINUX_FUTEX_PRIVATE_FLAG) #define LINUX_FUTEX_TRYLOCK_PI_PRIVATE (LINUX_FUTEX_TRYLOCK_PI | LINUX_FUTEX_PRIVATE_FLAG) #define LINUX_FUTEX_WAIT_BITSET_PRIVATE (LINUX_FUTEX_WAIT_BITS | LINUX_FUTEX_PRIVATE_FLAG) #define LINUX_FUTEX_WAKE_BITSET_PRIVATE (LINUX_FUTEX_WAKE_BITS | LINUX_FUTEX_PRIVATE_FLAG) struct linux_user_desc { int entry_number; unsigned int base_addr; unsigned int limit; unsigned int seg_32bit:1; unsigned int contents:2; unsigned int read_exec_only:1; unsigned int limit_in_pages:1; unsigned int seg_not_present:1; unsigned int useable:1; }; static pthread_mutex_t tlsmutex = PTHREAD_MUTEX_INITIALIZER; typedef u_int32_t DWORD; typedef u_int32_t ULONG; typedef u_int16_t WORD; typedef u_int8_t BYTE; #pragma pack(push) struct LDT_ENTRY { WORD LimitLow; WORD BaseLow; union { struct { BYTE BaseMid; BYTE Flags1; BYTE Flags2; BYTE BaseHi; } Bytes; struct { DWORD BaseMid:8; DWORD Type:5; DWORD Dpl:2; DWORD Pres:1; DWORD LimitHi:4; DWORD Sys:1; DWORD Reserved_0:1; DWORD Default_Big:1; DWORD Granularity:1; DWORD BaseHi:8; } Bits; } HighWord; }; #pragma pack(pop) extern "C" u_int32_t __stdcall NtSetLdtEntries( /*IN*/ ULONG Selector1, /*IN*/ LDT_ENTRY LdtEntry1, /*IN*/ ULONG Selector2, /*IN*/ LDT_ENTRY LdtEntry2); asm ("_NtSetLdtEntries: jmp _NtSetLdtEntries@24"); extern "C" u_int32_t __stdcall NtQueryInformationProcess( /*IN*/ int32_t ProcessHandle, /*IN*/ int32_t ProcessInformationClass, /*OUT*/ void* ProcessInformation, /*IN*/ u_int32_t ProcessInformationLength, /*OUT*/ u_int32_t* ReturnLength /*OPTIONAL*/); asm ("_NtQueryInformationProcess: jmp _NtQueryInformationProcess@20"); extern "C" u_int32_t __stdcall NtSetInformationProcess( /*IN*/ int32_t ProcessHandle, /*IN*/ int32_t ProcessInformationClass, /*IN*/ void* ProcessInformation, /*IN*/ u_int32_t ProcessInformationLength); asm ("_NtSetInformationProcess: jmp _NtSetInformationProcess@16"); static u_int32_t read_ldt(u_int32_t selector, LDT_ENTRY& ldt) { u_int32_t buffer[4]; buffer[0] = selector << 3; buffer[1] = sizeof(ldt); u_int32_t result = NtQueryInformationProcess(-1, 10, buffer, 16, NULL); if (buffer[1] == 0) ldt.HighWord.Bits.Pres = 0; else memcpy(&ldt, &buffer[2], sizeof(ldt)); return result; } static u_int32_t write_ldt(u_int32_t selector, const LDT_ENTRY& ldt) { u_int32_t buffer[4]; buffer[0] = selector << 3; buffer[1] = sizeof(ldt); memcpy(&buffer[2], &ldt, sizeof(ldt)); return NtSetInformationProcess(-1, 10, buffer, 16); } static int display_selector (LDT_ENTRY& info) { int base, limit; if (!info.HighWord.Bits.Pres) { log ("Segment not present\n"); return 0; } base = (info.HighWord.Bits.BaseHi << 24) + (info.HighWord.Bits.BaseMid << 16) + info.BaseLow; limit = (info.HighWord.Bits.LimitHi << 16) + info.LimitLow; if (info.HighWord.Bits.Granularity) limit = (limit << 12) | 0xfff; log ("base=0x%08x limit=0x%08x", base, limit); if (info.HighWord.Bits.Default_Big) log(" 32-bit "); else log(" 16-bit "); switch ((info.HighWord.Bits.Type & 0xf) >> 1) { case 0: log ("Data (Read-Only, Exp-up"); break; case 1: log ("Data (Read/Write, Exp-up"); break; case 2: log ("Unused segment ("); break; case 3: log ("Data (Read/Write, Exp-down"); break; case 4: log ("Code (Exec-Only, N.Conf"); break; case 5: log ("Code (Exec/Read, N.Conf"); break; case 6: log ("Code (Exec-Only, Conf"); break; case 7: log ("Code (Exec/Read, Conf"); break; default: log ("Unknown type 0x%x",info.HighWord.Bits.Type); } if ((info.HighWord.Bits.Type & 0x1) == 0) log(", N.Acc"); log (")\n"); if ((info.HighWord.Bits.Type & 0x10) == 0) log("System selector "); log ("Priviledge level = %d. ", info.HighWord.Bits.Dpl); if (info.HighWord.Bits.Granularity) log ("Page granular.\n"); else log ("Byte granular.\n"); return 1; } static bool try_perversion(Registers& regs, int offset) { u_int16_t& insn = *(u_int16_t*)(regs.eip+offset); if (insn == 0xe88e) { insn = 0x9090; return true; } return false; } int32_t sys_set_thread_area(Registers& regs) { Arguments& arg = regs.arg; struct linux_user_desc& u = *(struct linux_user_desc*) arg.a0.p; #if 0 log(" entry_number = %d", u.entry_number); log(" base_addr = %08x", u.base_addr); log(" limit = %08x", u.limit); log(" seg_32bit = %d", u.seg_32bit); log(" contents = %d", u.contents); log(" read_exec_only = %d", u.read_exec_only); log(" limit_in_pages = %d", u.limit_in_pages); log(" seg_not_present = %d", u.seg_not_present); log(" useable = %d", u.useable); #endif /* Sanitise the limit; NT enforces a certain upper limit. */ u_int64_t maximum = u.limit; if (u.limit_in_pages) maximum <<= 12; maximum += u.base_addr; if (maximum > 0x7ff00000) maximum = 0x7ff00000; LDT_ENTRY ldt; if (u.entry_number == -1) { /* Search for an unused segment. */ int selector = 512; while (selector < 8192) { //log("examining selector %d", selector); u_int32_t r = read_ldt(selector, ldt); if (r != 0) break; if (!ldt.HighWord.Bits.Pres) { /* This selector is unused. */ u.entry_number = selector; break; } selector++; } //log("found unused selector %d", u.entry_number); } if (u.entry_number == -1) return -ENOMEM; memset(&ldt, 0, sizeof(ldt)); u_int32_t limit = maximum - u.base_addr; //log("maximum=%08llx, limit=%08x", maximum, limit); ldt.BaseLow = (u.base_addr & 0xFFFF); ldt.HighWord.Bits.BaseMid = (u.base_addr >> 16) & 0xFF; ldt.HighWord.Bits.BaseHi = (u.base_addr >> 24) & 0xFF; ldt.HighWord.Bits.Type = 0x13; // RW data segment ldt.HighWord.Bits.Dpl = 3; // user segment ldt.HighWord.Bits.Pres = 1; // present ldt.HighWord.Bits.Sys = 0; ldt.HighWord.Bits.Default_Big = 1; // 386 segment if (limit > 0x100000) { ldt.HighWord.Bits.Granularity = 1; limit >>= 12; } else ldt.HighWord.Bits.Granularity = 0; ldt.LimitLow = (limit & 0xFFFF); ldt.HighWord.Bits.LimitHi = (limit >> 16) & 0xF; //display_selector(ldt); u_int32_t r = write_ldt(u.entry_number, ldt); if (r) return -EINVAL; if (try_perversion(regs, 48) || try_perversion(regs, 18) || try_perversion(regs, 28)) { u_int16_t fs; asm volatile ("mov %%fs, %w0" : "=r" (fs)); u_int16_t gs = (u.entry_number << 3) | 7; log("GS %04x now pointing at linear %08x", gs, u.base_addr); SetGS(gs, (void*) u.base_addr); //DumpMemory(u.base_addr, 32); } else { DumpMemory(regs.eip, 128); sleep(-1); error("unable to pervert GDT selector load; check code at %08x", regs.eip); } return 0; } /* Not implemented --- nop */ SYSCALL(sys_set_tid_address) { Warning("sys_set_tid_address() currently unimplemented"); return getpid(); } /* Not implemented */ SYSCALL(compat_sys_set_robust_list) { Warning("compat_sys_set_robust_list() currently unimplemented"); return -LINUX_ENOSYS; } SYSCALL(compat_sys_futex) { int* uaddr = (int*) arg.a0.p; int op = arg.a1.s; int val = arg.a2.s; const void* timespec = (const void*) arg.a3.p; int* uaddr2 = (int*) arg.a4.p; int val3 = arg.a5.s; log("uaddr=%08x, *uaddr=%08x, val=%08x", uaddr, *uaddr, val); //sleep(-1); log("compat_sys_futex(%x) currently unimplemented", op); return -LINUX_ENOSYS; } SYSCALL(sys_gettid) { return (u32) pthread_self(); } <commit_msg>Added just enough futex support to keep glibc happy when forking.<commit_after>#include "globals.h" #include "syscalls.h" #define LINUX_FUTEX_WAIT 0 #define LINUX_FUTEX_WAKE 1 #define LINUX_FUTEX_FD 2 #define LINUX_FUTEX_REQUEUE 3 #define LINUX_FUTEX_CMP_REQUEUE 4 #define LINUX_FUTEX_WAKE_OP 5 #define LINUX_FUTEX_LOCK_PI 6 #define LINUX_FUTEX_UNLOCK_PI 7 #define LINUX_FUTEX_TRYLOCK_PI 8 #define LINUX_FUTEX_WAIT_BITSET 9 #define LINUX_FUTEX_WAKE_BITSET 10 #define LINUX_FUTEX_PRIVATE_FLAG 128 #define LINUX_FUTEX_CLOCK_REALTIME 256 #define LINUX_FUTEX_CMD_MASK ~(LINUX_FUTEX_PRIVATE_FLAG | LINUX_FUTEX_CLOCK_REALTIME) #define LINUX_FUTEX_WAIT_PRIVATE (LINUX_FUTEX_WAIT | LINUX_FUTEX_PRIVATE_FLAG) #define LINUX_FUTEX_WAKE_PRIVATE (LINUX_FUTEX_WAKE | LINUX_FUTEX_PRIVATE_FLAG) #define LINUX_FUTEX_REQUEUE_PRIVATE (LINUX_FUTEX_REQUEUE | LINUX_FUTEX_PRIVATE_FLAG) #define LINUX_FUTEX_CMP_REQUEUE_PRIVATE (LINUX_FUTEX_CMP_REQUEUE | LINUX_FUTEX_PRIVATE_FLAG) #define LINUX_FUTEX_WAKE_OP_PRIVATE (LINUX_FUTEX_WAKE_OP | LINUX_FUTEX_PRIVATE_FLAG) #define LINUX_FUTEX_LOCK_PI_PRIVATE (LINUX_FUTEX_LOCK_PI | LINUX_FUTEX_PRIVATE_FLAG) #define LINUX_FUTEX_UNLOCK_PI_PRIVATE (LINUX_FUTEX_UNLOCK_PI | LINUX_FUTEX_PRIVATE_FLAG) #define LINUX_FUTEX_TRYLOCK_PI_PRIVATE (LINUX_FUTEX_TRYLOCK_PI | LINUX_FUTEX_PRIVATE_FLAG) #define LINUX_FUTEX_WAIT_BITSET_PRIVATE (LINUX_FUTEX_WAIT_BITS | LINUX_FUTEX_PRIVATE_FLAG) #define LINUX_FUTEX_WAKE_BITSET_PRIVATE (LINUX_FUTEX_WAKE_BITS | LINUX_FUTEX_PRIVATE_FLAG) struct linux_user_desc { int entry_number; unsigned int base_addr; unsigned int limit; unsigned int seg_32bit:1; unsigned int contents:2; unsigned int read_exec_only:1; unsigned int limit_in_pages:1; unsigned int seg_not_present:1; unsigned int useable:1; }; static pthread_mutex_t tlsmutex = PTHREAD_MUTEX_INITIALIZER; typedef u_int32_t DWORD; typedef u_int32_t ULONG; typedef u_int16_t WORD; typedef u_int8_t BYTE; #pragma pack(push) struct LDT_ENTRY { WORD LimitLow; WORD BaseLow; union { struct { BYTE BaseMid; BYTE Flags1; BYTE Flags2; BYTE BaseHi; } Bytes; struct { DWORD BaseMid:8; DWORD Type:5; DWORD Dpl:2; DWORD Pres:1; DWORD LimitHi:4; DWORD Sys:1; DWORD Reserved_0:1; DWORD Default_Big:1; DWORD Granularity:1; DWORD BaseHi:8; } Bits; } HighWord; }; #pragma pack(pop) extern "C" u_int32_t __stdcall NtSetLdtEntries( /*IN*/ ULONG Selector1, /*IN*/ LDT_ENTRY LdtEntry1, /*IN*/ ULONG Selector2, /*IN*/ LDT_ENTRY LdtEntry2); asm ("_NtSetLdtEntries: jmp _NtSetLdtEntries@24"); extern "C" u_int32_t __stdcall NtQueryInformationProcess( /*IN*/ int32_t ProcessHandle, /*IN*/ int32_t ProcessInformationClass, /*OUT*/ void* ProcessInformation, /*IN*/ u_int32_t ProcessInformationLength, /*OUT*/ u_int32_t* ReturnLength /*OPTIONAL*/); asm ("_NtQueryInformationProcess: jmp _NtQueryInformationProcess@20"); extern "C" u_int32_t __stdcall NtSetInformationProcess( /*IN*/ int32_t ProcessHandle, /*IN*/ int32_t ProcessInformationClass, /*IN*/ void* ProcessInformation, /*IN*/ u_int32_t ProcessInformationLength); asm ("_NtSetInformationProcess: jmp _NtSetInformationProcess@16"); static u_int32_t read_ldt(u_int32_t selector, LDT_ENTRY& ldt) { u_int32_t buffer[4]; buffer[0] = selector << 3; buffer[1] = sizeof(ldt); u_int32_t result = NtQueryInformationProcess(-1, 10, buffer, 16, NULL); if (buffer[1] == 0) ldt.HighWord.Bits.Pres = 0; else memcpy(&ldt, &buffer[2], sizeof(ldt)); return result; } static u_int32_t write_ldt(u_int32_t selector, const LDT_ENTRY& ldt) { u_int32_t buffer[4]; buffer[0] = selector << 3; buffer[1] = sizeof(ldt); memcpy(&buffer[2], &ldt, sizeof(ldt)); return NtSetInformationProcess(-1, 10, buffer, 16); } static int display_selector (LDT_ENTRY& info) { int base, limit; if (!info.HighWord.Bits.Pres) { log ("Segment not present\n"); return 0; } base = (info.HighWord.Bits.BaseHi << 24) + (info.HighWord.Bits.BaseMid << 16) + info.BaseLow; limit = (info.HighWord.Bits.LimitHi << 16) + info.LimitLow; if (info.HighWord.Bits.Granularity) limit = (limit << 12) | 0xfff; log ("base=0x%08x limit=0x%08x", base, limit); if (info.HighWord.Bits.Default_Big) log(" 32-bit "); else log(" 16-bit "); switch ((info.HighWord.Bits.Type & 0xf) >> 1) { case 0: log ("Data (Read-Only, Exp-up"); break; case 1: log ("Data (Read/Write, Exp-up"); break; case 2: log ("Unused segment ("); break; case 3: log ("Data (Read/Write, Exp-down"); break; case 4: log ("Code (Exec-Only, N.Conf"); break; case 5: log ("Code (Exec/Read, N.Conf"); break; case 6: log ("Code (Exec-Only, Conf"); break; case 7: log ("Code (Exec/Read, Conf"); break; default: log ("Unknown type 0x%x",info.HighWord.Bits.Type); } if ((info.HighWord.Bits.Type & 0x1) == 0) log(", N.Acc"); log (")\n"); if ((info.HighWord.Bits.Type & 0x10) == 0) log("System selector "); log ("Priviledge level = %d. ", info.HighWord.Bits.Dpl); if (info.HighWord.Bits.Granularity) log ("Page granular.\n"); else log ("Byte granular.\n"); return 1; } static bool try_perversion(Registers& regs, int offset) { u_int16_t& insn = *(u_int16_t*)(regs.eip+offset); if (insn == 0xe88e) { insn = 0x9090; return true; } return false; } int32_t sys_set_thread_area(Registers& regs) { Arguments& arg = regs.arg; struct linux_user_desc& u = *(struct linux_user_desc*) arg.a0.p; #if 0 log(" entry_number = %d", u.entry_number); log(" base_addr = %08x", u.base_addr); log(" limit = %08x", u.limit); log(" seg_32bit = %d", u.seg_32bit); log(" contents = %d", u.contents); log(" read_exec_only = %d", u.read_exec_only); log(" limit_in_pages = %d", u.limit_in_pages); log(" seg_not_present = %d", u.seg_not_present); log(" useable = %d", u.useable); #endif /* Sanitise the limit; NT enforces a certain upper limit. */ u_int64_t maximum = u.limit; if (u.limit_in_pages) maximum <<= 12; maximum += u.base_addr; if (maximum > 0x7ff00000) maximum = 0x7ff00000; LDT_ENTRY ldt; if (u.entry_number == -1) { /* Search for an unused segment. */ int selector = 512; while (selector < 8192) { //log("examining selector %d", selector); u_int32_t r = read_ldt(selector, ldt); if (r != 0) break; if (!ldt.HighWord.Bits.Pres) { /* This selector is unused. */ u.entry_number = selector; break; } selector++; } //log("found unused selector %d", u.entry_number); } if (u.entry_number == -1) return -ENOMEM; memset(&ldt, 0, sizeof(ldt)); u_int32_t limit = maximum - u.base_addr; //log("maximum=%08llx, limit=%08x", maximum, limit); ldt.BaseLow = (u.base_addr & 0xFFFF); ldt.HighWord.Bits.BaseMid = (u.base_addr >> 16) & 0xFF; ldt.HighWord.Bits.BaseHi = (u.base_addr >> 24) & 0xFF; ldt.HighWord.Bits.Type = 0x13; // RW data segment ldt.HighWord.Bits.Dpl = 3; // user segment ldt.HighWord.Bits.Pres = 1; // present ldt.HighWord.Bits.Sys = 0; ldt.HighWord.Bits.Default_Big = 1; // 386 segment if (limit > 0x100000) { ldt.HighWord.Bits.Granularity = 1; limit >>= 12; } else ldt.HighWord.Bits.Granularity = 0; ldt.LimitLow = (limit & 0xFFFF); ldt.HighWord.Bits.LimitHi = (limit >> 16) & 0xF; //display_selector(ldt); u_int32_t r = write_ldt(u.entry_number, ldt); if (r) return -EINVAL; if (try_perversion(regs, 48) || try_perversion(regs, 18) || try_perversion(regs, 28)) { u_int16_t fs; asm volatile ("mov %%fs, %w0" : "=r" (fs)); u_int16_t gs = (u.entry_number << 3) | 7; log("GS %04x now pointing at linear %08x", gs, u.base_addr); SetGS(gs, (void*) u.base_addr); //DumpMemory(u.base_addr, 32); } else { DumpMemory(regs.eip, 128); sleep(-1); error("unable to pervert GDT selector load; check code at %08x", regs.eip); } return 0; } /* Not implemented --- nop */ SYSCALL(sys_set_tid_address) { Warning("sys_set_tid_address() currently unimplemented"); return getpid(); } /* Not implemented */ SYSCALL(compat_sys_set_robust_list) { Warning("compat_sys_set_robust_list() currently unimplemented"); return 0; //-LINUX_ENOSYS; } SYSCALL(compat_sys_futex) { int* uaddr = (int*) arg.a0.p; int op = arg.a1.s; int val = arg.a2.s; const void* timespec = (const void*) arg.a3.p; int* uaddr2 = (int*) arg.a4.p; int val3 = arg.a5.s; log("op=%02x uaddr=%08x, *uaddr=%08x, val=%08x, timespec=%p, uaddr2=%08x, val3=%08x", op, uaddr, *uaddr, val, timespec, uaddr2, val3); int cmd = op & LINUX_FUTEX_CMD_MASK; switch (cmd) { case LINUX_FUTEX_WAIT: *uaddr = 0; log("FUTEX_WAIT faked"); return 0; case LINUX_FUTEX_WAKE: return 0; case LINUX_FUTEX_WAIT_BITSET: throw EINVAL; default: error("compat_sys_futex(%x) currently unimplemented", op); } //sleep(-1); throw ENOSYS; } SYSCALL(sys_gettid) { return (u32) pthread_self(); } <|endoftext|>
<commit_before>/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/core/kernels/data/optimize_dataset_op.h" // On mobile we do not provide optimize dataset op because not all of its // dependencies are available there. The op is replaced with a no-op. #if !defined(IS_MOBILE_PLATFORM) #include <map> #include "tensorflow/core/framework/partial_tensor_shape.h" #include "tensorflow/core/framework/tensor.h" #include "tensorflow/core/kernels/data/dataset_utils.h" #include "tensorflow/core/kernels/data/rewrite_utils.h" #include "tensorflow/core/lib/random/random.h" #include "tensorflow/core/platform/host_info.h" #include "tensorflow/core/protobuf/rewriter_config.pb.h" namespace tensorflow { namespace data { /* static */ constexpr const char* const OptimizeDatasetOp::kDatasetType; /* static */ constexpr const char* const OptimizeDatasetOp::kInputDataset; /* static */ constexpr const char* const OptimizeDatasetOp::kOptimizations; /* static */ constexpr const char* const OptimizeDatasetOp::kOptimizationsEnabled; /* static */ constexpr const char* const OptimizeDatasetOp::kOptimizationsDisabled; /* static */ constexpr const char* const OptimizeDatasetOp::kOptimizationsDefault; /* static */ constexpr const char* const OptimizeDatasetOp::kOutputTypes; /* static */ constexpr const char* const OptimizeDatasetOp::kOutputShapes; /* static */ constexpr const char* const OptimizeDatasetOp::kOptimizationConfigs; /* static */ constexpr const char* const OptimizeDatasetOp::kOptimizeDatasetV1; /* static */ constexpr const char* const OptimizeDatasetOp::kOptimizeDatasetV2; namespace { constexpr char kOptimizerName[] = "tf_data_meta_optimizer"; constexpr char kOptimizers[] = "optimizers"; constexpr char kOptimizerConfigs[] = "optimizer_configs"; // A wrapper around `SelectOptimizations` responsible for configuring which // tf.data experiments to apply. std::vector<tstring> SelectOptimizationsHelper( const std::vector<tstring>& optimizations_enabled, const std::vector<tstring>& optimizations_disabled, const std::vector<tstring>& optimizations_default) { string job_name = port::JobName(); // The map that stores the live experiment names and for how much percentage // of the Borg jobs, the experiments will be randomly turned on. // clang-format off absl::flat_hash_map<string, uint64> live_experiments = { {"enable_gradient_descent", 0}, {"use_private_thread_pool", 5} }; // clang-format on auto hash_func = [](const string& str) { return Hash64(str); }; auto optimizations = SelectOptimizations( job_name, live_experiments, optimizations_enabled, optimizations_disabled, optimizations_default, hash_func); // Log and record the live experiments that will be applied. if (!job_name.empty() && !live_experiments.empty()) { VLOG(1) << "The input pipeline is subject to tf.data experiment. " "Please see `go/tf-data-experiments` for more details."; for (auto& pair : live_experiments) { string experiment = pair.first; if (std::find(optimizations.begin(), optimizations.end(), experiment) != optimizations.end()) { VLOG(1) << "The live experiment \"" << experiment << "\" is applied."; metrics::RecordTFDataExperiment(experiment); } } } return optimizations; } RewriterConfig CreateConfig(const std::vector<tstring>& optimizations, const std::vector<string>& optimizations_configs) { RewriterConfig rewriter_config; rewriter_config.add_optimizers(kOptimizerName); rewriter_config.set_meta_optimizer_iterations(RewriterConfig::ONE); rewriter_config.set_fail_on_optimizer_errors(true); auto custom_optimizer = rewriter_config.add_custom_optimizers(); custom_optimizer->set_name(kOptimizerName); auto* custom_optimizations_list = (*custom_optimizer->mutable_parameter_map())[kOptimizers].mutable_list(); for (const auto& opt : optimizations) { custom_optimizations_list->add_s(opt.data(), opt.size()); } auto* config_list = (*custom_optimizer->mutable_parameter_map())[kOptimizerConfigs] .mutable_list(); for (const auto& config : optimizations_configs) { config_list->add_s(config.data(), config.size()); } return rewriter_config; } // Applies given optimizations and optimizatin_config in dataset graph rewrite // to return the OptimizeDataset. void MakeDatasetHelper(OpKernelContext* ctx, std::vector<tstring>& optimizations, const std::vector<string>& optimization_configs, DatasetBase* input, DatasetBase** output) { // The vector stores the graduated experiment names which will be turned on // for all input pipelines. // clang-format off std::vector<string> graduated_experiments = {"disable_intra_op_parallelism"}; // clang-format on // Add the graduated experiments to the optimization list and log them. for (auto& experiment : graduated_experiments) { if (std::find(optimizations.begin(), optimizations.end(), experiment) == optimizations.end()) { optimizations.push_back(experiment); } VLOG(1) << "The graduated experiment \"" << experiment << "\" is applied."; } // If there are no optimizations to be applied, directly return the input. if (optimizations.empty()) { *output = input; input->Ref(); return; } auto config_factory = [&optimizations, &optimization_configs]() { return CreateConfig(optimizations, optimization_configs); }; Status s = RewriteDataset(ctx, input, std::move(config_factory), /*record_fingerprint=*/true, output); if (errors::IsDeadlineExceeded(s)) { // Ignore DeadlineExceeded as it implies that the attempted rewrite took too // long which should not prevent further computation. LOG(WARNING) << s.ToString(); *output = input; input->Ref(); return; } OP_REQUIRES_OK(ctx, s); } } // namespace // static void OptimizeDatasetOp::MakeDatasetFromOptions( OpKernelContext* ctx, DatasetBase* input, const std::vector<tstring>& optimizations_enabled, const std::vector<tstring>& optimizations_disabled, const std::vector<tstring>& optimizations_default, const std::vector<string>& optimization_configs, DatasetBase** output) { std::vector<tstring> optimizations = SelectOptimizationsHelper( optimizations_enabled, optimizations_disabled, optimizations_default); MakeDatasetHelper(ctx, optimizations, optimization_configs, input, output); } OptimizeDatasetOp::OptimizeDatasetOp(OpKernelConstruction* ctx) : UnaryDatasetOpKernel(ctx) { auto& op_name = ctx->def().op(); if (op_name == kOptimizeDatasetV1) { op_version_ = 1; } else if (op_name == kOptimizeDatasetV2) { op_version_ = 2; } OP_REQUIRES_OK(ctx, ctx->GetAttr(kOptimizationConfigs, &optimization_configs_)); } void OptimizeDatasetOp::MakeDataset(OpKernelContext* ctx, DatasetBase* input, DatasetBase** output) { std::vector<tstring> optimizations; if (op_version_ == 1) { OP_REQUIRES_OK( ctx, ParseVectorArgument<tstring>(ctx, kOptimizations, &optimizations)); } else if (op_version_ == 2) { std::vector<tstring> optimizations_enabled, optimizations_disabled, optimizations_default; OP_REQUIRES_OK(ctx, ParseVectorArgument<tstring>(ctx, kOptimizationsEnabled, &optimizations_enabled)); OP_REQUIRES_OK(ctx, ParseVectorArgument<tstring>(ctx, kOptimizationsDisabled, &optimizations_disabled)); OP_REQUIRES_OK(ctx, ParseVectorArgument<tstring>(ctx, kOptimizationsDefault, &optimizations_default)); optimizations = SelectOptimizationsHelper( optimizations_enabled, optimizations_disabled, optimizations_default); } MakeDatasetHelper(ctx, optimizations, optimization_configs_, input, output); } namespace { REGISTER_KERNEL_BUILDER(Name("OptimizeDataset").Device(DEVICE_CPU), OptimizeDatasetOp); REGISTER_KERNEL_BUILDER(Name("OptimizeDatasetV2").Device(DEVICE_CPU), OptimizeDatasetOp); } // namespace } // namespace data } // namespace tensorflow #else // !IS_MOBILE_PLATFORM namespace tensorflow { namespace data { // static void OptimizeDatasetOp::MakeDatasetFromOptions( OpKernelContext* ctx, DatasetBase* input, const std::vector<tstring>& optimizations_enabled, const std::vector<tstring>& optimizations_disabled, const std::vector<tstring>& optimizations_default, const std::vector<string>& optimization_configs, DatasetBase** output) { input->Ref(); *output = input; } OptimizeDatasetOp::OptimizeDatasetOp(OpKernelConstruction* ctx) : UnaryDatasetOpKernel(ctx) {} void OptimizeDatasetOp::MakeDataset(OpKernelContext* ctx, DatasetBase* input, DatasetBase** output) { input->Ref(); *output = input; } namespace { REGISTER_KERNEL_BUILDER(Name("OptimizeDataset").Device(DEVICE_CPU), OptimizeDatasetOp); REGISTER_KERNEL_BUILDER(Name("OptimizeDatasetV2").Device(DEVICE_CPU), OptimizeDatasetOp); } // namespace } // namespace data } // namespace tensorflow #endif // !IS_MOBILE_PLATFORM <commit_msg>[tf.data] Roll out the optimization `use_private_thread_pool` to 20% of Borg jobs.<commit_after>/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/core/kernels/data/optimize_dataset_op.h" // On mobile we do not provide optimize dataset op because not all of its // dependencies are available there. The op is replaced with a no-op. #if !defined(IS_MOBILE_PLATFORM) #include <map> #include "tensorflow/core/framework/partial_tensor_shape.h" #include "tensorflow/core/framework/tensor.h" #include "tensorflow/core/kernels/data/dataset_utils.h" #include "tensorflow/core/kernels/data/rewrite_utils.h" #include "tensorflow/core/lib/random/random.h" #include "tensorflow/core/platform/host_info.h" #include "tensorflow/core/protobuf/rewriter_config.pb.h" namespace tensorflow { namespace data { /* static */ constexpr const char* const OptimizeDatasetOp::kDatasetType; /* static */ constexpr const char* const OptimizeDatasetOp::kInputDataset; /* static */ constexpr const char* const OptimizeDatasetOp::kOptimizations; /* static */ constexpr const char* const OptimizeDatasetOp::kOptimizationsEnabled; /* static */ constexpr const char* const OptimizeDatasetOp::kOptimizationsDisabled; /* static */ constexpr const char* const OptimizeDatasetOp::kOptimizationsDefault; /* static */ constexpr const char* const OptimizeDatasetOp::kOutputTypes; /* static */ constexpr const char* const OptimizeDatasetOp::kOutputShapes; /* static */ constexpr const char* const OptimizeDatasetOp::kOptimizationConfigs; /* static */ constexpr const char* const OptimizeDatasetOp::kOptimizeDatasetV1; /* static */ constexpr const char* const OptimizeDatasetOp::kOptimizeDatasetV2; namespace { constexpr char kOptimizerName[] = "tf_data_meta_optimizer"; constexpr char kOptimizers[] = "optimizers"; constexpr char kOptimizerConfigs[] = "optimizer_configs"; // A wrapper around `SelectOptimizations` responsible for configuring which // tf.data experiments to apply. std::vector<tstring> SelectOptimizationsHelper( const std::vector<tstring>& optimizations_enabled, const std::vector<tstring>& optimizations_disabled, const std::vector<tstring>& optimizations_default) { string job_name = port::JobName(); // The map that stores the live experiment names and for how much percentage // of the Borg jobs, the experiments will be randomly turned on. // clang-format off absl::flat_hash_map<string, uint64> live_experiments = { {"enable_gradient_descent", 0}, {"use_private_thread_pool", 20} }; // clang-format on auto hash_func = [](const string& str) { return Hash64(str); }; auto optimizations = SelectOptimizations( job_name, live_experiments, optimizations_enabled, optimizations_disabled, optimizations_default, hash_func); // Log and record the live experiments that will be applied. if (!job_name.empty() && !live_experiments.empty()) { VLOG(1) << "The input pipeline is subject to tf.data experiment. " "Please see `go/tf-data-experiments` for more details."; for (auto& pair : live_experiments) { string experiment = pair.first; if (std::find(optimizations.begin(), optimizations.end(), experiment) != optimizations.end()) { VLOG(1) << "The live experiment \"" << experiment << "\" is applied."; metrics::RecordTFDataExperiment(experiment); } } } return optimizations; } RewriterConfig CreateConfig(const std::vector<tstring>& optimizations, const std::vector<string>& optimizations_configs) { RewriterConfig rewriter_config; rewriter_config.add_optimizers(kOptimizerName); rewriter_config.set_meta_optimizer_iterations(RewriterConfig::ONE); rewriter_config.set_fail_on_optimizer_errors(true); auto custom_optimizer = rewriter_config.add_custom_optimizers(); custom_optimizer->set_name(kOptimizerName); auto* custom_optimizations_list = (*custom_optimizer->mutable_parameter_map())[kOptimizers].mutable_list(); for (const auto& opt : optimizations) { custom_optimizations_list->add_s(opt.data(), opt.size()); } auto* config_list = (*custom_optimizer->mutable_parameter_map())[kOptimizerConfigs] .mutable_list(); for (const auto& config : optimizations_configs) { config_list->add_s(config.data(), config.size()); } return rewriter_config; } // Applies given optimizations and optimizatin_config in dataset graph rewrite // to return the OptimizeDataset. void MakeDatasetHelper(OpKernelContext* ctx, std::vector<tstring>& optimizations, const std::vector<string>& optimization_configs, DatasetBase* input, DatasetBase** output) { // The vector stores the graduated experiment names which will be turned on // for all input pipelines. // clang-format off std::vector<string> graduated_experiments = {"disable_intra_op_parallelism"}; // clang-format on // Add the graduated experiments to the optimization list and log them. for (auto& experiment : graduated_experiments) { if (std::find(optimizations.begin(), optimizations.end(), experiment) == optimizations.end()) { optimizations.push_back(experiment); } VLOG(1) << "The graduated experiment \"" << experiment << "\" is applied."; } // If there are no optimizations to be applied, directly return the input. if (optimizations.empty()) { *output = input; input->Ref(); return; } auto config_factory = [&optimizations, &optimization_configs]() { return CreateConfig(optimizations, optimization_configs); }; Status s = RewriteDataset(ctx, input, std::move(config_factory), /*record_fingerprint=*/true, output); if (errors::IsDeadlineExceeded(s)) { // Ignore DeadlineExceeded as it implies that the attempted rewrite took too // long which should not prevent further computation. LOG(WARNING) << s.ToString(); *output = input; input->Ref(); return; } OP_REQUIRES_OK(ctx, s); } } // namespace // static void OptimizeDatasetOp::MakeDatasetFromOptions( OpKernelContext* ctx, DatasetBase* input, const std::vector<tstring>& optimizations_enabled, const std::vector<tstring>& optimizations_disabled, const std::vector<tstring>& optimizations_default, const std::vector<string>& optimization_configs, DatasetBase** output) { std::vector<tstring> optimizations = SelectOptimizationsHelper( optimizations_enabled, optimizations_disabled, optimizations_default); MakeDatasetHelper(ctx, optimizations, optimization_configs, input, output); } OptimizeDatasetOp::OptimizeDatasetOp(OpKernelConstruction* ctx) : UnaryDatasetOpKernel(ctx) { auto& op_name = ctx->def().op(); if (op_name == kOptimizeDatasetV1) { op_version_ = 1; } else if (op_name == kOptimizeDatasetV2) { op_version_ = 2; } OP_REQUIRES_OK(ctx, ctx->GetAttr(kOptimizationConfigs, &optimization_configs_)); } void OptimizeDatasetOp::MakeDataset(OpKernelContext* ctx, DatasetBase* input, DatasetBase** output) { std::vector<tstring> optimizations; if (op_version_ == 1) { OP_REQUIRES_OK( ctx, ParseVectorArgument<tstring>(ctx, kOptimizations, &optimizations)); } else if (op_version_ == 2) { std::vector<tstring> optimizations_enabled, optimizations_disabled, optimizations_default; OP_REQUIRES_OK(ctx, ParseVectorArgument<tstring>(ctx, kOptimizationsEnabled, &optimizations_enabled)); OP_REQUIRES_OK(ctx, ParseVectorArgument<tstring>(ctx, kOptimizationsDisabled, &optimizations_disabled)); OP_REQUIRES_OK(ctx, ParseVectorArgument<tstring>(ctx, kOptimizationsDefault, &optimizations_default)); optimizations = SelectOptimizationsHelper( optimizations_enabled, optimizations_disabled, optimizations_default); } MakeDatasetHelper(ctx, optimizations, optimization_configs_, input, output); } namespace { REGISTER_KERNEL_BUILDER(Name("OptimizeDataset").Device(DEVICE_CPU), OptimizeDatasetOp); REGISTER_KERNEL_BUILDER(Name("OptimizeDatasetV2").Device(DEVICE_CPU), OptimizeDatasetOp); } // namespace } // namespace data } // namespace tensorflow #else // !IS_MOBILE_PLATFORM namespace tensorflow { namespace data { // static void OptimizeDatasetOp::MakeDatasetFromOptions( OpKernelContext* ctx, DatasetBase* input, const std::vector<tstring>& optimizations_enabled, const std::vector<tstring>& optimizations_disabled, const std::vector<tstring>& optimizations_default, const std::vector<string>& optimization_configs, DatasetBase** output) { input->Ref(); *output = input; } OptimizeDatasetOp::OptimizeDatasetOp(OpKernelConstruction* ctx) : UnaryDatasetOpKernel(ctx) {} void OptimizeDatasetOp::MakeDataset(OpKernelContext* ctx, DatasetBase* input, DatasetBase** output) { input->Ref(); *output = input; } namespace { REGISTER_KERNEL_BUILDER(Name("OptimizeDataset").Device(DEVICE_CPU), OptimizeDatasetOp); REGISTER_KERNEL_BUILDER(Name("OptimizeDatasetV2").Device(DEVICE_CPU), OptimizeDatasetOp); } // namespace } // namespace data } // namespace tensorflow #endif // !IS_MOBILE_PLATFORM <|endoftext|>
<commit_before>// // Unit tests for denial-of-service detection/prevention code // #include <algorithm> #include <boost/assign/list_of.hpp> // for 'map_list_of()' #include <boost/date_time/posix_time/posix_time_types.hpp> #include <boost/test/unit_test.hpp> #include <boost/foreach.hpp> #include "main.h" #include "wallet.h" #include "net.h" #include "util.h" #include <stdint.h> // Tests this internal-to-main.cpp method: extern bool AddOrphanTx(const CTransaction& tx); extern unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans); extern std::map<uint256, CTransaction> mapOrphanTransactions; extern std::map<uint256, std::set<uint256> > mapOrphanTransactionsByPrev; CService ip(uint32_t i) { struct in_addr s; s.s_addr = i; return CService(CNetAddr(s), GetDefaultPort()); } BOOST_AUTO_TEST_SUITE(DoS_tests) BOOST_AUTO_TEST_CASE(DoS_banning) { CNode::ClearBanned(); CAddress addr1(ip(0xa0b0c001)); CNode dummyNode1(INVALID_SOCKET, addr1, "", true); dummyNode1.Misbehaving(100); // Should get banned BOOST_CHECK(CNode::IsBanned(addr1)); BOOST_CHECK(!CNode::IsBanned(ip(0xa0b0c001|0x0000ff00))); // Different IP, not banned CAddress addr2(ip(0xa0b0c002)); CNode dummyNode2(INVALID_SOCKET, addr2, "", true); dummyNode2.Misbehaving(50); BOOST_CHECK(!CNode::IsBanned(addr2)); // 2 not banned yet... BOOST_CHECK(CNode::IsBanned(addr1)); // ... but 1 still should be dummyNode2.Misbehaving(50); BOOST_CHECK(CNode::IsBanned(addr2)); } BOOST_AUTO_TEST_CASE(DoS_banscore) { CNode::ClearBanned(); mapArgs["-banscore"] = "111"; // because 11 is my favorite number CAddress addr1(ip(0xa0b0c001)); CNode dummyNode1(INVALID_SOCKET, addr1, "", true); dummyNode1.Misbehaving(100); BOOST_CHECK(!CNode::IsBanned(addr1)); dummyNode1.Misbehaving(10); BOOST_CHECK(!CNode::IsBanned(addr1)); dummyNode1.Misbehaving(1); BOOST_CHECK(CNode::IsBanned(addr1)); mapArgs.erase("-banscore"); } BOOST_AUTO_TEST_CASE(DoS_bantime) { CNode::ClearBanned(); int64 nStartTime = GetTime(); SetMockTime(nStartTime); // Overrides future calls to GetTime() CAddress addr(ip(0xa0b0c001)); CNode dummyNode(INVALID_SOCKET, addr, "", true); dummyNode.Misbehaving(100); BOOST_CHECK(CNode::IsBanned(addr)); SetMockTime(nStartTime+60*60); BOOST_CHECK(CNode::IsBanned(addr)); SetMockTime(nStartTime+60*60*24+1); BOOST_CHECK(!CNode::IsBanned(addr)); } static bool CheckNBits(unsigned int nbits1, int64 time1, unsigned int nbits2, int64 time2)\ { if (time1 > time2) return CheckNBits(nbits2, time2, nbits1, time1); int64 deltaTime = time2-time1; CBigNum required; required.SetCompact(ComputeMinWork(nbits1, deltaTime)); CBigNum have; have.SetCompact(nbits2); return (have <= required); } BOOST_AUTO_TEST_CASE(DoS_checknbits) { using namespace boost::assign; // for 'map_list_of()' // Timestamps,nBits from the bitcoin block chain. // These are the block-chain checkpoint blocks typedef std::map<int64, unsigned int> BlockData; BlockData chainData = map_list_of(1239852051,486604799)(1262749024,486594666) (1279305360,469854461)(1280200847,469830746)(1281678674,469809688) (1296207707,453179945)(1302624061,453036989)(1309640330,437004818) (1313172719,436789733); // Make sure CheckNBits considers every combination of block-chain-lock-in-points // "sane": BOOST_FOREACH(const BlockData::value_type& i, chainData) { BOOST_FOREACH(const BlockData::value_type& j, chainData) { BOOST_CHECK(CheckNBits(i.second, i.first, j.second, j.first)); } } // Test a couple of insane combinations: BlockData::value_type firstcheck = *(chainData.begin()); BlockData::value_type lastcheck = *(chainData.rbegin()); // First checkpoint difficulty at or a while after the last checkpoint time should fail when // compared to last checkpoint BOOST_CHECK(!CheckNBits(firstcheck.second, lastcheck.first+60*10, lastcheck.second, lastcheck.first)); BOOST_CHECK(!CheckNBits(firstcheck.second, lastcheck.first+60*60*24*14, lastcheck.second, lastcheck.first)); // ... but OK if enough time passed for difficulty to adjust downward: BOOST_CHECK(CheckNBits(firstcheck.second, lastcheck.first+60*60*24*365*4, lastcheck.second, lastcheck.first)); } CTransaction RandomOrphan() { std::map<uint256, CTransaction>::iterator it; it = mapOrphanTransactions.lower_bound(GetRandHash()); if (it == mapOrphanTransactions.end()) it = mapOrphanTransactions.begin(); return it->second; } BOOST_AUTO_TEST_CASE(DoS_mapOrphans) { CKey key; key.MakeNewKey(true); CBasicKeyStore keystore; keystore.AddKey(key); // 50 orphan transactions: for (int i = 0; i < 50; i++) { CTransaction tx; tx.vin.resize(1); tx.vin[0].prevout.n = 0; tx.vin[0].prevout.hash = GetRandHash(); tx.vin[0].scriptSig << OP_1; tx.vout.resize(1); tx.vout[0].nValue = 1*CENT; tx.vout[0].scriptPubKey.SetDestination(key.GetPubKey().GetID()); AddOrphanTx(tx); } // ... and 50 that depend on other orphans: for (int i = 0; i < 50; i++) { CTransaction txPrev = RandomOrphan(); CTransaction tx; tx.vin.resize(1); tx.vin[0].prevout.n = 0; tx.vin[0].prevout.hash = txPrev.GetHash(); tx.vout.resize(1); tx.vout[0].nValue = 1*CENT; tx.vout[0].scriptPubKey.SetDestination(key.GetPubKey().GetID()); SignSignature(keystore, txPrev, tx, 0); AddOrphanTx(tx); } // This really-big orphan should be ignored: for (int i = 0; i < 10; i++) { CTransaction txPrev = RandomOrphan(); CTransaction tx; tx.vout.resize(1); tx.vout[0].nValue = 1*CENT; tx.vout[0].scriptPubKey.SetDestination(key.GetPubKey().GetID()); tx.vin.resize(500); for (unsigned int j = 0; j < tx.vin.size(); j++) { tx.vin[j].prevout.n = j; tx.vin[j].prevout.hash = txPrev.GetHash(); } SignSignature(keystore, txPrev, tx, 0); // Re-use same signature for other inputs // (they don't have to be valid for this test) for (unsigned int j = 1; j < tx.vin.size(); j++) tx.vin[j].scriptSig = tx.vin[0].scriptSig; BOOST_CHECK(!AddOrphanTx(tx)); } // Test LimitOrphanTxSize() function: LimitOrphanTxSize(40); BOOST_CHECK(mapOrphanTransactions.size() <= 40); LimitOrphanTxSize(10); BOOST_CHECK(mapOrphanTransactions.size() <= 10); LimitOrphanTxSize(0); BOOST_CHECK(mapOrphanTransactions.empty()); BOOST_CHECK(mapOrphanTransactionsByPrev.empty()); } BOOST_AUTO_TEST_CASE(DoS_checkSig) { // Test signature caching code (see key.cpp Verify() methods) CKey key; key.MakeNewKey(true); CBasicKeyStore keystore; keystore.AddKey(key); unsigned int flags = SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_STRICTENC; // 100 orphan transactions: static const int NPREV=100; CTransaction orphans[NPREV]; for (int i = 0; i < NPREV; i++) { CTransaction& tx = orphans[i]; tx.vin.resize(1); tx.vin[0].prevout.n = 0; tx.vin[0].prevout.hash = GetRandHash(); tx.vin[0].scriptSig << OP_1; tx.vout.resize(1); tx.vout[0].nValue = 1*CENT; tx.vout[0].scriptPubKey.SetDestination(key.GetPubKey().GetID()); AddOrphanTx(tx); } // Create a transaction that depends on orphans: CTransaction tx; tx.vout.resize(1); tx.vout[0].nValue = 1*CENT; tx.vout[0].scriptPubKey.SetDestination(key.GetPubKey().GetID()); tx.vin.resize(NPREV); for (unsigned int j = 0; j < tx.vin.size(); j++) { tx.vin[j].prevout.n = 0; tx.vin[j].prevout.hash = orphans[j].GetHash(); } // Creating signatures primes the cache: boost::posix_time::ptime mst1 = boost::posix_time::microsec_clock::local_time(); for (unsigned int j = 0; j < tx.vin.size(); j++) BOOST_CHECK(SignSignature(keystore, orphans[j], tx, j)); boost::posix_time::ptime mst2 = boost::posix_time::microsec_clock::local_time(); boost::posix_time::time_duration msdiff = mst2 - mst1; long nOneValidate = msdiff.total_milliseconds(); if (fDebug) printf("DoS_Checksig sign: %ld\n", nOneValidate); // ... now validating repeatedly should be quick: // 2.8GHz machine, -g build: Sign takes ~760ms, // uncached Verify takes ~250ms, cached Verify takes ~50ms // (for 100 single-signature inputs) mst1 = boost::posix_time::microsec_clock::local_time(); for (unsigned int i = 0; i < 5; i++) for (unsigned int j = 0; j < tx.vin.size(); j++) BOOST_CHECK(VerifySignature(CCoins(orphans[j], MEMPOOL_HEIGHT), tx, j, flags, SIGHASH_ALL)); mst2 = boost::posix_time::microsec_clock::local_time(); msdiff = mst2 - mst1; long nManyValidate = msdiff.total_milliseconds(); if (fDebug) printf("DoS_Checksig five: %ld\n", nManyValidate); BOOST_CHECK_MESSAGE(nManyValidate < nOneValidate, "Signature cache timing failed"); // Empty a signature, validation should fail: CScript save = tx.vin[0].scriptSig; tx.vin[0].scriptSig = CScript(); BOOST_CHECK(!VerifySignature(CCoins(orphans[0], MEMPOOL_HEIGHT), tx, 0, flags, SIGHASH_ALL)); tx.vin[0].scriptSig = save; // Swap signatures, validation should fail: std::swap(tx.vin[0].scriptSig, tx.vin[1].scriptSig); BOOST_CHECK(!VerifySignature(CCoins(orphans[0], MEMPOOL_HEIGHT), tx, 0, flags, SIGHASH_ALL)); BOOST_CHECK(!VerifySignature(CCoins(orphans[1], MEMPOOL_HEIGHT), tx, 1, flags, SIGHASH_ALL)); std::swap(tx.vin[0].scriptSig, tx.vin[1].scriptSig); // Exercise -maxsigcachesize code: mapArgs["-maxsigcachesize"] = "10"; // Generate a new, different signature for vin[0] to trigger cache clear: CScript oldSig = tx.vin[0].scriptSig; BOOST_CHECK(SignSignature(keystore, orphans[0], tx, 0)); BOOST_CHECK(tx.vin[0].scriptSig != oldSig); for (unsigned int j = 0; j < tx.vin.size(); j++) BOOST_CHECK(VerifySignature(CCoins(orphans[j], MEMPOOL_HEIGHT), tx, j, flags, SIGHASH_ALL)); mapArgs.erase("-maxsigcachesize"); LimitOrphanTxSize(0); } BOOST_AUTO_TEST_SUITE_END() <commit_msg>Update to v3<commit_after>// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. // Copyright (c) 2013-2014 Memorycoin Dev Team // // Unit tests for denial-of-service detection/prevention code // #include <algorithm> #include <boost/assign/list_of.hpp> // for 'map_list_of()' #include <boost/date_time/posix_time/posix_time_types.hpp> #include <boost/test/unit_test.hpp> #include <boost/foreach.hpp> #include "main.h" #include "wallet.h" #include "net.h" #include "util.h" #include <stdint.h> // Tests this internal-to-main.cpp method: extern bool AddOrphanTx(const CTransaction& tx); extern unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans); extern std::map<uint256, CTransaction> mapOrphanTransactions; extern std::map<uint256, std::set<uint256> > mapOrphanTransactionsByPrev; CService ip(uint32_t i) { struct in_addr s; s.s_addr = i; return CService(CNetAddr(s), GetDefaultPort()); } BOOST_AUTO_TEST_SUITE(DoS_tests) BOOST_AUTO_TEST_CASE(DoS_banning) { CNode::ClearBanned(); CAddress addr1(ip(0xa0b0c001)); CNode dummyNode1(INVALID_SOCKET, addr1, "", true); dummyNode1.Misbehaving(100); // Should get banned BOOST_CHECK(CNode::IsBanned(addr1)); BOOST_CHECK(!CNode::IsBanned(ip(0xa0b0c001|0x0000ff00))); // Different IP, not banned CAddress addr2(ip(0xa0b0c002)); CNode dummyNode2(INVALID_SOCKET, addr2, "", true); dummyNode2.Misbehaving(50); BOOST_CHECK(!CNode::IsBanned(addr2)); // 2 not banned yet... BOOST_CHECK(CNode::IsBanned(addr1)); // ... but 1 still should be dummyNode2.Misbehaving(50); BOOST_CHECK(CNode::IsBanned(addr2)); } BOOST_AUTO_TEST_CASE(DoS_banscore) { CNode::ClearBanned(); mapArgs["-banscore"] = "111"; // because 11 is my favorite number CAddress addr1(ip(0xa0b0c001)); CNode dummyNode1(INVALID_SOCKET, addr1, "", true); dummyNode1.Misbehaving(100); BOOST_CHECK(!CNode::IsBanned(addr1)); dummyNode1.Misbehaving(10); BOOST_CHECK(!CNode::IsBanned(addr1)); dummyNode1.Misbehaving(1); BOOST_CHECK(CNode::IsBanned(addr1)); mapArgs.erase("-banscore"); } BOOST_AUTO_TEST_CASE(DoS_bantime) { CNode::ClearBanned(); int64 nStartTime = GetTime(); SetMockTime(nStartTime); // Overrides future calls to GetTime() CAddress addr(ip(0xa0b0c001)); CNode dummyNode(INVALID_SOCKET, addr, "", true); dummyNode.Misbehaving(100); BOOST_CHECK(CNode::IsBanned(addr)); SetMockTime(nStartTime+60*60); BOOST_CHECK(CNode::IsBanned(addr)); SetMockTime(nStartTime+60*60*24+1); BOOST_CHECK(!CNode::IsBanned(addr)); } static bool CheckNBits(unsigned int nbits1, int64 time1, unsigned int nbits2, int64 time2)\ { if (time1 > time2) return CheckNBits(nbits2, time2, nbits1, time1); int64 deltaTime = time2-time1; CBigNum required; required.SetCompact(ComputeMinWork(nbits1, deltaTime)); CBigNum have; have.SetCompact(nbits2); return (have <= required); } BOOST_AUTO_TEST_CASE(DoS_checknbits) { using namespace boost::assign; // for 'map_list_of()' // Timestamps,nBits from the bitcoin block chain. // These are the block-chain checkpoint blocks typedef std::map<int64, unsigned int> BlockData; BlockData chainData = map_list_of(1239852051,486604799)(1262749024,486594666) (1279305360,469854461)(1280200847,469830746)(1281678674,469809688) (1296207707,453179945)(1302624061,453036989)(1309640330,437004818) (1313172719,436789733); // Make sure CheckNBits considers every combination of block-chain-lock-in-points // "sane": BOOST_FOREACH(const BlockData::value_type& i, chainData) { BOOST_FOREACH(const BlockData::value_type& j, chainData) { BOOST_CHECK(CheckNBits(i.second, i.first, j.second, j.first)); } } // Test a couple of insane combinations: BlockData::value_type firstcheck = *(chainData.begin()); BlockData::value_type lastcheck = *(chainData.rbegin()); // First checkpoint difficulty at or a while after the last checkpoint time should fail when // compared to last checkpoint BOOST_CHECK(!CheckNBits(firstcheck.second, lastcheck.first+60*10, lastcheck.second, lastcheck.first)); BOOST_CHECK(!CheckNBits(firstcheck.second, lastcheck.first+60*60*24*14, lastcheck.second, lastcheck.first)); // ... but OK if enough time passed for difficulty to adjust downward: BOOST_CHECK(CheckNBits(firstcheck.second, lastcheck.first+60*60*24*365*4, lastcheck.second, lastcheck.first)); } CTransaction RandomOrphan() { std::map<uint256, CTransaction>::iterator it; it = mapOrphanTransactions.lower_bound(GetRandHash()); if (it == mapOrphanTransactions.end()) it = mapOrphanTransactions.begin(); return it->second; } BOOST_AUTO_TEST_CASE(DoS_mapOrphans) { CKey key; key.MakeNewKey(true); CBasicKeyStore keystore; keystore.AddKey(key); // 50 orphan transactions: for (int i = 0; i < 50; i++) { CTransaction tx; tx.vin.resize(1); tx.vin[0].prevout.n = 0; tx.vin[0].prevout.hash = GetRandHash(); tx.vin[0].scriptSig << OP_1; tx.vout.resize(1); tx.vout[0].nValue = 1*CENT; tx.vout[0].scriptPubKey.SetDestination(key.GetPubKey().GetID()); AddOrphanTx(tx); } // ... and 50 that depend on other orphans: for (int i = 0; i < 50; i++) { CTransaction txPrev = RandomOrphan(); CTransaction tx; tx.vin.resize(1); tx.vin[0].prevout.n = 0; tx.vin[0].prevout.hash = txPrev.GetHash(); tx.vout.resize(1); tx.vout[0].nValue = 1*CENT; tx.vout[0].scriptPubKey.SetDestination(key.GetPubKey().GetID()); SignSignature(keystore, txPrev, tx, 0); AddOrphanTx(tx); } // This really-big orphan should be ignored: for (int i = 0; i < 10; i++) { CTransaction txPrev = RandomOrphan(); CTransaction tx; tx.vout.resize(1); tx.vout[0].nValue = 1*CENT; tx.vout[0].scriptPubKey.SetDestination(key.GetPubKey().GetID()); tx.vin.resize(500); for (unsigned int j = 0; j < tx.vin.size(); j++) { tx.vin[j].prevout.n = j; tx.vin[j].prevout.hash = txPrev.GetHash(); } SignSignature(keystore, txPrev, tx, 0); // Re-use same signature for other inputs // (they don't have to be valid for this test) for (unsigned int j = 1; j < tx.vin.size(); j++) tx.vin[j].scriptSig = tx.vin[0].scriptSig; BOOST_CHECK(!AddOrphanTx(tx)); } // Test LimitOrphanTxSize() function: LimitOrphanTxSize(40); BOOST_CHECK(mapOrphanTransactions.size() <= 40); LimitOrphanTxSize(10); BOOST_CHECK(mapOrphanTransactions.size() <= 10); LimitOrphanTxSize(0); BOOST_CHECK(mapOrphanTransactions.empty()); BOOST_CHECK(mapOrphanTransactionsByPrev.empty()); } BOOST_AUTO_TEST_CASE(DoS_checkSig) { // Test signature caching code (see key.cpp Verify() methods) CKey key; key.MakeNewKey(true); CBasicKeyStore keystore; keystore.AddKey(key); unsigned int flags = SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_STRICTENC; // 100 orphan transactions: static const int NPREV=100; CTransaction orphans[NPREV]; for (int i = 0; i < NPREV; i++) { CTransaction& tx = orphans[i]; tx.vin.resize(1); tx.vin[0].prevout.n = 0; tx.vin[0].prevout.hash = GetRandHash(); tx.vin[0].scriptSig << OP_1; tx.vout.resize(1); tx.vout[0].nValue = 1*CENT; tx.vout[0].scriptPubKey.SetDestination(key.GetPubKey().GetID()); AddOrphanTx(tx); } // Create a transaction that depends on orphans: CTransaction tx; tx.vout.resize(1); tx.vout[0].nValue = 1*CENT; tx.vout[0].scriptPubKey.SetDestination(key.GetPubKey().GetID()); tx.vin.resize(NPREV); for (unsigned int j = 0; j < tx.vin.size(); j++) { tx.vin[j].prevout.n = 0; tx.vin[j].prevout.hash = orphans[j].GetHash(); } // Creating signatures primes the cache: boost::posix_time::ptime mst1 = boost::posix_time::microsec_clock::local_time(); for (unsigned int j = 0; j < tx.vin.size(); j++) BOOST_CHECK(SignSignature(keystore, orphans[j], tx, j)); boost::posix_time::ptime mst2 = boost::posix_time::microsec_clock::local_time(); boost::posix_time::time_duration msdiff = mst2 - mst1; long nOneValidate = msdiff.total_milliseconds(); if (fDebug) printf("DoS_Checksig sign: %ld\n", nOneValidate); // ... now validating repeatedly should be quick: // 2.8GHz machine, -g build: Sign takes ~760ms, // uncached Verify takes ~250ms, cached Verify takes ~50ms // (for 100 single-signature inputs) mst1 = boost::posix_time::microsec_clock::local_time(); for (unsigned int i = 0; i < 5; i++) for (unsigned int j = 0; j < tx.vin.size(); j++) BOOST_CHECK(VerifySignature(CCoins(orphans[j], MEMPOOL_HEIGHT), tx, j, flags, SIGHASH_ALL)); mst2 = boost::posix_time::microsec_clock::local_time(); msdiff = mst2 - mst1; long nManyValidate = msdiff.total_milliseconds(); if (fDebug) printf("DoS_Checksig five: %ld\n", nManyValidate); BOOST_CHECK_MESSAGE(nManyValidate < nOneValidate, "Signature cache timing failed"); // Empty a signature, validation should fail: CScript save = tx.vin[0].scriptSig; tx.vin[0].scriptSig = CScript(); BOOST_CHECK(!VerifySignature(CCoins(orphans[0], MEMPOOL_HEIGHT), tx, 0, flags, SIGHASH_ALL)); tx.vin[0].scriptSig = save; // Swap signatures, validation should fail: std::swap(tx.vin[0].scriptSig, tx.vin[1].scriptSig); BOOST_CHECK(!VerifySignature(CCoins(orphans[0], MEMPOOL_HEIGHT), tx, 0, flags, SIGHASH_ALL)); BOOST_CHECK(!VerifySignature(CCoins(orphans[1], MEMPOOL_HEIGHT), tx, 1, flags, SIGHASH_ALL)); std::swap(tx.vin[0].scriptSig, tx.vin[1].scriptSig); // Exercise -maxsigcachesize code: mapArgs["-maxsigcachesize"] = "10"; // Generate a new, different signature for vin[0] to trigger cache clear: CScript oldSig = tx.vin[0].scriptSig; BOOST_CHECK(SignSignature(keystore, orphans[0], tx, 0)); BOOST_CHECK(tx.vin[0].scriptSig != oldSig); for (unsigned int j = 0; j < tx.vin.size(); j++) BOOST_CHECK(VerifySignature(CCoins(orphans[j], MEMPOOL_HEIGHT), tx, j, flags, SIGHASH_ALL)); mapArgs.erase("-maxsigcachesize"); LimitOrphanTxSize(0); } BOOST_AUTO_TEST_SUITE_END() <|endoftext|>
<commit_before>#include "test_helper.h" #include "compiler/lexical_grammar.h" #include "compiler/prepare_grammar/expand_tokens.h" #include "helpers/stream_methods.h" START_TEST using namespace rules; using prepare_grammar::expand_token; using prepare_grammar::ExpandTokenResult; describe("expand_tokens", []() { MetadataParams string_token_params; string_token_params.is_string = true; string_token_params.is_token = true; describe("string rules", [&]() { it("replaces strings with sequences of character sets", [&]() { AssertThat( expand_token(Rule::seq({ String{"a"}, String{"bcd"}, String{"e"} })).rule, Equals(Rule::seq({ CharacterSet{{ 'a' }}, Rule::seq({ CharacterSet{{ 'b' }}, CharacterSet{{ 'c' }}, CharacterSet{{ 'd' }}, }), CharacterSet{{ 'e' }}, }))); }); it("handles strings containing non-ASCII UTF8 characters", [&]() { AssertThat( expand_token(String{"\u03B1 \u03B2"}).rule, Equals(Rule::seq({ CharacterSet{{ 945 }}, CharacterSet{{ ' ' }}, CharacterSet{{ 946 }}, })) ); }); }); describe("regexp rules", [&]() { it("replaces regexps with the equivalent rule tree", [&]() { AssertThat( expand_token(Rule::seq({ String{"a"}, Pattern{"x+"}, String{"b"}, })).rule, Equals(Rule::seq({ CharacterSet{{'a'}}, Repeat{CharacterSet{{ 'x' }}}, CharacterSet{{'b'}}, })) ); }); it("handles regexps containing non-ASCII UTF8 characters", [&]() { AssertThat( expand_token(Pattern{"[^\u03B1-\u03B4]+"}).rule, Equals(Rule(Repeat{ CharacterSet().include_all().exclude(945, 948) })) ); }); it("returns an error when the grammar contains an invalid regex", [&]() { AssertThat( expand_token(Rule::seq({ Pattern{"("}, String{"xyz"}, Pattern{"["}, })).error, Equals(CompileError( TSCompileErrorTypeInvalidRegex, "unmatched open paren" )) ); }); }); }); END_TEST <commit_msg>Avoid unicode literals in tests<commit_after>#include "test_helper.h" #include "compiler/lexical_grammar.h" #include "compiler/prepare_grammar/expand_tokens.h" #include "helpers/stream_methods.h" START_TEST using namespace rules; using prepare_grammar::expand_token; using prepare_grammar::ExpandTokenResult; describe("expand_tokens", []() { MetadataParams string_token_params; string_token_params.is_string = true; string_token_params.is_token = true; describe("string rules", [&]() { it("replaces strings with sequences of character sets", [&]() { AssertThat( expand_token(Rule::seq({ String{"a"}, String{"bcd"}, String{"e"} })).rule, Equals(Rule::seq({ CharacterSet{{ 'a' }}, Rule::seq({ CharacterSet{{ 'b' }}, CharacterSet{{ 'c' }}, CharacterSet{{ 'd' }}, }), CharacterSet{{ 'e' }}, }))); }); it("handles strings containing non-ASCII UTF8 characters", [&]() { AssertThat( expand_token(String{"\xCE\xB1 \xCE\xB2"}).rule, Equals(Rule::seq({ CharacterSet{{ 945 }}, CharacterSet{{ ' ' }}, CharacterSet{{ 946 }}, })) ); }); }); describe("regexp rules", [&]() { it("replaces regexps with the equivalent rule tree", [&]() { AssertThat( expand_token(Rule::seq({ String{"a"}, Pattern{"x+"}, String{"b"}, })).rule, Equals(Rule::seq({ CharacterSet{{'a'}}, Repeat{CharacterSet{{ 'x' }}}, CharacterSet{{'b'}}, })) ); }); it("handles regexps containing non-ASCII UTF8 characters", [&]() { AssertThat( expand_token(Pattern{"[^\xCE\xB1-\xCE\xB4]+"}).rule, Equals(Rule(Repeat{ CharacterSet().include_all().exclude(945, 948) })) ); }); it("returns an error when the grammar contains an invalid regex", [&]() { AssertThat( expand_token(Rule::seq({ Pattern{"("}, String{"xyz"}, Pattern{"["}, })).error, Equals(CompileError( TSCompileErrorTypeInvalidRegex, "unmatched open paren" )) ); }); }); }); END_TEST <|endoftext|>
<commit_before>#include "Consumer.hpp" #include <iostream> #include <fstream> using namespace std; using namespace data; Consumer::Consumer(std::string const& name, TaskCore::TaskState initial_state) : ConsumerBase(name, initial_state) {} /// The following lines are template definitions for the various state machine // hooks defined by Orocos::RTT. See Consumer.hpp for more detailed // documentation about them. // bool Consumer::configureHook() { return true; } bool Consumer::startHook() { outfile = new ofstream("data_trigger.txt"); return true; } void Consumer::updateHook(std::vector<RTT::PortInterface*> const& updated_ports) { if (find(updated_ports.begin(), updated_ports.end(), &_input) != updated_ports.end()) { double value; while (_input.read(value)) *outfile << value << " " << flush; } else *outfile << "U " << flush; } // void Consumer::errorHook() {} void Consumer::stopHook() { delete outfile; } // void Consumer::cleanupHook() {} <commit_msg>test: use isPortUpdated in data_triggered<commit_after>#include "Consumer.hpp" #include <iostream> #include <fstream> using namespace std; using namespace data; Consumer::Consumer(std::string const& name, TaskCore::TaskState initial_state) : ConsumerBase(name, initial_state) {} /// The following lines are template definitions for the various state machine // hooks defined by Orocos::RTT. See Consumer.hpp for more detailed // documentation about them. // bool Consumer::configureHook() { return true; } bool Consumer::startHook() { outfile = new ofstream("data_trigger.txt"); return true; } void Consumer::updateHook(std::vector<RTT::PortInterface*> const& updated_ports) { if (isPortUpdated(_input)) { double value; while (_input.read(value)) *outfile << value << " " << flush; } else *outfile << "U " << flush; } // void Consumer::errorHook() {} void Consumer::stopHook() { delete outfile; } // void Consumer::cleanupHook() {} <|endoftext|>
<commit_before>/* * Copyright (C) 2004, 2006, 2008 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "Scrollbar.h" #include "EventHandler.h" #include "Frame.h" #include "FrameView.h" #include "GraphicsContext.h" #include "PlatformMouseEvent.h" #include "ScrollbarClient.h" #include "ScrollbarTheme.h" #include <algorithm> using std::max; using std::min; // FIXME: These constants should come from the ScrollbarTheme. const double cInitialTimerDelay = 0.25; const double cNormalTimerDelay = 0.05; namespace WebCore { #if !USE(NSSCROLLER) && !PLATFORM(GTK) PassRefPtr<Scrollbar> Scrollbar::createNativeScrollbar(ScrollbarClient* client, ScrollbarOrientation orientation, ScrollbarControlSize size) { return adoptRef(new Scrollbar(client, orientation, size)); } #endif Scrollbar::Scrollbar(ScrollbarClient* client, ScrollbarOrientation orientation, ScrollbarControlSize controlSize, ScrollbarTheme* theme) : m_client(client) , m_orientation(orientation) , m_controlSize(controlSize) , m_theme(theme) , m_visibleSize(0) , m_totalSize(0) , m_currentPos(0) , m_lineStep(0) , m_pageStep(0) , m_pixelStep(1) , m_hoveredPart(NoPart) , m_pressedPart(NoPart) , m_pressedPos(0) , m_enabled(true) , m_scrollTimer(this, &Scrollbar::autoscrollTimerFired) , m_overlapsResizer(false) , m_suppressInvalidation(false) { if (!m_theme) m_theme = ScrollbarTheme::nativeTheme(); // FIXME: This is ugly and would not be necessary if we fix cross-platform code to actually query for // scrollbar thickness and use it when sizing scrollbars (rather than leaving one dimension of the scrollbar // alone when sizing). int thickness = m_theme->scrollbarThickness(controlSize); Widget::setFrameGeometry(IntRect(0, 0, thickness, thickness)); } Scrollbar::~Scrollbar() { stopTimerIfNeeded(); } bool Scrollbar::setValue(int v) { v = max(min(v, m_totalSize - m_visibleSize), 0); if (value() == v) return false; // Our value stayed the same. m_currentPos = v; updateThumbPosition(); if (client()) client()->valueChanged(this); return true; } void Scrollbar::setProportion(int visibleSize, int totalSize) { if (visibleSize == m_visibleSize && totalSize == m_totalSize) return; m_visibleSize = visibleSize; m_totalSize = totalSize; updateThumbProportion(); } void Scrollbar::setSteps(int lineStep, int pageStep, int pixelsPerStep) { m_lineStep = lineStep; m_pageStep = pageStep; m_pixelStep = 1.0f / pixelsPerStep; } bool Scrollbar::scroll(ScrollDirection direction, ScrollGranularity granularity, float multiplier) { float step = 0; if ((direction == ScrollUp && m_orientation == VerticalScrollbar) || (direction == ScrollLeft && m_orientation == HorizontalScrollbar)) step = -1; else if ((direction == ScrollDown && m_orientation == VerticalScrollbar) || (direction == ScrollRight && m_orientation == HorizontalScrollbar)) step = 1; if (granularity == ScrollByLine) step *= m_lineStep; else if (granularity == ScrollByPage) step *= m_pageStep; else if (granularity == ScrollByDocument) step *= m_totalSize; else if (granularity == ScrollByPixel) step *= m_pixelStep; float newPos = m_currentPos + step * multiplier; float maxPos = m_totalSize - m_visibleSize; newPos = max(min(newPos, maxPos), 0.0f); if (newPos == m_currentPos) return false; int oldValue = value(); m_currentPos = newPos; updateThumbPosition(); if (value() != oldValue && client()) client()->valueChanged(this); // return true even if the integer value did not change so that scroll event gets eaten return true; } void Scrollbar::updateThumbPosition() { theme()->invalidateParts(this, ForwardTrackPart | BackTrackPart | ThumbPart); } void Scrollbar::updateThumbProportion() { theme()->invalidateParts(this, ForwardTrackPart | BackTrackPart | ThumbPart); } void Scrollbar::paint(GraphicsContext* context, const IntRect& damageRect) { if (context->updatingControlTints() && theme()->supportsControlTints()) { invalidate(); return; } if (context->paintingDisabled() || !frameGeometry().intersects(damageRect)) return; if (!theme()->paint(this, context, damageRect)) Widget::paint(context, damageRect); } void Scrollbar::autoscrollTimerFired(Timer<Scrollbar>*) { autoscrollPressedPart(cNormalTimerDelay); // FIXME: Get timer delay from ScrollbarTheme. } static bool thumbUnderMouse(Scrollbar* scrollbar) { int thumbPos = scrollbar->theme()->trackPosition(scrollbar) + scrollbar->theme()->thumbPosition(scrollbar); int thumbLength = scrollbar->theme()->thumbLength(scrollbar); return scrollbar->pressedPos() >= thumbPos && scrollbar->pressedPos() < thumbPos + thumbLength; } void Scrollbar::autoscrollPressedPart(double delay) { // Don't do anything for the thumb or if nothing was pressed. if (m_pressedPart == ThumbPart || m_pressedPart == NoPart) return; // Handle the track. if ((m_pressedPart == BackTrackPart || m_pressedPart == ForwardTrackPart) && thumbUnderMouse(this)) { theme()->invalidatePart(this, m_pressedPart); m_hoveredPart = ThumbPart; return; } // Handle the arrows and track. if (scroll(pressedPartScrollDirection(), pressedPartScrollGranularity())) startTimerIfNeeded(delay); } void Scrollbar::startTimerIfNeeded(double delay) { // Don't do anything for the thumb. if (m_pressedPart == ThumbPart) return; // Handle the track. We halt track scrolling once the thumb is level // with us. if ((m_pressedPart == BackTrackPart || m_pressedPart == ForwardTrackPart) && thumbUnderMouse(this)) { theme()->invalidatePart(this, m_pressedPart); m_hoveredPart = ThumbPart; return; } // We can't scroll if we've hit the beginning or end. ScrollDirection dir = pressedPartScrollDirection(); if (dir == ScrollUp || dir == ScrollLeft) { if (m_currentPos == 0) return; } else { if (m_currentPos == maximum()) return; } m_scrollTimer.startOneShot(delay); } void Scrollbar::stopTimerIfNeeded() { if (m_scrollTimer.isActive()) m_scrollTimer.stop(); } ScrollDirection Scrollbar::pressedPartScrollDirection() { if (m_orientation == HorizontalScrollbar) { if (m_pressedPart == BackButtonPart || m_pressedPart == BackTrackPart) return ScrollLeft; return ScrollRight; } else { if (m_pressedPart == BackButtonPart || m_pressedPart == BackTrackPart) return ScrollUp; return ScrollDown; } } ScrollGranularity Scrollbar::pressedPartScrollGranularity() { if (m_pressedPart == BackButtonPart || m_pressedPart == ForwardButtonPart) return ScrollByLine; return ScrollByPage; } void Scrollbar::moveThumb(int pos) { // Drag the thumb. int thumbPos = theme()->thumbPosition(this); int thumbLen = theme()->thumbLength(this); int trackLen = theme()->trackLength(this); int maxPos = trackLen - thumbLen; int delta = pos - pressedPos(); if (delta > 0) delta = min(maxPos - thumbPos, delta); else if (delta < 0) delta = max(-thumbPos, delta); if (delta) { setValue(static_cast<float>(thumbPos + delta) * maximum() / (trackLen - thumbLen)); setPressedPos(pressedPos() + theme()->thumbPosition(this) - thumbPos); } } bool Scrollbar::handleMouseMoveEvent(const PlatformMouseEvent& evt) { if (m_pressedPart == ThumbPart) { moveThumb(m_orientation == HorizontalScrollbar ? convertFromContainingWindow(evt.pos()).x() : convertFromContainingWindow(evt.pos()).y()); return true; } if (m_pressedPart != NoPart) m_pressedPos = (orientation() == HorizontalScrollbar ? convertFromContainingWindow(evt.pos()).x() : convertFromContainingWindow(evt.pos()).y()); ScrollbarPart part = theme()->hitTest(this, evt); if (part != m_hoveredPart) { if (m_hoveredPart == NoPart && theme()->invalidateOnMouseEnterExit()) invalidate(); // Just invalidate the whole scrollbar, since the buttons at either end change anyway. if (m_pressedPart != NoPart) { if (part == m_pressedPart) { // The mouse is moving back over the pressed part. We // need to start up the timer action again. startTimerIfNeeded(cNormalTimerDelay); theme()->invalidatePart(this, m_pressedPart); } else if (m_hoveredPart == m_pressedPart) { // The mouse is leaving the pressed part. Kill our timer // if needed. stopTimerIfNeeded(); theme()->invalidatePart(this, m_pressedPart); } } else { theme()->invalidatePart(this, part); theme()->invalidatePart(this, m_hoveredPart); } m_hoveredPart = part; } return true; } bool Scrollbar::handleMouseOutEvent(const PlatformMouseEvent& event) { if (theme()->invalidateOnMouseEnterExit()) invalidate(); // Just invalidate the whole scrollbar, since the buttons at either end change anyway. else theme()->invalidatePart(this, m_hoveredPart); m_hoveredPart = NoPart; return true; } bool Scrollbar::handleMouseReleaseEvent(const PlatformMouseEvent& event) { theme()->invalidatePart(this, m_pressedPart); m_pressedPart = NoPart; m_pressedPos = 0; stopTimerIfNeeded(); if (parent() && parent()->isFrameView()) static_cast<FrameView*>(parent())->frame()->eventHandler()->setMousePressed(false); return true; } bool Scrollbar::handleMousePressEvent(const PlatformMouseEvent& evt) { // Early exit for right click if (evt.button() == RightButton) return true; // FIXME: Handled as context menu by Qt right now. Should just avoid even calling this method on a right click though. m_pressedPart = theme()->hitTest(this, evt); int pressedPos = (orientation() == HorizontalScrollbar ? convertFromContainingWindow(evt.pos()).x() : convertFromContainingWindow(evt.pos()).y()); if (theme()->shouldCenterOnThumb(this, evt)) { m_hoveredPart = m_pressedPart = ThumbPart; int thumbLen = theme()->thumbLength(this); int desiredPos = pressedPos - thumbLen / 2; // Set the pressed position to the top of the thumb so that when we do the move, the delta // will be from the current pixel position of the thumb to the new desired position for the thumb. m_pressedPos = theme()->trackPosition(this) + theme()->thumbPosition(this); moveThumb(desiredPos); return true; } m_pressedPos = pressedPos; theme()->invalidatePart(this, m_pressedPart); autoscrollPressedPart(theme()->initialAutoscrollTimerDelay()); return true; } void Scrollbar::setFrameGeometry(const IntRect& rect) { // Get our window resizer rect and see if we overlap. Adjust to avoid the overlap // if necessary. IntRect adjustedRect(rect); if (parent() && parent()->isFrameView()) { bool overlapsResizer = false; ScrollView* view = parent(); IntRect resizerRect = view->windowResizerRect(); resizerRect.setLocation(view->convertFromContainingWindow(resizerRect.location())); if (rect.intersects(resizerRect)) { if (orientation() == HorizontalScrollbar) { int overlap = rect.right() - resizerRect.x(); if (overlap > 0 && resizerRect.right() >= rect.right()) { adjustedRect.setWidth(rect.width() - overlap); overlapsResizer = true; } } else { int overlap = rect.bottom() - resizerRect.y(); if (overlap > 0 && resizerRect.bottom() >= rect.bottom()) { adjustedRect.setHeight(rect.height() - overlap); overlapsResizer = true; } } } if (overlapsResizer != m_overlapsResizer) { m_overlapsResizer = overlapsResizer; view->adjustOverlappingScrollbarCount(m_overlapsResizer ? 1 : -1); } } Widget::setFrameGeometry(adjustedRect); } void Scrollbar::setParent(ScrollView* parentView) { if (!parentView && m_overlapsResizer && parent() && parent()->isFrameView()) parent()->adjustOverlappingScrollbarCount(-1); Widget::setParent(parentView); } void Scrollbar::setEnabled(bool e) { if (m_enabled == e) return; m_enabled = e; invalidate(); } IntRect Scrollbar::windowClipRect() const { IntRect clipRect(0, 0, width(), height()); clipRect = convertToContainingWindow(clipRect); if (m_client) clipRect.intersect(m_client->windowClipRect()); return clipRect; } void Scrollbar::invalidateRect(const IntRect& rect) { if (suppressInvalidation()) return; Widget::invalidateRect(rect); } } <commit_msg>Fix Qt warning.<commit_after>/* * Copyright (C) 2004, 2006, 2008 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "Scrollbar.h" #include "EventHandler.h" #include "Frame.h" #include "FrameView.h" #include "GraphicsContext.h" #include "PlatformMouseEvent.h" #include "ScrollbarClient.h" #include "ScrollbarTheme.h" #include <algorithm> using std::max; using std::min; // FIXME: These constants should come from the ScrollbarTheme. const double cInitialTimerDelay = 0.25; const double cNormalTimerDelay = 0.05; namespace WebCore { #if !USE(NSSCROLLER) && !PLATFORM(GTK) PassRefPtr<Scrollbar> Scrollbar::createNativeScrollbar(ScrollbarClient* client, ScrollbarOrientation orientation, ScrollbarControlSize size) { return adoptRef(new Scrollbar(client, orientation, size)); } #endif Scrollbar::Scrollbar(ScrollbarClient* client, ScrollbarOrientation orientation, ScrollbarControlSize controlSize, ScrollbarTheme* theme) : m_client(client) , m_orientation(orientation) , m_controlSize(controlSize) , m_theme(theme) , m_visibleSize(0) , m_totalSize(0) , m_currentPos(0) , m_lineStep(0) , m_pageStep(0) , m_pixelStep(1) , m_hoveredPart(NoPart) , m_pressedPart(NoPart) , m_pressedPos(0) , m_enabled(true) , m_scrollTimer(this, &Scrollbar::autoscrollTimerFired) , m_overlapsResizer(false) , m_suppressInvalidation(false) { if (!m_theme) m_theme = ScrollbarTheme::nativeTheme(); // FIXME: This is ugly and would not be necessary if we fix cross-platform code to actually query for // scrollbar thickness and use it when sizing scrollbars (rather than leaving one dimension of the scrollbar // alone when sizing). int thickness = m_theme->scrollbarThickness(controlSize); Widget::setFrameGeometry(IntRect(0, 0, thickness, thickness)); } Scrollbar::~Scrollbar() { stopTimerIfNeeded(); } bool Scrollbar::setValue(int v) { v = max(min(v, m_totalSize - m_visibleSize), 0); if (value() == v) return false; // Our value stayed the same. m_currentPos = v; updateThumbPosition(); if (client()) client()->valueChanged(this); return true; } void Scrollbar::setProportion(int visibleSize, int totalSize) { if (visibleSize == m_visibleSize && totalSize == m_totalSize) return; m_visibleSize = visibleSize; m_totalSize = totalSize; updateThumbProportion(); } void Scrollbar::setSteps(int lineStep, int pageStep, int pixelsPerStep) { m_lineStep = lineStep; m_pageStep = pageStep; m_pixelStep = 1.0f / pixelsPerStep; } bool Scrollbar::scroll(ScrollDirection direction, ScrollGranularity granularity, float multiplier) { float step = 0; if ((direction == ScrollUp && m_orientation == VerticalScrollbar) || (direction == ScrollLeft && m_orientation == HorizontalScrollbar)) step = -1; else if ((direction == ScrollDown && m_orientation == VerticalScrollbar) || (direction == ScrollRight && m_orientation == HorizontalScrollbar)) step = 1; if (granularity == ScrollByLine) step *= m_lineStep; else if (granularity == ScrollByPage) step *= m_pageStep; else if (granularity == ScrollByDocument) step *= m_totalSize; else if (granularity == ScrollByPixel) step *= m_pixelStep; float newPos = m_currentPos + step * multiplier; float maxPos = m_totalSize - m_visibleSize; newPos = max(min(newPos, maxPos), 0.0f); if (newPos == m_currentPos) return false; int oldValue = value(); m_currentPos = newPos; updateThumbPosition(); if (value() != oldValue && client()) client()->valueChanged(this); // return true even if the integer value did not change so that scroll event gets eaten return true; } void Scrollbar::updateThumbPosition() { theme()->invalidateParts(this, ForwardTrackPart | BackTrackPart | ThumbPart); } void Scrollbar::updateThumbProportion() { theme()->invalidateParts(this, ForwardTrackPart | BackTrackPart | ThumbPart); } void Scrollbar::paint(GraphicsContext* context, const IntRect& damageRect) { if (context->updatingControlTints() && theme()->supportsControlTints()) { invalidate(); return; } if (context->paintingDisabled() || !frameGeometry().intersects(damageRect)) return; if (!theme()->paint(this, context, damageRect)) Widget::paint(context, damageRect); } void Scrollbar::autoscrollTimerFired(Timer<Scrollbar>*) { autoscrollPressedPart(cNormalTimerDelay); // FIXME: Get timer delay from ScrollbarTheme. } static bool thumbUnderMouse(Scrollbar* scrollbar) { int thumbPos = scrollbar->theme()->trackPosition(scrollbar) + scrollbar->theme()->thumbPosition(scrollbar); int thumbLength = scrollbar->theme()->thumbLength(scrollbar); return scrollbar->pressedPos() >= thumbPos && scrollbar->pressedPos() < thumbPos + thumbLength; } void Scrollbar::autoscrollPressedPart(double delay) { // Don't do anything for the thumb or if nothing was pressed. if (m_pressedPart == ThumbPart || m_pressedPart == NoPart) return; // Handle the track. if ((m_pressedPart == BackTrackPart || m_pressedPart == ForwardTrackPart) && thumbUnderMouse(this)) { theme()->invalidatePart(this, m_pressedPart); m_hoveredPart = ThumbPart; return; } // Handle the arrows and track. if (scroll(pressedPartScrollDirection(), pressedPartScrollGranularity())) startTimerIfNeeded(delay); } void Scrollbar::startTimerIfNeeded(double delay) { // Don't do anything for the thumb. if (m_pressedPart == ThumbPart) return; // Handle the track. We halt track scrolling once the thumb is level // with us. if ((m_pressedPart == BackTrackPart || m_pressedPart == ForwardTrackPart) && thumbUnderMouse(this)) { theme()->invalidatePart(this, m_pressedPart); m_hoveredPart = ThumbPart; return; } // We can't scroll if we've hit the beginning or end. ScrollDirection dir = pressedPartScrollDirection(); if (dir == ScrollUp || dir == ScrollLeft) { if (m_currentPos == 0) return; } else { if (m_currentPos == maximum()) return; } m_scrollTimer.startOneShot(delay); } void Scrollbar::stopTimerIfNeeded() { if (m_scrollTimer.isActive()) m_scrollTimer.stop(); } ScrollDirection Scrollbar::pressedPartScrollDirection() { if (m_orientation == HorizontalScrollbar) { if (m_pressedPart == BackButtonPart || m_pressedPart == BackTrackPart) return ScrollLeft; return ScrollRight; } else { if (m_pressedPart == BackButtonPart || m_pressedPart == BackTrackPart) return ScrollUp; return ScrollDown; } } ScrollGranularity Scrollbar::pressedPartScrollGranularity() { if (m_pressedPart == BackButtonPart || m_pressedPart == ForwardButtonPart) return ScrollByLine; return ScrollByPage; } void Scrollbar::moveThumb(int pos) { // Drag the thumb. int thumbPos = theme()->thumbPosition(this); int thumbLen = theme()->thumbLength(this); int trackLen = theme()->trackLength(this); int maxPos = trackLen - thumbLen; int delta = pos - pressedPos(); if (delta > 0) delta = min(maxPos - thumbPos, delta); else if (delta < 0) delta = max(-thumbPos, delta); if (delta) { setValue(static_cast<int>(static_cast<float>(thumbPos + delta) * maximum() / (trackLen - thumbLen))); setPressedPos(pressedPos() + theme()->thumbPosition(this) - thumbPos); } } bool Scrollbar::handleMouseMoveEvent(const PlatformMouseEvent& evt) { if (m_pressedPart == ThumbPart) { moveThumb(m_orientation == HorizontalScrollbar ? convertFromContainingWindow(evt.pos()).x() : convertFromContainingWindow(evt.pos()).y()); return true; } if (m_pressedPart != NoPart) m_pressedPos = (orientation() == HorizontalScrollbar ? convertFromContainingWindow(evt.pos()).x() : convertFromContainingWindow(evt.pos()).y()); ScrollbarPart part = theme()->hitTest(this, evt); if (part != m_hoveredPart) { if (m_hoveredPart == NoPart && theme()->invalidateOnMouseEnterExit()) invalidate(); // Just invalidate the whole scrollbar, since the buttons at either end change anyway. if (m_pressedPart != NoPart) { if (part == m_pressedPart) { // The mouse is moving back over the pressed part. We // need to start up the timer action again. startTimerIfNeeded(cNormalTimerDelay); theme()->invalidatePart(this, m_pressedPart); } else if (m_hoveredPart == m_pressedPart) { // The mouse is leaving the pressed part. Kill our timer // if needed. stopTimerIfNeeded(); theme()->invalidatePart(this, m_pressedPart); } } else { theme()->invalidatePart(this, part); theme()->invalidatePart(this, m_hoveredPart); } m_hoveredPart = part; } return true; } bool Scrollbar::handleMouseOutEvent(const PlatformMouseEvent& event) { if (theme()->invalidateOnMouseEnterExit()) invalidate(); // Just invalidate the whole scrollbar, since the buttons at either end change anyway. else theme()->invalidatePart(this, m_hoveredPart); m_hoveredPart = NoPart; return true; } bool Scrollbar::handleMouseReleaseEvent(const PlatformMouseEvent& event) { theme()->invalidatePart(this, m_pressedPart); m_pressedPart = NoPart; m_pressedPos = 0; stopTimerIfNeeded(); if (parent() && parent()->isFrameView()) static_cast<FrameView*>(parent())->frame()->eventHandler()->setMousePressed(false); return true; } bool Scrollbar::handleMousePressEvent(const PlatformMouseEvent& evt) { // Early exit for right click if (evt.button() == RightButton) return true; // FIXME: Handled as context menu by Qt right now. Should just avoid even calling this method on a right click though. m_pressedPart = theme()->hitTest(this, evt); int pressedPos = (orientation() == HorizontalScrollbar ? convertFromContainingWindow(evt.pos()).x() : convertFromContainingWindow(evt.pos()).y()); if (theme()->shouldCenterOnThumb(this, evt)) { m_hoveredPart = m_pressedPart = ThumbPart; int thumbLen = theme()->thumbLength(this); int desiredPos = pressedPos - thumbLen / 2; // Set the pressed position to the top of the thumb so that when we do the move, the delta // will be from the current pixel position of the thumb to the new desired position for the thumb. m_pressedPos = theme()->trackPosition(this) + theme()->thumbPosition(this); moveThumb(desiredPos); return true; } m_pressedPos = pressedPos; theme()->invalidatePart(this, m_pressedPart); autoscrollPressedPart(theme()->initialAutoscrollTimerDelay()); return true; } void Scrollbar::setFrameGeometry(const IntRect& rect) { // Get our window resizer rect and see if we overlap. Adjust to avoid the overlap // if necessary. IntRect adjustedRect(rect); if (parent() && parent()->isFrameView()) { bool overlapsResizer = false; ScrollView* view = parent(); IntRect resizerRect = view->windowResizerRect(); resizerRect.setLocation(view->convertFromContainingWindow(resizerRect.location())); if (rect.intersects(resizerRect)) { if (orientation() == HorizontalScrollbar) { int overlap = rect.right() - resizerRect.x(); if (overlap > 0 && resizerRect.right() >= rect.right()) { adjustedRect.setWidth(rect.width() - overlap); overlapsResizer = true; } } else { int overlap = rect.bottom() - resizerRect.y(); if (overlap > 0 && resizerRect.bottom() >= rect.bottom()) { adjustedRect.setHeight(rect.height() - overlap); overlapsResizer = true; } } } if (overlapsResizer != m_overlapsResizer) { m_overlapsResizer = overlapsResizer; view->adjustOverlappingScrollbarCount(m_overlapsResizer ? 1 : -1); } } Widget::setFrameGeometry(adjustedRect); } void Scrollbar::setParent(ScrollView* parentView) { if (!parentView && m_overlapsResizer && parent() && parent()->isFrameView()) parent()->adjustOverlappingScrollbarCount(-1); Widget::setParent(parentView); } void Scrollbar::setEnabled(bool e) { if (m_enabled == e) return; m_enabled = e; invalidate(); } IntRect Scrollbar::windowClipRect() const { IntRect clipRect(0, 0, width(), height()); clipRect = convertToContainingWindow(clipRect); if (m_client) clipRect.intersect(m_client->windowClipRect()); return clipRect; } void Scrollbar::invalidateRect(const IntRect& rect) { if (suppressInvalidation()) return; Widget::invalidateRect(rect); } } <|endoftext|>
<commit_before>// Copyright (c) 2015-2019 The Bitcoin Core developers // Copyright (c) 2019-2020 The Auroracoin developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <chain.h> #include <chainparams.h> #include <pow.h> #include <util/system.h> #include <test/setup_common.h> #include <boost/test/unit_test.hpp> BOOST_FIXTURE_TEST_SUITE(pow_tests, BasicTestingSetup) /* Test calculation of next difficulty target with no constraints applying */ BOOST_AUTO_TEST_CASE(get_next_work) { const auto chainParams = CreateChainParams(CBaseChainParams::MAIN); int64_t nLastRetargetTime = 1261130161; // Block #30240 CBlockIndex pindexLast; pindexLast.nHeight = 32255; pindexLast.nTime = 1262152739; // Block #32255 pindexLast.nBits = 0x1d00ffff; BOOST_CHECK_EQUAL(CalculateNextWorkRequired(&pindexLast, nLastRetargetTime, chainParams->GetConsensus()), 0x1d00d86aU); } /* Test the constraint on the upper bound for next work */ BOOST_AUTO_TEST_CASE(get_next_work_pow_limit) { const auto chainParams = CreateChainParams(CBaseChainParams::MAIN); int64_t nLastRetargetTime = 1231006505; // Block #0 CBlockIndex pindexLast; pindexLast.nHeight = 2015; pindexLast.nTime = 1233061996; // Block #2015 pindexLast.nBits = 0x1d00ffff; BOOST_CHECK_EQUAL(CalculateNextWorkRequired(&pindexLast, nLastRetargetTime, chainParams->GetConsensus()), 0x1d00ffffU); } /* Test the constraint on the lower bound for actual time taken */ BOOST_AUTO_TEST_CASE(get_next_work_lower_limit_actual) { const auto chainParams = CreateChainParams(CBaseChainParams::MAIN); int64_t nLastRetargetTime = 1279008237; // Block #66528 CBlockIndex pindexLast; pindexLast.nHeight = 68543; pindexLast.nTime = 1279297671; // Block #68543 pindexLast.nBits = 0x1c05a3f4; BOOST_CHECK_EQUAL(CalculateNextWorkRequired(&pindexLast, nLastRetargetTime, chainParams->GetConsensus()), 0x1c0168fdU); } /* Test the constraint on the upper bound for actual time taken */ BOOST_AUTO_TEST_CASE(get_next_work_upper_limit_actual) { const auto chainParams = CreateChainParams(CBaseChainParams::MAIN); int64_t nLastRetargetTime = 1263163443; // NOTE: Not an actual block time CBlockIndex pindexLast; pindexLast.nHeight = 46367; pindexLast.nTime = 1269211443; // Block #46367 pindexLast.nBits = 0x1c387f6f; BOOST_CHECK_EQUAL(CalculateNextWorkRequired(&pindexLast, nLastRetargetTime, chainParams->GetConsensus()), 0x1d00e1fdU); } BOOST_AUTO_TEST_CASE(GetBlockProofEquivalentTime_test) { const auto chainParams = CreateChainParams(CBaseChainParams::MAIN); std::vector<CBlockIndex> blocks(10000); for (int i = 0; i < 10000; i++) { blocks[i].pprev = i ? &blocks[i - 1] : nullptr; blocks[i].nHeight = i; blocks[i].nTime = 1269211443 + i * chainParams->GetConsensus().nPowTargetSpacing; blocks[i].nBits = 0x207fffff; /* target 0x7fffff000... */ blocks[i].nChainWork = i ? blocks[i - 1].nChainWork + GetBlockProof(blocks[i - 1]) : arith_uint256(0); } for (int j = 0; j < 1000; j++) { CBlockIndex *p1 = &blocks[InsecureRandRange(10000)]; CBlockIndex *p2 = &blocks[InsecureRandRange(10000)]; CBlockIndex *p3 = &blocks[InsecureRandRange(10000)]; int64_t tdiff = GetBlockProofEquivalentTime(*p1, *p2, *p3, chainParams->GetConsensus()); BOOST_CHECK_EQUAL(tdiff, p1->GetBlockTime() - p2->GetBlockTime()); } } BOOST_AUTO_TEST_SUITE_END() <commit_msg>Bitcoin: 0cc7dd74e0af735dddf7e786f4ed136c382a4ad5 (test: add unittests for CheckProofOfWork).<commit_after>// Copyright (c) 2015-2019 The Bitcoin Core developers // Copyright (c) 2019-2020 The Auroracoin developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <chain.h> #include <chainparams.h> #include <pow.h> #include <util/system.h> #include <test/setup_common.h> #include <boost/test/unit_test.hpp> BOOST_FIXTURE_TEST_SUITE(pow_tests, BasicTestingSetup) /* Test calculation of next difficulty target with no constraints applying */ BOOST_AUTO_TEST_CASE(get_next_work) { const auto chainParams = CreateChainParams(CBaseChainParams::MAIN); int64_t nLastRetargetTime = 1261130161; // Block #30240 CBlockIndex pindexLast; pindexLast.nHeight = 32255; pindexLast.nTime = 1262152739; // Block #32255 pindexLast.nBits = 0x1d00ffff; BOOST_CHECK_EQUAL(CalculateNextWorkRequired(&pindexLast, nLastRetargetTime, chainParams->GetConsensus()), 0x1d00d86aU); } /* Test the constraint on the upper bound for next work */ BOOST_AUTO_TEST_CASE(get_next_work_pow_limit) { const auto chainParams = CreateChainParams(CBaseChainParams::MAIN); int64_t nLastRetargetTime = 1231006505; // Block #0 CBlockIndex pindexLast; pindexLast.nHeight = 2015; pindexLast.nTime = 1233061996; // Block #2015 pindexLast.nBits = 0x1d00ffff; BOOST_CHECK_EQUAL(CalculateNextWorkRequired(&pindexLast, nLastRetargetTime, chainParams->GetConsensus()), 0x1d00ffffU); } /* Test the constraint on the lower bound for actual time taken */ BOOST_AUTO_TEST_CASE(get_next_work_lower_limit_actual) { const auto chainParams = CreateChainParams(CBaseChainParams::MAIN); int64_t nLastRetargetTime = 1279008237; // Block #66528 CBlockIndex pindexLast; pindexLast.nHeight = 68543; pindexLast.nTime = 1279297671; // Block #68543 pindexLast.nBits = 0x1c05a3f4; BOOST_CHECK_EQUAL(CalculateNextWorkRequired(&pindexLast, nLastRetargetTime, chainParams->GetConsensus()), 0x1c0168fdU); } /* Test the constraint on the upper bound for actual time taken */ BOOST_AUTO_TEST_CASE(get_next_work_upper_limit_actual) { const auto chainParams = CreateChainParams(CBaseChainParams::MAIN); int64_t nLastRetargetTime = 1263163443; // NOTE: Not an actual block time CBlockIndex pindexLast; pindexLast.nHeight = 46367; pindexLast.nTime = 1269211443; // Block #46367 pindexLast.nBits = 0x1c387f6f; BOOST_CHECK_EQUAL(CalculateNextWorkRequired(&pindexLast, nLastRetargetTime, chainParams->GetConsensus()), 0x1d00e1fdU); } BOOST_AUTO_TEST_CASE(CheckProofOfWork_test_negative_target) { const auto consensus = CreateChainParams(CBaseChainParams::MAIN)->GetConsensus(); uint256 hash; unsigned int nBits; nBits = UintToArith256(consensus.powLimit).GetCompact(true); hash.SetHex("0x1"); BOOST_CHECK(!CheckProofOfWork(hash, nBits, consensus)); } BOOST_AUTO_TEST_CASE(CheckProofOfWork_test_overflow_target) { const auto consensus = CreateChainParams(CBaseChainParams::MAIN)->GetConsensus(); uint256 hash; unsigned int nBits = ~0x00800000; hash.SetHex("0x1"); BOOST_CHECK(!CheckProofOfWork(hash, nBits, consensus)); } BOOST_AUTO_TEST_CASE(CheckProofOfWork_test_too_easy_target) { const auto consensus = CreateChainParams(CBaseChainParams::MAIN)->GetConsensus(); uint256 hash; unsigned int nBits; arith_uint256 nBits_arith = UintToArith256(consensus.powLimit); nBits_arith *= 2; nBits = nBits_arith.GetCompact(); hash.SetHex("0x1"); BOOST_CHECK(!CheckProofOfWork(hash, nBits, consensus)); } BOOST_AUTO_TEST_CASE(CheckProofOfWork_test_biger_hash_than_target) { const auto consensus = CreateChainParams(CBaseChainParams::MAIN)->GetConsensus(); uint256 hash; unsigned int nBits; arith_uint256 hash_arith = UintToArith256(consensus.powLimit); nBits = hash_arith.GetCompact(); hash_arith *= 2; // hash > nBits hash = ArithToUint256(hash_arith); BOOST_CHECK(!CheckProofOfWork(hash, nBits, consensus)); } BOOST_AUTO_TEST_CASE(CheckProofOfWork_test_zero_target) { const auto consensus = CreateChainParams(CBaseChainParams::MAIN)->GetConsensus(); uint256 hash; unsigned int nBits; arith_uint256 hash_arith{0}; nBits = hash_arith.GetCompact(); hash = ArithToUint256(hash_arith); BOOST_CHECK(!CheckProofOfWork(hash, nBits, consensus)); } BOOST_AUTO_TEST_CASE(GetBlockProofEquivalentTime_test) { const auto chainParams = CreateChainParams(CBaseChainParams::MAIN); std::vector<CBlockIndex> blocks(10000); for (int i = 0; i < 10000; i++) { blocks[i].pprev = i ? &blocks[i - 1] : nullptr; blocks[i].nHeight = i; blocks[i].nTime = 1269211443 + i * chainParams->GetConsensus().nPowTargetSpacing; blocks[i].nBits = 0x207fffff; /* target 0x7fffff000... */ blocks[i].nChainWork = i ? blocks[i - 1].nChainWork + GetBlockProof(blocks[i - 1]) : arith_uint256(0); } for (int j = 0; j < 1000; j++) { CBlockIndex *p1 = &blocks[InsecureRandRange(10000)]; CBlockIndex *p2 = &blocks[InsecureRandRange(10000)]; CBlockIndex *p3 = &blocks[InsecureRandRange(10000)]; int64_t tdiff = GetBlockProofEquivalentTime(*p1, *p2, *p3, chainParams->GetConsensus()); BOOST_CHECK_EQUAL(tdiff, p1->GetBlockTime() - p2->GetBlockTime()); } } BOOST_AUTO_TEST_SUITE_END() <|endoftext|>
<commit_before>// Copyright (c) 2013 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/metrics/chrome_browser_main_extra_parts_metrics.h" #include <string> #include "base/bind.h" #include "base/command_line.h" #include "base/cpu.h" #include "base/metrics/histogram.h" #include "base/metrics/sparse_histogram.h" #include "base/sys_info.h" #include "base/threading/sequenced_worker_pool.h" #include "base/time/time.h" #include "chrome/browser/about_flags.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/chrome_browser_main.h" #include "chrome/browser/chrome_browser_metrics_service_observer.h" #include "chrome/browser/mac/bluetooth_utility.h" #include "chrome/browser/pref_service_flags_storage.h" #include "chrome/browser/shell_integration.h" #include "content/public/browser/browser_thread.h" #include "ui/base/touch/touch_device.h" #include "ui/base/ui_base_switches.h" #include "ui/events/event_switches.h" #if defined(OS_LINUX) && !defined(OS_CHROMEOS) #include <gnu/libc-version.h> #include "base/version.h" #include "ui/base/x/x11_util.h" #endif // defined(OS_LINUX) && !defined(OS_CHROMEOS) #if defined(OS_WIN) #include "chrome/installer/util/google_update_settings.h" #endif // defined(OS_WIN) namespace { enum UMALinuxGlibcVersion { UMA_LINUX_GLIBC_NOT_PARSEABLE, UMA_LINUX_GLIBC_UNKNOWN, UMA_LINUX_GLIBC_2_11, UMA_LINUX_GLIBC_2_19 = UMA_LINUX_GLIBC_2_11 + 8, // NOTE: Add new version above this line and update the enum list in // tools/metrics/histograms/histograms.xml accordingly. UMA_LINUX_GLIBC_VERSION_COUNT }; enum UMALinuxWindowManager { UMA_LINUX_WINDOW_MANAGER_OTHER, UMA_LINUX_WINDOW_MANAGER_BLACKBOX, UMA_LINUX_WINDOW_MANAGER_CHROME_OS, UMA_LINUX_WINDOW_MANAGER_COMPIZ, UMA_LINUX_WINDOW_MANAGER_ENLIGHTENMENT, UMA_LINUX_WINDOW_MANAGER_ICE_WM, UMA_LINUX_WINDOW_MANAGER_KWIN, UMA_LINUX_WINDOW_MANAGER_METACITY, UMA_LINUX_WINDOW_MANAGER_MUFFIN, UMA_LINUX_WINDOW_MANAGER_MUTTER, UMA_LINUX_WINDOW_MANAGER_OPENBOX, UMA_LINUX_WINDOW_MANAGER_XFWM4, // NOTE: Add new window managers above this line and update the enum list in // tools/metrics/histograms/histograms.xml accordingly. UMA_LINUX_WINDOW_MANAGER_COUNT }; enum UMATouchEventsState { UMA_TOUCH_EVENTS_ENABLED, UMA_TOUCH_EVENTS_AUTO_ENABLED, UMA_TOUCH_EVENTS_AUTO_DISABLED, UMA_TOUCH_EVENTS_DISABLED, // NOTE: Add states only immediately above this line. Make sure to // update the enum list in tools/metrics/histograms/histograms.xml // accordingly. UMA_TOUCH_EVENTS_STATE_COUNT }; void RecordMicroArchitectureStats() { #if defined(ARCH_CPU_X86_FAMILY) base::CPU cpu; base::CPU::IntelMicroArchitecture arch = cpu.GetIntelMicroArchitecture(); UMA_HISTOGRAM_ENUMERATION("Platform.IntelMaxMicroArchitecture", arch, base::CPU::MAX_INTEL_MICRO_ARCHITECTURE); #endif // defined(ARCH_CPU_X86_FAMILY) UMA_HISTOGRAM_SPARSE_SLOWLY("Platform.LogicalCpuCount", base::SysInfo::NumberOfProcessors()); } // Called on the blocking pool some time after startup to avoid slowing down // startup with metrics that aren't trivial to compute. void RecordStartupMetricsOnBlockingPool() { #if defined(OS_WIN) GoogleUpdateSettings::RecordChromeUpdatePolicyHistograms(); #endif // defined(OS_WIN) #if defined(OS_MACOSX) && !defined(OS_IOS) bluetooth_utility::BluetoothAvailability availability = bluetooth_utility::GetBluetoothAvailability(); UMA_HISTOGRAM_ENUMERATION("OSX.BluetoothAvailability", availability, bluetooth_utility::BLUETOOTH_AVAILABILITY_COUNT); #endif // defined(OS_MACOSX) && !defined(OS_IOS) } void RecordLinuxGlibcVersion() { #if defined(OS_LINUX) && !defined(OS_CHROMEOS) Version version(gnu_get_libc_version()); UMALinuxGlibcVersion glibc_version_result = UMA_LINUX_GLIBC_NOT_PARSEABLE; if (version.IsValid() && version.components().size() == 2) { glibc_version_result = UMA_LINUX_GLIBC_UNKNOWN; int glibc_major_version = version.components()[0]; int glibc_minor_version = version.components()[1]; if (glibc_major_version == 2) { // A constant to translate glibc 2.x minor versions to their // equivalent UMALinuxGlibcVersion values. const int kGlibcMinorVersionTranslationOffset = 11 - UMA_LINUX_GLIBC_2_11; int translated_glibc_minor_version = glibc_minor_version - kGlibcMinorVersionTranslationOffset; if (translated_glibc_minor_version >= UMA_LINUX_GLIBC_2_11 && translated_glibc_minor_version <= UMA_LINUX_GLIBC_2_19) { glibc_version_result = static_cast<UMALinuxGlibcVersion>(translated_glibc_minor_version); } } } UMA_HISTOGRAM_ENUMERATION("Linux.GlibcVersion", glibc_version_result, UMA_LINUX_GLIBC_VERSION_COUNT); #endif } void RecordLinuxWindowManager() { #if defined(OS_LINUX) && !defined(OS_CHROMEOS) ui::WindowManagerName name = ui::GuessWindowManager(); UMALinuxWindowManager uma_name = UMA_LINUX_WINDOW_MANAGER_OTHER; switch (name) { case ui::WM_UNKNOWN: uma_name = UMA_LINUX_WINDOW_MANAGER_OTHER; break; case ui::WM_BLACKBOX: uma_name = UMA_LINUX_WINDOW_MANAGER_BLACKBOX; break; case ui::WM_CHROME_OS: uma_name = UMA_LINUX_WINDOW_MANAGER_CHROME_OS; break; case ui::WM_COMPIZ: uma_name = UMA_LINUX_WINDOW_MANAGER_COMPIZ; break; case ui::WM_ENLIGHTENMENT: uma_name = UMA_LINUX_WINDOW_MANAGER_ENLIGHTENMENT; break; case ui::WM_ICE_WM: uma_name = UMA_LINUX_WINDOW_MANAGER_ICE_WM; break; case ui::WM_KWIN: uma_name = UMA_LINUX_WINDOW_MANAGER_KWIN; break; case ui::WM_METACITY: uma_name = UMA_LINUX_WINDOW_MANAGER_METACITY; break; case ui::WM_MUFFIN: uma_name = UMA_LINUX_WINDOW_MANAGER_MUFFIN; break; case ui::WM_MUTTER: uma_name = UMA_LINUX_WINDOW_MANAGER_MUTTER; break; case ui::WM_OPENBOX: uma_name = UMA_LINUX_WINDOW_MANAGER_OPENBOX; break; case ui::WM_XFWM4: uma_name = UMA_LINUX_WINDOW_MANAGER_XFWM4; break; } UMA_HISTOGRAM_ENUMERATION("Linux.WindowManager", uma_name, UMA_LINUX_WINDOW_MANAGER_COUNT); #endif } void RecordTouchEventState() { const CommandLine& command_line = *CommandLine::ForCurrentProcess(); const std::string touch_enabled_switch = command_line.HasSwitch(switches::kTouchEvents) ? command_line.GetSwitchValueASCII(switches::kTouchEvents) : switches::kTouchEventsAuto; UMATouchEventsState state; if (touch_enabled_switch.empty() || touch_enabled_switch == switches::kTouchEventsEnabled) { state = UMA_TOUCH_EVENTS_ENABLED; } else if (touch_enabled_switch == switches::kTouchEventsAuto) { state = ui::IsTouchDevicePresent() ? UMA_TOUCH_EVENTS_AUTO_ENABLED : UMA_TOUCH_EVENTS_AUTO_DISABLED; } else if (touch_enabled_switch == switches::kTouchEventsDisabled) { state = UMA_TOUCH_EVENTS_DISABLED; } else { NOTREACHED(); return; } UMA_HISTOGRAM_ENUMERATION("Touchscreen.TouchEventsEnabled", state, UMA_TOUCH_EVENTS_STATE_COUNT); } } // namespace ChromeBrowserMainExtraPartsMetrics::ChromeBrowserMainExtraPartsMetrics() { } ChromeBrowserMainExtraPartsMetrics::~ChromeBrowserMainExtraPartsMetrics() { } void ChromeBrowserMainExtraPartsMetrics::PreProfileInit() { RecordMicroArchitectureStats(); } void ChromeBrowserMainExtraPartsMetrics::PreBrowserStart() { about_flags::PrefServiceFlagsStorage flags_storage_( g_browser_process->local_state()); about_flags::RecordUMAStatistics(&flags_storage_); } void ChromeBrowserMainExtraPartsMetrics::PostBrowserStart() { RecordLinuxGlibcVersion(); RecordLinuxWindowManager(); RecordTouchEventState(); const int kStartupMetricsGatheringDelaySeconds = 45; content::BrowserThread::GetBlockingPool()->PostDelayedTask( FROM_HERE, base::Bind(&RecordStartupMetricsOnBlockingPool), base::TimeDelta::FromSeconds(kStartupMetricsGatheringDelaySeconds)); // Create the metrics log observer. // We only need this for Android for now. #if defined(ANDROID) metrics_service_observer_.reset(new ChromeBrowserMetricsServiceObserver()); #endif } namespace chrome { void AddMetricsExtraParts(ChromeBrowserMainParts* main_parts) { main_parts->AddParts(new ChromeBrowserMainExtraPartsMetrics()); } } // namespace chrome <commit_msg>GuessWindowManager is defined only on x11 platform. This CL changes the platform check from Linux to X11.<commit_after>// Copyright (c) 2013 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/metrics/chrome_browser_main_extra_parts_metrics.h" #include <string> #include "base/bind.h" #include "base/command_line.h" #include "base/cpu.h" #include "base/metrics/histogram.h" #include "base/metrics/sparse_histogram.h" #include "base/sys_info.h" #include "base/threading/sequenced_worker_pool.h" #include "base/time/time.h" #include "chrome/browser/about_flags.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/chrome_browser_main.h" #include "chrome/browser/chrome_browser_metrics_service_observer.h" #include "chrome/browser/mac/bluetooth_utility.h" #include "chrome/browser/pref_service_flags_storage.h" #include "chrome/browser/shell_integration.h" #include "content/public/browser/browser_thread.h" #include "ui/base/touch/touch_device.h" #include "ui/base/ui_base_switches.h" #include "ui/events/event_switches.h" #if defined(OS_LINUX) && !defined(OS_CHROMEOS) #include <gnu/libc-version.h> #include "base/version.h" #if defined(USE_X11) #include "ui/base/x/x11_util.h" #endif #endif // defined(OS_LINUX) && !defined(OS_CHROMEOS) #if defined(OS_WIN) #include "chrome/installer/util/google_update_settings.h" #endif // defined(OS_WIN) namespace { enum UMALinuxGlibcVersion { UMA_LINUX_GLIBC_NOT_PARSEABLE, UMA_LINUX_GLIBC_UNKNOWN, UMA_LINUX_GLIBC_2_11, UMA_LINUX_GLIBC_2_19 = UMA_LINUX_GLIBC_2_11 + 8, // NOTE: Add new version above this line and update the enum list in // tools/metrics/histograms/histograms.xml accordingly. UMA_LINUX_GLIBC_VERSION_COUNT }; enum UMALinuxWindowManager { UMA_LINUX_WINDOW_MANAGER_OTHER, UMA_LINUX_WINDOW_MANAGER_BLACKBOX, UMA_LINUX_WINDOW_MANAGER_CHROME_OS, UMA_LINUX_WINDOW_MANAGER_COMPIZ, UMA_LINUX_WINDOW_MANAGER_ENLIGHTENMENT, UMA_LINUX_WINDOW_MANAGER_ICE_WM, UMA_LINUX_WINDOW_MANAGER_KWIN, UMA_LINUX_WINDOW_MANAGER_METACITY, UMA_LINUX_WINDOW_MANAGER_MUFFIN, UMA_LINUX_WINDOW_MANAGER_MUTTER, UMA_LINUX_WINDOW_MANAGER_OPENBOX, UMA_LINUX_WINDOW_MANAGER_XFWM4, // NOTE: Add new window managers above this line and update the enum list in // tools/metrics/histograms/histograms.xml accordingly. UMA_LINUX_WINDOW_MANAGER_COUNT }; enum UMATouchEventsState { UMA_TOUCH_EVENTS_ENABLED, UMA_TOUCH_EVENTS_AUTO_ENABLED, UMA_TOUCH_EVENTS_AUTO_DISABLED, UMA_TOUCH_EVENTS_DISABLED, // NOTE: Add states only immediately above this line. Make sure to // update the enum list in tools/metrics/histograms/histograms.xml // accordingly. UMA_TOUCH_EVENTS_STATE_COUNT }; void RecordMicroArchitectureStats() { #if defined(ARCH_CPU_X86_FAMILY) base::CPU cpu; base::CPU::IntelMicroArchitecture arch = cpu.GetIntelMicroArchitecture(); UMA_HISTOGRAM_ENUMERATION("Platform.IntelMaxMicroArchitecture", arch, base::CPU::MAX_INTEL_MICRO_ARCHITECTURE); #endif // defined(ARCH_CPU_X86_FAMILY) UMA_HISTOGRAM_SPARSE_SLOWLY("Platform.LogicalCpuCount", base::SysInfo::NumberOfProcessors()); } // Called on the blocking pool some time after startup to avoid slowing down // startup with metrics that aren't trivial to compute. void RecordStartupMetricsOnBlockingPool() { #if defined(OS_WIN) GoogleUpdateSettings::RecordChromeUpdatePolicyHistograms(); #endif // defined(OS_WIN) #if defined(OS_MACOSX) && !defined(OS_IOS) bluetooth_utility::BluetoothAvailability availability = bluetooth_utility::GetBluetoothAvailability(); UMA_HISTOGRAM_ENUMERATION("OSX.BluetoothAvailability", availability, bluetooth_utility::BLUETOOTH_AVAILABILITY_COUNT); #endif // defined(OS_MACOSX) && !defined(OS_IOS) } void RecordLinuxGlibcVersion() { #if defined(OS_LINUX) && !defined(OS_CHROMEOS) Version version(gnu_get_libc_version()); UMALinuxGlibcVersion glibc_version_result = UMA_LINUX_GLIBC_NOT_PARSEABLE; if (version.IsValid() && version.components().size() == 2) { glibc_version_result = UMA_LINUX_GLIBC_UNKNOWN; int glibc_major_version = version.components()[0]; int glibc_minor_version = version.components()[1]; if (glibc_major_version == 2) { // A constant to translate glibc 2.x minor versions to their // equivalent UMALinuxGlibcVersion values. const int kGlibcMinorVersionTranslationOffset = 11 - UMA_LINUX_GLIBC_2_11; int translated_glibc_minor_version = glibc_minor_version - kGlibcMinorVersionTranslationOffset; if (translated_glibc_minor_version >= UMA_LINUX_GLIBC_2_11 && translated_glibc_minor_version <= UMA_LINUX_GLIBC_2_19) { glibc_version_result = static_cast<UMALinuxGlibcVersion>(translated_glibc_minor_version); } } } UMA_HISTOGRAM_ENUMERATION("Linux.GlibcVersion", glibc_version_result, UMA_LINUX_GLIBC_VERSION_COUNT); #endif } void RecordLinuxWindowManager() { #if defined(USE_X11) && !defined(OS_CHROMEOS) ui::WindowManagerName name = ui::GuessWindowManager(); UMALinuxWindowManager uma_name = UMA_LINUX_WINDOW_MANAGER_OTHER; switch (name) { case ui::WM_UNKNOWN: uma_name = UMA_LINUX_WINDOW_MANAGER_OTHER; break; case ui::WM_BLACKBOX: uma_name = UMA_LINUX_WINDOW_MANAGER_BLACKBOX; break; case ui::WM_CHROME_OS: uma_name = UMA_LINUX_WINDOW_MANAGER_CHROME_OS; break; case ui::WM_COMPIZ: uma_name = UMA_LINUX_WINDOW_MANAGER_COMPIZ; break; case ui::WM_ENLIGHTENMENT: uma_name = UMA_LINUX_WINDOW_MANAGER_ENLIGHTENMENT; break; case ui::WM_ICE_WM: uma_name = UMA_LINUX_WINDOW_MANAGER_ICE_WM; break; case ui::WM_KWIN: uma_name = UMA_LINUX_WINDOW_MANAGER_KWIN; break; case ui::WM_METACITY: uma_name = UMA_LINUX_WINDOW_MANAGER_METACITY; break; case ui::WM_MUFFIN: uma_name = UMA_LINUX_WINDOW_MANAGER_MUFFIN; break; case ui::WM_MUTTER: uma_name = UMA_LINUX_WINDOW_MANAGER_MUTTER; break; case ui::WM_OPENBOX: uma_name = UMA_LINUX_WINDOW_MANAGER_OPENBOX; break; case ui::WM_XFWM4: uma_name = UMA_LINUX_WINDOW_MANAGER_XFWM4; break; } UMA_HISTOGRAM_ENUMERATION("Linux.WindowManager", uma_name, UMA_LINUX_WINDOW_MANAGER_COUNT); #endif } void RecordTouchEventState() { const CommandLine& command_line = *CommandLine::ForCurrentProcess(); const std::string touch_enabled_switch = command_line.HasSwitch(switches::kTouchEvents) ? command_line.GetSwitchValueASCII(switches::kTouchEvents) : switches::kTouchEventsAuto; UMATouchEventsState state; if (touch_enabled_switch.empty() || touch_enabled_switch == switches::kTouchEventsEnabled) { state = UMA_TOUCH_EVENTS_ENABLED; } else if (touch_enabled_switch == switches::kTouchEventsAuto) { state = ui::IsTouchDevicePresent() ? UMA_TOUCH_EVENTS_AUTO_ENABLED : UMA_TOUCH_EVENTS_AUTO_DISABLED; } else if (touch_enabled_switch == switches::kTouchEventsDisabled) { state = UMA_TOUCH_EVENTS_DISABLED; } else { NOTREACHED(); return; } UMA_HISTOGRAM_ENUMERATION("Touchscreen.TouchEventsEnabled", state, UMA_TOUCH_EVENTS_STATE_COUNT); } } // namespace ChromeBrowserMainExtraPartsMetrics::ChromeBrowserMainExtraPartsMetrics() { } ChromeBrowserMainExtraPartsMetrics::~ChromeBrowserMainExtraPartsMetrics() { } void ChromeBrowserMainExtraPartsMetrics::PreProfileInit() { RecordMicroArchitectureStats(); } void ChromeBrowserMainExtraPartsMetrics::PreBrowserStart() { about_flags::PrefServiceFlagsStorage flags_storage_( g_browser_process->local_state()); about_flags::RecordUMAStatistics(&flags_storage_); } void ChromeBrowserMainExtraPartsMetrics::PostBrowserStart() { RecordLinuxGlibcVersion(); RecordLinuxWindowManager(); RecordTouchEventState(); const int kStartupMetricsGatheringDelaySeconds = 45; content::BrowserThread::GetBlockingPool()->PostDelayedTask( FROM_HERE, base::Bind(&RecordStartupMetricsOnBlockingPool), base::TimeDelta::FromSeconds(kStartupMetricsGatheringDelaySeconds)); // Create the metrics log observer. // We only need this for Android for now. #if defined(ANDROID) metrics_service_observer_.reset(new ChromeBrowserMetricsServiceObserver()); #endif } namespace chrome { void AddMetricsExtraParts(ChromeBrowserMainParts* main_parts) { main_parts->AddParts(new ChromeBrowserMainExtraPartsMetrics()); } } // namespace chrome <|endoftext|>
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/renderer_host/gtk_key_bindings_handler.h" #include <gdk/gdkkeysyms.h> #include <string> #include <utility> #include <vector> #include "base/basictypes.h" #include "base/file_util.h" #include "base/path_service.h" #include "base/string_util.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/edit_command.h" #include "chrome/common/native_web_keyboard_event.h" #include "testing/gtest/include/gtest/gtest.h" class GtkKeyBindingsHandlerTest : public testing::Test { protected: struct EditCommand { const char* name; const char* value; }; GtkKeyBindingsHandlerTest() : window_(gtk_window_new(GTK_WINDOW_TOPLEVEL)), handler_(NULL) { FilePath gtkrc; PathService::Get(chrome::DIR_TEST_DATA, &gtkrc); gtkrc = gtkrc.AppendASCII("gtk_key_bindings_test_gtkrc"); gtk_rc_parse(gtkrc.value().c_str()); GtkWidget* fixed = gtk_fixed_new(); handler_ = new GtkKeyBindingsHandler(fixed); gtk_container_add(GTK_CONTAINER(window_), fixed); gtk_widget_show(fixed); gtk_widget_show(window_); } ~GtkKeyBindingsHandlerTest() { gtk_widget_destroy(window_); delete handler_; } NativeWebKeyboardEvent NewNativeWebKeyboardEvent(guint keyval, guint state) { GdkKeymap* keymap = gdk_keymap_get_for_display(gtk_widget_get_display(window_)); GdkKeymapKey *keys = NULL; gint n_keys = 0; if (gdk_keymap_get_entries_for_keyval(keymap, keyval, &keys, &n_keys)) { GdkEventKey event; event.type = GDK_KEY_PRESS; event.window = NULL; event.send_event = 0; event.time = 0; event.state = state; event.keyval = keyval; event.length = 0; event.string = NULL; event.hardware_keycode = keys[0].keycode; event.group = keys[0].group; event.is_modifier = 0; g_free(keys); return NativeWebKeyboardEvent(&event); } return NativeWebKeyboardEvent(); } void TestKeyBinding(const NativeWebKeyboardEvent& event, const EditCommand expected_result[], size_t size) { EditCommands result; ASSERT_TRUE(handler_->Match(event, &result)); ASSERT_EQ(size, result.size()); for (size_t i = 0; i < size; ++i) { ASSERT_STREQ(expected_result[i].name, result[i].name.c_str()); ASSERT_STREQ(expected_result[i].value, result[i].value.c_str()); } } protected: GtkWidget* window_; GtkKeyBindingsHandler* handler_; }; TEST_F(GtkKeyBindingsHandlerTest, MoveCursor) { static const EditCommand kEditCommands[] = { // "move-cursor" (logical-positions, -2, 0) { "MoveBackward", "" }, { "MoveBackward", "" }, // "move-cursor" (logical-positions, 2, 0) { "MoveForward", "" }, { "MoveForward", "" }, // "move-cursor" (visual-positions, -1, 1) { "MoveLeftAndModifySelection", "" }, // "move-cursor" (visual-positions, 1, 1) { "MoveRightAndModifySelection", "" }, // "move-cursor" (words, -1, 0) { "MoveWordBackward", "" }, // "move-cursor" (words, 1, 0) { "MoveWordForward", "" }, // "move-cursor" (display-lines, -1, 0) { "MoveUp", "" }, // "move-cursor" (display-lines, 1, 0) { "MoveDown", "" }, // "move-cursor" (display-line-ends, -1, 0) { "MoveToBeginningOfLine", "" }, // "move-cursor" (display-line-ends, 1, 0) { "MoveToEndOfLine", "" }, // "move-cursor" (paragraph-ends, -1, 0) { "MoveToBeginningOfParagraph", "" }, // "move-cursor" (paragraph-ends, 1, 0) { "MoveToEndOfParagraph", "" }, // "move-cursor" (pages, -1, 0) { "MovePageUp", "" }, // "move-cursor" (pages, 1, 0) { "MovePageDown", "" }, // "move-cursor" (buffer-ends, -1, 0) { "MoveToBeginningOfDocument", "" }, // "move-cursor" (buffer-ends, 1, 0) { "MoveToEndOfDocument", "" } }; TestKeyBinding(NewNativeWebKeyboardEvent(GDK_1, GDK_CONTROL_MASK), kEditCommands, arraysize(kEditCommands)); } TEST_F(GtkKeyBindingsHandlerTest, DeleteFromCursor) { static const EditCommand kEditCommands[] = { // "delete-from-cursor" (chars, -2) { "DeleteBackward", "" }, { "DeleteBackward", "" }, // "delete-from-cursor" (chars, 2) { "DeleteForward", "" }, { "DeleteForward", "" }, // "delete-from-cursor" (word-ends, -1) { "DeleteWordBackward", "" }, // "delete-from-cursor" (word-ends, 1) { "DeleteWordForward", "" }, // "delete-from-cursor" (words, -1) { "MoveWordBackward", "" }, { "DeleteWordForward", "" }, // "delete-from-cursor" (words, 1) { "MoveWordForward", "" }, { "DeleteWordBackward", "" }, // "delete-from-cursor" (display-lines, -1) { "MoveToBeginningOfLine", "" }, { "DeleteToEndOfLine", "" }, // "delete-from-cursor" (display-lines, 1) { "MoveToBeginningOfLine", "" }, { "DeleteToEndOfLine", "" }, // "delete-from-cursor" (display-line-ends, -1) { "DeleteToBeginningOfLine", "" }, // "delete-from-cursor" (display-line-ends, 1) { "DeleteToEndOfLine", "" }, // "delete-from-cursor" (paragraph-ends, -1) { "DeleteToBeginningOfParagraph", "" }, // "delete-from-cursor" (paragraph-ends, 1) { "DeleteToEndOfParagraph", "" }, // "delete-from-cursor" (paragraphs, -1) { "MoveToBeginningOfParagraph", "" }, { "DeleteToEndOfParagraph", "" }, // "delete-from-cursor" (paragraphs, 1) { "MoveToBeginningOfParagraph", "" }, { "DeleteToEndOfParagraph", "" }, }; TestKeyBinding(NewNativeWebKeyboardEvent(GDK_2, GDK_CONTROL_MASK), kEditCommands, arraysize(kEditCommands)); } TEST_F(GtkKeyBindingsHandlerTest, OtherActions) { static const EditCommand kBackspace[] = { { "DeleteBackward", "" } }; TestKeyBinding(NewNativeWebKeyboardEvent(GDK_3, GDK_CONTROL_MASK), kBackspace, arraysize(kBackspace)); static const EditCommand kCopyClipboard[] = { { "Copy", "" } }; TestKeyBinding(NewNativeWebKeyboardEvent(GDK_4, GDK_CONTROL_MASK), kCopyClipboard, arraysize(kCopyClipboard)); static const EditCommand kCutClipboard[] = { { "Cut", "" } }; TestKeyBinding(NewNativeWebKeyboardEvent(GDK_5, GDK_CONTROL_MASK), kCutClipboard, arraysize(kCutClipboard)); static const EditCommand kInsertAtCursor[] = { { "InsertText", "hello" } }; TestKeyBinding(NewNativeWebKeyboardEvent(GDK_6, GDK_CONTROL_MASK), kInsertAtCursor, arraysize(kInsertAtCursor)); static const EditCommand kPasteClipboard[] = { { "Paste", "" } }; TestKeyBinding(NewNativeWebKeyboardEvent(GDK_7, GDK_CONTROL_MASK), kPasteClipboard, arraysize(kPasteClipboard)); static const EditCommand kSelectAll[] = { { "Unselect", "" }, { "SelectAll", "" } }; TestKeyBinding(NewNativeWebKeyboardEvent(GDK_8, GDK_CONTROL_MASK), kSelectAll, arraysize(kSelectAll)); static const EditCommand kSetAnchor[] = { { "SetMark", "" } }; TestKeyBinding(NewNativeWebKeyboardEvent(GDK_9, GDK_CONTROL_MASK), kSetAnchor, arraysize(kSetAnchor)); } <commit_msg>Mark the GtkKeyBindingsHandlerTest tests as flaky since they don't work in a chroot.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/renderer_host/gtk_key_bindings_handler.h" #include <gdk/gdkkeysyms.h> #include <string> #include <utility> #include <vector> #include "base/basictypes.h" #include "base/file_util.h" #include "base/path_service.h" #include "base/string_util.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/edit_command.h" #include "chrome/common/native_web_keyboard_event.h" #include "testing/gtest/include/gtest/gtest.h" class GtkKeyBindingsHandlerTest : public testing::Test { protected: struct EditCommand { const char* name; const char* value; }; GtkKeyBindingsHandlerTest() : window_(gtk_window_new(GTK_WINDOW_TOPLEVEL)), handler_(NULL) { FilePath gtkrc; PathService::Get(chrome::DIR_TEST_DATA, &gtkrc); gtkrc = gtkrc.AppendASCII("gtk_key_bindings_test_gtkrc"); gtk_rc_parse(gtkrc.value().c_str()); GtkWidget* fixed = gtk_fixed_new(); handler_ = new GtkKeyBindingsHandler(fixed); gtk_container_add(GTK_CONTAINER(window_), fixed); gtk_widget_show(fixed); gtk_widget_show(window_); } ~GtkKeyBindingsHandlerTest() { gtk_widget_destroy(window_); delete handler_; } NativeWebKeyboardEvent NewNativeWebKeyboardEvent(guint keyval, guint state) { GdkKeymap* keymap = gdk_keymap_get_for_display(gtk_widget_get_display(window_)); GdkKeymapKey *keys = NULL; gint n_keys = 0; if (gdk_keymap_get_entries_for_keyval(keymap, keyval, &keys, &n_keys)) { GdkEventKey event; event.type = GDK_KEY_PRESS; event.window = NULL; event.send_event = 0; event.time = 0; event.state = state; event.keyval = keyval; event.length = 0; event.string = NULL; event.hardware_keycode = keys[0].keycode; event.group = keys[0].group; event.is_modifier = 0; g_free(keys); return NativeWebKeyboardEvent(&event); } return NativeWebKeyboardEvent(); } void TestKeyBinding(const NativeWebKeyboardEvent& event, const EditCommand expected_result[], size_t size) { EditCommands result; ASSERT_TRUE(handler_->Match(event, &result)); ASSERT_EQ(size, result.size()); for (size_t i = 0; i < size; ++i) { ASSERT_STREQ(expected_result[i].name, result[i].name.c_str()); ASSERT_STREQ(expected_result[i].value, result[i].value.c_str()); } } protected: GtkWidget* window_; GtkKeyBindingsHandler* handler_; }; // Does not work in a chroot. See bug 60363. TEST_F(GtkKeyBindingsHandlerTest, FLAKY_MoveCursor) { static const EditCommand kEditCommands[] = { // "move-cursor" (logical-positions, -2, 0) { "MoveBackward", "" }, { "MoveBackward", "" }, // "move-cursor" (logical-positions, 2, 0) { "MoveForward", "" }, { "MoveForward", "" }, // "move-cursor" (visual-positions, -1, 1) { "MoveLeftAndModifySelection", "" }, // "move-cursor" (visual-positions, 1, 1) { "MoveRightAndModifySelection", "" }, // "move-cursor" (words, -1, 0) { "MoveWordBackward", "" }, // "move-cursor" (words, 1, 0) { "MoveWordForward", "" }, // "move-cursor" (display-lines, -1, 0) { "MoveUp", "" }, // "move-cursor" (display-lines, 1, 0) { "MoveDown", "" }, // "move-cursor" (display-line-ends, -1, 0) { "MoveToBeginningOfLine", "" }, // "move-cursor" (display-line-ends, 1, 0) { "MoveToEndOfLine", "" }, // "move-cursor" (paragraph-ends, -1, 0) { "MoveToBeginningOfParagraph", "" }, // "move-cursor" (paragraph-ends, 1, 0) { "MoveToEndOfParagraph", "" }, // "move-cursor" (pages, -1, 0) { "MovePageUp", "" }, // "move-cursor" (pages, 1, 0) { "MovePageDown", "" }, // "move-cursor" (buffer-ends, -1, 0) { "MoveToBeginningOfDocument", "" }, // "move-cursor" (buffer-ends, 1, 0) { "MoveToEndOfDocument", "" } }; TestKeyBinding(NewNativeWebKeyboardEvent(GDK_1, GDK_CONTROL_MASK), kEditCommands, arraysize(kEditCommands)); } // Does not work in a chroot. See bug 60363. TEST_F(GtkKeyBindingsHandlerTest, FLAKY_DeleteFromCursor) { static const EditCommand kEditCommands[] = { // "delete-from-cursor" (chars, -2) { "DeleteBackward", "" }, { "DeleteBackward", "" }, // "delete-from-cursor" (chars, 2) { "DeleteForward", "" }, { "DeleteForward", "" }, // "delete-from-cursor" (word-ends, -1) { "DeleteWordBackward", "" }, // "delete-from-cursor" (word-ends, 1) { "DeleteWordForward", "" }, // "delete-from-cursor" (words, -1) { "MoveWordBackward", "" }, { "DeleteWordForward", "" }, // "delete-from-cursor" (words, 1) { "MoveWordForward", "" }, { "DeleteWordBackward", "" }, // "delete-from-cursor" (display-lines, -1) { "MoveToBeginningOfLine", "" }, { "DeleteToEndOfLine", "" }, // "delete-from-cursor" (display-lines, 1) { "MoveToBeginningOfLine", "" }, { "DeleteToEndOfLine", "" }, // "delete-from-cursor" (display-line-ends, -1) { "DeleteToBeginningOfLine", "" }, // "delete-from-cursor" (display-line-ends, 1) { "DeleteToEndOfLine", "" }, // "delete-from-cursor" (paragraph-ends, -1) { "DeleteToBeginningOfParagraph", "" }, // "delete-from-cursor" (paragraph-ends, 1) { "DeleteToEndOfParagraph", "" }, // "delete-from-cursor" (paragraphs, -1) { "MoveToBeginningOfParagraph", "" }, { "DeleteToEndOfParagraph", "" }, // "delete-from-cursor" (paragraphs, 1) { "MoveToBeginningOfParagraph", "" }, { "DeleteToEndOfParagraph", "" }, }; TestKeyBinding(NewNativeWebKeyboardEvent(GDK_2, GDK_CONTROL_MASK), kEditCommands, arraysize(kEditCommands)); } // Does not work in a chroot. See bug 60363. TEST_F(GtkKeyBindingsHandlerTest, FLAKY_OtherActions) { static const EditCommand kBackspace[] = { { "DeleteBackward", "" } }; TestKeyBinding(NewNativeWebKeyboardEvent(GDK_3, GDK_CONTROL_MASK), kBackspace, arraysize(kBackspace)); static const EditCommand kCopyClipboard[] = { { "Copy", "" } }; TestKeyBinding(NewNativeWebKeyboardEvent(GDK_4, GDK_CONTROL_MASK), kCopyClipboard, arraysize(kCopyClipboard)); static const EditCommand kCutClipboard[] = { { "Cut", "" } }; TestKeyBinding(NewNativeWebKeyboardEvent(GDK_5, GDK_CONTROL_MASK), kCutClipboard, arraysize(kCutClipboard)); static const EditCommand kInsertAtCursor[] = { { "InsertText", "hello" } }; TestKeyBinding(NewNativeWebKeyboardEvent(GDK_6, GDK_CONTROL_MASK), kInsertAtCursor, arraysize(kInsertAtCursor)); static const EditCommand kPasteClipboard[] = { { "Paste", "" } }; TestKeyBinding(NewNativeWebKeyboardEvent(GDK_7, GDK_CONTROL_MASK), kPasteClipboard, arraysize(kPasteClipboard)); static const EditCommand kSelectAll[] = { { "Unselect", "" }, { "SelectAll", "" } }; TestKeyBinding(NewNativeWebKeyboardEvent(GDK_8, GDK_CONTROL_MASK), kSelectAll, arraysize(kSelectAll)); static const EditCommand kSetAnchor[] = { { "SetMark", "" } }; TestKeyBinding(NewNativeWebKeyboardEvent(GDK_9, GDK_CONTROL_MASK), kSetAnchor, arraysize(kSetAnchor)); } <|endoftext|>
<commit_before>#include <QtWidgets> #include "mainwindow.h" #include <fts_fuzzy_match.h> #include <glob.h> #include <string> #include <map> #include <database.h> Window::Window(QWidget *parent) : QMainWindow(parent) { // Initalise database db.setDatabaseName("recipes.db"); // Initialise widgets searchBox = new SearchBox(); searchBox->setPlaceholderText("Search for recipes"); recipeBox = new QComboBox(); QStringList recipeCategories; recipeCategories << "All Recipes" << "Beef" << "Chicken" << "Dessert" << "Lamb" << "Pork" << "Seafood" << "Turkey" << "Veggie"; recipeBox->addItems(recipeCategories); createRecipeList(); numResults = new QLabel(); // Set layout centralWidget = new QWidget(); QGridLayout *mainLayout = new QGridLayout(centralWidget); mainLayout->addWidget(searchBox, 0, 0, 1, 6); mainLayout->addWidget(numResults, 0, 6, 1, 1); mainLayout->addWidget(recipeBox, 0, 7, 1, 1); mainLayout->addWidget(recipeList, 1, 0, 1, 8); centralWidget->setLayout(mainLayout); centralWidget->show(); setCentralWidget(centralWidget); // Create menus optionsMenu = new QMenu("Options"); updateDb = new QAction("Update database", this); connect(updateDb, &QAction::triggered, this, &Window::updateDatabase); cleanDb = new QAction("Clean database", this); connect(cleanDb, &QAction::triggered, this, &Window::cleanDatabase); optionsMenu->addAction(updateDb); optionsMenu->addAction(cleanDb); menuBar()->addMenu(optionsMenu); // Set window paramters setWindowTitle(tr("Find Recipes")); setMinimumSize(600, 400); // Set signals connect(recipeList, &QListWidget::itemDoubleClicked, this, &Window::openFile); connect(searchBox, SIGNAL(inputText(QString)), this, SLOT(updateRecipesDiplay(QString))); connect(searchBox, SIGNAL(returnPressed()), recipeList, SLOT(setFocus())); connect(recipeBox, SIGNAL(currentTextChanged(QString)), searchBox, SLOT(recipeFiterChanged(QString))); // Populate list on start up updateRecipesDiplay(""); } // Get list of files according to glob patternn QStringList globVector(const std::string& pattern){ glob_t glob_result; glob(pattern.c_str(),GLOB_TILDE,NULL,&glob_result); QStringList files; for(unsigned int i=0; i<glob_result.gl_pathc; ++i){ files << QString(glob_result.gl_pathv[i]); } globfree(&glob_result); return files; } void SearchBox::recipeFiterChanged(QString newFilter){ // When the recipe filter changes, emit this signal to call updateRecipeDisplay emit inputText(text()); } void SearchBox::keyPressEvent(QKeyEvent *evt){ QLineEdit::keyPressEvent(evt); setPlaceholderText("Search for recipes"); // When the search changes, emit this signal to call updateRecipeDisplay emit inputText(text()); } void Window::updateRecipesDiplay(QString searchText){ recipeList->clear(); QList<QListWidgetItem*> recipes = getRecipeList(searchText); for (int i=0; i<recipes.size(); ++i){ recipeList->addItem(recipes[i]); } if(searchText.isEmpty()){ recipeList->sortItems(); } QString text = QString("%1 recipes").arg(recipes.size()); if (recipes.size() == 1){ text = "1 recipe"; } numResults->setText(text); } QList<QListWidgetItem*> Window::getRecipeList(QString searchText){ QList<QListWidgetItem*> recipes; if (searchText.isEmpty()) { recipes = getAllRecipes(); }else{ recipes = getMatchingRecipes(searchText); } return recipes; } QList<QListWidgetItem*> Window::getAllRecipes(){ QList<QListWidgetItem*> recipes; // Open database and execute query db.open(); // Prepare query based on filter QSqlQuery query = QSqlQuery(); if(recipeBox->currentText() != "All Recipes"){ QString category = recipeBox->currentText(); query.prepare("select TITLE, IMG_PATH, HTML_PATH from RECIPES where CATEGORY = :category"); query.bindValue(":category", category); query.setForwardOnly(true); }else{ query.prepare("select TITLE, IMG_PATH, HTML_PATH from RECIPES"); query.setForwardOnly(true); } // Execute query query.exec(); while(query.next()){ // Extract info from query results QString title = query.value(0).toString(); QString img_path = query.value(1).toString(); QString html_path = query.value(2).toString(); // Create QListWidgetItems QListWidgetItem *recipe = new QListWidgetItem; recipe->setText(title); recipe->setData(Qt::UserRole, html_path); QImage *img = new QImage(); bool loaded = img->load(img_path); if (loaded){ recipe->setIcon(QPixmap::fromImage(*img)); }else{ // If image doesn't exist, use placeholder image bool loaded = img->load("./images/Placeholder.jpg"); if (loaded){ recipe->setIcon(QPixmap::fromImage(*img)); } } recipes.append(recipe); } db.close(); return recipes; } QList<QListWidgetItem*> Window::getMatchingRecipes(QString searchText){ QList<QListWidgetItem*> recipes; // Get matching recipes and their scores. The QStringList contains title, img_path, file_path in order. std::map<double, QStringList> matchingRecipes = findMatches(searchText); // Build QListWidgetItems and add to QList // By default the map should be in ascending order, so use reverse iterator to get highest matches first for (auto iter = matchingRecipes.rbegin(); iter != matchingRecipes.rend(); ++iter){ QString title = iter->second[0]; QString img_path = iter->second[1]; QString html_path = iter->second[2]; QListWidgetItem *recipe = new QListWidgetItem; recipe->setText(title); recipe->setData(Qt::UserRole, html_path); QImage *img = new QImage(); bool loaded = img->load(img_path); if (loaded){ recipe->setIcon(QPixmap::fromImage(*img)); }else{ // If image doesn't exist, use placeholder image bool loaded = img->load("./Images/Placeholder.jpg"); if (loaded){ recipe->setIcon(QPixmap::fromImage(*img)); } } recipes.append(recipe); } return recipes; } std::map<double, QStringList> Window::findMatches(QString text) { // Open database db.open(); // Prepare query based on filter QSqlQuery query = QSqlQuery(); if(recipeBox->currentText() != "All Recipes"){ QString category = recipeBox->currentText(); query.prepare("select TITLE, IMG_PATH, HTML_PATH from RECIPES where CATEGORY = :category"); query.bindValue(":category", category); query.setForwardOnly(true); }else{ query.prepare("select TITLE, IMG_PATH, HTML_PATH from RECIPES"); query.setForwardOnly(true); } // Execute query query.exec(); // Get matching files and their scores std::map<double, QStringList> matchingFiles; std::string txtstr = text.toStdString(); while(query.next()){ int score; QString title = query.value(0).toString(); QString img_path = query.value(1).toString().replace("\'", "").replace(",", ""); QString file_path = query.value(2).toString(); std::string titlestr = title.toStdString(); if (fts::fuzzy_match_score(txtstr.c_str(), titlestr.c_str(), score)){ // If a map entry already has the current score, increase score by 0.01. double dbscore = (double)score; if (matchingFiles.count(dbscore) > 0){ dbscore += 0.01; } matchingFiles[dbscore] = QStringList() << title << img_path << file_path; } } db.close(); return matchingFiles; } void Window::createRecipeList() { recipeList = new QListWidget(); recipeList->setViewMode(QListView::IconMode); recipeList->setIconSize(QSize(267, 150)); recipeList->setGridSize(QSize(280, 185)); recipeList->setWordWrap(true); recipeList->setTextElideMode(Qt::ElideNone); } void Window::openFile(QListWidgetItem *recipe) { // Read hidden data to find full file path QString path = recipe->data(Qt::UserRole).toString(); QDesktopServices::openUrl(QUrl::fromLocalFile(currentDir.absoluteFilePath(path))); } void Window::updateDatabase(){ db_ops::update_database(&db); searchBox->setPlaceholderText("Search for recipes - Updated!"); // Repopulate list updateRecipesDiplay(""); } void Window::cleanDatabase(){ db_ops::clean_database(&db); searchBox->setPlaceholderText("Search for recipes - Cleaned!"); } void Window::resizeEvent(QResizeEvent *event){ int iconWidth, iconHeight, gridWidth, gridHeight, columns; double gridRatio = 280.0/185.0; double iconRatio = 267.0/150.0; QSize recipeListSize = recipeList->size(); if(recipeListSize.width()<=587){ // Set defaults for minimum size columns = 2; iconWidth = 267; iconHeight = 150; gridWidth = 280; gridHeight = 185; }else{ // Icons should never go larger than default, so set number of columns to round up columns = ceil(recipeListSize.width()/280.0); // Width of grid is widget_width/columns, with extra width removed to allow for scrollbar gridWidth = int(recipeListSize.width()/columns) - ceil(18.0/columns); // Calculate other parameters based on ratios of default values. gridHeight = int(gridWidth/gridRatio); iconWidth = gridWidth - 13; iconHeight = int(iconWidth/iconRatio); } recipeList->setIconSize(QSize(iconWidth, iconHeight)); recipeList->setGridSize(QSize(gridWidth, gridHeight)); } <commit_msg>Fix placeholder image not appearing when searching<commit_after>#include <QtWidgets> #include "mainwindow.h" #include <fts_fuzzy_match.h> #include <glob.h> #include <string> #include <map> #include <database.h> Window::Window(QWidget *parent) : QMainWindow(parent) { // Initalise database db.setDatabaseName("recipes.db"); // Initialise widgets searchBox = new SearchBox(); searchBox->setPlaceholderText("Search for recipes"); recipeBox = new QComboBox(); QStringList recipeCategories; recipeCategories << "All Recipes" << "Beef" << "Chicken" << "Dessert" << "Lamb" << "Pork" << "Seafood" << "Turkey" << "Veggie"; recipeBox->addItems(recipeCategories); createRecipeList(); numResults = new QLabel(); // Set layout centralWidget = new QWidget(); QGridLayout *mainLayout = new QGridLayout(centralWidget); mainLayout->addWidget(searchBox, 0, 0, 1, 6); mainLayout->addWidget(numResults, 0, 6, 1, 1); mainLayout->addWidget(recipeBox, 0, 7, 1, 1); mainLayout->addWidget(recipeList, 1, 0, 1, 8); centralWidget->setLayout(mainLayout); centralWidget->show(); setCentralWidget(centralWidget); // Create menus optionsMenu = new QMenu("Options"); updateDb = new QAction("Update database", this); connect(updateDb, &QAction::triggered, this, &Window::updateDatabase); cleanDb = new QAction("Clean database", this); connect(cleanDb, &QAction::triggered, this, &Window::cleanDatabase); optionsMenu->addAction(updateDb); optionsMenu->addAction(cleanDb); menuBar()->addMenu(optionsMenu); // Set window paramters setWindowTitle(tr("Find Recipes")); setMinimumSize(600, 400); // Set signals connect(recipeList, &QListWidget::itemDoubleClicked, this, &Window::openFile); connect(searchBox, SIGNAL(inputText(QString)), this, SLOT(updateRecipesDiplay(QString))); connect(searchBox, SIGNAL(returnPressed()), recipeList, SLOT(setFocus())); connect(recipeBox, SIGNAL(currentTextChanged(QString)), searchBox, SLOT(recipeFiterChanged(QString))); // Populate list on start up updateRecipesDiplay(""); } // Get list of files according to glob patternn QStringList globVector(const std::string& pattern){ glob_t glob_result; glob(pattern.c_str(),GLOB_TILDE,NULL,&glob_result); QStringList files; for(unsigned int i=0; i<glob_result.gl_pathc; ++i){ files << QString(glob_result.gl_pathv[i]); } globfree(&glob_result); return files; } void SearchBox::recipeFiterChanged(QString newFilter){ // When the recipe filter changes, emit this signal to call updateRecipeDisplay emit inputText(text()); } void SearchBox::keyPressEvent(QKeyEvent *evt){ QLineEdit::keyPressEvent(evt); setPlaceholderText("Search for recipes"); // When the search changes, emit this signal to call updateRecipeDisplay emit inputText(text()); } void Window::updateRecipesDiplay(QString searchText){ recipeList->clear(); QList<QListWidgetItem*> recipes = getRecipeList(searchText); for (int i=0; i<recipes.size(); ++i){ recipeList->addItem(recipes[i]); } if(searchText.isEmpty()){ recipeList->sortItems(); } QString text = QString("%1 recipes").arg(recipes.size()); if (recipes.size() == 1){ text = "1 recipe"; } numResults->setText(text); } QList<QListWidgetItem*> Window::getRecipeList(QString searchText){ QList<QListWidgetItem*> recipes; if (searchText.isEmpty()) { recipes = getAllRecipes(); }else{ recipes = getMatchingRecipes(searchText); } return recipes; } QList<QListWidgetItem*> Window::getAllRecipes(){ QList<QListWidgetItem*> recipes; // Open database and execute query db.open(); // Prepare query based on filter QSqlQuery query = QSqlQuery(); if(recipeBox->currentText() != "All Recipes"){ QString category = recipeBox->currentText(); query.prepare("select TITLE, IMG_PATH, HTML_PATH from RECIPES where CATEGORY = :category"); query.bindValue(":category", category); query.setForwardOnly(true); }else{ query.prepare("select TITLE, IMG_PATH, HTML_PATH from RECIPES"); query.setForwardOnly(true); } // Execute query query.exec(); while(query.next()){ // Extract info from query results QString title = query.value(0).toString(); QString img_path = query.value(1).toString(); QString html_path = query.value(2).toString(); // Create QListWidgetItems QListWidgetItem *recipe = new QListWidgetItem; recipe->setText(title); recipe->setData(Qt::UserRole, html_path); QImage *img = new QImage(); bool loaded = img->load(img_path); if (loaded){ recipe->setIcon(QPixmap::fromImage(*img)); }else{ // If image doesn't exist, use placeholder image bool loaded = img->load("./images/Placeholder.jpg"); if (loaded){ recipe->setIcon(QPixmap::fromImage(*img)); } } recipes.append(recipe); } db.close(); return recipes; } QList<QListWidgetItem*> Window::getMatchingRecipes(QString searchText){ QList<QListWidgetItem*> recipes; // Get matching recipes and their scores. The QStringList contains title, img_path, file_path in order. std::map<double, QStringList> matchingRecipes = findMatches(searchText); // Build QListWidgetItems and add to QList // By default the map should be in ascending order, so use reverse iterator to get highest matches first for (auto iter = matchingRecipes.rbegin(); iter != matchingRecipes.rend(); ++iter){ QString title = iter->second[0]; QString img_path = iter->second[1]; QString html_path = iter->second[2]; QListWidgetItem *recipe = new QListWidgetItem; recipe->setText(title); recipe->setData(Qt::UserRole, html_path); QImage *img = new QImage(); bool loaded = img->load(img_path); if (loaded){ recipe->setIcon(QPixmap::fromImage(*img)); }else{ // If image doesn't exist, use placeholder image bool loaded = img->load("./images/Placeholder.jpg"); if (loaded){ recipe->setIcon(QPixmap::fromImage(*img)); } } recipes.append(recipe); } return recipes; } std::map<double, QStringList> Window::findMatches(QString text) { // Open database db.open(); // Prepare query based on filter QSqlQuery query = QSqlQuery(); if(recipeBox->currentText() != "All Recipes"){ QString category = recipeBox->currentText(); query.prepare("select TITLE, IMG_PATH, HTML_PATH from RECIPES where CATEGORY = :category"); query.bindValue(":category", category); query.setForwardOnly(true); }else{ query.prepare("select TITLE, IMG_PATH, HTML_PATH from RECIPES"); query.setForwardOnly(true); } // Execute query query.exec(); // Get matching files and their scores std::map<double, QStringList> matchingFiles; std::string txtstr = text.toStdString(); while(query.next()){ int score; QString title = query.value(0).toString(); QString img_path = query.value(1).toString().replace("\'", "").replace(",", ""); QString file_path = query.value(2).toString(); std::string titlestr = title.toStdString(); if (fts::fuzzy_match_score(txtstr.c_str(), titlestr.c_str(), score)){ // If a map entry already has the current score, increase score by 0.01. double dbscore = (double)score; if (matchingFiles.count(dbscore) > 0){ dbscore += 0.01; } matchingFiles[dbscore] = QStringList() << title << img_path << file_path; } } db.close(); return matchingFiles; } void Window::createRecipeList() { recipeList = new QListWidget(); recipeList->setViewMode(QListView::IconMode); recipeList->setIconSize(QSize(267, 150)); recipeList->setGridSize(QSize(280, 185)); recipeList->setWordWrap(true); recipeList->setTextElideMode(Qt::ElideNone); } void Window::openFile(QListWidgetItem *recipe) { // Read hidden data to find full file path QString path = recipe->data(Qt::UserRole).toString(); QDesktopServices::openUrl(QUrl::fromLocalFile(currentDir.absoluteFilePath(path))); } void Window::updateDatabase(){ db_ops::update_database(&db); searchBox->setPlaceholderText("Search for recipes - Updated!"); // Repopulate list updateRecipesDiplay(""); } void Window::cleanDatabase(){ db_ops::clean_database(&db); searchBox->setPlaceholderText("Search for recipes - Cleaned!"); } void Window::resizeEvent(QResizeEvent *event){ int iconWidth, iconHeight, gridWidth, gridHeight, columns; double gridRatio = 280.0/185.0; double iconRatio = 267.0/150.0; QSize recipeListSize = recipeList->size(); if(recipeListSize.width()<=587){ // Set defaults for minimum size columns = 2; iconWidth = 267; iconHeight = 150; gridWidth = 280; gridHeight = 185; }else{ // Icons should never go larger than default, so set number of columns to round up columns = ceil(recipeListSize.width()/280.0); // Width of grid is widget_width/columns, with extra width removed to allow for scrollbar gridWidth = int(recipeListSize.width()/columns) - ceil(18.0/columns); // Calculate other parameters based on ratios of default values. gridHeight = int(gridWidth/gridRatio); iconWidth = gridWidth - 13; iconHeight = int(iconWidth/iconRatio); } recipeList->setIconSize(QSize(iconWidth, iconHeight)); recipeList->setGridSize(QSize(gridWidth, gridHeight)); } <|endoftext|>
<commit_before>/* Copyright (C) 2012 Kolibre This file is part of kolibre-player. Kolibre-player 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. Kolibre-player 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 kolibre-player. If not, see <http://www.gnu.org/licenses/>. */ #include <cstdlib> #include "PlayerImpl.h" #include "setup_logging.h" bool playerMessageSlot( Player::playerMessage message ) { std::cout << "Got player message " << message << std::endl; switch (message) { case Player::PLAYER_CONTINUE: return false; case Player::PLAYER_ERROR: return true; } } int main(int argc, char *argv[]) { setup_logging(); PlayerImpl Player; Player.doOnPlayerMessage(playerMessageSlot); bool res = Player.sendERRORSignal(); assert(res); res = Player.sendCONTSignal(); assert(!res); return 0; } <commit_msg>Add more signaltests<commit_after>/* Copyright (C) 2012 Kolibre This file is part of kolibre-player. Kolibre-player 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. Kolibre-player 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 kolibre-player. If not, see <http://www.gnu.org/licenses/>. */ #include <cstdlib> #include "PlayerImpl.h" #include "setup_logging.h" bool playerMessageSlot( Player::playerMessage message ) { std::cout << "Got player message " << message << std::endl; switch (message) { case Player::PLAYER_CONTINUE: return false; case Player::PLAYER_ERROR: return true; } } int main(int argc, char *argv[]) { setup_logging(); PlayerImpl Player; //Test sending a message with no slots bool res = Player.sendERRORSignal(); assert(!res); res = Player.sendBUFFERINGSignal(); assert(!res); res = Player.sendCONTSignal(); assert(!res); res = Player.sendEOSSignal(); assert(!res); Player.doOnPlayerMessage(playerMessageSlot); res = Player.sendERRORSignal(); assert(res); res = Player.sendCONTSignal(); assert(!res); return 0; } <|endoftext|>
<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include <glog/logging.h> #include "cnetlink.h" #include "nbi_impl.h" #include "tap_manager.h" #include "netlink/ctapdev.h" #include "utils/utils.h" namespace basebox { nbi_impl::nbi_impl(std::shared_ptr<cnetlink> nl, std::shared_ptr<tap_manager> tap_man) : nl(nl), tap_man(tap_man) { nl->set_tapmanager(tap_man); } nbi_impl::~nbi_impl() { nl->stop(); } void nbi_impl::resend_state() noexcept { nl->resend_state(); } void nbi_impl::register_switch(switch_interface *swi) noexcept { this->swi = swi; nl->register_switch(swi); } void nbi_impl::switch_state_notification(enum switch_state state) noexcept { switch (state) { case SWITCH_STATE_UP: nl->start(); break; case SWITCH_STATE_DOWN: case SWITCH_STATE_FAILED: case SWITCH_STATE_UNKNOWN: nl->stop(); break; default: LOG(FATAL) << __FUNCTION__ << ": invalid state"; break; } } void nbi_impl::port_notification( std::deque<port_notification_data> &notifications) noexcept { for (auto &&ntfy : notifications) { switch (ntfy.ev) { case PORT_EVENT_MODIFY: switch (get_port_type(ntfy.port_id)) { case nbi::port_type_physical: LOG(INFO) << __FUNCTION__ << ": port state changed, continuing"; break; default: LOG(ERROR) << __FUNCTION__ << ": unknown port"; break; } break; case PORT_EVENT_ADD: switch (get_port_type(ntfy.port_id)) { case nbi::port_type_physical: if (tap_man->create_tapdev(ntfy.port_id, ntfy.name, *this) == -EEXIST) { LOG(INFO) << __FUNCTION__ << ": port already exists"; break; } tap_man->change_port_status(ntfy.name, ntfy.status); break; case nbi::port_type_vxlan: // XXX TODO notify this? LOG(INFO) << __FUNCTION__ << ": port_type_vxlan added"; break; default: LOG(ERROR) << __FUNCTION__ << ": unknown port"; break; } break; case PORT_EVENT_DEL: switch (get_port_type(ntfy.port_id)) { case nbi::port_type_physical: tap_man->destroy_tapdev(ntfy.port_id, ntfy.name); break; case nbi::port_type_vxlan: // XXX TODO notify this? LOG(INFO) << __FUNCTION__ << ": port_type_vxlan removed"; break; default: LOG(ERROR) << __FUNCTION__ << ": unknown port"; break; } break; default: break; } } } int nbi_impl::enqueue_to_switch(uint32_t port_id, basebox::packet *packet) { swi->enqueue(port_id, packet); return 0; } int nbi_impl::enqueue(uint32_t port_id, basebox::packet *pkt) noexcept { int rv = 0; assert(pkt); try { // detour via netlink to learn the source mac int fd = tap_man->get_fd(port_id); nl->learn_l2(port_id, fd, pkt); } catch (std::exception &e) { LOG(ERROR) << __FUNCTION__ << ": failed to enqueue packet for port_id=" << port_id << ": " << e.what(); std::free(pkt); rv = -1; } return rv; } int nbi_impl::fdb_timeout(uint32_t port_id, uint16_t vid, const rofl::caddress_ll &mac) noexcept { nl->fdb_timeout(port_id, vid, mac); return 0; } } // namespace basebox <commit_msg>nbi_impl: start netlink handling as early as possible<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include <glog/logging.h> #include "cnetlink.h" #include "nbi_impl.h" #include "tap_manager.h" #include "netlink/ctapdev.h" #include "utils/utils.h" namespace basebox { nbi_impl::nbi_impl(std::shared_ptr<cnetlink> nl, std::shared_ptr<tap_manager> tap_man) : nl(nl), tap_man(tap_man) { nl->set_tapmanager(tap_man); nl->start(); } nbi_impl::~nbi_impl() { nl->stop(); } void nbi_impl::resend_state() noexcept { nl->resend_state(); } void nbi_impl::register_switch(switch_interface *swi) noexcept { this->swi = swi; nl->register_switch(swi); } void nbi_impl::switch_state_notification(enum switch_state state) noexcept { switch (state) { case SWITCH_STATE_UP: case SWITCH_STATE_DOWN: case SWITCH_STATE_FAILED: case SWITCH_STATE_UNKNOWN: break; default: LOG(FATAL) << __FUNCTION__ << ": invalid state"; break; } } void nbi_impl::port_notification( std::deque<port_notification_data> &notifications) noexcept { for (auto &&ntfy : notifications) { switch (ntfy.ev) { case PORT_EVENT_MODIFY: switch (get_port_type(ntfy.port_id)) { case nbi::port_type_physical: LOG(INFO) << __FUNCTION__ << ": port state changed, continuing"; break; default: LOG(ERROR) << __FUNCTION__ << ": unknown port"; break; } break; case PORT_EVENT_ADD: switch (get_port_type(ntfy.port_id)) { case nbi::port_type_physical: if (tap_man->create_tapdev(ntfy.port_id, ntfy.name, *this) == -EEXIST) { LOG(INFO) << __FUNCTION__ << ": port already exists"; break; } tap_man->change_port_status(ntfy.name, ntfy.status); break; case nbi::port_type_vxlan: // XXX TODO notify this? LOG(INFO) << __FUNCTION__ << ": port_type_vxlan added"; break; default: LOG(ERROR) << __FUNCTION__ << ": unknown port"; break; } break; case PORT_EVENT_DEL: switch (get_port_type(ntfy.port_id)) { case nbi::port_type_physical: tap_man->destroy_tapdev(ntfy.port_id, ntfy.name); break; case nbi::port_type_vxlan: // XXX TODO notify this? LOG(INFO) << __FUNCTION__ << ": port_type_vxlan removed"; break; default: LOG(ERROR) << __FUNCTION__ << ": unknown port"; break; } break; default: break; } } } int nbi_impl::enqueue_to_switch(uint32_t port_id, basebox::packet *packet) { swi->enqueue(port_id, packet); return 0; } int nbi_impl::enqueue(uint32_t port_id, basebox::packet *pkt) noexcept { int rv = 0; assert(pkt); try { // detour via netlink to learn the source mac int fd = tap_man->get_fd(port_id); nl->learn_l2(port_id, fd, pkt); } catch (std::exception &e) { LOG(ERROR) << __FUNCTION__ << ": failed to enqueue packet for port_id=" << port_id << ": " << e.what(); std::free(pkt); rv = -1; } return rv; } int nbi_impl::fdb_timeout(uint32_t port_id, uint16_t vid, const rofl::caddress_ll &mac) noexcept { nl->fdb_timeout(port_id, vid, mac); return 0; } } // namespace basebox <|endoftext|>
<commit_before>/** * Copyright (c) 2011-2018 libbitcoin developers (see AUTHORS) * * This file is part of libbitcoin. * * libbitcoin 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 <bitcoin/bitcoin/network/channel.hpp> #include <bitcoin/bitcoin/network/authority.hpp> #include <bitcoin/bitcoin/network/channel_proxy.hpp> #include <bitcoin/bitcoin/primitives.hpp> namespace libbitcoin { namespace network { channel::channel(channel_proxy_ptr proxy) : weak_proxy_(proxy) { } channel::~channel() { stop(); } void channel::stop() const { const auto proxy = weak_proxy_.lock(); if (proxy) proxy->stop(); } bool channel::stopped() const { const auto proxy = weak_proxy_.lock(); if (proxy) return proxy->stopped(); return true; } authority channel::address() const { const auto proxy = weak_proxy_.lock(); if (proxy) return proxy->address(); return address(); } void channel::send_raw(const header_type& packet_header, const data_chunk& payload, channel_proxy::send_handler handle_send) { const auto proxy = weak_proxy_.lock(); if (proxy) proxy->send_raw(packet_header, payload, handle_send); else handle_send(error::service_stopped); } void channel::subscribe_version( channel_proxy::receive_version_handler handle_receive) { const auto proxy = weak_proxy_.lock(); if (proxy) proxy->subscribe_version(handle_receive); else handle_receive(error::service_stopped, version_type()); } void channel::subscribe_verack( channel_proxy::receive_verack_handler handle_receive) { const auto proxy = weak_proxy_.lock(); if (proxy) proxy->subscribe_verack(handle_receive); else handle_receive(error::service_stopped, verack_type()); } void channel::subscribe_address( channel_proxy::receive_address_handler handle_receive) { const auto proxy = weak_proxy_.lock(); if (proxy) proxy->subscribe_address(handle_receive); else handle_receive(error::service_stopped, address_type()); } void channel::subscribe_get_address( channel_proxy::receive_get_address_handler handle_receive) { const auto proxy = weak_proxy_.lock(); if (proxy) proxy->subscribe_get_address(handle_receive); else handle_receive(error::service_stopped, get_address_type()); } void channel::subscribe_inventory( channel_proxy::receive_inventory_handler handle_receive) { const auto proxy = weak_proxy_.lock(); if (proxy) proxy->subscribe_inventory(handle_receive); else handle_receive(error::service_stopped, inventory_type()); } void channel::subscribe_get_data( channel_proxy::receive_get_data_handler handle_receive) { const auto proxy = weak_proxy_.lock(); if (proxy) proxy->subscribe_get_data(handle_receive); else handle_receive(error::service_stopped, get_data_type()); } void channel::subscribe_get_blocks( channel_proxy::receive_get_blocks_handler handle_receive) { const auto proxy = weak_proxy_.lock(); if (proxy) proxy->subscribe_get_blocks(handle_receive); else handle_receive(error::service_stopped, get_blocks_type()); } void channel::subscribe_transaction( channel_proxy::receive_transaction_handler handle_receive) { const auto proxy = weak_proxy_.lock(); if (proxy) proxy->subscribe_transaction(handle_receive); else handle_receive(error::service_stopped, transaction_type()); } void channel::subscribe_block( channel_proxy::receive_block_handler handle_receive) { const auto proxy = weak_proxy_.lock(); if (proxy) proxy->subscribe_block(handle_receive); else handle_receive(error::service_stopped, block_type()); } void channel::subscribe_raw( channel_proxy::receive_raw_handler handle_receive) { const auto proxy = weak_proxy_.lock(); if (proxy) proxy->subscribe_raw(handle_receive); else handle_receive(error::service_stopped, header_type(), data_chunk()); } void channel::subscribe_stop( channel_proxy::stop_handler handle_stop) { const auto proxy = weak_proxy_.lock(); if (proxy) proxy->subscribe_stop(handle_stop); else handle_stop(error::service_stopped); } } // namespace network } // namespace libbitcoin <commit_msg>Oops, fix infinite recursion from partially-applied coincidental name change.<commit_after>/** * Copyright (c) 2011-2018 libbitcoin developers (see AUTHORS) * * This file is part of libbitcoin. * * libbitcoin 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 <bitcoin/bitcoin/network/channel.hpp> #include <bitcoin/bitcoin/network/authority.hpp> #include <bitcoin/bitcoin/network/channel_proxy.hpp> #include <bitcoin/bitcoin/primitives.hpp> namespace libbitcoin { namespace network { channel::channel(channel_proxy_ptr proxy) : weak_proxy_(proxy) { } channel::~channel() { stop(); } void channel::stop() const { const auto proxy = weak_proxy_.lock(); if (proxy) proxy->stop(); } bool channel::stopped() const { const auto proxy = weak_proxy_.lock(); if (proxy) return proxy->stopped(); return true; } authority channel::address() const { const auto proxy = weak_proxy_.lock(); if (proxy) return proxy->address(); return authority(); } void channel::send_raw(const header_type& packet_header, const data_chunk& payload, channel_proxy::send_handler handle_send) { const auto proxy = weak_proxy_.lock(); if (proxy) proxy->send_raw(packet_header, payload, handle_send); else handle_send(error::service_stopped); } void channel::subscribe_version( channel_proxy::receive_version_handler handle_receive) { const auto proxy = weak_proxy_.lock(); if (proxy) proxy->subscribe_version(handle_receive); else handle_receive(error::service_stopped, version_type()); } void channel::subscribe_verack( channel_proxy::receive_verack_handler handle_receive) { const auto proxy = weak_proxy_.lock(); if (proxy) proxy->subscribe_verack(handle_receive); else handle_receive(error::service_stopped, verack_type()); } void channel::subscribe_address( channel_proxy::receive_address_handler handle_receive) { const auto proxy = weak_proxy_.lock(); if (proxy) proxy->subscribe_address(handle_receive); else handle_receive(error::service_stopped, address_type()); } void channel::subscribe_get_address( channel_proxy::receive_get_address_handler handle_receive) { const auto proxy = weak_proxy_.lock(); if (proxy) proxy->subscribe_get_address(handle_receive); else handle_receive(error::service_stopped, get_address_type()); } void channel::subscribe_inventory( channel_proxy::receive_inventory_handler handle_receive) { const auto proxy = weak_proxy_.lock(); if (proxy) proxy->subscribe_inventory(handle_receive); else handle_receive(error::service_stopped, inventory_type()); } void channel::subscribe_get_data( channel_proxy::receive_get_data_handler handle_receive) { const auto proxy = weak_proxy_.lock(); if (proxy) proxy->subscribe_get_data(handle_receive); else handle_receive(error::service_stopped, get_data_type()); } void channel::subscribe_get_blocks( channel_proxy::receive_get_blocks_handler handle_receive) { const auto proxy = weak_proxy_.lock(); if (proxy) proxy->subscribe_get_blocks(handle_receive); else handle_receive(error::service_stopped, get_blocks_type()); } void channel::subscribe_transaction( channel_proxy::receive_transaction_handler handle_receive) { const auto proxy = weak_proxy_.lock(); if (proxy) proxy->subscribe_transaction(handle_receive); else handle_receive(error::service_stopped, transaction_type()); } void channel::subscribe_block( channel_proxy::receive_block_handler handle_receive) { const auto proxy = weak_proxy_.lock(); if (proxy) proxy->subscribe_block(handle_receive); else handle_receive(error::service_stopped, block_type()); } void channel::subscribe_raw( channel_proxy::receive_raw_handler handle_receive) { const auto proxy = weak_proxy_.lock(); if (proxy) proxy->subscribe_raw(handle_receive); else handle_receive(error::service_stopped, header_type(), data_chunk()); } void channel::subscribe_stop( channel_proxy::stop_handler handle_stop) { const auto proxy = weak_proxy_.lock(); if (proxy) proxy->subscribe_stop(handle_stop); else handle_stop(error::service_stopped); } } // namespace network } // namespace libbitcoin <|endoftext|>
<commit_before>// @(#)root/qtgsi:$Id$ // Author: Denis Bertini, M. Al-Turany 01/11/2000 /************************************************************************* * Copyright (C) 1995-2006, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #include "Riostream.h" #include "qevent.h" #include "qdialog.h" #include "qpushbutton.h" #include "qlabel.h" #include "qpainter.h" #if (QT_VERSION > 0x039999) // Added by cholm@nbi.dk - for Qt 4 # include "qmenu.h" # include "q3popupmenu.h" typedef Q3PopupMenu QPopupMenu; #else # include "qpopupmenu.h" #endif #include "TQCanvasMenu.h" #include "TClass.h" #include "TROOT.h" #include "TMethod.h" #include "TMethodCall.h" #include "TMethodArg.h" #include "TCanvas.h" #include "TDataType.h" #include "TQRootDialog.h" ClassImp(TQCanvasMenu) //______________________________________________________________________________ TQCanvasMenu::TQCanvasMenu(QWidget* parent, TCanvas *canvas) { // ctor, create the popup menu fc = canvas; fPopup = new QPopupMenu; fCurrObj = 0; fParent = parent; fTabWin = 0; fDialog = 0; fMousePosX = fMousePosY = 0; } //______________________________________________________________________________ TQCanvasMenu::TQCanvasMenu(QWidget* parent, QWidget *tabWin, TCanvas *canvas) { // ctor, create the popup menu fc = canvas; fPopup = new QPopupMenu; fParent = parent; fTabWin = tabWin; fCurrObj = 0; fDialog = 0; fMousePosX = fMousePosY = 0; } //______________________________________________________________________________ TQCanvasMenu::~TQCanvasMenu() { // dtor if (fPopup) delete fPopup; } //______________________________________________________________________________ char *TQCanvasMenu::CreateDialogTitle( TObject *object, TMethod *method ) { // Create title for dialog box retrieving argument values. static char methodTitle[128]; if (object && method) snprintf(methodTitle, 127, "%s::%s", object->ClassName(), method->GetName()); else *methodTitle = 0; return methodTitle; } //______________________________________________________________________________ char *TQCanvasMenu::CreateArgumentTitle(TMethodArg *argument) { // Create string describing argument (for use in dialog box). static Char_t argTitle[128]; if (argument) { snprintf(argTitle, 127, "(%s) %s", argument->GetTitle(), argument->GetName()); const char *arg_def = argument->GetDefault(); if (arg_def && *arg_def) { strncat(argTitle, " [default: ", 127 - strlen(argTitle)); strncat(argTitle, arg_def, 127 - strlen(argTitle)); strncat(argTitle, "]", 127 - strlen(argTitle)); } } else *argTitle = 0; return argTitle; } //______________________________________________________________________________ void TQCanvasMenu::Popup(TObject *obj, double x, double y, QMouseEvent *e) { // Perform the corresponding selected TObject popup // in the position defined // by x, y coordinates (in user coordinate system). // @param obj (TObject*) // @param p (QPoint&) TClass *klass=obj->IsA(); Int_t curId=-1; fCurrObj=obj; fPopup->clear(); fMethods.Clear(); QString buffer=klass->GetName(); buffer+="::"; buffer+=obj->GetName(); fPopup->insertItem(buffer, this, SLOT( Execute(int) ), 0,curId); curId++; klass->GetMenuItems(&fMethods); fPopup->insertSeparator(); TIter iter(&fMethods); TMethod *method=0; while ( (method = dynamic_cast<TMethod*>(iter())) != 0) { buffer=method->GetName(); fPopup->insertItem(buffer, this, SLOT( Execute(int) ), 0,curId); curId++; } // hold the position where the mouse was clicked fMousePosX= x; fMousePosY= y; // let Qt decide how to draw the popup Menu otherwise we have a problem that // the visible rectangle can get outside the screen (M.T. 03.06.02) fPopup->popup(e->globalPos(), 0); } //______________________________________________________________________________ void TQCanvasMenu::Execute(int id) { // Slot defined to execute a method from a selected TObject // using TObject::Execute() function. QString text=""; TVirtualPad *psave = gROOT->GetSelectedPad(); TMethod *method=(TMethod *)fMethods.At(id); fc->HandleInput(kButton3Up,gPad->XtoAbsPixel(fMousePosX), gPad->YtoAbsPixel(fMousePosY) ); if ( method->GetListOfMethodArgs()->First() ) { Dialog(fCurrObj,method); } else { gROOT->SetFromPopUp(kTRUE); fCurrObj->Execute((char *) method->GetName(), ""); } fc->GetPadSave()->Update(); fc->GetPadSave()->Modified(); gROOT->SetSelectedPad(psave); gROOT->GetSelectedPad()->Update(); gROOT->GetSelectedPad()->Modified(); fc->Modified(); fc->ForceUpdate(); gROOT->SetFromPopUp( kFALSE ); } //______________________________________________________________________________ void TQCanvasMenu::Dialog(TObject* object, TMethod* method) { // Create dialog object with OK and Cancel buttons. This dialog // prompts for the arguments of "method". if (!(object && method)) return; fDialog = new TQRootDialog(fParent,CreateDialogTitle(object, method),0,object ,method); fDialog->SetTCanvas(fc); // iterate through all arguments and create apropriate input-data objects: // inputlines, option menus... TMethodArg *argument = 0; TIter next(method->GetListOfMethodArgs()); while ((argument = (TMethodArg *) next())) { char *argname = CreateArgumentTitle(argument); const char *type = argument->GetTypeName(); TDataType *datatype = gROOT->GetType(type); const char *charstar = "char*"; char basictype [32]; if (datatype) { strlcpy(basictype, datatype->GetTypeName(),32); } else { if (strncmp(type, "enum", 4) != 0) cout << "*** Warning in Dialog(): data type is not basic type, assuming (int)\n"; strcpy(basictype, "int"); } if (strchr(argname, '*')) { strcat(basictype, "*"); type = charstar; } TDataMember *m = argument->GetDataMember(); if (m && m->GetterMethod()) { char gettername[256] = ""; strlcpy(gettername, m->GetterMethod()->GetMethodName(),256); m->GetterMethod()->Init(object->IsA(), gettername, ""); // Get the current value and form it as a text: char val[256]; if (!strncmp(basictype, "char*", 5)) { char *tdefval; m->GetterMethod()->Execute(object, "", &tdefval); strlcpy(val, tdefval, 256); } else if (!strncmp(basictype, "float", 5) || !strncmp(basictype, "double", 6)) { Double_t ddefval; m->GetterMethod()->Execute(object, "", ddefval); snprintf(val, 255, "%g", ddefval); } else if (!strncmp(basictype, "char", 4) || !strncmp(basictype, "int", 3) || !strncmp(basictype, "long", 4) || !strncmp(basictype, "short", 5)) { Long_t ldefval; m->GetterMethod()->Execute(object, "", ldefval); snprintf(val, 255, "%li", ldefval); } // Find out whether we have options ... TList *opt; if ((opt = m->GetOptions())) { cout << "*** Warning in Dialog(): option menu not yet implemented " << opt << endl; // should stop dialog return; } else { // we haven't got options - textfield ... fDialog->Add(argname, val, type); } } else { // if m not found ... char val[256] = ""; const char *tval = argument->GetDefault(); if (tval) strlcpy(val, tval, 256); fDialog->Add(argname, val, type); } } //end while fDialog->Popup(); } <commit_msg>Fix coverity reports #32499 & #32500 (uninitialized scalar variables)<commit_after>// @(#)root/qtgsi:$Id$ // Author: Denis Bertini, M. Al-Turany 01/11/2000 /************************************************************************* * Copyright (C) 1995-2006, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #include "Riostream.h" #include "qevent.h" #include "qdialog.h" #include "qpushbutton.h" #include "qlabel.h" #include "qpainter.h" #if (QT_VERSION > 0x039999) // Added by cholm@nbi.dk - for Qt 4 # include "qmenu.h" # include "q3popupmenu.h" typedef Q3PopupMenu QPopupMenu; #else # include "qpopupmenu.h" #endif #include "TQCanvasMenu.h" #include "TClass.h" #include "TROOT.h" #include "TMethod.h" #include "TMethodCall.h" #include "TMethodArg.h" #include "TCanvas.h" #include "TDataType.h" #include "TQRootDialog.h" ClassImp(TQCanvasMenu) //______________________________________________________________________________ TQCanvasMenu::TQCanvasMenu(QWidget* parent, TCanvas *canvas) { // ctor, create the popup menu fc = canvas; fPopup = new QPopupMenu; fCurrObj = 0; fParent = parent; fTabWin = 0; fDialog = 0; fMousePosX = fMousePosY = 0; } //______________________________________________________________________________ TQCanvasMenu::TQCanvasMenu(QWidget* parent, QWidget *tabWin, TCanvas *canvas) { // ctor, create the popup menu fc = canvas; fPopup = new QPopupMenu; fParent = parent; fTabWin = tabWin; fCurrObj = 0; fDialog = 0; fMousePosX = fMousePosY = 0; } //______________________________________________________________________________ TQCanvasMenu::~TQCanvasMenu() { // dtor if (fPopup) delete fPopup; } //______________________________________________________________________________ char *TQCanvasMenu::CreateDialogTitle( TObject *object, TMethod *method ) { // Create title for dialog box retrieving argument values. static char methodTitle[128]; if (object && method) snprintf(methodTitle, 127, "%s::%s", object->ClassName(), method->GetName()); else *methodTitle = 0; return methodTitle; } //______________________________________________________________________________ char *TQCanvasMenu::CreateArgumentTitle(TMethodArg *argument) { // Create string describing argument (for use in dialog box). static Char_t argTitle[128]; if (argument) { snprintf(argTitle, 127, "(%s) %s", argument->GetTitle(), argument->GetName()); const char *arg_def = argument->GetDefault(); if (arg_def && *arg_def) { strncat(argTitle, " [default: ", 127 - strlen(argTitle)); strncat(argTitle, arg_def, 127 - strlen(argTitle)); strncat(argTitle, "]", 127 - strlen(argTitle)); } } else *argTitle = 0; return argTitle; } //______________________________________________________________________________ void TQCanvasMenu::Popup(TObject *obj, double x, double y, QMouseEvent *e) { // Perform the corresponding selected TObject popup // in the position defined // by x, y coordinates (in user coordinate system). // @param obj (TObject*) // @param p (QPoint&) TClass *klass=obj->IsA(); Int_t curId=-1; fCurrObj=obj; fPopup->clear(); fMethods.Clear(); QString buffer=klass->GetName(); buffer+="::"; buffer+=obj->GetName(); fPopup->insertItem(buffer, this, SLOT( Execute(int) ), 0,curId); curId++; klass->GetMenuItems(&fMethods); fPopup->insertSeparator(); TIter iter(&fMethods); TMethod *method=0; while ( (method = dynamic_cast<TMethod*>(iter())) != 0) { buffer=method->GetName(); fPopup->insertItem(buffer, this, SLOT( Execute(int) ), 0,curId); curId++; } // hold the position where the mouse was clicked fMousePosX= x; fMousePosY= y; // let Qt decide how to draw the popup Menu otherwise we have a problem that // the visible rectangle can get outside the screen (M.T. 03.06.02) fPopup->popup(e->globalPos(), 0); } //______________________________________________________________________________ void TQCanvasMenu::Execute(int id) { // Slot defined to execute a method from a selected TObject // using TObject::Execute() function. QString text=""; TVirtualPad *psave = gROOT->GetSelectedPad(); TMethod *method=(TMethod *)fMethods.At(id); fc->HandleInput(kButton3Up,gPad->XtoAbsPixel(fMousePosX), gPad->YtoAbsPixel(fMousePosY) ); if ( method->GetListOfMethodArgs()->First() ) { Dialog(fCurrObj,method); } else { gROOT->SetFromPopUp(kTRUE); fCurrObj->Execute((char *) method->GetName(), ""); } fc->GetPadSave()->Update(); fc->GetPadSave()->Modified(); gROOT->SetSelectedPad(psave); gROOT->GetSelectedPad()->Update(); gROOT->GetSelectedPad()->Modified(); fc->Modified(); fc->ForceUpdate(); gROOT->SetFromPopUp( kFALSE ); } //______________________________________________________________________________ void TQCanvasMenu::Dialog(TObject* object, TMethod* method) { // Create dialog object with OK and Cancel buttons. This dialog // prompts for the arguments of "method". if (!(object && method)) return; fDialog = new TQRootDialog(fParent,CreateDialogTitle(object, method),0,object ,method); fDialog->SetTCanvas(fc); // iterate through all arguments and create apropriate input-data objects: // inputlines, option menus... TMethodArg *argument = 0; TIter next(method->GetListOfMethodArgs()); while ((argument = (TMethodArg *) next())) { char *argname = CreateArgumentTitle(argument); const char *type = argument->GetTypeName(); TDataType *datatype = gROOT->GetType(type); const char *charstar = "char*"; char basictype [32]; if (datatype) { strlcpy(basictype, datatype->GetTypeName(),32); } else { if (strncmp(type, "enum", 4) != 0) cout << "*** Warning in Dialog(): data type is not basic type, assuming (int)\n"; strcpy(basictype, "int"); } if (strchr(argname, '*')) { strcat(basictype, "*"); type = charstar; } TDataMember *m = argument->GetDataMember(); if (m && m->GetterMethod()) { char gettername[256] = ""; strlcpy(gettername, m->GetterMethod()->GetMethodName(),256); m->GetterMethod()->Init(object->IsA(), gettername, ""); // Get the current value and form it as a text: char val[256]; if (!strncmp(basictype, "char*", 5)) { char *tdefval; m->GetterMethod()->Execute(object, "", &tdefval); strlcpy(val, tdefval, 256); } else if (!strncmp(basictype, "float", 5) || !strncmp(basictype, "double", 6)) { Double_t ddefval = 0.0; m->GetterMethod()->Execute(object, "", ddefval); snprintf(val, 255, "%g", ddefval); } else if (!strncmp(basictype, "char", 4) || !strncmp(basictype, "int", 3) || !strncmp(basictype, "long", 4) || !strncmp(basictype, "short", 5)) { Long_t ldefval = 0L; m->GetterMethod()->Execute(object, "", ldefval); snprintf(val, 255, "%li", ldefval); } // Find out whether we have options ... TList *opt; if ((opt = m->GetOptions())) { cout << "*** Warning in Dialog(): option menu not yet implemented " << opt << endl; // should stop dialog return; } else { // we haven't got options - textfield ... fDialog->Add(argname, val, type); } } else { // if m not found ... char val[256] = ""; const char *tval = argument->GetDefault(); if (tval) strlcpy(val, tval, 256); fDialog->Add(argname, val, type); } } //end while fDialog->Popup(); } <|endoftext|>
<commit_before>#define CATCH_CONFIG_MAIN #include <catch2/catch.hpp> #include "types.hpp" TEST_CASE("sizeof") { REQUIRE(sizeof(krbn::absolute_time_point) == 8); REQUIRE(sizeof(krbn::vendor_id) == 4); REQUIRE(sizeof(krbn::product_id) == 4); REQUIRE(sizeof(krbn::location_id) == 4); } TEST_CASE("absolute_time_point") { krbn::absolute_time_point t1(1000); krbn::absolute_time_point t2(2000); { auto d = t2 - t1; REQUIRE(d == krbn::absolute_time_duration(1000)); } { auto d = t1 - t2; REQUIRE(d == krbn::absolute_time_duration(-1000)); } { auto t = t1 + krbn::absolute_time_duration(100); REQUIRE(t == krbn::absolute_time_point(1100)); } { auto t = t1 - krbn::absolute_time_duration(100); REQUIRE(t == krbn::absolute_time_point(900)); } { auto t = t1; t += krbn::absolute_time_duration(100); REQUIRE(t == krbn::absolute_time_point(1100)); } { auto t = t1; t -= krbn::absolute_time_duration(100); REQUIRE(t == krbn::absolute_time_point(900)); } } TEST_CASE("operation_type") { krbn::operation_type_connect_console_user_server_struct s; std::vector<uint8_t> buffer(sizeof(s)); memcpy(&(buffer[0]), &s, sizeof(s)); REQUIRE(krbn::types::find_operation_type(buffer) == krbn::operation_type::connect_console_user_server); } TEST_CASE("grabbable_state") { { krbn::grabbable_state grabbable_state; REQUIRE(grabbable_state.get_device_id() == krbn::device_id(0)); REQUIRE(grabbable_state.get_state() == krbn::grabbable_state::state::grabbable); REQUIRE(grabbable_state.get_ungrabbable_temporarily_reason() == krbn::grabbable_state::ungrabbable_temporarily_reason::none); REQUIRE(grabbable_state.get_time_stamp() == krbn::absolute_time_point(0)); } { krbn::grabbable_state grabbable_state(krbn::device_id(1234), krbn::grabbable_state::state::ungrabbable_temporarily, krbn::grabbable_state::ungrabbable_temporarily_reason::key_repeating, krbn::absolute_time_point(1000)); REQUIRE(grabbable_state.get_device_id() == krbn::device_id(1234)); REQUIRE(grabbable_state.get_state() == krbn::grabbable_state::state::ungrabbable_temporarily); REQUIRE(grabbable_state.get_ungrabbable_temporarily_reason() == krbn::grabbable_state::ungrabbable_temporarily_reason::key_repeating); REQUIRE(grabbable_state.get_time_stamp() == krbn::absolute_time_point(1000)); } } TEST_CASE("grabbable_state::equals_except_time_stamp") { { krbn::grabbable_state grabbable_state1(krbn::device_id(1234), krbn::grabbable_state::state::ungrabbable_temporarily, krbn::grabbable_state::ungrabbable_temporarily_reason::key_repeating, krbn::absolute_time_point(1000)); krbn::grabbable_state grabbable_state2(krbn::device_id(1234), krbn::grabbable_state::state::ungrabbable_temporarily, krbn::grabbable_state::ungrabbable_temporarily_reason::key_repeating, krbn::absolute_time_point(2000)); krbn::grabbable_state grabbable_state3(krbn::device_id(1234), krbn::grabbable_state::state::device_error, krbn::grabbable_state::ungrabbable_temporarily_reason::none, krbn::absolute_time_point(3000)); REQUIRE(grabbable_state1 != grabbable_state2); REQUIRE(grabbable_state1.equals_except_time_stamp(grabbable_state2)); REQUIRE(!grabbable_state1.equals_except_time_stamp(grabbable_state3)); } } TEST_CASE("make_key_code") { REQUIRE(krbn::types::make_key_code("spacebar") == krbn::key_code::spacebar); REQUIRE(krbn::types::make_key_code("unknown") == std::nullopt); REQUIRE(krbn::types::make_key_code_name(krbn::key_code::spacebar) == std::string("spacebar")); REQUIRE(krbn::types::make_key_code_name(krbn::key_code::left_option) == std::string("left_alt")); { auto actual = krbn::types::make_key_code(krbn::hid_usage_page(kHIDPage_KeyboardOrKeypad), krbn::hid_usage(kHIDUsage_KeyboardTab)); REQUIRE(*actual == krbn::key_code(kHIDUsage_KeyboardTab)); } { auto actual = krbn::types::make_key_code(krbn::hid_usage_page(krbn::kHIDPage_AppleVendorTopCase), krbn::hid_usage(krbn::kHIDUsage_AV_TopCase_KeyboardFn)); REQUIRE(*actual == krbn::key_code::fn); } { auto actual = krbn::types::make_key_code(krbn::hid_usage_page(krbn::kHIDPage_AppleVendorKeyboard), krbn::hid_usage(krbn::kHIDUsage_AppleVendorKeyboard_Function)); REQUIRE(*actual == krbn::key_code::fn); } { auto actual = krbn::types::make_key_code(krbn::hid_usage_page(kHIDPage_Button), krbn::hid_usage(1)); REQUIRE(actual == std::nullopt); } } TEST_CASE("make_key_code (modifier_flag)") { REQUIRE(krbn::types::make_key_code(krbn::modifier_flag::zero) == std::nullopt); REQUIRE(krbn::types::make_key_code(krbn::modifier_flag::caps_lock) == krbn::key_code::caps_lock); REQUIRE(krbn::types::make_key_code(krbn::modifier_flag::left_control) == krbn::key_code::left_control); REQUIRE(krbn::types::make_key_code(krbn::modifier_flag::left_shift) == krbn::key_code::left_shift); REQUIRE(krbn::types::make_key_code(krbn::modifier_flag::left_option) == krbn::key_code::left_option); REQUIRE(krbn::types::make_key_code(krbn::modifier_flag::left_command) == krbn::key_code::left_command); REQUIRE(krbn::types::make_key_code(krbn::modifier_flag::right_control) == krbn::key_code::right_control); REQUIRE(krbn::types::make_key_code(krbn::modifier_flag::right_shift) == krbn::key_code::right_shift); REQUIRE(krbn::types::make_key_code(krbn::modifier_flag::right_option) == krbn::key_code::right_option); REQUIRE(krbn::types::make_key_code(krbn::modifier_flag::right_command) == krbn::key_code::right_command); REQUIRE(krbn::types::make_key_code(krbn::modifier_flag::fn) == krbn::key_code::fn); REQUIRE(krbn::types::make_key_code(krbn::modifier_flag::end_) == std::nullopt); } TEST_CASE("make_modifier_flag") { REQUIRE(krbn::types::make_modifier_flag(krbn::key_code::caps_lock) == std::nullopt); REQUIRE(krbn::types::make_modifier_flag(krbn::key_code::left_control) == krbn::modifier_flag::left_control); REQUIRE(krbn::types::make_modifier_flag(krbn::key_code::left_shift) == krbn::modifier_flag::left_shift); REQUIRE(krbn::types::make_modifier_flag(krbn::key_code::left_option) == krbn::modifier_flag::left_option); REQUIRE(krbn::types::make_modifier_flag(krbn::key_code::left_command) == krbn::modifier_flag::left_command); REQUIRE(krbn::types::make_modifier_flag(krbn::key_code::right_control) == krbn::modifier_flag::right_control); REQUIRE(krbn::types::make_modifier_flag(krbn::key_code::right_shift) == krbn::modifier_flag::right_shift); REQUIRE(krbn::types::make_modifier_flag(krbn::key_code::right_option) == krbn::modifier_flag::right_option); REQUIRE(krbn::types::make_modifier_flag(krbn::key_code::right_command) == krbn::modifier_flag::right_command); REQUIRE(krbn::types::make_modifier_flag(krbn::key_code::fn) == krbn::modifier_flag::fn); REQUIRE(krbn::types::make_modifier_flag(krbn::hid_usage_page::keyboard_or_keypad, krbn::hid_usage(kHIDUsage_KeyboardA)) == std::nullopt); REQUIRE(krbn::types::make_modifier_flag(krbn::hid_usage_page::keyboard_or_keypad, krbn::hid_usage(kHIDUsage_KeyboardErrorRollOver)) == std::nullopt); REQUIRE(krbn::types::make_modifier_flag(krbn::hid_usage_page::keyboard_or_keypad, krbn::hid_usage(kHIDUsage_KeyboardLeftShift)) == krbn::modifier_flag::left_shift); REQUIRE(krbn::types::make_modifier_flag(krbn::hid_usage_page::button, krbn::hid_usage(1)) == std::nullopt); } TEST_CASE("make_consumer_key_code") { REQUIRE(krbn::types::make_consumer_key_code("mute") == krbn::consumer_key_code::mute); REQUIRE(!krbn::types::make_consumer_key_code("unknown")); REQUIRE(krbn::types::make_consumer_key_code_name(krbn::consumer_key_code::mute) == std::string("mute")); REQUIRE(krbn::types::make_consumer_key_code(krbn::hid_usage_page::consumer, krbn::hid_usage::csmr_mute) == krbn::consumer_key_code::mute); REQUIRE(!krbn::types::make_consumer_key_code(krbn::hid_usage_page::keyboard_or_keypad, krbn::hid_usage(kHIDUsage_KeyboardA))); REQUIRE(krbn::types::make_hid_usage_page(krbn::consumer_key_code::mute) == krbn::hid_usage_page::consumer); REQUIRE(krbn::types::make_hid_usage(krbn::consumer_key_code::mute) == krbn::hid_usage::csmr_mute); } TEST_CASE("make_pointing_button") { REQUIRE(krbn::types::make_pointing_button("button1") == krbn::pointing_button::button1); REQUIRE(!krbn::types::make_pointing_button("unknown")); REQUIRE(krbn::types::make_pointing_button_name(krbn::pointing_button::button1) == std::string("button1")); { auto actual = krbn::types::make_pointing_button(krbn::hid_usage_page(kHIDPage_Button), krbn::hid_usage(1)); REQUIRE(*actual == krbn::pointing_button::button1); } { auto actual = krbn::types::make_pointing_button(krbn::hid_usage_page(kHIDPage_KeyboardOrKeypad), krbn::hid_usage(kHIDUsage_KeyboardTab)); REQUIRE(actual == std::nullopt); } } <commit_msg>update tests<commit_after>#define CATCH_CONFIG_MAIN #include <catch2/catch.hpp> #include "types.hpp" TEST_CASE("sizeof") { REQUIRE(sizeof(krbn::vendor_id) == 4); REQUIRE(sizeof(krbn::product_id) == 4); REQUIRE(sizeof(krbn::location_id) == 4); } TEST_CASE("operation_type") { krbn::operation_type_connect_console_user_server_struct s; std::vector<uint8_t> buffer(sizeof(s)); memcpy(&(buffer[0]), &s, sizeof(s)); REQUIRE(krbn::types::find_operation_type(buffer) == krbn::operation_type::connect_console_user_server); } TEST_CASE("grabbable_state") { { krbn::grabbable_state grabbable_state; REQUIRE(grabbable_state.get_device_id() == krbn::device_id(0)); REQUIRE(grabbable_state.get_state() == krbn::grabbable_state::state::grabbable); REQUIRE(grabbable_state.get_ungrabbable_temporarily_reason() == krbn::grabbable_state::ungrabbable_temporarily_reason::none); REQUIRE(grabbable_state.get_time_stamp() == krbn::absolute_time_point(0)); } { krbn::grabbable_state grabbable_state(krbn::device_id(1234), krbn::grabbable_state::state::ungrabbable_temporarily, krbn::grabbable_state::ungrabbable_temporarily_reason::key_repeating, krbn::absolute_time_point(1000)); REQUIRE(grabbable_state.get_device_id() == krbn::device_id(1234)); REQUIRE(grabbable_state.get_state() == krbn::grabbable_state::state::ungrabbable_temporarily); REQUIRE(grabbable_state.get_ungrabbable_temporarily_reason() == krbn::grabbable_state::ungrabbable_temporarily_reason::key_repeating); REQUIRE(grabbable_state.get_time_stamp() == krbn::absolute_time_point(1000)); } } TEST_CASE("grabbable_state::equals_except_time_stamp") { { krbn::grabbable_state grabbable_state1(krbn::device_id(1234), krbn::grabbable_state::state::ungrabbable_temporarily, krbn::grabbable_state::ungrabbable_temporarily_reason::key_repeating, krbn::absolute_time_point(1000)); krbn::grabbable_state grabbable_state2(krbn::device_id(1234), krbn::grabbable_state::state::ungrabbable_temporarily, krbn::grabbable_state::ungrabbable_temporarily_reason::key_repeating, krbn::absolute_time_point(2000)); krbn::grabbable_state grabbable_state3(krbn::device_id(1234), krbn::grabbable_state::state::device_error, krbn::grabbable_state::ungrabbable_temporarily_reason::none, krbn::absolute_time_point(3000)); REQUIRE(grabbable_state1 != grabbable_state2); REQUIRE(grabbable_state1.equals_except_time_stamp(grabbable_state2)); REQUIRE(!grabbable_state1.equals_except_time_stamp(grabbable_state3)); } } TEST_CASE("make_key_code") { REQUIRE(krbn::types::make_key_code("spacebar") == krbn::key_code::spacebar); REQUIRE(krbn::types::make_key_code("unknown") == std::nullopt); REQUIRE(krbn::types::make_key_code_name(krbn::key_code::spacebar) == std::string("spacebar")); REQUIRE(krbn::types::make_key_code_name(krbn::key_code::left_option) == std::string("left_alt")); { auto actual = krbn::types::make_key_code(krbn::hid_usage_page(kHIDPage_KeyboardOrKeypad), krbn::hid_usage(kHIDUsage_KeyboardTab)); REQUIRE(*actual == krbn::key_code(kHIDUsage_KeyboardTab)); } { auto actual = krbn::types::make_key_code(krbn::hid_usage_page(krbn::kHIDPage_AppleVendorTopCase), krbn::hid_usage(krbn::kHIDUsage_AV_TopCase_KeyboardFn)); REQUIRE(*actual == krbn::key_code::fn); } { auto actual = krbn::types::make_key_code(krbn::hid_usage_page(krbn::kHIDPage_AppleVendorKeyboard), krbn::hid_usage(krbn::kHIDUsage_AppleVendorKeyboard_Function)); REQUIRE(*actual == krbn::key_code::fn); } { auto actual = krbn::types::make_key_code(krbn::hid_usage_page(kHIDPage_Button), krbn::hid_usage(1)); REQUIRE(actual == std::nullopt); } } TEST_CASE("make_key_code (modifier_flag)") { REQUIRE(krbn::types::make_key_code(krbn::modifier_flag::zero) == std::nullopt); REQUIRE(krbn::types::make_key_code(krbn::modifier_flag::caps_lock) == krbn::key_code::caps_lock); REQUIRE(krbn::types::make_key_code(krbn::modifier_flag::left_control) == krbn::key_code::left_control); REQUIRE(krbn::types::make_key_code(krbn::modifier_flag::left_shift) == krbn::key_code::left_shift); REQUIRE(krbn::types::make_key_code(krbn::modifier_flag::left_option) == krbn::key_code::left_option); REQUIRE(krbn::types::make_key_code(krbn::modifier_flag::left_command) == krbn::key_code::left_command); REQUIRE(krbn::types::make_key_code(krbn::modifier_flag::right_control) == krbn::key_code::right_control); REQUIRE(krbn::types::make_key_code(krbn::modifier_flag::right_shift) == krbn::key_code::right_shift); REQUIRE(krbn::types::make_key_code(krbn::modifier_flag::right_option) == krbn::key_code::right_option); REQUIRE(krbn::types::make_key_code(krbn::modifier_flag::right_command) == krbn::key_code::right_command); REQUIRE(krbn::types::make_key_code(krbn::modifier_flag::fn) == krbn::key_code::fn); REQUIRE(krbn::types::make_key_code(krbn::modifier_flag::end_) == std::nullopt); } TEST_CASE("make_modifier_flag") { REQUIRE(krbn::types::make_modifier_flag(krbn::key_code::caps_lock) == std::nullopt); REQUIRE(krbn::types::make_modifier_flag(krbn::key_code::left_control) == krbn::modifier_flag::left_control); REQUIRE(krbn::types::make_modifier_flag(krbn::key_code::left_shift) == krbn::modifier_flag::left_shift); REQUIRE(krbn::types::make_modifier_flag(krbn::key_code::left_option) == krbn::modifier_flag::left_option); REQUIRE(krbn::types::make_modifier_flag(krbn::key_code::left_command) == krbn::modifier_flag::left_command); REQUIRE(krbn::types::make_modifier_flag(krbn::key_code::right_control) == krbn::modifier_flag::right_control); REQUIRE(krbn::types::make_modifier_flag(krbn::key_code::right_shift) == krbn::modifier_flag::right_shift); REQUIRE(krbn::types::make_modifier_flag(krbn::key_code::right_option) == krbn::modifier_flag::right_option); REQUIRE(krbn::types::make_modifier_flag(krbn::key_code::right_command) == krbn::modifier_flag::right_command); REQUIRE(krbn::types::make_modifier_flag(krbn::key_code::fn) == krbn::modifier_flag::fn); REQUIRE(krbn::types::make_modifier_flag(krbn::hid_usage_page::keyboard_or_keypad, krbn::hid_usage(kHIDUsage_KeyboardA)) == std::nullopt); REQUIRE(krbn::types::make_modifier_flag(krbn::hid_usage_page::keyboard_or_keypad, krbn::hid_usage(kHIDUsage_KeyboardErrorRollOver)) == std::nullopt); REQUIRE(krbn::types::make_modifier_flag(krbn::hid_usage_page::keyboard_or_keypad, krbn::hid_usage(kHIDUsage_KeyboardLeftShift)) == krbn::modifier_flag::left_shift); REQUIRE(krbn::types::make_modifier_flag(krbn::hid_usage_page::button, krbn::hid_usage(1)) == std::nullopt); } TEST_CASE("make_consumer_key_code") { REQUIRE(krbn::types::make_consumer_key_code("mute") == krbn::consumer_key_code::mute); REQUIRE(!krbn::types::make_consumer_key_code("unknown")); REQUIRE(krbn::types::make_consumer_key_code_name(krbn::consumer_key_code::mute) == std::string("mute")); REQUIRE(krbn::types::make_consumer_key_code(krbn::hid_usage_page::consumer, krbn::hid_usage::csmr_mute) == krbn::consumer_key_code::mute); REQUIRE(!krbn::types::make_consumer_key_code(krbn::hid_usage_page::keyboard_or_keypad, krbn::hid_usage(kHIDUsage_KeyboardA))); REQUIRE(krbn::types::make_hid_usage_page(krbn::consumer_key_code::mute) == krbn::hid_usage_page::consumer); REQUIRE(krbn::types::make_hid_usage(krbn::consumer_key_code::mute) == krbn::hid_usage::csmr_mute); } TEST_CASE("make_pointing_button") { REQUIRE(krbn::types::make_pointing_button("button1") == krbn::pointing_button::button1); REQUIRE(!krbn::types::make_pointing_button("unknown")); REQUIRE(krbn::types::make_pointing_button_name(krbn::pointing_button::button1) == std::string("button1")); { auto actual = krbn::types::make_pointing_button(krbn::hid_usage_page(kHIDPage_Button), krbn::hid_usage(1)); REQUIRE(*actual == krbn::pointing_button::button1); } { auto actual = krbn::types::make_pointing_button(krbn::hid_usage_page(kHIDPage_KeyboardOrKeypad), krbn::hid_usage(kHIDUsage_KeyboardTab)); REQUIRE(actual == std::nullopt); } } <|endoftext|>
<commit_before>/** @file A brief file description @section license License Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /*************************** -*- Mod: C++ -*- ****************************** SslConfig.cc Created On : 07/20/2000 Description: SSL Configurations ****************************************************************************/ #include "libts.h" #include "I_Layout.h" #include <string.h> #include "P_Net.h" #include <openssl/ssl.h> int SslConfig::id = 0; bool SslConfig::serverSSLTermination = 0; SslConfig sslTerminationConfig; #ifndef USE_CONFIG_PROCESSOR SslConfigParams *SslConfig::ssl_config_params; #endif SslConfigParams::SslConfigParams() { serverCertPath = serverCertPathOnly = serverCertChainPath = serverKeyPath = configFilePath = CACertFilename = CACertPath = clientCertPath = clientKeyPath = clientCACertFilename = clientCACertPath = cipherSuite = serverKeyPathOnly = NULL; clientCertLevel = client_verify_depth = verify_depth = clientVerify = 0; ssl_accept_port_number = 443; termMode = SSL_TERM_MODE_NONE; ssl_ctx_options = 0; ssl_session_cache = SSL_SESSION_CACHE_MODE_SERVER; ssl_session_cache_size = 1024*20; } SslConfigParams::~SslConfigParams() { cleanup(); } void SslConfigParams::cleanup() { if (serverCertPath) { ats_free(serverCertPath); serverCertPath = NULL; } if (serverCertChainPath) { ats_free(serverCertChainPath); serverCertChainPath = NULL; } if (serverKeyPath) { ats_free(serverKeyPath); serverKeyPath = NULL; } if (CACertFilename) { ats_free(CACertFilename); CACertFilename = NULL; } if (CACertPath) { ats_free(CACertPath); CACertPath = NULL; } if (clientCertPath) { ats_free(clientCertPath); clientCertPath = NULL; } if (clientKeyPath) { ats_free(clientKeyPath); clientKeyPath = NULL; } if (clientCACertFilename) { ats_free(clientCACertFilename); clientCACertFilename = NULL; } if (clientCACertPath) { ats_free(clientCACertPath); clientCACertPath = NULL; } if (configFilePath) { ats_free(configFilePath); configFilePath = NULL; } if (serverCertPathOnly) { ats_free(serverCertPathOnly); serverCertPathOnly = NULL; } if (serverKeyPathOnly) { ats_free(serverKeyPathOnly); serverKeyPathOnly = NULL; } if (cipherSuite) { ats_free(cipherSuite); cipherSuite = NULL; } clientCertLevel = client_verify_depth = verify_depth = clientVerify = 0; ssl_accept_port_number = -1; termMode = SSL_TERM_MODE_NONE; } // XXX: Add handling for Windows? // If path is *not* absolute, consider it relative to PREFIX // if it's empty, just take SYSCONFDIR, otherwise we can take it as-is static void set_paths_helper(const char *path, const char *filename, char **final_path, char **final_filename) { if (final_path != NULL) { if (path && path[0] != '/') { *final_path = Layout::get()->relative_to(Layout::get()->prefix, path); } else if (!path || path[0] == '\0'){ *final_path = ats_strdup(Layout::get()->sysconfdir); } else { *final_path = ats_strdup(path); } } if (filename) { *final_filename = ats_strdup(Layout::get()->relative_to(path, filename)); } else { *final_filename = NULL; } #ifdef _WIN32 i = 0; while (final_path[i] != 0) { if (final_path[i] == '/') final_path[i] = '\\'; i++; } i = 0; while (final_filename[i] != 0) { if (final_filename[i] == '/') final_filename[i] = '\\'; i++; } #endif } void SslConfigParams::initialize() { char serverCertFilename[PATH_NAME_MAX] = ""; char serverCertRelativePath[PATH_NAME_MAX] = ""; char *ssl_server_private_key_filename = NULL; char *ssl_server_private_key_path = NULL; char *CACertRelativePath = NULL; char *ssl_client_cert_filename = NULL; char *ssl_client_cert_path = NULL; char *ssl_client_private_key_filename = NULL; char *ssl_client_private_key_path = NULL; char *clientCACertRelativePath = NULL; char *multicert_config_file = NULL; int ssl_mode = SSL_TERM_MODE_NONE; #ifdef _WIN32 int i; #endif cleanup(); //+++++++++++++++++++++++++ Server part +++++++++++++++++++++++++++++++++ verify_depth = 7; IOCORE_ReadConfigInteger(ssl_mode, "proxy.config.ssl.enabled"); ssl_mode &= SSL_TERM_MODE_BOTH; termMode = (SSL_TERMINATION_MODE) ssl_mode; IOCORE_ReadConfigInt32(ssl_accept_port_number, "proxy.config.ssl.server_port"); IOCORE_ReadConfigInt32(clientCertLevel, "proxy.config.ssl.client.certification_level"); IOCORE_ReadConfigStringAlloc(cipherSuite, "proxy.config.ssl.server.cipher_suite"); int options; IOCORE_ReadConfigInteger(options, "proxy.config.ssl.SSLv2"); if (!options) ssl_ctx_options |= SSL_OP_NO_SSLv2; IOCORE_ReadConfigInteger(options, "proxy.config.ssl.SSLv3"); if (!options) ssl_ctx_options |= SSL_OP_NO_SSLv3; IOCORE_ReadConfigInteger(options, "proxy.config.ssl.TLSv1"); if (!options) ssl_ctx_options |= SSL_OP_NO_TLSv1; #ifdef SSL_OP_CIPHER_SERVER_PREFERENCE IOCORE_ReadConfigInteger(options, "proxy.config.ssl.server.honor_cipher_order"); if (!options) ssl_ctx_options |= SSL_OP_CIPHER_SERVER_PREFERENCE; #endif #ifdef SSL_OP_NO_COMPRESSION IOCORE_ReadConfigInteger(options, "proxy.config.ssl.compression"); if (!options) ssl_ctx_options |= SSL_OP_NO_COMPRESSION; #endif IOCORE_ReadConfigString(serverCertFilename, "proxy.config.ssl.server.cert.filename", PATH_NAME_MAX); IOCORE_ReadConfigString(serverCertRelativePath, "proxy.config.ssl.server.cert.path", PATH_NAME_MAX); set_paths_helper(serverCertRelativePath, serverCertFilename, &serverCertPathOnly, &serverCertPath); char *cert_chain = NULL; IOCORE_ReadConfigStringAlloc(cert_chain, "proxy.config.ssl.server.cert_chain.filename"); set_paths_helper(serverCertRelativePath, cert_chain, &serverCertPathOnly, &serverCertChainPath); ats_free(cert_chain); IOCORE_ReadConfigStringAlloc(multicert_config_file, "proxy.config.ssl.server.multicert.filename"); set_paths_helper(Layout::get()->sysconfdir, multicert_config_file, NULL, &configFilePath); ats_free(multicert_config_file); IOCORE_ReadConfigStringAlloc(ssl_server_private_key_filename, "proxy.config.ssl.server.private_key.filename"); IOCORE_ReadConfigStringAlloc(ssl_server_private_key_path, "proxy.config.ssl.server.private_key.path"); set_paths_helper(ssl_server_private_key_path, ssl_server_private_key_filename, &serverKeyPathOnly, &serverKeyPath); ats_free(ssl_server_private_key_filename); ats_free(ssl_server_private_key_path); IOCORE_ReadConfigStringAlloc(CACertFilename, "proxy.config.ssl.CA.cert.filename"); IOCORE_ReadConfigStringAlloc(CACertRelativePath, "proxy.config.ssl.CA.cert.path"); set_paths_helper(CACertRelativePath, CACertFilename, &CACertPath, &CACertFilename); ats_free(CACertRelativePath); // SSL session cache configurations IOCORE_ReadConfigInteger(ssl_session_cache, "proxy.config.ssl.session_cache"); IOCORE_ReadConfigInteger(ssl_session_cache_size, "proxy.config.ssl.session_cache.size"); // ++++++++++++++++++++++++ Client part ++++++++++++++++++++ client_verify_depth = 7; IOCORE_ReadConfigInt32(clientVerify, "proxy.config.ssl.client.verify.server"); ssl_client_cert_filename = NULL; ssl_client_cert_path = NULL; IOCORE_ReadConfigStringAlloc(ssl_client_cert_filename, "proxy.config.ssl.client.cert.filename"); IOCORE_ReadConfigStringAlloc(ssl_client_cert_path, "proxy.config.ssl.client.cert.path"); if (ssl_client_cert_path == NULL) { ssl_client_cert_path = ats_strdup(Layout::get()->sysconfdir); } if (ssl_client_cert_filename != NULL) { char *abs_path = Layout::get()->relative_to(Layout::get()->sysconfdir, ssl_client_cert_path); clientCertPath = Layout::get()->Layout::relative_to(abs_path, ssl_client_cert_filename); #ifdef _WIN32 i = 0; while (clientCertPath[i] != 0) { if (clientCertPath[i] == '/') clientCertPath[i] = '\\'; i++; } #endif ats_free(abs_path); ats_free(ssl_client_cert_filename); } ats_free(ssl_client_cert_path); ssl_client_cert_filename = NULL; ssl_client_cert_path = NULL; IOCORE_ReadConfigStringAlloc(ssl_client_private_key_filename, "proxy.config.ssl.client.private_key.filename"); IOCORE_ReadConfigStringAlloc(ssl_client_private_key_path, "proxy.config.ssl.client.private_key.path"); if (ssl_client_private_key_path == NULL) { ssl_client_private_key_path = ats_strdup(Layout::get()->sysconfdir); } if (ssl_client_private_key_filename != NULL) { char *abs_path = Layout::get()->relative_to(Layout::get()->sysconfdir, ssl_client_private_key_path); clientCertPath = Layout::get()->Layout::relative_to(abs_path, ssl_client_private_key_filename); #ifdef _WIN32 i = 0; while (clientKeyPath[i] != 0) { if (clientKeyPath[i] == '/') clientKeyPath[i] = '\\'; i++; } #endif ats_free(abs_path); ats_free(ssl_client_private_key_filename); } ats_free(ssl_client_private_key_path); ssl_client_private_key_path = NULL; IOCORE_ReadConfigStringAlloc(clientCACertFilename, "proxy.config.ssl.client.CA.cert.filename"); if (clientCACertFilename && (*clientCACertFilename == 0)) { ats_free(clientCACertFilename); clientCACertFilename = NULL; } IOCORE_ReadConfigStringAlloc(clientCACertRelativePath, "proxy.config.ssl.client.CA.cert.path"); // Notice that we don't put the filename at the // end of this path. Its a quirk of the SSL lib interface. if (clientCACertRelativePath != NULL) { clientCACertPath = Layout::get()->relative_to(Layout::get()->sysconfdir, clientCACertRelativePath); #ifdef _WIN32 i = 0; while (clientCACertPath[i] != 0) { if (clientCACertPath[i] == '/') clientCACertPath[i] = '\\'; i++; } #endif ats_free(clientCACertRelativePath); } } void SslConfig::startup() { reconfigure(); } void SslConfig::reconfigure() { SslConfigParams *params; params = NEW(new SslConfigParams); params->initialize(); // re-read configuration #ifdef USE_CONFIG_PROCESSOR id = configProcessor.set(id, params); #else ssl_config_params = params; #endif serverSSLTermination = (params->termMode & SslConfigParams::SSL_TERM_MODE_SERVER) != 0; } SslConfigParams * SslConfig::acquire() { #ifndef USE_CONFIG_PROCESSOR return ssl_config_params; #else return ((SslConfigParams *) configProcessor.get(id)); #endif } void SslConfig::release(SslConfigParams * params) { (void) params; #ifdef USE_CONFIG_PROCESSOR configProcessor.release(id, params); #endif } <commit_msg>More cleanup re TS-944. All paths are now handled with set_paths_helper()<commit_after>/** @file A brief file description @section license License Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /*************************** -*- Mod: C++ -*- ****************************** SslConfig.cc Created On : 07/20/2000 Description: SSL Configurations ****************************************************************************/ #include "libts.h" #include "I_Layout.h" #include <string.h> #include "P_Net.h" #include <openssl/ssl.h> int SslConfig::id = 0; bool SslConfig::serverSSLTermination = 0; SslConfig sslTerminationConfig; #ifndef USE_CONFIG_PROCESSOR SslConfigParams *SslConfig::ssl_config_params; #endif SslConfigParams::SslConfigParams() { serverCertPath = serverCertPathOnly = serverCertChainPath = serverKeyPath = configFilePath = CACertFilename = CACertPath = clientCertPath = clientKeyPath = clientCACertFilename = clientCACertPath = cipherSuite = serverKeyPathOnly = NULL; clientCertLevel = client_verify_depth = verify_depth = clientVerify = 0; ssl_accept_port_number = 443; termMode = SSL_TERM_MODE_NONE; ssl_ctx_options = 0; ssl_session_cache = SSL_SESSION_CACHE_MODE_SERVER; ssl_session_cache_size = 1024*20; } SslConfigParams::~SslConfigParams() { cleanup(); } void SslConfigParams::cleanup() { if (serverCertPath) { ats_free(serverCertPath); serverCertPath = NULL; } if (serverCertChainPath) { ats_free(serverCertChainPath); serverCertChainPath = NULL; } if (serverKeyPath) { ats_free(serverKeyPath); serverKeyPath = NULL; } if (CACertFilename) { ats_free(CACertFilename); CACertFilename = NULL; } if (CACertPath) { ats_free(CACertPath); CACertPath = NULL; } if (clientCertPath) { ats_free(clientCertPath); clientCertPath = NULL; } if (clientKeyPath) { ats_free(clientKeyPath); clientKeyPath = NULL; } if (clientCACertFilename) { ats_free(clientCACertFilename); clientCACertFilename = NULL; } if (clientCACertPath) { ats_free(clientCACertPath); clientCACertPath = NULL; } if (configFilePath) { ats_free(configFilePath); configFilePath = NULL; } if (serverCertPathOnly) { ats_free(serverCertPathOnly); serverCertPathOnly = NULL; } if (serverKeyPathOnly) { ats_free(serverKeyPathOnly); serverKeyPathOnly = NULL; } if (cipherSuite) { ats_free(cipherSuite); cipherSuite = NULL; } clientCertLevel = client_verify_depth = verify_depth = clientVerify = 0; ssl_accept_port_number = -1; termMode = SSL_TERM_MODE_NONE; } /** set_paths_helper If path is *not* absolute, consider it relative to PREFIX if it's empty, just take SYSCONFDIR, otherwise we can take it as-is if final_path is NULL, it will not be updated. XXX: Add handling for Windows? */ static void set_paths_helper(const char *path, const char *filename, char **final_path, char **final_filename) { if (final_path != NULL) { if (path && path[0] != '/') { *final_path = Layout::get()->relative_to(Layout::get()->prefix, path); } else if (!path || path[0] == '\0'){ *final_path = ats_strdup(Layout::get()->sysconfdir); } else { *final_path = ats_strdup(path); } } if (filename) { *final_filename = ats_strdup(Layout::get()->relative_to(path, filename)); } else { *final_filename = NULL; } #ifdef _WIN32 i = 0; while (final_path[i] != 0) { if (final_path[i] == '/') final_path[i] = '\\'; i++; } i = 0; while (final_filename[i] != 0) { if (final_filename[i] == '/') final_filename[i] = '\\'; i++; } #endif } void SslConfigParams::initialize() { char serverCertFilename[PATH_NAME_MAX] = ""; char serverCertRelativePath[PATH_NAME_MAX] = ""; char *ssl_server_private_key_filename = NULL; char *ssl_server_private_key_path = NULL; char *CACertRelativePath = NULL; char *ssl_client_cert_filename = NULL; char *ssl_client_cert_path = NULL; char *ssl_client_private_key_filename = NULL; char *ssl_client_private_key_path = NULL; char *clientCACertRelativePath = NULL; char *multicert_config_file = NULL; int ssl_mode = SSL_TERM_MODE_NONE; cleanup(); //+++++++++++++++++++++++++ Server part +++++++++++++++++++++++++++++++++ verify_depth = 7; IOCORE_ReadConfigInteger(ssl_mode, "proxy.config.ssl.enabled"); ssl_mode &= SSL_TERM_MODE_BOTH; termMode = (SSL_TERMINATION_MODE) ssl_mode; IOCORE_ReadConfigInt32(ssl_accept_port_number, "proxy.config.ssl.server_port"); IOCORE_ReadConfigInt32(clientCertLevel, "proxy.config.ssl.client.certification_level"); IOCORE_ReadConfigStringAlloc(cipherSuite, "proxy.config.ssl.server.cipher_suite"); int options; IOCORE_ReadConfigInteger(options, "proxy.config.ssl.SSLv2"); if (!options) ssl_ctx_options |= SSL_OP_NO_SSLv2; IOCORE_ReadConfigInteger(options, "proxy.config.ssl.SSLv3"); if (!options) ssl_ctx_options |= SSL_OP_NO_SSLv3; IOCORE_ReadConfigInteger(options, "proxy.config.ssl.TLSv1"); if (!options) ssl_ctx_options |= SSL_OP_NO_TLSv1; #ifdef SSL_OP_CIPHER_SERVER_PREFERENCE IOCORE_ReadConfigInteger(options, "proxy.config.ssl.server.honor_cipher_order"); if (!options) ssl_ctx_options |= SSL_OP_CIPHER_SERVER_PREFERENCE; #endif #ifdef SSL_OP_NO_COMPRESSION IOCORE_ReadConfigInteger(options, "proxy.config.ssl.compression"); if (!options) ssl_ctx_options |= SSL_OP_NO_COMPRESSION; #endif IOCORE_ReadConfigString(serverCertFilename, "proxy.config.ssl.server.cert.filename", PATH_NAME_MAX); IOCORE_ReadConfigString(serverCertRelativePath, "proxy.config.ssl.server.cert.path", PATH_NAME_MAX); set_paths_helper(serverCertRelativePath, serverCertFilename, &serverCertPathOnly, &serverCertPath); char *cert_chain = NULL; IOCORE_ReadConfigStringAlloc(cert_chain, "proxy.config.ssl.server.cert_chain.filename"); set_paths_helper(serverCertRelativePath, cert_chain, &serverCertPathOnly, &serverCertChainPath); ats_free(cert_chain); IOCORE_ReadConfigStringAlloc(multicert_config_file, "proxy.config.ssl.server.multicert.filename"); set_paths_helper(Layout::get()->sysconfdir, multicert_config_file, NULL, &configFilePath); ats_free(multicert_config_file); IOCORE_ReadConfigStringAlloc(ssl_server_private_key_filename, "proxy.config.ssl.server.private_key.filename"); IOCORE_ReadConfigStringAlloc(ssl_server_private_key_path, "proxy.config.ssl.server.private_key.path"); set_paths_helper(ssl_server_private_key_path, ssl_server_private_key_filename, &serverKeyPathOnly, &serverKeyPath); ats_free(ssl_server_private_key_filename); ats_free(ssl_server_private_key_path); IOCORE_ReadConfigStringAlloc(CACertFilename, "proxy.config.ssl.CA.cert.filename"); IOCORE_ReadConfigStringAlloc(CACertRelativePath, "proxy.config.ssl.CA.cert.path"); set_paths_helper(CACertRelativePath, CACertFilename, &CACertPath, &CACertFilename); ats_free(CACertRelativePath); // SSL session cache configurations IOCORE_ReadConfigInteger(ssl_session_cache, "proxy.config.ssl.session_cache"); IOCORE_ReadConfigInteger(ssl_session_cache_size, "proxy.config.ssl.session_cache.size"); // ++++++++++++++++++++++++ Client part ++++++++++++++++++++ client_verify_depth = 7; IOCORE_ReadConfigInt32(clientVerify, "proxy.config.ssl.client.verify.server"); ssl_client_cert_filename = NULL; ssl_client_cert_path = NULL; IOCORE_ReadConfigStringAlloc(ssl_client_cert_filename, "proxy.config.ssl.client.cert.filename"); IOCORE_ReadConfigStringAlloc(ssl_client_cert_path, "proxy.config.ssl.client.cert.path"); set_paths_helper(ssl_client_cert_path ssl_client_cert_filename, NULL, &clientCertPath); ats_free_null(ssl_client_cert_filename); ats_fre_nulle(ssl_client_cert_path); IOCORE_ReadConfigStringAlloc(ssl_client_private_key_filename, "proxy.config.ssl.client.private_key.filename"); IOCORE_ReadConfigStringAlloc(ssl_client_private_key_path, "proxy.config.ssl.client.private_key.path"); set_paths_helper(ssl_client_private_key_path, ssl_client_private_key_filename, NULL, &clientKeyPath); ats_free_null(ssl_client_private_key_filename); ats_fre_nulle(ssl_client_private_key_path); IOCORE_ReadConfigStringAlloc(clientCACertFilename, "proxy.config.ssl.client.CA.cert.filename"); IOCORE_ReadConfigStringAlloc(clientCACertRelativePath, "proxy.config.ssl.client.CA.cert.path"); set_paths_helper(clientCACertRelativePath, clientCACertFilename, &clientCACertPath, &clientCACertFilename); ats_free(clientCACertRelativePath); } void SslConfig::startup() { reconfigure(); } void SslConfig::reconfigure() { SslConfigParams *params; params = NEW(new SslConfigParams); params->initialize(); // re-read configuration #ifdef USE_CONFIG_PROCESSOR id = configProcessor.set(id, params); #else ssl_config_params = params; #endif serverSSLTermination = (params->termMode & SslConfigParams::SSL_TERM_MODE_SERVER) != 0; } SslConfigParams * SslConfig::acquire() { #ifndef USE_CONFIG_PROCESSOR return ssl_config_params; #else return ((SslConfigParams *) configProcessor.get(id)); #endif } void SslConfig::release(SslConfigParams * params) { (void) params; #ifdef USE_CONFIG_PROCESSOR configProcessor.release(id, params); #endif } <|endoftext|>
<commit_before>#include "ofxSquareScreen.h" //-------------------------------------------------------------- void ofxSquareScreen::setup(){ mode = SC_MODE_INIT; sWidth = ofGetWidth(); sHeight = ofGetHeight(); tween.setParameters(easingsine, ofxTween::easeInOut , sWidth , sWidth , 100,0); } //-------------------------------------------------------------- void ofxSquareScreen::nextMode(){ mode = (mode + 1) % 6; cout << "new mode : " << ofToString(mode) << endl; switch (mode) { case SC_MODE_INIT : setup(); break; case SC_MODE_BEGIN : { tween.setParameters(easingsine, ofxTween::easeInOut , ofGetWidth() , 0 , 30000,0); } break; case SC_MODE_LINE: { tween.setParameters(easingexpo, ofxTween::easeInOut , 0 , PI , 500,0); } break; case SC_MODE_BEGIN_REOPEN: { tween.setParameters(easingback, ofxTween::easeOut , 0 , ofGetWidth()*0.3 , 2000,0); } break; case SC_MODE_CLOSE : { tween.setParameters(easingquad, ofxTween::easeInOut , ofGetWidth()*0.3 , 0 , 10000, 0); } break; case SC_MODE_VOPEN : { sWidth = ofGetWidth(); sHeight = 0; tween.setParameters(easingquad, ofxTween::easeInOut , 0 , ofGetHeight() , 10000, 0); } break; default: break; } } //-------------------------------------------------------------- void ofxSquareScreen::update(){ } //-------------------------------------------------------------- void ofxSquareScreen::draw(){ int w = ofGetWidth(); int h = ofGetHeight(); int backColor = 0; // dimensions update switch (mode) { default : sWidth = tween.update(); break; case SC_MODE_VOPEN : sHeight = tween.update(); break; } // other updates (alpha, color, mode change) switch (mode) { case SC_MODE_BEGIN : if (tween.isCompleted()) nextMode(); break; case SC_MODE_LINE : // same as begin but color { backColor = (int)(abs(sin(2.f*sWidth))*255); if (tween.isCompleted()) nextMode(); } break; default: break; } int foreColor = 255-backColor; ofPushMatrix(); ofClear(backColor); ofFill(); ofSetColor(foreColor); switch (mode) { case SC_MODE_LINE: { float lineWidth = (float)w * sin(sWidth); //cout << ofToString(lineWidth) << endl; ofTranslate((w - lineWidth)/2, (h/2-5)); ofRect(0, 0, lineWidth, 5); } break; case SC_MODE_VOPEN: { if (openFromBottom) { ofTranslate(0, (h-sHeight)); } else { ofTranslate(0, 0); } ofRect(0, 0, w, sHeight); } break; default: { ofTranslate((w - sWidth)/2, 0); ofRect(0, 0, sWidth, h); } break; } ofPopMatrix(); } //-------------------------------------------------------------- void ofxSquareScreen::keyPressed(int key){ switch (key) { case ' ' : nextMode(); break; case 'r': setup(); break; default: break; } }<commit_msg>replaced ofClear by ofBackground to fix postProcessing<commit_after>#include "ofxSquareScreen.h" //-------------------------------------------------------------- void ofxSquareScreen::setup(){ mode = SC_MODE_INIT; sWidth = ofGetWidth(); sHeight = ofGetHeight(); tween.setParameters(easingsine, ofxTween::easeInOut , sWidth , sWidth , 100,0); } //-------------------------------------------------------------- void ofxSquareScreen::nextMode(){ mode = (mode + 1) % 6; cout << "new mode : " << ofToString(mode) << endl; switch (mode) { case SC_MODE_INIT : setup(); break; case SC_MODE_BEGIN : { tween.setParameters(easingsine, ofxTween::easeInOut , ofGetWidth() , 0 , 30000,0); } break; case SC_MODE_LINE: { tween.setParameters(easingexpo, ofxTween::easeInOut , 0 , PI , 500,0); } break; case SC_MODE_BEGIN_REOPEN: { tween.setParameters(easingback, ofxTween::easeOut , 0 , ofGetWidth()*0.3 , 2000,0); } break; case SC_MODE_CLOSE : { tween.setParameters(easingquad, ofxTween::easeInOut , ofGetWidth()*0.3 , 0 , 10000, 0); } break; case SC_MODE_VOPEN : { sWidth = ofGetWidth(); sHeight = 0; tween.setParameters(easingquad, ofxTween::easeInOut , 0 , ofGetHeight() , 10000, 0); } break; default: break; } } //-------------------------------------------------------------- void ofxSquareScreen::update(){ } //-------------------------------------------------------------- void ofxSquareScreen::draw(){ int w = ofGetWidth(); int h = ofGetHeight(); int backColor = 0; // dimensions update switch (mode) { default : sWidth = tween.update(); break; case SC_MODE_VOPEN : sHeight = tween.update(); break; } // other updates (alpha, color, mode change) switch (mode) { case SC_MODE_BEGIN : if (tween.isCompleted()) nextMode(); break; case SC_MODE_LINE : // same as begin but color { backColor = (int)(abs(sin(2.f*sWidth))*255); if (tween.isCompleted()) nextMode(); } break; default: break; } int foreColor = 255-backColor; ofPushMatrix(); ofBackground(backColor); ofFill(); ofSetColor(foreColor); switch (mode) { case SC_MODE_LINE: { float lineWidth = (float)w * sin(sWidth); //cout << ofToString(lineWidth) << endl; ofTranslate((w - lineWidth)/2, (h/2-5)); ofRect(0, 0, lineWidth, 5); } break; case SC_MODE_VOPEN: { if (openFromBottom) { ofTranslate(0, (h-sHeight)); } else { ofTranslate(0, 0); } ofRect(0, 0, w, sHeight); } break; default: { ofTranslate((w - sWidth)/2, 0); ofRect(0, 0, sWidth, h); } break; } ofPopMatrix(); } //-------------------------------------------------------------- void ofxSquareScreen::keyPressed(int key){ switch (key) { case ' ' : nextMode(); break; case 'r': setup(); break; default: break; } }<|endoftext|>
<commit_before>/** @file Support class for describing the local machine. @section license License Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "libts.h" #include "I_Machine.h" #include <ifaddrs.h> // Singleton Machine* Machine::_instance = NULL; Machine* Machine::instance() { ink_assert(_instance || !"Machine instance accessed before initialization"); return Machine::_instance; } Machine* Machine::init(char const* name, sockaddr const* ip) { ink_assert(!_instance || !"Machine instance initialized twice."); Machine::_instance = new Machine(name, ip); return Machine::_instance; } Machine::Machine(char const* the_hostname, sockaddr const* addr) : hostname(0), hostname_len(0) , ip_string_len(0) , ip_hex_string_len(0) { char localhost[1024]; int status; // return for system calls. ip_string[0] = 0; ip_hex_string[0] = 0; ink_zero(ip); ink_zero(ip4); ink_zero(ip6); localhost[sizeof(localhost)-1] = 0; // ensure termination. if (!ink_inet_is_ip(addr)) { if (!the_hostname) { ink_release_assert(!gethostname(localhost, sizeof(localhost)-1)); the_hostname = localhost; } hostname = ats_strdup(the_hostname); ifaddrs* ifa_addrs = 0; status = getifaddrs(&ifa_addrs); if (0 != status) { Warning("Unable to determine local host '%s' address information - %s" , hostname , strerror(errno) ); } else { /* Loop through the interface addresses. We have to prioritize the values a little bit. The worst is the loopback address, we accept that only if we can't find anything else. Next best are non-routables and the best are "global" addresses. */ enum { NA, LO, NR, MC, GA } spot_type = NA, type = NA, ip4_type = NA, ip6_type = NA; for (ifaddrs* spot = ifa_addrs ; spot ; spot = spot->ifa_next ) { if (!ink_inet_is_ip(spot->ifa_addr)) spot_type = NA; else if (ink_inet_is_loopback(spot->ifa_addr)) spot_type = LO; else if (ink_inet_is_nonroutable(spot->ifa_addr)) spot_type = NR; else if (ink_inet_is_multicast(spot->ifa_addr)) spot_type = MC; else type = GA; if (spot_type == NA) continue; // Next! if (ink_inet_is_ip4(spot->ifa_addr)) { if (spot_type > ip4_type) { ink_inet_copy(&ip4, spot->ifa_addr); ip4_type = spot_type; } } else if (ink_inet_is_ip6(spot->ifa_addr)) { if (spot_type > ip6_type) { ink_inet_copy(&ip6, spot->ifa_addr); ip6_type = spot_type; } } } freeifaddrs(ifa_addrs); // What about the general address? Prefer IPv4? if (ip4_type >= ip6_type) ink_inet_copy(&ip.sa, &ip4.sa); else ink_inet_copy(&ip.sa, &ip6.sa); } } else { // address provided. ink_inet_copy(&ip, addr); if (ink_inet_is_ip4(addr)) ink_inet_copy(&ip4, addr); else if (ink_inet_is_ip6(addr)) ink_inet_copy(&ip6, addr); status = getnameinfo( addr, ink_inet_ip_size(addr), localhost, sizeof(localhost) - 1, 0, 0, // do not request service info 0 // no flags. ); if (0 != status) { ip_text_buffer ipbuff; Warning("Failed to find hostname for address '%s' - %s" , ink_inet_ntop(addr, ipbuff, sizeof(ipbuff)) , gai_strerror(status) ); } else hostname = ats_strdup(localhost); } hostname_len = hostname ? strlen(hostname) : 0; ink_inet_ntop(&ip.sa, ip_string, sizeof(ip_string)); ip_string_len = strlen(ip_string); ip_hex_string_len = ink_inet_to_hex(&ip.sa, ip_hex_string, sizeof(ip_hex_string)); } Machine::~Machine() { ats_free(hostname); } <commit_msg>Fix building with -Werror=unused-but-set-variable for last checkin<commit_after>/** @file Support class for describing the local machine. @section license License Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "libts.h" #include "I_Machine.h" #include <ifaddrs.h> // Singleton Machine* Machine::_instance = NULL; Machine* Machine::instance() { ink_assert(_instance || !"Machine instance accessed before initialization"); return Machine::_instance; } Machine* Machine::init(char const* name, sockaddr const* ip) { ink_assert(!_instance || !"Machine instance initialized twice."); Machine::_instance = new Machine(name, ip); return Machine::_instance; } Machine::Machine(char const* the_hostname, sockaddr const* addr) : hostname(0), hostname_len(0) , ip_string_len(0) , ip_hex_string_len(0) { char localhost[1024]; int status; // return for system calls. ip_string[0] = 0; ip_hex_string[0] = 0; ink_zero(ip); ink_zero(ip4); ink_zero(ip6); localhost[sizeof(localhost)-1] = 0; // ensure termination. if (!ink_inet_is_ip(addr)) { if (!the_hostname) { ink_release_assert(!gethostname(localhost, sizeof(localhost)-1)); the_hostname = localhost; } hostname = ats_strdup(the_hostname); ifaddrs* ifa_addrs = 0; status = getifaddrs(&ifa_addrs); if (0 != status) { Warning("Unable to determine local host '%s' address information - %s" , hostname , strerror(errno) ); } else { /* Loop through the interface addresses. We have to prioritize the values a little bit. The worst is the loopback address, we accept that only if we can't find anything else. Next best are non-routables and the best are "global" addresses. */ enum { NA, LO, NR, MC, GA } spot_type = NA, ip4_type = NA, ip6_type = NA; for (ifaddrs* spot = ifa_addrs ; spot ; spot = spot->ifa_next ) { if (!ink_inet_is_ip(spot->ifa_addr)) spot_type = NA; else if (ink_inet_is_loopback(spot->ifa_addr)) spot_type = LO; else if (ink_inet_is_nonroutable(spot->ifa_addr)) spot_type = NR; else if (ink_inet_is_multicast(spot->ifa_addr)) spot_type = MC; if (spot_type == NA) continue; // Next! if (ink_inet_is_ip4(spot->ifa_addr)) { if (spot_type > ip4_type) { ink_inet_copy(&ip4, spot->ifa_addr); ip4_type = spot_type; } } else if (ink_inet_is_ip6(spot->ifa_addr)) { if (spot_type > ip6_type) { ink_inet_copy(&ip6, spot->ifa_addr); ip6_type = spot_type; } } } freeifaddrs(ifa_addrs); // What about the general address? Prefer IPv4? if (ip4_type >= ip6_type) ink_inet_copy(&ip.sa, &ip4.sa); else ink_inet_copy(&ip.sa, &ip6.sa); } } else { // address provided. ink_inet_copy(&ip, addr); if (ink_inet_is_ip4(addr)) ink_inet_copy(&ip4, addr); else if (ink_inet_is_ip6(addr)) ink_inet_copy(&ip6, addr); status = getnameinfo( addr, ink_inet_ip_size(addr), localhost, sizeof(localhost) - 1, 0, 0, // do not request service info 0 // no flags. ); if (0 != status) { ip_text_buffer ipbuff; Warning("Failed to find hostname for address '%s' - %s" , ink_inet_ntop(addr, ipbuff, sizeof(ipbuff)) , gai_strerror(status) ); } else hostname = ats_strdup(localhost); } hostname_len = hostname ? strlen(hostname) : 0; ink_inet_ntop(&ip.sa, ip_string, sizeof(ip_string)); ip_string_len = strlen(ip_string); ip_hex_string_len = ink_inet_to_hex(&ip.sa, ip_hex_string, sizeof(ip_hex_string)); } Machine::~Machine() { ats_free(hostname); } <|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 "ipc/ipc_channel_nacl.h" #include <errno.h> #include <stddef.h> #include <sys/nacl_imc_api.h> #include <sys/nacl_syscalls.h> #include <sys/types.h> #include <algorithm> #include "base/bind.h" #include "base/file_util.h" #include "base/logging.h" #include "base/message_loop_proxy.h" #include "base/process_util.h" #include "base/synchronization/lock.h" #include "base/task_runner_util.h" #include "base/threading/simple_thread.h" #include "ipc/file_descriptor_set_posix.h" #include "ipc/ipc_logging.h" namespace IPC { namespace { scoped_ptr<std::vector<char> > ReadDataOnReaderThread(int pipe) { DCHECK(pipe >= 0); if (pipe < 0) return scoped_ptr<std::vector<char> >(); scoped_ptr<std::vector<char> > buffer( new std::vector<char>(Channel::kReadBufferSize)); struct NaClImcMsgHdr msg = {0}; struct NaClImcMsgIoVec iov = {&buffer->at(0), buffer->size()}; msg.iov = &iov; msg.iov_length = 1; int bytes_read = imc_recvmsg(pipe, &msg, 0); if (bytes_read <= 0) { // NaClIPCAdapter::BlockingReceive returns -1 when the pipe closes (either // due to error or for regular shutdown). return scoped_ptr<std::vector<char> >(); } DCHECK(bytes_read); buffer->resize(bytes_read); return buffer.Pass(); } } // namespace class Channel::ChannelImpl::ReaderThreadRunner : public base::DelegateSimpleThread::Delegate { public: // |pipe|: A file descriptor from which we will read using imc_recvmsg. // |data_read_callback|: A callback we invoke (on the main thread) when we // have read data. The callback is passed a buffer of // data that was read. // |failure_callback|: A callback we invoke when we have a failure reading // from |pipe|. // |main_message_loop|: A proxy for the main thread, where we will invoke the // above callbacks. ReaderThreadRunner( int pipe, base::Callback<void (scoped_ptr<std::vector<char> >)> data_read_callback, base::Callback<void ()> failure_callback, base::MessageLoopProxy* main_message_loop); // DelegateSimpleThread implementation. Reads data from the pipe in a loop // until either we are told to quit or a read fails. virtual void Run() OVERRIDE; private: int pipe_; base::Callback<void (scoped_ptr<std::vector<char> >)> data_read_callback_; base::Callback<void ()> failure_callback_; base::MessageLoopProxy* main_message_loop_; DISALLOW_COPY_AND_ASSIGN(ReaderThreadRunner); }; Channel::ChannelImpl::ReaderThreadRunner::ReaderThreadRunner( int pipe, base::Callback<void (scoped_ptr<std::vector<char> >)> data_read_callback, base::Callback<void ()> failure_callback, base::MessageLoopProxy* main_message_loop) : pipe_(pipe), data_read_callback_(data_read_callback), failure_callback_(failure_callback), main_message_loop_(main_message_loop) { } void Channel::ChannelImpl::ReaderThreadRunner::Run() { while (true) { scoped_ptr<std::vector<char> > buffer(ReadDataOnReaderThread(pipe_)); if (buffer.get()) { main_message_loop_->PostTask(FROM_HERE, base::Bind(data_read_callback_, base::Passed(buffer.Pass()))); } else { main_message_loop_->PostTask(FROM_HERE, failure_callback_); // Because the read failed, we know we're going to quit. Don't bother // trying to read again. return; } } } Channel::ChannelImpl::ChannelImpl(const IPC::ChannelHandle& channel_handle, Mode mode, Listener* listener) : ChannelReader(listener), mode_(mode), waiting_connect_(true), pipe_(-1), pipe_name_(channel_handle.name), weak_ptr_factory_(ALLOW_THIS_IN_INITIALIZER_LIST(this)) { if (!CreatePipe(channel_handle)) { // The pipe may have been closed already. const char *modestr = (mode_ & MODE_SERVER_FLAG) ? "server" : "client"; LOG(WARNING) << "Unable to create pipe named \"" << channel_handle.name << "\" in " << modestr << " mode"; } reader_thread_runner_.reset( new ReaderThreadRunner( pipe_, base::Bind(&Channel::ChannelImpl::DidRecvMsg, weak_ptr_factory_.GetWeakPtr()), base::Bind(&Channel::ChannelImpl::ReadDidFail, weak_ptr_factory_.GetWeakPtr()), base::MessageLoopProxy::current())); reader_thread_.reset( new base::DelegateSimpleThread(reader_thread_runner_.get(), "ipc_channel_nacl reader thread")); } Channel::ChannelImpl::~ChannelImpl() { Close(); } bool Channel::ChannelImpl::Connect() { if (pipe_ == -1) { DLOG(INFO) << "Channel creation failed: " << pipe_name_; return false; } reader_thread_->Start(); waiting_connect_ = false; // If there were any messages queued before connection, send them. ProcessOutgoingMessages(); } void Channel::ChannelImpl::Close() { // For now, we assume that at shutdown, the reader thread will be woken with // a failure (see NaClIPCAdapter::BlockingRead and CloseChannel). Or... we // might simply be killed with no chance to clean up anyway :-). // If untrusted code tries to close the channel prior to shutdown, it's likely // to hang. // TODO(dmichael): Can we do anything smarter here to make sure the reader // thread wakes up and quits? reader_thread_->Join(); close(pipe_); pipe_ = -1; reader_thread_runner_.reset(); reader_thread_.reset(); read_queue_.clear(); output_queue_.clear(); } bool Channel::ChannelImpl::Send(Message* message) { DVLOG(2) << "sending message @" << message << " on channel @" << this << " with type " << message->type(); scoped_ptr<Message> message_ptr(message); #ifdef IPC_MESSAGE_LOG_ENABLED Logging::GetInstance()->OnSendMessage(message, ""); #endif // IPC_MESSAGE_LOG_ENABLED output_queue_.push_back(linked_ptr<Message>(message)); if (!waiting_connect_) return ProcessOutgoingMessages(); return true; } void Channel::ChannelImpl::DidRecvMsg(scoped_ptr<std::vector<char> > buffer) { // Close sets the pipe to -1. It's possible we'll get a buffer sent to us from // the reader thread after Close is called. If so, we ignore it. if (pipe_ == -1) return; read_queue_.push_back(linked_ptr<std::vector<char> >(buffer.release())); } void Channel::ChannelImpl::ReadDidFail() { Close(); } bool Channel::ChannelImpl::CreatePipe( const IPC::ChannelHandle& channel_handle) { DCHECK(pipe_ == -1); // There's one possible case in NaCl: // 1) It's a channel wrapping a pipe that is given to us. // We don't support these: // 2) It's for a named channel. // 3) It's for a client that we implement ourself. // 4) It's the initial IPC channel. if (channel_handle.socket.fd == -1) { NOTIMPLEMENTED(); return false; } pipe_ = channel_handle.socket.fd; return true; } bool Channel::ChannelImpl::ProcessOutgoingMessages() { DCHECK(!waiting_connect_); // Why are we trying to send messages if there's // no connection? if (output_queue_.empty()) return true; if (pipe_ == -1) return false; // Write out all the messages. The trusted implementation is guaranteed to not // block. See NaClIPCAdapter::Send for the implementation of imc_sendmsg. while (!output_queue_.empty()) { linked_ptr<Message> msg = output_queue_.front(); output_queue_.pop_front(); struct NaClImcMsgHdr msgh = {0}; struct NaClImcMsgIoVec iov = {const_cast<void*>(msg->data()), msg->size()}; msgh.iov = &iov; msgh.iov_length = 1; ssize_t bytes_written = imc_sendmsg(pipe_, &msgh, 0); if (bytes_written < 0) { // The trusted side should only ever give us an error of EPIPE. We // should never be interrupted, nor should we get EAGAIN. DCHECK(errno == EPIPE); Close(); PLOG(ERROR) << "pipe_ error on " << pipe_ << " Currently writing message of size: " << msg->size(); return false; } // Message sent OK! DVLOG(2) << "sent message @" << msg.get() << " with type " << msg->type() << " on fd " << pipe_; } return true; } Channel::ChannelImpl::ReadState Channel::ChannelImpl::ReadData( char* buffer, int buffer_len, int* bytes_read) { *bytes_read = 0; if (pipe_ == -1) return READ_FAILED; if (read_queue_.empty()) return READ_PENDING; while (!read_queue_.empty() && *bytes_read < buffer_len) { linked_ptr<std::vector<char> > vec(read_queue_.front()); int bytes_to_read = buffer_len - *bytes_read; if (vec->size() <= bytes_to_read) { // We can read and discard the entire vector. std::copy(vec->begin(), vec->end(), buffer + *bytes_read); *bytes_read += vec->size(); read_queue_.pop_front(); } else { // Read all the bytes we can and discard them from the front of the // vector. (This can be slowish, since erase has to move the back of the // vector to the front, but it's hopefully a temporary hack and it keeps // the code simple). std::copy(vec->begin(), vec->begin() + bytes_to_read, buffer + *bytes_read); vec->erase(vec->begin(), vec->begin() + bytes_to_read); *bytes_read += bytes_to_read; } } return READ_SUCCEEDED; } bool Channel::ChannelImpl::WillDispatchInputMessage(Message* msg) { return true; } bool Channel::ChannelImpl::DidEmptyInputBuffers() { return true; } void Channel::ChannelImpl::HandleHelloMessage(const Message& msg) { // The trusted side IPC::Channel should handle the "hello" handshake; we // should not receive the "Hello" message. NOTREACHED(); } //------------------------------------------------------------------------------ // Channel's methods simply call through to ChannelImpl. Channel::Channel(const IPC::ChannelHandle& channel_handle, Mode mode, Listener* listener) : channel_impl_(new ChannelImpl(channel_handle, mode, listener)) { } Channel::~Channel() { delete channel_impl_; } bool Channel::Connect() { return channel_impl_->Connect(); } void Channel::Close() { channel_impl_->Close(); } void Channel::set_listener(Listener* listener) { channel_impl_->set_listener(listener); } base::ProcessId Channel::peer_pid() const { // This shouldn't actually get used in the untrusted side of the proxy, and we // don't have the real pid anyway. return -1; } bool Channel::Send(Message* message) { return channel_impl_->Send(message); } // static std::string Channel::GenerateVerifiedChannelID(const std::string& prefix) { // A random name is sufficient validation on posix systems, so we don't need // an additional shared secret. std::string id = prefix; if (!id.empty()) id.append("."); return id.append(GenerateUniqueRandomChannelID()); } } // namespace IPC <commit_msg>PPAPI/NaCl: Minor fixes to ipc_channel_nacl<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 "ipc/ipc_channel_nacl.h" #include <errno.h> #include <stddef.h> #include <sys/nacl_imc_api.h> #include <sys/nacl_syscalls.h> #include <sys/types.h> #include <algorithm> #include "base/bind.h" #include "base/file_util.h" #include "base/logging.h" #include "base/message_loop_proxy.h" #include "base/process_util.h" #include "base/synchronization/lock.h" #include "base/task_runner_util.h" #include "base/threading/simple_thread.h" #include "ipc/file_descriptor_set_posix.h" #include "ipc/ipc_logging.h" namespace IPC { namespace { scoped_ptr<std::vector<char> > ReadDataOnReaderThread(int pipe) { DCHECK(pipe >= 0); if (pipe < 0) return scoped_ptr<std::vector<char> >(); scoped_ptr<std::vector<char> > buffer( new std::vector<char>(Channel::kReadBufferSize)); struct NaClImcMsgHdr msg = {0}; struct NaClImcMsgIoVec iov = {&buffer->at(0), buffer->size()}; msg.iov = &iov; msg.iov_length = 1; int bytes_read = imc_recvmsg(pipe, &msg, 0); if (bytes_read <= 0) { // NaClIPCAdapter::BlockingReceive returns -1 when the pipe closes (either // due to error or for regular shutdown). return scoped_ptr<std::vector<char> >(); } DCHECK(bytes_read); buffer->resize(bytes_read); return buffer.Pass(); } } // namespace class Channel::ChannelImpl::ReaderThreadRunner : public base::DelegateSimpleThread::Delegate { public: // |pipe|: A file descriptor from which we will read using imc_recvmsg. // |data_read_callback|: A callback we invoke (on the main thread) when we // have read data. The callback is passed a buffer of // data that was read. // |failure_callback|: A callback we invoke when we have a failure reading // from |pipe|. // |main_message_loop|: A proxy for the main thread, where we will invoke the // above callbacks. ReaderThreadRunner( int pipe, base::Callback<void (scoped_ptr<std::vector<char> >)> data_read_callback, base::Callback<void ()> failure_callback, base::MessageLoopProxy* main_message_loop); // DelegateSimpleThread implementation. Reads data from the pipe in a loop // until either we are told to quit or a read fails. virtual void Run() OVERRIDE; private: int pipe_; base::Callback<void (scoped_ptr<std::vector<char> >)> data_read_callback_; base::Callback<void ()> failure_callback_; scoped_refptr<base::MessageLoopProxy> main_message_loop_; DISALLOW_COPY_AND_ASSIGN(ReaderThreadRunner); }; Channel::ChannelImpl::ReaderThreadRunner::ReaderThreadRunner( int pipe, base::Callback<void (scoped_ptr<std::vector<char> >)> data_read_callback, base::Callback<void ()> failure_callback, base::MessageLoopProxy* main_message_loop) : pipe_(pipe), data_read_callback_(data_read_callback), failure_callback_(failure_callback), main_message_loop_(main_message_loop) { } void Channel::ChannelImpl::ReaderThreadRunner::Run() { while (true) { scoped_ptr<std::vector<char> > buffer(ReadDataOnReaderThread(pipe_)); if (buffer.get()) { main_message_loop_->PostTask(FROM_HERE, base::Bind(data_read_callback_, base::Passed(buffer.Pass()))); } else { main_message_loop_->PostTask(FROM_HERE, failure_callback_); // Because the read failed, we know we're going to quit. Don't bother // trying to read again. return; } } } Channel::ChannelImpl::ChannelImpl(const IPC::ChannelHandle& channel_handle, Mode mode, Listener* listener) : ChannelReader(listener), mode_(mode), waiting_connect_(true), pipe_(-1), pipe_name_(channel_handle.name), weak_ptr_factory_(ALLOW_THIS_IN_INITIALIZER_LIST(this)) { if (!CreatePipe(channel_handle)) { // The pipe may have been closed already. const char *modestr = (mode_ & MODE_SERVER_FLAG) ? "server" : "client"; LOG(WARNING) << "Unable to create pipe named \"" << channel_handle.name << "\" in " << modestr << " mode"; } reader_thread_runner_.reset( new ReaderThreadRunner( pipe_, base::Bind(&Channel::ChannelImpl::DidRecvMsg, weak_ptr_factory_.GetWeakPtr()), base::Bind(&Channel::ChannelImpl::ReadDidFail, weak_ptr_factory_.GetWeakPtr()), base::MessageLoopProxy::current())); reader_thread_.reset( new base::DelegateSimpleThread(reader_thread_runner_.get(), "ipc_channel_nacl reader thread")); } Channel::ChannelImpl::~ChannelImpl() { Close(); } bool Channel::ChannelImpl::Connect() { if (pipe_ == -1) { DLOG(INFO) << "Channel creation failed: " << pipe_name_; return false; } reader_thread_->Start(); waiting_connect_ = false; // If there were any messages queued before connection, send them. ProcessOutgoingMessages(); return true; } void Channel::ChannelImpl::Close() { // For now, we assume that at shutdown, the reader thread will be woken with // a failure (see NaClIPCAdapter::BlockingRead and CloseChannel). Or... we // might simply be killed with no chance to clean up anyway :-). // If untrusted code tries to close the channel prior to shutdown, it's likely // to hang. // TODO(dmichael): Can we do anything smarter here to make sure the reader // thread wakes up and quits? reader_thread_->Join(); close(pipe_); pipe_ = -1; reader_thread_runner_.reset(); reader_thread_.reset(); read_queue_.clear(); output_queue_.clear(); } bool Channel::ChannelImpl::Send(Message* message) { DVLOG(2) << "sending message @" << message << " on channel @" << this << " with type " << message->type(); scoped_ptr<Message> message_ptr(message); #ifdef IPC_MESSAGE_LOG_ENABLED Logging::GetInstance()->OnSendMessage(message, ""); #endif // IPC_MESSAGE_LOG_ENABLED output_queue_.push_back(linked_ptr<Message>(message)); if (!waiting_connect_) return ProcessOutgoingMessages(); return true; } void Channel::ChannelImpl::DidRecvMsg(scoped_ptr<std::vector<char> > buffer) { // Close sets the pipe to -1. It's possible we'll get a buffer sent to us from // the reader thread after Close is called. If so, we ignore it. if (pipe_ == -1) return; read_queue_.push_back(linked_ptr<std::vector<char> >(buffer.release())); } void Channel::ChannelImpl::ReadDidFail() { Close(); } bool Channel::ChannelImpl::CreatePipe( const IPC::ChannelHandle& channel_handle) { DCHECK(pipe_ == -1); // There's one possible case in NaCl: // 1) It's a channel wrapping a pipe that is given to us. // We don't support these: // 2) It's for a named channel. // 3) It's for a client that we implement ourself. // 4) It's the initial IPC channel. if (channel_handle.socket.fd == -1) { NOTIMPLEMENTED(); return false; } pipe_ = channel_handle.socket.fd; return true; } bool Channel::ChannelImpl::ProcessOutgoingMessages() { DCHECK(!waiting_connect_); // Why are we trying to send messages if there's // no connection? if (output_queue_.empty()) return true; if (pipe_ == -1) return false; // Write out all the messages. The trusted implementation is guaranteed to not // block. See NaClIPCAdapter::Send for the implementation of imc_sendmsg. while (!output_queue_.empty()) { linked_ptr<Message> msg = output_queue_.front(); output_queue_.pop_front(); struct NaClImcMsgHdr msgh = {0}; struct NaClImcMsgIoVec iov = {const_cast<void*>(msg->data()), msg->size()}; msgh.iov = &iov; msgh.iov_length = 1; ssize_t bytes_written = imc_sendmsg(pipe_, &msgh, 0); if (bytes_written < 0) { // The trusted side should only ever give us an error of EPIPE. We // should never be interrupted, nor should we get EAGAIN. DCHECK(errno == EPIPE); Close(); PLOG(ERROR) << "pipe_ error on " << pipe_ << " Currently writing message of size: " << msg->size(); return false; } // Message sent OK! DVLOG(2) << "sent message @" << msg.get() << " with type " << msg->type() << " on fd " << pipe_; } return true; } Channel::ChannelImpl::ReadState Channel::ChannelImpl::ReadData( char* buffer, int buffer_len, int* bytes_read) { *bytes_read = 0; if (pipe_ == -1) return READ_FAILED; if (read_queue_.empty()) return READ_PENDING; while (!read_queue_.empty() && *bytes_read < buffer_len) { linked_ptr<std::vector<char> > vec(read_queue_.front()); int bytes_to_read = buffer_len - *bytes_read; if (vec->size() <= bytes_to_read) { // We can read and discard the entire vector. std::copy(vec->begin(), vec->end(), buffer + *bytes_read); *bytes_read += vec->size(); read_queue_.pop_front(); } else { // Read all the bytes we can and discard them from the front of the // vector. (This can be slowish, since erase has to move the back of the // vector to the front, but it's hopefully a temporary hack and it keeps // the code simple). std::copy(vec->begin(), vec->begin() + bytes_to_read, buffer + *bytes_read); vec->erase(vec->begin(), vec->begin() + bytes_to_read); *bytes_read += bytes_to_read; } } return READ_SUCCEEDED; } bool Channel::ChannelImpl::WillDispatchInputMessage(Message* msg) { return true; } bool Channel::ChannelImpl::DidEmptyInputBuffers() { return true; } void Channel::ChannelImpl::HandleHelloMessage(const Message& msg) { // The trusted side IPC::Channel should handle the "hello" handshake; we // should not receive the "Hello" message. NOTREACHED(); } //------------------------------------------------------------------------------ // Channel's methods simply call through to ChannelImpl. Channel::Channel(const IPC::ChannelHandle& channel_handle, Mode mode, Listener* listener) : channel_impl_(new ChannelImpl(channel_handle, mode, listener)) { } Channel::~Channel() { delete channel_impl_; } bool Channel::Connect() { return channel_impl_->Connect(); } void Channel::Close() { channel_impl_->Close(); } void Channel::set_listener(Listener* listener) { channel_impl_->set_listener(listener); } base::ProcessId Channel::peer_pid() const { // This shouldn't actually get used in the untrusted side of the proxy, and we // don't have the real pid anyway. return -1; } bool Channel::Send(Message* message) { return channel_impl_->Send(message); } // static std::string Channel::GenerateVerifiedChannelID(const std::string& prefix) { // A random name is sufficient validation on posix systems, so we don't need // an additional shared secret. std::string id = prefix; if (!id.empty()) id.append("."); return id.append(GenerateUniqueRandomChannelID()); } } // namespace IPC <|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 "build/build_config.h" #if defined(OS_WIN) #include <windows.h> #endif #include <stack> #include "base/atomic_sequence_num.h" #include "base/logging.h" #include "base/synchronization/waitable_event.h" #include "ipc/ipc_sync_message.h" namespace IPC { #define kSyncMessageHeaderSize 4 static base::AtomicSequenceNumber g_next_id(base::LINKER_INITIALIZED); static base::WaitableEvent* dummy_event = new base::WaitableEvent(true, true); SyncMessage::SyncMessage( int32 routing_id, uint32 type, PriorityValue priority, MessageReplyDeserializer* deserializer) : Message(routing_id, type, priority), deserializer_(deserializer), pump_messages_event_(NULL) { set_sync(); set_unblock(true); // Add synchronous message data before the message payload. SyncHeader header; header.message_id = g_next_id.GetNext(); WriteSyncHeader(this, header); } SyncMessage::~SyncMessage() { } MessageReplyDeserializer* SyncMessage::GetReplyDeserializer() { DCHECK(deserializer_.get()); return deserializer_.release(); } void SyncMessage::EnableMessagePumping() { DCHECK(!pump_messages_event_); set_pump_messages_event(dummy_event); } bool SyncMessage::IsMessageReplyTo(const Message& msg, int request_id) { if (!msg.is_reply()) return false; return GetMessageId(msg) == request_id; } void* SyncMessage::GetDataIterator(const Message* msg) { void* iter = const_cast<char*>(msg->payload()); UpdateIter(&iter, kSyncMessageHeaderSize); return iter; } int SyncMessage::GetMessageId(const Message& msg) { if (!msg.is_sync() && !msg.is_reply()) return 0; SyncHeader header; if (!ReadSyncHeader(msg, &header)) return 0; return header.message_id; } Message* SyncMessage::GenerateReply(const Message* msg) { DCHECK(msg->is_sync()); Message* reply = new Message(msg->routing_id(), IPC_REPLY_ID, msg->priority()); reply->set_reply(); SyncHeader header; // use the same message id, but this time reply bit is set header.message_id = GetMessageId(*msg); WriteSyncHeader(reply, header); return reply; } bool SyncMessage::ReadSyncHeader(const Message& msg, SyncHeader* header) { DCHECK(msg.is_sync() || msg.is_reply()); void* iter = NULL; bool result = msg.ReadInt(&iter, &header->message_id); if (!result) { NOTREACHED(); return false; } return true; } bool SyncMessage::WriteSyncHeader(Message* msg, const SyncHeader& header) { DCHECK(msg->is_sync() || msg->is_reply()); DCHECK(msg->payload_size() == 0); bool result = msg->WriteInt(header.message_id); if (!result) { NOTREACHED(); return false; } // Note: if you add anything here, you need to update kSyncMessageHeaderSize. DCHECK(kSyncMessageHeaderSize == msg->payload_size()); return true; } bool MessageReplyDeserializer::SerializeOutputParameters(const Message& msg) { return SerializeOutputParameters(msg, SyncMessage::GetDataIterator(&msg)); } } // namespace IPC <commit_msg>Remove static initializer in dummy_event<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 "build/build_config.h" #if defined(OS_WIN) #include <windows.h> #endif #include <stack> #include "base/atomic_sequence_num.h" #include "base/lazy_instance.h" #include "base/logging.h" #include "base/synchronization/waitable_event.h" #include "ipc/ipc_sync_message.h" namespace { struct WaitableEventLazyInstanceTraits : public base::DefaultLazyInstanceTraits<base::WaitableEvent> { static base::WaitableEvent* New(void* instance) { // Use placement new to initialize our instance in our preallocated space. return new (instance) base::WaitableEvent(true, true); } }; static base::LazyInstance<base::WaitableEvent, WaitableEventLazyInstanceTraits> dummy_event = LAZY_INSTANCE_INITIALIZER; } namespace IPC { #define kSyncMessageHeaderSize 4 static base::AtomicSequenceNumber g_next_id(base::LINKER_INITIALIZED); SyncMessage::SyncMessage( int32 routing_id, uint32 type, PriorityValue priority, MessageReplyDeserializer* deserializer) : Message(routing_id, type, priority), deserializer_(deserializer), pump_messages_event_(NULL) { set_sync(); set_unblock(true); // Add synchronous message data before the message payload. SyncHeader header; header.message_id = g_next_id.GetNext(); WriteSyncHeader(this, header); } SyncMessage::~SyncMessage() { } MessageReplyDeserializer* SyncMessage::GetReplyDeserializer() { DCHECK(deserializer_.get()); return deserializer_.release(); } void SyncMessage::EnableMessagePumping() { DCHECK(!pump_messages_event_); set_pump_messages_event(dummy_event.Pointer()); } bool SyncMessage::IsMessageReplyTo(const Message& msg, int request_id) { if (!msg.is_reply()) return false; return GetMessageId(msg) == request_id; } void* SyncMessage::GetDataIterator(const Message* msg) { void* iter = const_cast<char*>(msg->payload()); UpdateIter(&iter, kSyncMessageHeaderSize); return iter; } int SyncMessage::GetMessageId(const Message& msg) { if (!msg.is_sync() && !msg.is_reply()) return 0; SyncHeader header; if (!ReadSyncHeader(msg, &header)) return 0; return header.message_id; } Message* SyncMessage::GenerateReply(const Message* msg) { DCHECK(msg->is_sync()); Message* reply = new Message(msg->routing_id(), IPC_REPLY_ID, msg->priority()); reply->set_reply(); SyncHeader header; // use the same message id, but this time reply bit is set header.message_id = GetMessageId(*msg); WriteSyncHeader(reply, header); return reply; } bool SyncMessage::ReadSyncHeader(const Message& msg, SyncHeader* header) { DCHECK(msg.is_sync() || msg.is_reply()); void* iter = NULL; bool result = msg.ReadInt(&iter, &header->message_id); if (!result) { NOTREACHED(); return false; } return true; } bool SyncMessage::WriteSyncHeader(Message* msg, const SyncHeader& header) { DCHECK(msg->is_sync() || msg->is_reply()); DCHECK(msg->payload_size() == 0); bool result = msg->WriteInt(header.message_id); if (!result) { NOTREACHED(); return false; } // Note: if you add anything here, you need to update kSyncMessageHeaderSize. DCHECK(kSyncMessageHeaderSize == msg->payload_size()); return true; } bool MessageReplyDeserializer::SerializeOutputParameters(const Message& msg) { return SerializeOutputParameters(msg, SyncMessage::GetDataIterator(&msg)); } } // namespace IPC <|endoftext|>
<commit_before>//--------------------------------------------------------------------------- // hexanoise/generator_opencl.cpp // // Copyright 2014, nocte@hippie.nu Released under the MIT License. //--------------------------------------------------------------------------- #include "generator_opencl.hpp" #include <iostream> #include <cmath> #include <fstream> #include <stdexcept> #include "node.hpp" #ifndef OPENCL_OCTAVES_LIMIT # define OPENCL_OCTAVES_LIMIT 16 #endif namespace hexa { namespace noise { generator_opencl::generator_opencl (const generator_context& ctx, cl::Context& opencl_context, cl::Device& opencl_device, const node& n, const std::string& opencl_file) : generator_i(ctx) , count_(1) , context_(opencl_context) , queue_ (opencl_context, opencl_device) { std::string body (co(n)); std::ifstream file (opencl_file.c_str(), std::ios::binary); if (!file) throw std::runtime_error("cannot open OpenCL file " + opencl_file); file.seekg(0, std::ios::end); main_.resize(file.tellg()); file.seekg(0, std::ios::beg); file.read(&main_[0], main_.size()); file.close(); main_ += "\n"; for (auto& p : functions_) { main_ += p; main_ += "\n\n"; } main_ += "\n" \ "__kernel void noisemain(\n" \ " __global double* output, const double2 start, const double2 step)\n" \ "{\n"\ " int2 coord = (int2)(get_global_id(0), get_global_id(1));\n"\ " int sizex = get_global_size(0);\n"\ " double2 p = mad(step, (double2)(coord.x, coord.y), start);\n" \ " output[coord.y * sizex + coord.x] = "; main_ += body; main_ += ";\n}\n"; std::vector<cl::Device> device_vec; device_vec.emplace_back(opencl_device); cl::Program::Sources sources (1, { main_.c_str(), main_.size() }); program_ = cl::Program(opencl_context, sources); try { program_.build(device_vec); } catch (cl::Error&) { std::cerr << program_.getBuildInfo<CL_PROGRAM_BUILD_LOG>(opencl_device) << std::endl; throw; } kernel_ = cl::Kernel(program_, "noisemain"); } std::vector<double> generator_opencl::run (const glm::dvec2& corner, const glm::dvec2& step, const glm::ivec2& count) { unsigned int width (count.x), height (count.y); std::vector<double> result (width * height); cl::Buffer output (context_, CL_MEM_WRITE_ONLY | CL_MEM_USE_HOST_PTR, result.size() * sizeof(double), &result[0]); kernel_.setArg(0, output); kernel_.setArg(1, sizeof(corner), (void*)&corner); kernel_.setArg(2, sizeof(step), (void*)&step); auto memobj (queue_.enqueueMapBuffer(output, true, CL_MAP_WRITE, 0, result.size() * sizeof(double))); queue_.enqueueNDRangeKernel(kernel_, cl::NullRange, {width, height}, cl::NullRange); queue_.enqueueUnmapMemObject(output, memobj); return result; } std::string generator_opencl::pl (const node& n) { std::string result ("("); for (auto i (n.input.begin()); i != n.input.end(); ) { result += co(*i); ++i; if (i != n.input.end()) result.push_back(','); } result += ')'; return result; } std::string generator_opencl::co (const node& n) { switch (n.type) { case node::entry_point: return "p"; case node::const_var: return std::to_string(n.aux_var); case node::const_bool: return std::to_string(n.aux_bool); case node::const_str: throw std::runtime_error("string encountered"); case node::rotate: return "p_rotate" + pl(n); case node::scale: return "("+co(n.input[0])+"/"+co(n.input[1])+")"; case node::shift: return "("+co(n.input[0])+"+"+co(n.input[1])+")"; case node::swap: return "p_swap" + pl(n); case node::map: { std::string func_name ("p_map" + std::to_string(count_++)); std::stringstream func_body; func_body << "inline double2 " << func_name << " (const double2 p) { return (double2)(" << co(n.input[1]) << ", " << co(n.input[2]) << "); }" << std::endl; functions_.emplace_back(func_body.str()); return func_name + "("+ co(n.input[0]) + ")"; } case node::turbulence: { std::string func_name ("p_map" + std::to_string(count_++)); std::stringstream func_body; func_body << "inline double2 " << func_name << " (const double2 p) { return (double2)(" << "p.x+(" << co(n.input[1]) << "), " << "p.y+(" << co(n.input[2]) << ")); }" << std::endl; functions_.emplace_back(func_body.str()); return func_name + "("+ co(n.input[0]) + ")"; } case node::worley: { std::string func_name ("p_worley" + std::to_string(count_++)); std::stringstream func_body; func_body << "inline double " << func_name << " (const double2 q, uint seed) { " << " double2 p = p_worley(q, seed);" << " return " << co(n.input[1]) << "; }" << std::endl; functions_.emplace_back(func_body.str()); return func_name + "("+co(n.input[0])+ ","+co(n.input[2])+")"; } case node::voronoi: { std::string func_name ("p_voronoi" + std::to_string(count_++)); std::stringstream func_body; func_body << "inline double " << func_name << " (const double2 q, uint seed) { " << " double2 p = p_voronoi(q, seed);" << " return " << co(n.input[1]) << "; }" << std::endl; functions_.emplace_back(func_body.str()); return func_name + "("+co(n.input[0])+ ","+co(n.input[2])+")"; } case node::angle: return "p_angle" + pl(n); case node::chebyshev: return "p_chebyshev" + pl(n); case node::checkerboard: return "p_checkerboard" + pl(n); case node::distance: return "length" + pl(n); case node::manhattan: return "p_manhattan" + pl(n); case node::perlin: return "p_perlin" + pl(n); case node::x: return co(n.input[0])+".x"; case node::y: return co(n.input[0])+".y"; case node::add: return "("+co(n.input[0])+"+"+co(n.input[1])+")"; case node::sub: return "("+co(n.input[0])+"-"+co(n.input[1])+")"; case node::mul: return "("+co(n.input[0])+"*"+co(n.input[1])+")"; case node::div: return "("+co(n.input[0])+"/"+co(n.input[1])+")"; case node::abs: return "fabs" + pl(n); case node::blend: return "p_blend" + pl(n); case node::cos: return "cospi" + pl(n); case node::min: return "fmin" + pl(n); case node::max: return "fmax" + pl(n); case node::neg: return "-" + co(n.input[0]); case node::pow: { if (n.input[1].is_const) { double exp (std::floor(n.input[1].aux_var)); if (std::abs(exp - n.input[1].aux_var) < 1e-9) return "pown("+co(n.input[0])+","+std::to_string((int)exp)+")"; } return "pow"+pl(n); } case node::saw: return "p_saw" + pl(n); case node::sin: return "sinpi" + pl(n); case node::sqrt: return "sqrt" + pl(n); case node::tan: return "tanpi" + pl(n); case node::band: return co(n.input[0])+"&&"+co(n.input[1]); case node::bor: return co(n.input[0])+"||"+co(n.input[1]); case node::bxor: return co(n.input[0])+"^^"+co(n.input[1]); case node::bnot: return "!"+co(n.input[0]); case node::is_equal: return co(n.input[0])+"=="+co(n.input[1]); case node::is_greaterthan: return co(n.input[0])+">"+co(n.input[1]); case node::is_gte: return co(n.input[0])+">="+co(n.input[1]); case node::is_lessthan: return co(n.input[0])+"<"+co(n.input[1]); case node::is_lte: return co(n.input[0])+"<="+co(n.input[1]); case node::is_in_circle: return "p_is_in_circle" + pl(n); case node::is_in_rectangle: return "p_is_in_rectangle" + pl(n); case node::then_else: return "("+co(n.input[0])+")?("+co(n.input[1])+"):("+co(n.input[2])+")"; case node::fractal: { assert(n.input.size() == 5); if (!n.input[2].is_const) throw std::runtime_error("fractal octave count must be a constexpr"); int octaves (std::min<int>(n.input[2].aux_var, OPENCL_OCTAVES_LIMIT)); std::string func_name ("p_fractal_" + std::to_string(count_++)); std::stringstream func_body; func_body << "double " << func_name << " (double2 p, const double lac, const double per) {" << "double result = 0.0; double div = 0.0; double step = 1.0;" << "for(int i = 0; i < " << octaves << "; ++i)" << "{" << " result += " << co(n.input[1]) << " * step;" << " div += step;" << " step *= lac;" << " p *= per;" << "}" << "return result / div;" << "}"; functions_.emplace_back(func_body.str()); return func_name + "(" + co(n.input[0]) + "," + co(n.input[3]) + "," + co(n.input[4]) + ")"; } case node::lambda_: { assert(n.input.size() == 2); std::string func_name ("p_lambda_" + std::to_string(count_++)); std::stringstream func_body; func_body << "double " << func_name << " (double2 p) {" << "return " << co(n.input[1]) << ";}" << std::endl; functions_.emplace_back(func_body.str()); return func_name +"("+ co(n.input[0])+")"; } case node::external_: throw std::runtime_error("OpenCL @external not implemented yet"); case node::simplex: throw std::runtime_error("OpenCL simplex not implemented yet"); case node::curve_linear: throw std::runtime_error("OpenCL curve_linear not implemented yet"); case node::curve_spline: throw std::runtime_error("OpenCL curve_spline not implemented yet"); case node::png_lookup: throw std::runtime_error("OpenCL png_lookup not implemented yet"); default: throw std::runtime_error("function not implemented in OpenCL yet"); } return std::string(); } }} // namespace hexa::noise <commit_msg>Wait for kernel to finish before returning<commit_after>//--------------------------------------------------------------------------- // hexanoise/generator_opencl.cpp // // Copyright 2014, nocte@hippie.nu Released under the MIT License. //--------------------------------------------------------------------------- #include "generator_opencl.hpp" #include <iostream> #include <cmath> #include <fstream> #include <stdexcept> #include "node.hpp" #ifndef OPENCL_OCTAVES_LIMIT # define OPENCL_OCTAVES_LIMIT 16 #endif namespace hexa { namespace noise { generator_opencl::generator_opencl (const generator_context& ctx, cl::Context& opencl_context, cl::Device& opencl_device, const node& n, const std::string& opencl_file) : generator_i(ctx) , count_(1) , context_(opencl_context) , queue_ (opencl_context, opencl_device) { std::string body (co(n)); std::ifstream file (opencl_file.c_str(), std::ios::binary); if (!file) throw std::runtime_error("cannot open OpenCL file " + opencl_file); file.seekg(0, std::ios::end); main_.resize(file.tellg()); file.seekg(0, std::ios::beg); file.read(&main_[0], main_.size()); file.close(); main_ += "\n"; for (auto& p : functions_) { main_ += p; main_ += "\n\n"; } main_ += "\n" \ "__kernel void noisemain(\n" \ " __global double* output, const double2 start, const double2 step)\n" \ "{\n"\ " int2 coord = (int2)(get_global_id(0), get_global_id(1));\n"\ " int sizex = get_global_size(0);\n"\ " double2 p = mad(step, (double2)(coord.x, coord.y), start);\n" \ " output[coord.y * sizex + coord.x] = "; main_ += body; main_ += ";\n}\n"; std::vector<cl::Device> device_vec; device_vec.emplace_back(opencl_device); cl::Program::Sources sources (1, { main_.c_str(), main_.size() }); program_ = cl::Program(opencl_context, sources); try { program_.build(device_vec); } catch (cl::Error&) { std::cerr << program_.getBuildInfo<CL_PROGRAM_BUILD_LOG>(opencl_device) << std::endl; throw; } kernel_ = cl::Kernel(program_, "noisemain"); } std::vector<double> generator_opencl::run (const glm::dvec2& corner, const glm::dvec2& step, const glm::ivec2& count) { unsigned int width (count.x), height (count.y); std::vector<double> result (width * height); cl::Buffer output (context_, CL_MEM_WRITE_ONLY | CL_MEM_USE_HOST_PTR, result.size() * sizeof(double), &result[0]); kernel_.setArg(0, output); kernel_.setArg(1, sizeof(corner), (void*)&corner); kernel_.setArg(2, sizeof(step), (void*)&step); auto memobj (queue_.enqueueMapBuffer(output, true, CL_MAP_WRITE, 0, result.size() * sizeof(double))); cl::Event ev; queue_.enqueueNDRangeKernel(kernel_, cl::NullRange, {width, height}, cl::NullRange, nullptr, &ev); queue_.enqueueUnmapMemObject(output, memobj); ev.wait(); return result; } std::string generator_opencl::pl (const node& n) { std::string result ("("); for (auto i (n.input.begin()); i != n.input.end(); ) { result += co(*i); ++i; if (i != n.input.end()) result.push_back(','); } result += ')'; return result; } std::string generator_opencl::co (const node& n) { switch (n.type) { case node::entry_point: return "p"; case node::const_var: return std::to_string(n.aux_var); case node::const_bool: return std::to_string(n.aux_bool); case node::const_str: throw std::runtime_error("string encountered"); case node::rotate: return "p_rotate" + pl(n); case node::scale: return "("+co(n.input[0])+"/"+co(n.input[1])+")"; case node::shift: return "("+co(n.input[0])+"+"+co(n.input[1])+")"; case node::swap: return "p_swap" + pl(n); case node::map: { std::string func_name ("p_map" + std::to_string(count_++)); std::stringstream func_body; func_body << "inline double2 " << func_name << " (const double2 p) { return (double2)(" << co(n.input[1]) << ", " << co(n.input[2]) << "); }" << std::endl; functions_.emplace_back(func_body.str()); return func_name + "("+ co(n.input[0]) + ")"; } case node::turbulence: { std::string func_name ("p_map" + std::to_string(count_++)); std::stringstream func_body; func_body << "inline double2 " << func_name << " (const double2 p) { return (double2)(" << "p.x+(" << co(n.input[1]) << "), " << "p.y+(" << co(n.input[2]) << ")); }" << std::endl; functions_.emplace_back(func_body.str()); return func_name + "("+ co(n.input[0]) + ")"; } case node::worley: { std::string func_name ("p_worley" + std::to_string(count_++)); std::stringstream func_body; func_body << "inline double " << func_name << " (const double2 q, uint seed) { " << " double2 p = p_worley(q, seed);" << " return " << co(n.input[1]) << "; }" << std::endl; functions_.emplace_back(func_body.str()); return func_name + "("+co(n.input[0])+ ","+co(n.input[2])+")"; } case node::voronoi: { std::string func_name ("p_voronoi" + std::to_string(count_++)); std::stringstream func_body; func_body << "inline double " << func_name << " (const double2 q, uint seed) { " << " double2 p = p_voronoi(q, seed);" << " return " << co(n.input[1]) << "; }" << std::endl; functions_.emplace_back(func_body.str()); return func_name + "("+co(n.input[0])+ ","+co(n.input[2])+")"; } case node::angle: return "p_angle" + pl(n); case node::chebyshev: return "p_chebyshev" + pl(n); case node::checkerboard: return "p_checkerboard" + pl(n); case node::distance: return "length" + pl(n); case node::manhattan: return "p_manhattan" + pl(n); case node::perlin: return "p_perlin" + pl(n); case node::x: return co(n.input[0])+".x"; case node::y: return co(n.input[0])+".y"; case node::add: return "("+co(n.input[0])+"+"+co(n.input[1])+")"; case node::sub: return "("+co(n.input[0])+"-"+co(n.input[1])+")"; case node::mul: return "("+co(n.input[0])+"*"+co(n.input[1])+")"; case node::div: return "("+co(n.input[0])+"/"+co(n.input[1])+")"; case node::abs: return "fabs" + pl(n); case node::blend: return "p_blend" + pl(n); case node::cos: return "cospi" + pl(n); case node::min: return "fmin" + pl(n); case node::max: return "fmax" + pl(n); case node::neg: return "-" + co(n.input[0]); case node::pow: { if (n.input[1].is_const) { double exp (std::floor(n.input[1].aux_var)); if (std::abs(exp - n.input[1].aux_var) < 1e-9) return "pown("+co(n.input[0])+","+std::to_string((int)exp)+")"; } return "pow"+pl(n); } case node::saw: return "p_saw" + pl(n); case node::sin: return "sinpi" + pl(n); case node::sqrt: return "sqrt" + pl(n); case node::tan: return "tanpi" + pl(n); case node::band: return co(n.input[0])+"&&"+co(n.input[1]); case node::bor: return co(n.input[0])+"||"+co(n.input[1]); case node::bxor: return co(n.input[0])+"^^"+co(n.input[1]); case node::bnot: return "!"+co(n.input[0]); case node::is_equal: return co(n.input[0])+"=="+co(n.input[1]); case node::is_greaterthan: return co(n.input[0])+">"+co(n.input[1]); case node::is_gte: return co(n.input[0])+">="+co(n.input[1]); case node::is_lessthan: return co(n.input[0])+"<"+co(n.input[1]); case node::is_lte: return co(n.input[0])+"<="+co(n.input[1]); case node::is_in_circle: return "p_is_in_circle" + pl(n); case node::is_in_rectangle: return "p_is_in_rectangle" + pl(n); case node::then_else: return "("+co(n.input[0])+")?("+co(n.input[1])+"):("+co(n.input[2])+")"; case node::fractal: { assert(n.input.size() == 5); if (!n.input[2].is_const) throw std::runtime_error("fractal octave count must be a constexpr"); int octaves (std::min<int>(n.input[2].aux_var, OPENCL_OCTAVES_LIMIT)); std::string func_name ("p_fractal_" + std::to_string(count_++)); std::stringstream func_body; func_body << "double " << func_name << " (double2 p, const double lac, const double per) {" << "double result = 0.0; double div = 0.0; double step = 1.0;" << "for(int i = 0; i < " << octaves << "; ++i)" << "{" << " result += " << co(n.input[1]) << " * step;" << " div += step;" << " step *= lac;" << " p *= per;" << "}" << "return result / div;" << "}"; functions_.emplace_back(func_body.str()); return func_name + "(" + co(n.input[0]) + "," + co(n.input[3]) + "," + co(n.input[4]) + ")"; } case node::lambda_: { assert(n.input.size() == 2); std::string func_name ("p_lambda_" + std::to_string(count_++)); std::stringstream func_body; func_body << "double " << func_name << " (double2 p) {" << "return " << co(n.input[1]) << ";}" << std::endl; functions_.emplace_back(func_body.str()); return func_name +"("+ co(n.input[0])+")"; } case node::external_: throw std::runtime_error("OpenCL @external not implemented yet"); case node::simplex: throw std::runtime_error("OpenCL simplex not implemented yet"); case node::curve_linear: throw std::runtime_error("OpenCL curve_linear not implemented yet"); case node::curve_spline: throw std::runtime_error("OpenCL curve_spline not implemented yet"); case node::png_lookup: throw std::runtime_error("OpenCL png_lookup not implemented yet"); default: throw std::runtime_error("function not implemented in OpenCL yet"); } return std::string(); } }} // namespace hexa::noise <|endoftext|>
<commit_before>#include "frost.h" #include "forecast_time.h" #include "level.h" #include "logger.h" #include "plugin_factory.h" #include "fetcher.h" #include "radon.h" #include <NFmiLocation.h> #include <NFmiMetTime.h> using namespace std; using namespace himan; using namespace himan::plugin; // rampDown function returns a value between 1 and 0, // depending where valueInBetween is in the interval between start and end. double rampDown(const double& start, const double& end, const double& valueInBetween) { if (valueInBetween <= start) return 1.0; if (valueInBetween >= end) return 0.0; return (end - valueInBetween) / (end - start); } const param FParam("PROB-FROST-1"); frost::frost() { itsLogger = logger("frost"); } void frost::Process(std::shared_ptr<const plugin_configuration> conf) { Init(conf); SetParams({FParam}); Start(); } void frost::Calculate(shared_ptr<info<double>> myTargetInfo, unsigned short threadIndex) { NFmiMetTime theTime(static_cast<short>(stoi(myTargetInfo->Time().ValidDateTime().String("%Y"))), static_cast<short>(stoi(myTargetInfo->Time().ValidDateTime().String("%m"))), static_cast<short>(stoi(myTargetInfo->Time().ValidDateTime().String("%d"))), static_cast<short>(stoi(myTargetInfo->Time().ValidDateTime().String("%H"))), static_cast<short>(stoi(myTargetInfo->Time().ValidDateTime().String("%M")))); const param TParam("T-K"); const param TDParam("TD-K"); const param TGParam("TG-K"); const param WGParam("FFG-MS"); const param T0Param("PROB-TC-0"); const param NParam("N-PRCNT"); const param RADParam("RADGLO-WM2"); const param ICNParam("IC-0TO1"); //const param LCParam("LC-0TO1"); auto myThreadedLogger = logger("frostThread #" + to_string(threadIndex)); forecast_time forecastTime = myTargetInfo->Time(); level forecastLevel = myTargetInfo->Level(); forecast_type forecastType = myTargetInfo->ForecastType(); myThreadedLogger.Info("Calculating time " + static_cast<string>(forecastTime.ValidDateTime()) + ", level " + static_cast<string>(forecastLevel)); // Get the latest data from producer 181. info_t TInfo = Fetch(forecastTime, level(kHeight, 2), TParam, forecastType, false); info_t TDInfo = Fetch(forecastTime, level(kHeight, 2), TDParam, forecastType, false); info_t NInfo = Fetch(forecastTime, level(kHeight, 0), NParam, forecastType, false); // Change forecastTime for producer 131 due to varying forecastTime with producer 181. auto r = GET_PLUGIN(radon); auto latestFromDatabase = r->RadonDB().GetLatestTime(131, "", 0); forecastTime.OriginDateTime(latestFromDatabase); info_t TGInfo = Fetch(forecastTime, level(kGroundDepth, 0, 7), TGParam, forecastType, false); info_t WGInfo = Fetch(forecastTime, level(kGround, 0), WGParam, forecastType, false); // Change forecastTime to 00 or 12 if necessary. int latestHour = std::stoi(forecastTime.OriginDateTime().String("%H")); if (latestHour > 0 && latestHour < 12) { forecastTime.OriginDateTime().Adjust(kHourResolution, -latestHour); } if (latestHour > 12 && latestHour <= 23) { forecastTime.OriginDateTime().Adjust(kHourResolution, -latestHour); forecastTime.OriginDateTime().Adjust(kHourResolution, 12); } info_t ICNInfo = Fetch(forecastTime, level(kGround, 0), ICNParam, forecastType, false); //info_t LCInfo = Fetch(forecastTime, level(kGround, 0), LCParam, forecastType, false); // Get the latest RADGLO-WM2. info_t RADInfo; latestFromDatabase = r->RadonDB().GetLatestTime(240, "ECGLO0100", 0); forecastTime.OriginDateTime(latestFromDatabase); auto cnf = make_shared<plugin_configuration>(*itsConfiguration); auto f = GET_PLUGIN(fetcher); try { cnf->SourceProducers({producer(240, 86, 240, "ECGMTA")}); RADInfo = f->Fetch(cnf, forecastTime, level(kHeight, 0), RADParam, forecastType, false); } catch (HPExceptionType& e) { if (e == kFileDataNotFound) { myThreadedLogger.Error("No data found."); } return; } // Get the latest ECMWF PROB-TC-0. info_t T0ECInfo; latestFromDatabase = r->RadonDB().GetLatestTime(242, "ECEUR0200", 0); forecastTime.OriginDateTime(latestFromDatabase); forecast_type stat_type = forecast_type(kStatisticalProcessing); try { cnf->SourceProducers({producer(242, 86, 242, "ECM_PROB")}); cnf->SourceGeomNames({"ECEUR0200"}); T0ECInfo = f->Fetch(cnf, forecastTime, level(kGround, 0), T0Param, stat_type, false); } catch (HPExceptionType& e) { if (e == kFileDataNotFound) { myThreadedLogger.Error("No data found."); } return; } // Get the latest MEPS PROB-TC-0 from hour 00, 03, 06, 09, 12, 15, 18 or 21. info_t T0MEPSInfo; latestFromDatabase = r->RadonDB().GetLatestTime(260, "MEPS2500D", 1); forecastTime.OriginDateTime(latestFromDatabase); latestHour = std::stoi(forecastTime.OriginDateTime().String("%H")); if (latestHour == 1 || latestHour == 4 || latestHour == 7 || latestHour == 10 ||latestHour == 13 || latestHour == 16 ||latestHour == 19 || latestHour == 22) { forecastTime.OriginDateTime().Adjust(kHourResolution, -1); } if (latestHour == 2 || latestHour == 5 || latestHour == 8 || latestHour == 11 ||latestHour == 14 || latestHour == 17 ||latestHour == 20 || latestHour == 23) { forecastTime.OriginDateTime().Adjust(kHourResolution, -2); } try { cnf->SourceProducers({producer(260, 86, 204, "MEPSMTA")}); cnf->SourceGeomNames({"MEPS2500D"}); T0MEPSInfo = f->Fetch(cnf, forecastTime, level(kHeight, 2), T0Param, stat_type, false); } catch (HPExceptionType& e) { if (e == kFileDataNotFound) { myThreadedLogger.Error("No data found."); } return; } if (!TInfo || !TDInfo || !TGInfo || !WGInfo || !NInfo || !RADInfo || !T0ECInfo || !T0MEPSInfo || !ICNInfo) // LCINfo removed. { myThreadedLogger.Warning("Skipping step " + static_cast<string>(forecastTime.Step()) + ", level " + static_cast<string>(forecastLevel)); return; } string deviceType = "CPU"; LOCKSTEP(myTargetInfo, TInfo, TDInfo, TGInfo, WGInfo, NInfo, RADInfo, T0ECInfo, T0MEPSInfo, ICNInfo) // LCInfo removed. { double T = TInfo->Value() - himan::constants::kKelvin; double TD = TDInfo->Value() - himan::constants::kKelvin; double TG = TGInfo->Value() - himan::constants::kKelvin; double WG = WGInfo->Value(); double N = NInfo->Value(); double RAD = RADInfo->Value(); double T0EC = T0ECInfo->Value(); double T0MEPS = T0MEPSInfo->Value(); double ICN = ICNInfo->Value(); //double LC = LCInfo->Value(); if (IsMissingValue({T, TD, TG, WG, N, RAD, T0EC, T0MEPS, ICN})) // LC { continue; } // Calculating indexes and coefficients. // dewIndex double dewIndex = kHPMissingValue; dewIndex = rampDown(-5.0, 5.0, TD); // TD -5...5 // nIndex double nIndex = kHPMissingValue; nIndex = (100.0 - N) / 100.0; // tIndexHigh double tIndexHigh = kHPMissingValue; tIndexHigh = rampDown(2.5, 15.0, T) * rampDown(2.5, 15.0, T); // wgWind double wgWind = kHPMissingValue; wgWind = rampDown(1.0, 6.0, WG); double lowWindCoef = 1.0; double nCoef = 1.0; double weight = 4.0; double stabCoef = 1.5 * wgWind + 1.0; // Adjusting coefficients when T above and near zero. if (T >= 0 && T < 2.5) { lowWindCoef = rampDown(0, 2.5, T) * weight + 1.0; nCoef = 1.0 / lowWindCoef; } // Calculating frost probability. double frost_prob = MissingDouble(); if (T < -3.0) { frost_prob = 1.0; } else if (T < 0) { frost_prob = 0.9; } else { frost_prob = ((lowWindCoef * dewIndex) + stabCoef + (nCoef * nIndex)) / (lowWindCoef + stabCoef + (1.0 / lowWindCoef)) * tIndexHigh; } // Raising the frost probability due to ground temperature TG. double tgModel = kHPMissingValue; if (T < 5.0) { tgModel = sqrt(rampDown(-6.0, 5.0, TG)); } if (frost_prob < tgModel) { frost_prob = tgModel; } // Raising the frost probability due to probability of T<0 and T. Both EC and MEPS cases. if (T0EC > 0.6 && T < 5.0 && frost_prob < T0EC) { frost_prob = T0EC; } if (frost_prob < T0MEPS && T0MEPS > 0.4) { frost_prob = (frost_prob * 2.0 + T0MEPS) / 3.0; } // No frost when radiation is high enough. Valid in 1.4.-15.9. int month = stoi(forecastTime.ValidDateTime().String("%m")); int day = stoi(forecastTime.ValidDateTime().String("%d")); if ((month >= 4 && month <= 8) || (month == 9 && day <= 15)) { if (RAD > 175) { frost_prob = 0.0; } } // Lowering frost probability due to sun's elevation angle. Valid in 1.4.-15.9. if ((month >= 4 && month <= 8) || (month == 9 && day <= 15)) { NFmiLocation theLocation(myTargetInfo->LatLon().X(), myTargetInfo->LatLon().Y()); double elevationAngle = theLocation.ElevationAngle(theTime); double angleCoef = kHPMissingValue; angleCoef = rampDown(-1.0, 20.0, elevationAngle); frost_prob = angleCoef * frost_prob; } // No frost probability on sea when there is no ice. /*if (ICN == 0 && LC == 0) { frost_prob = 0; }*/ // Lowering frost probability when forecasted T is high enough. if (T > 6.0) { frost_prob = frost_prob * rampDown(6.0, 15.0, T); } myTargetInfo->Value(frost_prob); } myThreadedLogger.Info("[" + deviceType + "] Missing values: " + to_string(myTargetInfo->Data().MissingCount()) + "/" + to_string(myTargetInfo->Data().Size())); } <commit_msg>Code review changes, checks for forecast availability etc.<commit_after>#include "frost.h" #include "forecast_time.h" #include "level.h" #include "logger.h" #include "plugin_factory.h" #include "fetcher.h" #include "radon.h" #include <NFmiLocation.h> #include <NFmiMetTime.h> using namespace std; using namespace himan; using namespace himan::plugin; // rampDown function returns a value between 1 and 0, // depending where valueInBetween is in the interval between start and end. double rampDown(const double& start, const double& end, const double& valueInBetween) { if (valueInBetween <= start) return 1.0; if (valueInBetween >= end) return 0.0; return (end - valueInBetween) / (end - start); } const param FParam("PROB-FROST-1"); frost::frost() { itsLogger = logger("frost"); } void frost::Process(std::shared_ptr<const plugin_configuration> conf) { Init(conf); SetParams({FParam}); Start(); } void frost::Calculate(shared_ptr<info<double>> myTargetInfo, unsigned short threadIndex) { NFmiMetTime theTime(static_cast<short>(stoi(myTargetInfo->Time().ValidDateTime().String("%Y"))), static_cast<short>(stoi(myTargetInfo->Time().ValidDateTime().String("%m"))), static_cast<short>(stoi(myTargetInfo->Time().ValidDateTime().String("%d"))), static_cast<short>(stoi(myTargetInfo->Time().ValidDateTime().String("%H"))), static_cast<short>(stoi(myTargetInfo->Time().ValidDateTime().String("%M")))); const param TParam("T-K"); const param TDParam("TD-K"); const param TGParam("TG-K"); const param WGParam("FFG-MS"); const param T0Param("PROB-TC-0"); const param NParam("N-PRCNT"); const param RADParam("RADGLO-WM2"); const param ICNParam("IC-0TO1"); const param LCParam("LC-0TO1"); auto myThreadedLogger = logger("frostThread #" + to_string(threadIndex)); forecast_time forecastTime = myTargetInfo->Time(); level forecastLevel = myTargetInfo->Level(); forecast_type forecastType = myTargetInfo->ForecastType(); myThreadedLogger.Info("Calculating time " + static_cast<string>(forecastTime.ValidDateTime()) + ", level " + static_cast<string>(forecastLevel)); // Get the latest data from producer 181. info_t TInfo = Fetch(forecastTime, level(kHeight, 2), TParam, forecastType, false); info_t TDInfo = Fetch(forecastTime, level(kHeight, 2), TDParam, forecastType, false); info_t NInfo = Fetch(forecastTime, level(kHeight, 0), NParam, forecastType, false); // Change forecastTime for producer 131 due to varying forecastTime with producer 181. auto r = GET_PLUGIN(radon); auto latestFromDatabase = r->RadonDB().GetLatestTime(131, "", 0); forecastTime.OriginDateTime(latestFromDatabase); auto cnf = make_shared<plugin_configuration>(*itsConfiguration); auto f = GET_PLUGIN(fetcher); // Get the latest TG-K. info_t TGInfo; try { cnf->SourceProducers({producer(131, 98, 150, "ECG")}); TGInfo = f->Fetch(cnf, forecastTime, level(kGroundDepth, 0, 7), TGParam, forecastType, false); } catch (HPExceptionType& e) { if (e == kFileDataNotFound) { myThreadedLogger.Error("No data found."); } return; } // Get the latest FFG-MS. info_t WGInfo; try { cnf->SourceProducers({producer(131, 98, 150, "ECG")}); WGInfo = f->Fetch(cnf, forecastTime, level(kGround, 0), WGParam, forecastType, false); } catch (HPExceptionType& e) { if (e == kFileDataNotFound) { myThreadedLogger.Error("No data found."); } return; } // Get the latest IC-0TO1. info_t ICNInfo; // Change forecastTime to 00 or 12 if necessary. int latestHour = std::stoi(forecastTime.OriginDateTime().String("%H")); if (latestHour > 0 && latestHour < 12) { forecastTime.OriginDateTime().Adjust(kHourResolution, -latestHour); } if (latestHour > 12 && latestHour <= 23) { forecastTime.OriginDateTime().Adjust(kHourResolution, -latestHour); forecastTime.OriginDateTime().Adjust(kHourResolution, 12); } try { cnf->SourceProducers({producer(131, 98, 150, "ECG")}); ICNInfo = f->Fetch(cnf, forecastTime, level(kGround, 0), ICNParam, forecastType, false); } catch (HPExceptionType& e) { if (e == kFileDataNotFound) { myThreadedLogger.Error("No data found."); } return; } // Get the latest LC-0TO1, avalable only for hour 00. info_t LCInfo; forecast_time LC_time(forecastTime.OriginDateTime(), forecastTime.ValidDateTime()); latestFromDatabase = r->RadonDB().GetLatestTime(131, "ECEUR0100", 0); LC_time.OriginDateTime(latestFromDatabase); LC_time.ValidDateTime(forecastTime.OriginDateTime()); try { cnf->SourceProducers({producer(131, 98, 150, "ECG")}); cnf->SourceGeomNames({"ECEUR0100"}); LCInfo = f->Fetch(cnf, LC_time, level(kGround, 0), LCParam, forecastType, false); } catch (HPExceptionType& e) { if (e == kFileDataNotFound) { myThreadedLogger.Error("No data found."); } return; } // Get the latest RADGLO-WM2. info_t RADInfo; latestFromDatabase = r->RadonDB().GetLatestTime(240, "ECGLO0100", 0); forecastTime.OriginDateTime(latestFromDatabase); try { cnf->SourceProducers({producer(240, 86, 240, "ECGMTA")}); cnf->SourceGeomNames({"ECGLO0100"}); RADInfo = f->Fetch(cnf, forecastTime, level(kHeight, 0), RADParam, forecastType, false); } catch (HPExceptionType& e) { if (e == kFileDataNotFound) { myThreadedLogger.Error("No data found."); } return; } // Get the latest ECMWF PROB-TC-0. If not found, get earlier. info_t T0ECInfo; forecast_type stat_type = forecast_type(kStatisticalProcessing); int ec_offset = 0; latestFromDatabase = r->RadonDB().GetLatestTime(242, "ECEUR0200", ec_offset); forecastTime.OriginDateTime(latestFromDatabase); // ECMWF PROB-TC-0 is calculated only for every 3 hours. int forecastHour = std::stoi(forecastTime.ValidDateTime().String("%H")); if (forecastHour % 3 == 1 || forecastHour % 3 == 2) { myThreadedLogger.Error("ECMWF PROB-TC-0 not available for forecast hour: " + forecastTime.ValidDateTime().String("%H")); return; } bool success = false; while (success == false) { latestHour = std::stoi(forecastTime.OriginDateTime().String("%H")); try { success = true; cnf->SourceProducers({producer(242, 86, 242, "ECM_PROB")}); cnf->SourceGeomNames({"ECEUR0200"}); T0ECInfo = f->Fetch(cnf, forecastTime, level(kGround, 0), T0Param, stat_type, false); } catch (HPExceptionType& e) { if (e == kFileDataNotFound) { myThreadedLogger.Error("No data found."); } ec_offset++; if (ec_offset > 1) { return; } latestFromDatabase = r->RadonDB().GetLatestTime(242, "ECEUR0200", ec_offset); const string analtime = forecastTime.OriginDateTime().String("%Y-%m-%d %H:%M:%S"); myThreadedLogger.Error("ECMWF PROB-TC-0 from analysis time " + analtime + " not found, using " + static_cast<string>(latestFromDatabase)); forecastTime.OriginDateTime(latestFromDatabase); success = false; } } // Get the latest MEPS PROB-TC-0 from hour 00, 03, 06, 09, 12, 15, 18 or 21. If not found get earlier. info_t T0MEPSInfo; int MEPS_offset = 1; success = false; latestFromDatabase = r->RadonDB().GetLatestTime(260, "MEPS2500D", MEPS_offset); forecastTime.OriginDateTime(latestFromDatabase); while (success == false) { latestHour = std::stoi(forecastTime.OriginDateTime().String("%H")); if (latestHour == 1 || latestHour == 4 || latestHour == 7 || latestHour == 10 ||latestHour == 13 || latestHour == 16 ||latestHour == 19 || latestHour == 22) { forecastTime.OriginDateTime().Adjust(kHourResolution, -1); } if (latestHour == 2 || latestHour == 5 || latestHour == 8 || latestHour == 11 ||latestHour == 14 || latestHour == 17 ||latestHour == 20 || latestHour == 23) { forecastTime.OriginDateTime().Adjust(kHourResolution, -2); } try { success = true; cnf->SourceProducers({producer(260, 86, 204, "MEPSMTA")}); cnf->SourceGeomNames({"MEPS2500D"}); T0MEPSInfo = f->Fetch(cnf, forecastTime, level(kHeight, 2), T0Param, stat_type, false); } catch (HPExceptionType& e) { if (e == kFileDataNotFound) { myThreadedLogger.Error("No data found."); } MEPS_offset++; if (MEPS_offset > 2) { return; } latestFromDatabase = r->RadonDB().GetLatestTime(260, "MEPS2500D", MEPS_offset); const string analtime = forecastTime.OriginDateTime().String("%Y-%m-%d %H:%M:%S"); myThreadedLogger.Error("MEPS PROB-TC-0 from analysis time " + analtime + " not found, using " + static_cast<string>(latestFromDatabase)); forecastTime.OriginDateTime(latestFromDatabase); success = false; } } if (!TInfo || !TDInfo || !TGInfo || !WGInfo || !NInfo || !RADInfo || !T0ECInfo || !T0MEPSInfo || !ICNInfo || !LCInfo) { myThreadedLogger.Warning("Skipping step " + static_cast<string>(forecastTime.Step()) + ", level " + static_cast<string>(forecastLevel)); return; } string deviceType = "CPU"; LOCKSTEP(myTargetInfo, TInfo, TDInfo, TGInfo, WGInfo, NInfo, RADInfo, T0ECInfo, T0MEPSInfo, ICNInfo, LCInfo) { double T = TInfo->Value() - himan::constants::kKelvin; double TD = TDInfo->Value() - himan::constants::kKelvin; double TG = TGInfo->Value() - himan::constants::kKelvin; double WG = WGInfo->Value(); double N = NInfo->Value(); double RAD = RADInfo->Value(); double T0EC = T0ECInfo->Value(); double T0MEPS = T0MEPSInfo->Value(); double ICN = ICNInfo->Value(); double LC = LCInfo->Value(); if (IsMissingValue({T, TD, TG, WG, N, RAD, T0EC, T0MEPS, ICN, LC})) { continue; } // Calculating indexes and coefficients. // dewIndex double dewIndex = kHPMissingValue; dewIndex = rampDown(-5.0, 5.0, TD); // TD -5...5 // nIndex double nIndex = kHPMissingValue; nIndex = (100.0 - N) / 100.0; // tIndexHigh double tIndexHigh = kHPMissingValue; tIndexHigh = rampDown(2.5, 15.0, T) * rampDown(2.5, 15.0, T); // wgWind double wgWind = kHPMissingValue; wgWind = rampDown(1.0, 6.0, WG); double lowWindCoef = 1.0; double nCoef = 1.0; double weight = 4.0; double stabCoef = 1.5 * wgWind + 1.0; // Adjusting coefficients when T above and near zero. if (T >= 0 && T < 2.5) { lowWindCoef = rampDown(0, 2.5, T) * weight + 1.0; nCoef = 1.0 / lowWindCoef; } // Calculating frost probability. double frost_prob = MissingDouble(); if (T < -3.0) { frost_prob = 1.0; } else if (T < 0) { frost_prob = 0.9; } else { frost_prob = ((lowWindCoef * dewIndex) + stabCoef + (nCoef * nIndex)) / (lowWindCoef + stabCoef + (1.0 / lowWindCoef)) * tIndexHigh; } // Raising the frost probability due to ground temperature TG. double tgModel = kHPMissingValue; if (T < 5.0) { tgModel = sqrt(rampDown(-6.0, 5.0, TG)); } if (frost_prob < tgModel) { frost_prob = tgModel; } // Raising the frost probability due to probability of T<0 and T. Both EC and MEPS cases. if (T0EC > 0.6 && T < 5.0 && frost_prob < T0EC) { frost_prob = T0EC; } if (frost_prob < T0MEPS && T0MEPS > 0.4) { frost_prob = (frost_prob * 2.0 + T0MEPS) / 3.0; } // No frost when radiation is high enough. Valid in 1.4.-15.9. int month = stoi(forecastTime.ValidDateTime().String("%m")); int day = stoi(forecastTime.ValidDateTime().String("%d")); if ((month >= 4 && month <= 8) || (month == 9 && day <= 15)) { if (RAD > 175) { frost_prob = 0.0; } } // Lowering frost probability due to sun's elevation angle. Valid in 1.4.-15.9. if ((month >= 4 && month <= 8) || (month == 9 && day <= 15)) { NFmiLocation theLocation(myTargetInfo->LatLon().X(), myTargetInfo->LatLon().Y()); double elevationAngle = theLocation.ElevationAngle(theTime); double angleCoef = kHPMissingValue; angleCoef = rampDown(-1.0, 20.0, elevationAngle); frost_prob = angleCoef * frost_prob; } // No frost probability on sea when there is no ice. if (ICN == 0 && LC == 0) { frost_prob = 0; } // Lowering frost probability when forecasted T is high enough. if (T > 6.0) { frost_prob = frost_prob * rampDown(6.0, 15.0, T); } myTargetInfo->Value(frost_prob); } myThreadedLogger.Info("[" + deviceType + "] Missing values: " + to_string(myTargetInfo->Data().MissingCount()) + "/" + to_string(myTargetInfo->Data().Size())); } <|endoftext|>
<commit_before>/* options.cpp - CS 472 Project #2: Genetic Programming * Copyright 2014 Andrew Schwartzmeyer * * Source file for options namespace */ #include <cassert> #include <cstdlib> #include <fstream> #include <iostream> #include <sstream> #include <boost/program_options.hpp> #include "options.hpp" namespace options { Position::Position(): x{0}, y{0}, direction{Direction::east} {} Map::Map(): width{0}, height{0}, ticks{0}, max_ticks{0}, score{0}, pieces{0}, position{Position{}} {} Map::Map(std::string filename, unsigned int ticks): width{0}, height{0}, ticks{0}, max_ticks{ticks}, score{0}, pieces{0}, position{Position{}} { // Try to open the given file. std::ifstream data_file{filename}; if (not data_file.is_open()) { std::cerr << "File " << filename << " could not be read!\n"; std::exit(EXIT_FAILURE); } // Parse file into map structure std::string line; while (data_file >> line) { std::vector<Cell> row; if (width != 0) row.reserve(width); for (const char& c : line) { if (c != '.' and c != 'x' and c != '\n') { std::cerr << "File " << filename << " had bad cells!\n" << "They were: " << c << std::endl; std::exit(EXIT_FAILURE); } else if (c != '\n') { Cell cell = (c == 'x') ? Cell{Cell::food} : Cell{Cell::blank}; row.emplace_back(cell); if (cell == Cell::food) ++pieces; } } if (width == 0) width = row.size(); // Get initial width else if (row.size() != width) { // Verify all lines are same width std::cerr << "File " << filename << " had uneven lines!\n" << "The width is: " << width << " and the line was " << row.size() << std::endl; std::exit(EXIT_FAILURE); } rows.emplace_back(row); } height = rows.size(); } bool Map::active() const { return ticks < max_ticks; } bool Map::look() const { Position ahead = position; if (position.direction == Direction::north) ahead.y = (position.y - 1) % height; else if (position.direction == Direction::west) ahead.x = (position.x - 1) % width; else if (position.direction == Direction::south) ahead.y = (position.y + 1) % height; else if (position.direction == Direction::east) ahead.y = (position.x + 1) % width; return rows[ahead.y][ahead.x] == Cell::food; } bool Map::forward() { // Move forward in specified direction if (position.direction == Direction::north) position.y = (position.y - 1) % height; else if (position.direction == Direction::west) position.x = (position.x - 1) % width; else if (position.direction == Direction::south) position.y = (position.y + 1) % height; else if (position.direction == Direction::east) position.y = (position.x + 1) % width; // Increment score if moved onto food if (rows[position.y][position.x] == Cell::food) ++score; // Mark location on map as visitied rows[position.y][position.x] = Cell::marked; ++ticks; return active(); } bool Map::left() { if (position.direction == Direction::north) position.direction = Direction::west; else if (position.direction == Direction::west) position.direction = Direction::south; else if (position.direction == Direction::south) position.direction = Direction::east; else if (position.direction == Direction::east) position.direction = Direction::north; ++ticks; return active(); } bool Map::right() { if (position.direction == Direction::north) position.direction = Direction::east; else if (position.direction == Direction::east) position.direction = Direction::south; else if (position.direction == Direction::south) position.direction = Direction::west; else if (position.direction == Direction::west) position.direction = Direction::north; ++ticks; return active(); } unsigned int Map::fitness() const { return score; } unsigned int Map::max() const { return pieces; } std::string Map::print() const { std::stringstream out; out << "# 'x' is food and 'o' is ant trail\n"; for (const std::vector<Cell>& row : rows) { for (const Cell& cell : row) { // Add blank, food, and marked locations if (cell == Cell::blank) out << '.'; else if (cell == Cell::food) out << 'x'; else if (cell == Cell::marked) out << 'o'; else { std::cerr << "Map is malformed!\n"; std::exit(EXIT_FAILURE); } } // Add newline after each row out << '\n'; } return out.str(); } // Validates options parameters; should instead be unit tests. void Options::validate() const { assert(trials > 0); assert(iterations > 0); assert(population_size > 0); assert(tournament_size > 0 and tournament_size <= population_size); assert(crossover_size == 2); assert(elitism_size <= population_size); assert(grow_chance >= 0 and grow_chance <= 1); assert(mutate_chance >= 0 and mutate_chance <= 1); assert(crossover_chance >= 0 and crossover_chance <= 1); assert(internals_chance >= 0 and internals_chance <= 1); } /* Given main's argc and argv, this will parse command-line options and the optional config file to return a built-up Options struct with all values, default or explicitly set. */ const Options parse(int argc, char* argv[]) { using std::string; using namespace boost::program_options; string filename; unsigned int ticks; Options options; positional_options_description positionals; variables_map variables_map; options_description description{"Allowed options"}; // sets up all available CLI options description.add_options() ("help,h", "produce help message") ("config,c", value<string>()-> default_value("search.cfg"), "specify the configuration file") ("file,f", value<string>(&filename)-> default_value("test/santa-fe-trail.dat"), "specify the location of the columnized test data \"X Y\"") ("trials,t", value<unsigned int>(&options.trials)-> default_value(4), "set the number of trials to run") ("iterations,i", value<unsigned int>(&options.iterations)-> default_value(128), "set the number of iterations for which to run each trial") ("population,p", value<unsigned int>(&options.population_size)-> default_value(128), "set the size of each population") ("depth,d", value<unsigned int>(&options.max_depth)-> default_value(4), "set the maximum depth for initial populations") ("tournament,T", value<unsigned int>(&options.tournament_size)-> default_value(3), "set the tournment size to adjust selection pressure") ("crossover,C", value<unsigned int>(&options.crossover_size)-> default_value(2), "set the crossover size(binary in current implementation)") ("elitism,e", value<unsigned int>(&options.elitism_size)-> default_value(2), "set the number of elitism replacements to make each iteration") ("ticks", value<unsigned int>(&ticks)-> default_value(600), "set the number of moves the any may move") ("penalty,P", value<double>(&options.penalty)-> default_value(0.1), "set the constant scalar of the size penalty for fitness") ("grow,g", value<double>(&options.grow_chance)-> default_value(0.5), "set the probability that an initial tree will be made by the grow method") ("mutate,m", value<double>(&options.mutate_chance)-> default_value(0.01), "set the probability that a single node will mutate") ("crossover_chance", value<double>(&options.crossover_chance)-> default_value(0.8), "set the probability that a selected pair of invididuals will undergo crossover") ("internals,I", value<double>(&options.internals_chance)-> default_value(0.9), "set the probability that a crossover target node will be an internal node") ("logs", value<string>(&options.logs_dir)-> default_value("logs/"), "set the save directory for log files") ("plots", value<string>(&options.plots_dir)-> default_value("plots/"), "set the save directory for plot data files") ("verbosity,v", value<unsigned int>(&options.verbosity)-> default_value(1), "set the verbosity: 0 - no logging; 1 - normal logging; 2 - debug output"); /* Stores CLI and config file options. Will catch exception and exit with EXIT_FAILURE if given bad input. */ try { store(parse_command_line(argc, argv, description), variables_map); std::ifstream config{variables_map["config"].as<string>()}; if (config.is_open()) store(parse_config_file(config, description), variables_map); notify(variables_map); } catch (std::exception& e) { std::cerr << e.what() << std::endl; std::exit(EXIT_FAILURE); } // Print options help and exit with EXIT_SUCCESS when finished. if (variables_map.count("help")) { std::cout << "Genetic Program implemented in C++ by Andrew Schwartzmeyer\n" << "Code located at https://github.com/andschwa/uidaho-cs472-project2\n\n" << "Logs saved to <logs>/<Unix time>.dat\n" << "Plot data saved to <plots>/<Unix time>.dat\n" << "GNUPlot PNG generation script './plot <plots>'\n\n" << description << std::endl; std::exit(EXIT_SUCCESS); } // get values from given test file options.map = Map(filename, ticks); options.validate(); return options; } } <commit_msg>Alex wins; switched to switches; reindented<commit_after>/* options.cpp - CS 472 Project #2: Genetic Programming * Copyright 2014 Andrew Schwartzmeyer * * Source file for options namespace */ #include <cassert> #include <cstdlib> #include <fstream> #include <iostream> #include <sstream> #include <boost/program_options.hpp> #include "options.hpp" namespace options { Position::Position(): x{0}, y{0}, direction{Direction::east} {} Map::Map(): width{0}, height{0}, ticks{0}, max_ticks{0}, score{0}, pieces{0}, position{Position{}} {} Map::Map(std::string filename, unsigned int ticks): width{0}, height{0}, ticks{0}, max_ticks{ticks}, score{0}, pieces{0}, position{Position{}} { // Try to open the given file. std::ifstream data_file{filename}; if (not data_file.is_open()) { std::cerr << "File " << filename << " could not be read!\n"; std::exit(EXIT_FAILURE); } // Parse file into map structure std::string line; while (data_file >> line) { std::vector<Cell> row; if (width != 0) row.reserve(width); for (const char& c : line) { if (c != '.' and c != 'x' and c != '\n') { std::cerr << "File " << filename << " had bad cells!\n" << "They were: " << c << std::endl; std::exit(EXIT_FAILURE); } else if (c != '\n') { Cell cell = (c == 'x') ? Cell{Cell::food} : Cell{Cell::blank}; row.emplace_back(cell); if (cell == Cell::food) ++pieces; } } if (width == 0) width = row.size(); // Get initial width else if (row.size() != width) { // Verify all lines are same width std::cerr << "File " << filename << " had uneven lines!\n" << "The width is: " << width << " and the line was " << row.size() << std::endl; std::exit(EXIT_FAILURE); } rows.emplace_back(row); } height = rows.size(); } bool Map::active() const { return ticks < max_ticks; } bool Map::look() const { Position ahead = position; switch (position.direction) { case Direction::north: ahead.y = (position.y - 1) % height; break; case Direction::west: ahead.x = (position.x - 1) % width; break; case Direction::south: ahead.y = (position.y + 1) % height; break; case Direction::east: ahead.y = (position.x + 1) % width; break; } return rows[ahead.y][ahead.x] == Cell::food; } bool Map::forward() { switch (position.direction) { case Direction::north: position.y = (position.y - 1) % height; break; case Direction::west: position.x = (position.x - 1) % width; break; case Direction::south: position.y = (position.y + 1) % height; break; case Direction::east: position.y = (position.x + 1) % width; break; } // Increment score if moved onto food if (rows[position.y][position.x] == Cell::food) ++score; // Mark location on map as visitied rows[position.y][position.x] = Cell::marked; ++ticks; return active(); } bool Map::left() { switch (position.direction) { case Direction::north: position.direction = Direction::west; break; case Direction::west: position.direction = Direction::south; break; case Direction::south: position.direction = Direction::east; break; case Direction::east: position.direction = Direction::north; break; } ++ticks; return active(); } bool Map::right() { switch (position.direction) { case Direction::north: position.direction = Direction::east; break; case Direction::east: position.direction = Direction::south; break; case Direction::south: position.direction = Direction::west; break; case Direction::west: position.direction = Direction::north; break; } ++ticks; return active(); } unsigned int Map::fitness() const { return score; } unsigned int Map::max() const { return pieces; } std::string Map::print() const { std::stringstream out; out << "# 'x' is food and 'o' is ant trail\n"; for (const std::vector<Cell>& row : rows) { for (const Cell& cell : row) { // Add blank, food, and marked locations if (cell == Cell::blank) out << '.'; else if (cell == Cell::food) out << 'x'; else if (cell == Cell::marked) out << 'o'; else { std::cerr << "Map is malformed!\n"; std::exit(EXIT_FAILURE); } } // Add newline after each row out << '\n'; } return out.str(); } // Validates options parameters; should instead be unit tests. void Options::validate() const { assert(trials > 0); assert(iterations > 0); assert(population_size > 0); assert(tournament_size > 0 and tournament_size <= population_size); assert(crossover_size == 2); assert(elitism_size <= population_size); assert(grow_chance >= 0 and grow_chance <= 1); assert(mutate_chance >= 0 and mutate_chance <= 1); assert(crossover_chance >= 0 and crossover_chance <= 1); assert(internals_chance >= 0 and internals_chance <= 1); } /* Given main's argc and argv, this will parse command-line options and the optional config file to return a built-up Options struct with all values, default or explicitly set. */ const Options parse(int argc, char* argv[]) { using std::string; using namespace boost::program_options; string filename; unsigned int ticks; Options options; positional_options_description positionals; variables_map variables_map; options_description description{"Allowed options"}; // sets up all available CLI options description.add_options() ("help,h", "produce help message") ("config,c", value<string>()-> default_value("search.cfg"), "specify the configuration file") ("file,f", value<string>(&filename)-> default_value("test/santa-fe-trail.dat"), "specify the location of the columnized test data \"X Y\"") ("trials,t", value<unsigned int>(&options.trials)-> default_value(4), "set the number of trials to run") ("iterations,i", value<unsigned int>(&options.iterations)-> default_value(128), "set the number of iterations for which to run each trial") ("population,p", value<unsigned int>(&options.population_size)-> default_value(128), "set the size of each population") ("depth,d", value<unsigned int>(&options.max_depth)-> default_value(4), "set the maximum depth for initial populations") ("tournament,T", value<unsigned int>(&options.tournament_size)-> default_value(3), "set the tournment size to adjust selection pressure") ("crossover,C", value<unsigned int>(&options.crossover_size)-> default_value(2), "set the crossover size(binary in current implementation)") ("elitism,e", value<unsigned int>(&options.elitism_size)-> default_value(2), "set the number of elitism replacements to make each iteration") ("ticks", value<unsigned int>(&ticks)-> default_value(600), "set the number of moves the any may move") ("penalty,P", value<double>(&options.penalty)-> default_value(0.1), "set the constant scalar of the size penalty for fitness") ("grow,g", value<double>(&options.grow_chance)-> default_value(0.5), "set the probability that an initial tree will be made by the grow method") ("mutate,m", value<double>(&options.mutate_chance)-> default_value(0.01), "set the probability that a single node will mutate") ("crossover_chance", value<double>(&options.crossover_chance)-> default_value(0.8), "set the probability that a selected pair of invididuals will undergo crossover") ("internals,I", value<double>(&options.internals_chance)-> default_value(0.9), "set the probability that a crossover target node will be an internal node") ("logs", value<string>(&options.logs_dir)-> default_value("logs/"), "set the save directory for log files") ("plots", value<string>(&options.plots_dir)-> default_value("plots/"), "set the save directory for plot data files") ("verbosity,v", value<unsigned int>(&options.verbosity)-> default_value(1), "set the verbosity: 0 - no logging; 1 - normal logging; 2 - debug output"); /* Stores CLI and config file options. Will catch exception and exit with EXIT_FAILURE if given bad input. */ try { store(parse_command_line(argc, argv, description), variables_map); std::ifstream config{variables_map["config"].as<string>()}; if (config.is_open()) store(parse_config_file(config, description), variables_map); notify(variables_map); } catch (std::exception& e) { std::cerr << e.what() << std::endl; std::exit(EXIT_FAILURE); } // Print options help and exit with EXIT_SUCCESS when finished. if (variables_map.count("help")) { std::cout << "Genetic Program implemented in C++ by Andrew Schwartzmeyer\n" << "Code located at https://github.com/andschwa/uidaho-cs472-project2\n\n" << "Logs saved to <logs>/<Unix time>.dat\n" << "Plot data saved to <plots>/<Unix time>.dat\n" << "GNUPlot PNG generation script './plot <plots>'\n\n" << description << std::endl; std::exit(EXIT_SUCCESS); } // get values from given test file options.map = Map(filename, ticks); options.validate(); return options; } } <|endoftext|>
<commit_before>// $Id$ /* Copyright (c) 2007-2009, Trustees of The Leland Stanford Junior University All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of the Stanford University nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef _TRAFFICMANAGER_HPP_ #define _TRAFFICMANAGER_HPP_ #include <list> #include <map> #include <set> #include "module.hpp" #include "config_utils.hpp" #include "network.hpp" #include "flit.hpp" #include "buffer_state.hpp" #include "stats.hpp" #include "traffic.hpp" #include "routefunc.hpp" #include "outputset.hpp" #include "injection.hpp" #include <assert.h> //register the requests to a node struct Packet_Reply { int source; int time; int ttime; bool record; Flit::FlitType type; }; class TrafficManager : public Module { protected: unsigned int _sources; unsigned int _dests; unsigned int _routers; vector<Network *> _net; vector<vector<Router *> > _router_map; // ============ Message priorities ============ enum ePriority { class_based, age_based, network_age_based, local_age_based, queue_length_based, hop_count_based, sequence_based, none }; ePriority _pri_type; int _classes; // ============ Injection VC states ============ vector<vector<BufferState *> > _buf_states; // ============ Injection queues ============ int _voqing; vector<vector<int> > _qtime; vector<vector<bool> > _qdrained; vector<vector<vector<list<Flit *> > > > _partial_packets; map<int, Flit *> _measured_in_flight_flits; multimap<int, Flit *> _measured_in_flight_packets; map<int, Flit *> _total_in_flight_flits; multimap<int, Flit *> _total_in_flight_packets; bool _empty_network; bool _use_lagging; // ============ sub-networks and deadlock ========== short _duplicate_networks; unsigned char _deadlock_counter; // ============ batch mode ========================== vector<int> _packets_sent; int _batch_size; int _batch_count; vector<list<int> > _repliesPending; map<int, Packet_Reply*> _repliesDetails; vector<int> _requestsOutstanding; int _maxOutstanding; bool _replies_inherit_priority; int _last_id; int _last_pid; // ============voq mode ============================= vector<vector<list<Flit*> > > _voq; vector<list<int> > _active_list; vector<vector<bool> > _active_vc; // ============ Statistics ============ vector<Stats *> _latency_stats; vector<Stats *> _overall_min_latency; vector<Stats *> _overall_avg_latency; vector<Stats *> _overall_max_latency; vector<Stats *> _tlat_stats; vector<Stats *> _overall_min_tlat; vector<Stats *> _overall_avg_tlat; vector<Stats *> _overall_max_tlat; vector<Stats *> _frag_stats; vector<Stats *> _overall_min_frag; vector<Stats *> _overall_avg_frag; vector<Stats *> _overall_max_frag; vector<Stats *> _pair_latency; vector<Stats *> _pair_tlat; Stats * _hop_stats; vector<Stats *> _sent_flits; vector<Stats *> _accepted_flits; Stats * _overall_accepted; Stats * _overall_accepted_min; Stats * _batch_time; Stats * _overall_batch_time; vector<unsigned int> _injected_flow; vector<unsigned int> _ejected_flow; vector<unsigned int> _received_flow; vector<unsigned int> _sent_flow; vector<int> _slowest_flit; map<string, Stats *> _stats; // ============ Simulation parameters ============ enum eSimState { warming_up, running, draining, done }; eSimState _sim_state; enum eSimMode { latency, throughput, batch }; eSimMode _sim_mode; //batched time-mode, know what you are doing bool _timed_mode; int _limit; //any higher clients do not generate packets int _warmup_time; int _drain_time; float _load; float _flit_rate; int _packet_size; /*false means all packet types are the same length "gConstantsize" *All packets uses all VCS *packet types are generated randomly, essentially making it only 1 type *of packet in the network * *True means only request packets are generated and replies are generated *as a response to the requests, packets are now difference length, correspond *to "read_request_size" etc. */ bool _use_read_write; int _read_request_size; int _read_reply_size; int _write_request_size; int _write_reply_size; int _total_sims; int _sample_period; int _max_samples; int _warmup_periods; vector<vector<short> > _class_array; short _sub_network; int _include_queuing; double _latency_thres; double _stopping_threshold; double _acc_stopping_threshold; double _warmup_threshold; float _internal_speedup; vector<float> _partial_internal_cycles; int _cur_id; int _cur_pid; int _time; list<Flit *> _used_flits; list<Flit *> _free_flits; tTrafficFunction _traffic_function; tRoutingFunction _routing_function; tInjectionProcess _injection_process; set<int> _flits_to_watch; set<int> _packets_to_watch; bool _print_csv_results; bool _print_vc_stats; string _traffic; bool _drain_measured_only; //flits to watch ostream * _stats_out; ostream * _flow_out; // ============ Internal methods ============ protected: virtual Flit *_NewFlit( ); virtual void _RetireFlit( Flit *f, int dest ); void _FirstStep( ); void _NormalInject(); void _BatchInject(); void _Step( ); bool _PacketsOutstanding( ) const; virtual int _IssuePacket( int source, int cl ); virtual void _GeneratePacket( int source, int size, int cl, int time ); void _ClearStats( ); int _ComputeStats( const vector<Stats *> & stats, double *avg, double *min ) const; virtual bool _SingleSim( ); int DivisionAlgorithm(int packet_type); void _DisplayRemaining( ) const; void _LoadWatchList(const string & filename); public: TrafficManager( const Configuration &config, const vector<Network *> & net ); ~TrafficManager( ); bool Run( ); void DisplayStats(); const Stats * GetOverallLatency(int c) { return _overall_avg_latency[c]; } const Stats * GetAccepted() { return _overall_accepted; } const Stats * GetAcceptedMin() { return _overall_accepted_min; } const Stats * GetHops() { return _hop_stats; } inline int getTime() { return _time;} Stats * getStats(const string & name) { return _stats[name]; } }; #endif <commit_msg>remove obsolete member variables<commit_after>// $Id$ /* Copyright (c) 2007-2009, Trustees of The Leland Stanford Junior University All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of the Stanford University nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef _TRAFFICMANAGER_HPP_ #define _TRAFFICMANAGER_HPP_ #include <list> #include <map> #include <set> #include "module.hpp" #include "config_utils.hpp" #include "network.hpp" #include "flit.hpp" #include "buffer_state.hpp" #include "stats.hpp" #include "traffic.hpp" #include "routefunc.hpp" #include "outputset.hpp" #include "injection.hpp" #include <assert.h> //register the requests to a node struct Packet_Reply { int source; int time; int ttime; bool record; Flit::FlitType type; }; class TrafficManager : public Module { protected: unsigned int _sources; unsigned int _dests; unsigned int _routers; vector<Network *> _net; vector<vector<Router *> > _router_map; // ============ Message priorities ============ enum ePriority { class_based, age_based, network_age_based, local_age_based, queue_length_based, hop_count_based, sequence_based, none }; ePriority _pri_type; int _classes; // ============ Injection VC states ============ vector<vector<BufferState *> > _buf_states; // ============ Injection queues ============ int _voqing; vector<vector<int> > _qtime; vector<vector<bool> > _qdrained; vector<vector<vector<list<Flit *> > > > _partial_packets; map<int, Flit *> _measured_in_flight_flits; multimap<int, Flit *> _measured_in_flight_packets; map<int, Flit *> _total_in_flight_flits; multimap<int, Flit *> _total_in_flight_packets; bool _empty_network; bool _use_lagging; // ============ sub-networks and deadlock ========== short _duplicate_networks; unsigned char _deadlock_counter; // ============ batch mode ========================== vector<int> _packets_sent; int _batch_size; int _batch_count; vector<list<int> > _repliesPending; map<int, Packet_Reply*> _repliesDetails; vector<int> _requestsOutstanding; int _maxOutstanding; bool _replies_inherit_priority; int _last_id; int _last_pid; // ============voq mode ============================= vector<vector<list<Flit*> > > _voq; vector<list<int> > _active_list; vector<vector<bool> > _active_vc; // ============ Statistics ============ vector<Stats *> _latency_stats; vector<Stats *> _overall_min_latency; vector<Stats *> _overall_avg_latency; vector<Stats *> _overall_max_latency; vector<Stats *> _tlat_stats; vector<Stats *> _overall_min_tlat; vector<Stats *> _overall_avg_tlat; vector<Stats *> _overall_max_tlat; vector<Stats *> _frag_stats; vector<Stats *> _overall_min_frag; vector<Stats *> _overall_avg_frag; vector<Stats *> _overall_max_frag; vector<Stats *> _pair_latency; vector<Stats *> _pair_tlat; Stats * _hop_stats; vector<Stats *> _sent_flits; vector<Stats *> _accepted_flits; Stats * _overall_accepted; Stats * _overall_accepted_min; Stats * _batch_time; Stats * _overall_batch_time; vector<unsigned int> _injected_flow; vector<unsigned int> _ejected_flow; vector<unsigned int> _received_flow; vector<unsigned int> _sent_flow; vector<int> _slowest_flit; map<string, Stats *> _stats; // ============ Simulation parameters ============ enum eSimState { warming_up, running, draining, done }; eSimState _sim_state; enum eSimMode { latency, throughput, batch }; eSimMode _sim_mode; //batched time-mode, know what you are doing bool _timed_mode; int _limit; //any higher clients do not generate packets int _warmup_time; int _drain_time; float _load; float _flit_rate; int _packet_size; /*false means all packet types are the same length "gConstantsize" *All packets uses all VCS *packet types are generated randomly, essentially making it only 1 type *of packet in the network * *True means only request packets are generated and replies are generated *as a response to the requests, packets are now difference length, correspond *to "read_request_size" etc. */ bool _use_read_write; int _read_request_size; int _read_reply_size; int _write_request_size; int _write_reply_size; int _total_sims; int _sample_period; int _max_samples; int _warmup_periods; vector<vector<short> > _class_array; short _sub_network; int _include_queuing; double _latency_thres; double _stopping_threshold; double _acc_stopping_threshold; double _warmup_threshold; float _internal_speedup; vector<float> _partial_internal_cycles; int _cur_id; int _cur_pid; int _time; tTrafficFunction _traffic_function; tRoutingFunction _routing_function; tInjectionProcess _injection_process; set<int> _flits_to_watch; set<int> _packets_to_watch; bool _print_csv_results; bool _print_vc_stats; string _traffic; bool _drain_measured_only; //flits to watch ostream * _stats_out; ostream * _flow_out; // ============ Internal methods ============ protected: virtual Flit *_NewFlit( ); virtual void _RetireFlit( Flit *f, int dest ); void _FirstStep( ); void _NormalInject(); void _BatchInject(); void _Step( ); bool _PacketsOutstanding( ) const; virtual int _IssuePacket( int source, int cl ); virtual void _GeneratePacket( int source, int size, int cl, int time ); void _ClearStats( ); int _ComputeStats( const vector<Stats *> & stats, double *avg, double *min ) const; virtual bool _SingleSim( ); int DivisionAlgorithm(int packet_type); void _DisplayRemaining( ) const; void _LoadWatchList(const string & filename); public: TrafficManager( const Configuration &config, const vector<Network *> & net ); ~TrafficManager( ); bool Run( ); void DisplayStats(); const Stats * GetOverallLatency(int c) { return _overall_avg_latency[c]; } const Stats * GetAccepted() { return _overall_accepted; } const Stats * GetAcceptedMin() { return _overall_accepted_min; } const Stats * GetHops() { return _hop_stats; } inline int getTime() { return _time;} Stats * getStats(const string & name) { return _stats[name]; } }; #endif <|endoftext|>
<commit_before>/* * MRustC - Rust Compiler * - By John Hodge (Mutabah/thePowersGang) * * trans/mangling.hpp * - Name mangling support * * * $D = ! type * $A = Array * $S = *-ptr * $R = &-ptr * $P = + symbol * $E = = symbol * $C = , symbol * $H = # symbol * $pL/$pR = Left/right paren * $aL/$aR = Left/right angle (<>) */ #include "mangling.hpp" #include <hir/type.hpp> #include <hir/path.hpp> namespace { ::std::string escape_str(const char* s, size_t len) { ::std::string output; output.reserve(len + 1); for(auto vp = s; vp != s + len; vp ++) { auto v= *vp; if( v == '#' ) output += "$H"; else if( v == '-' ) output += "_"; else output += v; } return output; } ::std::string escape_str(const RcString& s) { return escape_str(s.c_str(), s.size()); } ::std::string escape_str(const ::std::string& s) { return escape_str(s.c_str(), s.size()); } ::FmtLambda emit_params(const ::HIR::PathParams& params) { return FMT_CB(ss, if( params.m_types.size() > 0 ) { ss << "$aL"; for(unsigned int i = 0; i < params.m_types.size(); i ++) { if(i != 0) ss << "$C"; ss << Trans_Mangle( params.m_types[i] ); } ss << "$aR"; } ); } } ::FmtLambda Trans_Mangle(const ::HIR::SimplePath& path) { return FMT_CB(ss, ss << "_ZN"; { ::std::string cn; for(auto c : path.m_crate_name) { if(c == '-') { cn += "$$"; } else if( ('0' <= c && c <= '9') || ('A' <= c && c <= 'Z') || ('a' <= c && c <= 'z') || c == '_' ) { cn += c; } else { } } ss << cn.size() << cn; } for(const auto& comp : path.m_components) { auto v = escape_str(comp); ss << v.size() << v; } ); } ::FmtLambda Trans_Mangle(const ::HIR::GenericPath& path) { return FMT_CB(ss, ss << Trans_Mangle(path.m_path); ss << emit_params(path.m_params); ); } ::FmtLambda Trans_Mangle(const ::HIR::Path& path) { TU_MATCHA( (path.m_data), (pe), (Generic, return Trans_Mangle(pe); ), (UfcsUnknown, BUG(Span(), "UfcsUnknown - " << path); ), (UfcsKnown, return FMT_CB(ss, ss << "_ZRK$aL"; ss << Trans_Mangle(*pe.type); ss << "_as_"; ss << Trans_Mangle(pe.trait); ss << "$aR"; auto v = escape_str(pe.item); ss << v.size() << v; ss << emit_params(pe.params); ); ), (UfcsInherent, return FMT_CB(ss, ss << "_ZRI$aL"; ss << Trans_Mangle(*pe.type); ss << "$aR"; auto v = escape_str(pe.item); ss << v.size() << v; ss << emit_params(pe.params); ); ) ) throw ""; } ::FmtLambda Trans_Mangle(const ::HIR::TypeRef& ty) { TU_MATCHA( (ty.m_data), (te), (Infer, BUG(Span(), "Infer in trans"); ), (Diverge, return FMT_CB(ss, ss << "$D";); ), (Primitive, return FMT_CB(ss, ss << te;); ), (Path, return Trans_Mangle(te.path); ), (Generic, BUG(Span(), "Generic in trans - " << ty); ), (TraitObject, return FMT_CB(ss, ss << "$pL"; ss << Trans_Mangle(te.m_trait.m_path); for(const auto& bound : te.m_trait.m_type_bounds) { ss << "_" << bound.first << "$E" << Trans_Mangle(bound.second); } for(const auto& marker : te.m_markers) { ss << "$P" << Trans_Mangle(marker); } ss << "$pR"; ); ), (ErasedType, BUG(Span(), "ErasedType in trans - " << ty); ), (Array, return FMT_CB(ss, ss << "$A" << te.size_val << "_" << Trans_Mangle(*te.inner);); ), (Slice, return FMT_CB(ss, ss << "$A" << "_" << Trans_Mangle(*te.inner);); ), (Tuple, return FMT_CB(ss, ss << "$T" << te.size(); for(const auto& t : te) ss << "_" << Trans_Mangle(t); ); ), (Borrow, return FMT_CB(ss, ss << "$R"; switch(te.type) { case ::HIR::BorrowType::Shared: ss << "s"; break; case ::HIR::BorrowType::Unique: ss << "u"; break; case ::HIR::BorrowType::Owned : ss << "o"; break; } ss << "_" << Trans_Mangle(*te.inner); ); ), (Pointer, return FMT_CB(ss, ss << "$S"; switch(te.type) { case ::HIR::BorrowType::Shared: ss << "s"; break; case ::HIR::BorrowType::Unique: ss << "u"; break; case ::HIR::BorrowType::Owned : ss << "o"; break; } ss << "_" << Trans_Mangle(*te.inner); ); ), (Function, return FMT_CB(ss, if(te.m_abi != "Rust") ss << "extern_" << escape_str(te.m_abi) << "_"; if(te.is_unsafe) ss << "unsafe_"; ss << "fn_" << te.m_arg_types.size(); for(const auto& ty : te.m_arg_types) ss << "_" << Trans_Mangle(ty); ss << "_" << Trans_Mangle(*te.m_rettype); ); ), (Closure, BUG(Span(), "Closure during trans - " << ty); ) ) throw ""; } <commit_msg>(minor) Fix comment typo<commit_after>/* * MRustC - Rust Compiler * - By John Hodge (Mutabah/thePowersGang) * * trans/mangling.cpp * - Name mangling support * * * $D = ! type * $A = Array * $S = *-ptr * $R = &-ptr * $P = + symbol * $E = = symbol * $C = , symbol * $H = # symbol * $pL/$pR = Left/right paren * $aL/$aR = Left/right angle (<>) */ #include "mangling.hpp" #include <hir/type.hpp> #include <hir/path.hpp> namespace { ::std::string escape_str(const char* s, size_t len) { ::std::string output; output.reserve(len + 1); for(auto vp = s; vp != s + len; vp ++) { auto v= *vp; if( v == '#' ) output += "$H"; else if( v == '-' ) output += "_"; else output += v; } return output; } ::std::string escape_str(const RcString& s) { return escape_str(s.c_str(), s.size()); } ::std::string escape_str(const ::std::string& s) { return escape_str(s.c_str(), s.size()); } ::FmtLambda emit_params(const ::HIR::PathParams& params) { return FMT_CB(ss, if( params.m_types.size() > 0 ) { ss << "$aL"; for(unsigned int i = 0; i < params.m_types.size(); i ++) { if(i != 0) ss << "$C"; ss << Trans_Mangle( params.m_types[i] ); } ss << "$aR"; } ); } } ::FmtLambda Trans_Mangle(const ::HIR::SimplePath& path) { return FMT_CB(ss, ss << "_ZN"; { ::std::string cn; for(auto c : path.m_crate_name) { if(c == '-') { cn += "$$"; } else if( ('0' <= c && c <= '9') || ('A' <= c && c <= 'Z') || ('a' <= c && c <= 'z') || c == '_' ) { cn += c; } else { } } ss << cn.size() << cn; } for(const auto& comp : path.m_components) { auto v = escape_str(comp); ss << v.size() << v; } ); } ::FmtLambda Trans_Mangle(const ::HIR::GenericPath& path) { return FMT_CB(ss, ss << Trans_Mangle(path.m_path); ss << emit_params(path.m_params); ); } ::FmtLambda Trans_Mangle(const ::HIR::Path& path) { TU_MATCHA( (path.m_data), (pe), (Generic, return Trans_Mangle(pe); ), (UfcsUnknown, BUG(Span(), "UfcsUnknown - " << path); ), (UfcsKnown, return FMT_CB(ss, ss << "_ZRK$aL"; ss << Trans_Mangle(*pe.type); ss << "_as_"; ss << Trans_Mangle(pe.trait); ss << "$aR"; auto v = escape_str(pe.item); ss << v.size() << v; ss << emit_params(pe.params); ); ), (UfcsInherent, return FMT_CB(ss, ss << "_ZRI$aL"; ss << Trans_Mangle(*pe.type); ss << "$aR"; auto v = escape_str(pe.item); ss << v.size() << v; ss << emit_params(pe.params); ); ) ) throw ""; } ::FmtLambda Trans_Mangle(const ::HIR::TypeRef& ty) { TU_MATCHA( (ty.m_data), (te), (Infer, BUG(Span(), "Infer in trans"); ), (Diverge, return FMT_CB(ss, ss << "$D";); ), (Primitive, return FMT_CB(ss, ss << te;); ), (Path, return Trans_Mangle(te.path); ), (Generic, BUG(Span(), "Generic in trans - " << ty); ), (TraitObject, return FMT_CB(ss, ss << "$pL"; ss << Trans_Mangle(te.m_trait.m_path); for(const auto& bound : te.m_trait.m_type_bounds) { ss << "_" << bound.first << "$E" << Trans_Mangle(bound.second); } for(const auto& marker : te.m_markers) { ss << "$P" << Trans_Mangle(marker); } ss << "$pR"; ); ), (ErasedType, BUG(Span(), "ErasedType in trans - " << ty); ), (Array, return FMT_CB(ss, ss << "$A" << te.size_val << "_" << Trans_Mangle(*te.inner);); ), (Slice, return FMT_CB(ss, ss << "$A" << "_" << Trans_Mangle(*te.inner);); ), (Tuple, return FMT_CB(ss, ss << "$T" << te.size(); for(const auto& t : te) ss << "_" << Trans_Mangle(t); ); ), (Borrow, return FMT_CB(ss, ss << "$R"; switch(te.type) { case ::HIR::BorrowType::Shared: ss << "s"; break; case ::HIR::BorrowType::Unique: ss << "u"; break; case ::HIR::BorrowType::Owned : ss << "o"; break; } ss << "_" << Trans_Mangle(*te.inner); ); ), (Pointer, return FMT_CB(ss, ss << "$S"; switch(te.type) { case ::HIR::BorrowType::Shared: ss << "s"; break; case ::HIR::BorrowType::Unique: ss << "u"; break; case ::HIR::BorrowType::Owned : ss << "o"; break; } ss << "_" << Trans_Mangle(*te.inner); ); ), (Function, return FMT_CB(ss, if(te.m_abi != "Rust") ss << "extern_" << escape_str(te.m_abi) << "_"; if(te.is_unsafe) ss << "unsafe_"; ss << "fn_" << te.m_arg_types.size(); for(const auto& ty : te.m_arg_types) ss << "_" << Trans_Mangle(ty); ss << "_" << Trans_Mangle(*te.m_rettype); ); ), (Closure, BUG(Span(), "Closure during trans - " << ty); ) ) throw ""; } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: officeinstallationdirectories.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2004-07-05 10:36:13 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): Kai Sommerfeld ( kso@sun.com ) * * ************************************************************************/ /************************************************************************** TODO ************************************************************************** *************************************************************************/ #include "osl/file.hxx" #include "com/sun/star/beans/XPropertySet.hpp" #include "com/sun/star/util/XMacroExpander.hpp" #include "officeinstallationdirectories.hxx" using namespace com::sun::star; using namespace comphelper; //========================================================================= // helpers //========================================================================= uno::Sequence< rtl::OUString > SAL_CALL OfficeInstallationDirectories_getSupportedServiceNames() throw() { const rtl::OUString aServiceName( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.util.OfficeInstallationDirectories" ) ); return uno::Sequence< rtl::OUString >( &aServiceName, 1 ); } //========================================================================= rtl::OUString SAL_CALL OfficeInstallationDirectories_getImplementationName() throw() { return rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.comp.util.OfficeInstallationDirectories" ) ); } //========================================================================= rtl::OUString SAL_CALL OfficeInstallationDirectories_getSingletonName() throw() { return rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.util.theOfficeInstallationDirectories" ) ); } //========================================================================= rtl::OUString SAL_CALL OfficeInstallationDirectories_getSingletonServiceName() throw() { return rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.util.OfficeInstallationDirectories" ) ); } //========================================================================= uno::Reference< uno::XInterface > SAL_CALL OfficeInstallationDirectories_createInstance( const uno::Reference< lang::XMultiServiceFactory > & xSMgr ) throw( uno::Exception ) { OSL_ENSURE( xSMgr.is(), "No service manager!" ); uno::Reference< uno::XComponentContext > xCtx; uno::Reference< beans::XPropertySet > xPropSet( xSMgr, uno::UNO_QUERY ); if ( xPropSet.is() ) { xPropSet->getPropertyValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "DefaultContext" ) ) ) >>= xCtx; } if ( !xCtx.is() ) { throw uno::RuntimeException( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Unable to obtain component context from service manager!" ) ), uno::Reference< uno::XInterface >() ); } return static_cast< cppu::OWeakObject * >( new OfficeInstallationDirectories( xCtx ) ); } //========================================================================= static bool makeCanonicalFileURL( rtl::OUString & rURL ) { OSL_ENSURE( rURL.matchAsciiL( "file:", sizeof( "file:" ) - 1 , 0 ) , "File URL expected!" ); rtl::OUString aNormalizedURL; if ( osl::FileBase::getAbsoluteFileURL( rtl::OUString(), rURL, aNormalizedURL ) == osl::DirectoryItem::E_None ) { osl::DirectoryItem aDirItem; if ( osl::DirectoryItem::get( aNormalizedURL, aDirItem ) == osl::DirectoryItem::E_None ) { osl::FileStatus aFileStatus( FileStatusMask_FileURL ); if ( aDirItem.getFileStatus( aFileStatus ) == osl::DirectoryItem::E_None ) { aNormalizedURL = aFileStatus.getFileURL(); if ( aNormalizedURL.getLength() > 0 ) { if ( aNormalizedURL .getStr()[ aNormalizedURL.getLength() - 1 ] != sal_Unicode( '/' ) ) rURL = aNormalizedURL; else rURL = aNormalizedURL .copy( 0, aNormalizedURL.getLength() - 1 ); return true; } } } } return false; } //========================================================================= //========================================================================= // // OfficeInstallationDirectories Implementation. // //========================================================================= //========================================================================= OfficeInstallationDirectories::OfficeInstallationDirectories( const uno::Reference< uno::XComponentContext > & xCtx ) : m_aOfficeDirMacro( RTL_CONSTASCII_USTRINGPARAM( "$(baseinsturl)" ) ), m_aUserDirMacro( RTL_CONSTASCII_USTRINGPARAM( "$(userdataurl)" ) ), m_xCtx( xCtx ), m_pOfficeDir( 0 ), m_pUserDir( 0 ) { } //========================================================================= // virtual OfficeInstallationDirectories::~OfficeInstallationDirectories() { } //========================================================================= // util::XOfficeInstallationDirectories //========================================================================= // virtual rtl::OUString SAL_CALL OfficeInstallationDirectories::getOfficeInstallationDirectoryURL() throw ( uno::RuntimeException ) { // late init m_pOfficeDir and m_pUserDir initDirs(); return rtl::OUString( *m_pOfficeDir ); } //========================================================================= // virtual rtl::OUString SAL_CALL OfficeInstallationDirectories::getOfficeUserDataDirectoryURL() throw ( uno::RuntimeException ) { // late init m_pOfficeDir and m_pUserDir initDirs(); return rtl::OUString( *m_pUserDir ); } //========================================================================= // virtual rtl::OUString SAL_CALL OfficeInstallationDirectories::makeRelocatableURL( const rtl::OUString& URL ) throw ( uno::RuntimeException ) { if ( URL.getLength() > 0 ) { // late init m_pOfficeDir and m_pUserDir initDirs(); rtl::OUString aCanonicalURL( URL ); makeCanonicalFileURL( aCanonicalURL ); sal_Int32 nIndex = aCanonicalURL.indexOf( *m_pOfficeDir ); if ( nIndex != -1 ) { return rtl::OUString( URL.replaceAt( nIndex, m_pOfficeDir->getLength(), m_aOfficeDirMacro ) ); } else { sal_Int32 nIndex = aCanonicalURL.indexOf( *m_pUserDir ); if ( nIndex != -1 ) { return rtl::OUString( URL.replaceAt( nIndex, m_pUserDir->getLength(), m_aUserDirMacro ) ); } } } return rtl::OUString( URL ); } //========================================================================= // virtual rtl::OUString SAL_CALL OfficeInstallationDirectories::makeAbsoluteURL( const rtl::OUString& URL ) throw ( uno::RuntimeException ) { if ( URL.getLength() > 0 ) { sal_Int32 nIndex = URL.indexOf( m_aOfficeDirMacro ); if ( nIndex != -1 ) { // late init m_pOfficeDir and m_pUserDir initDirs(); return rtl::OUString( URL.replaceAt( nIndex, m_aOfficeDirMacro.getLength(), *m_pOfficeDir ) ); } else { sal_Int32 nIndex = URL.indexOf( m_aUserDirMacro ); if ( nIndex != -1 ) { // late init m_pOfficeDir and m_pUserDir initDirs(); return rtl::OUString( URL.replaceAt( nIndex, m_aUserDirMacro.getLength(), *m_pUserDir ) ); } } } return rtl::OUString( URL ); } //========================================================================= // lang::XServiceInfo //========================================================================= // virtual rtl::OUString SAL_CALL OfficeInstallationDirectories::getImplementationName() throw ( uno::RuntimeException ) { return OfficeInstallationDirectories_getImplementationName(); } //========================================================================= // virtual sal_Bool SAL_CALL OfficeInstallationDirectories::supportsService( const rtl::OUString& ServiceName ) throw ( uno::RuntimeException ) { const uno::Sequence< rtl::OUString > & aNames = OfficeInstallationDirectories_getSupportedServiceNames(); const rtl::OUString * p = aNames.getConstArray(); for ( sal_Int32 nPos = 0; nPos < aNames.getLength(); nPos++ ) { if ( p[ nPos ].equals( ServiceName ) ) return sal_True; } return sal_False; } //========================================================================= // virtual uno::Sequence< ::rtl::OUString > SAL_CALL OfficeInstallationDirectories::getSupportedServiceNames() throw ( uno::RuntimeException ) { return OfficeInstallationDirectories_getSupportedServiceNames(); } //========================================================================= // non-UNO //========================================================================= void OfficeInstallationDirectories::initDirs() { if ( m_pOfficeDir == 0 ) { osl::MutexGuard aGuard( m_aMutex ); if ( m_pOfficeDir == 0 ) { m_pOfficeDir = new rtl::OUString; m_pUserDir = new rtl::OUString; uno::Reference< util::XMacroExpander > xExpander; m_xCtx->getValueByName( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "/singletons/com.sun.star.util.theMacroExpander" ) ) ) >>= xExpander; OSL_ENSURE( xExpander.is(), "Unable to obtain macro expander singleton!" ); if ( xExpander.is() ) { *m_pOfficeDir = xExpander->expandMacros( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "${$SYSBINDIR/" SAL_CONFIGFILE( "bootstrap" ) ":BaseInstallation}" ) ) ); OSL_ENSURE( m_pOfficeDir->getLength() > 0, "Unable to obtain office installation directory!" ); makeCanonicalFileURL( *m_pOfficeDir ); *m_pUserDir = xExpander->expandMacros( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "${$SYSBINDIR/" SAL_CONFIGFILE( "bootstrap" ) ":UserInstallation}" ) ) ); OSL_ENSURE( m_pUserDir->getLength() > 0, "Unable to obtain office user data directory!" ); makeCanonicalFileURL( *m_pUserDir ); } } } } <commit_msg>INTEGRATION: CWS ooo19126 (1.3.134); FILE MERGED 2005/09/05 15:24:05 rt 1.3.134.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: officeinstallationdirectories.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: rt $ $Date: 2005-09-08 02:54:13 $ * * 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 * ************************************************************************/ /************************************************************************** TODO ************************************************************************** *************************************************************************/ #include "osl/file.hxx" #include "com/sun/star/beans/XPropertySet.hpp" #include "com/sun/star/util/XMacroExpander.hpp" #include "officeinstallationdirectories.hxx" using namespace com::sun::star; using namespace comphelper; //========================================================================= // helpers //========================================================================= uno::Sequence< rtl::OUString > SAL_CALL OfficeInstallationDirectories_getSupportedServiceNames() throw() { const rtl::OUString aServiceName( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.util.OfficeInstallationDirectories" ) ); return uno::Sequence< rtl::OUString >( &aServiceName, 1 ); } //========================================================================= rtl::OUString SAL_CALL OfficeInstallationDirectories_getImplementationName() throw() { return rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.comp.util.OfficeInstallationDirectories" ) ); } //========================================================================= rtl::OUString SAL_CALL OfficeInstallationDirectories_getSingletonName() throw() { return rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.util.theOfficeInstallationDirectories" ) ); } //========================================================================= rtl::OUString SAL_CALL OfficeInstallationDirectories_getSingletonServiceName() throw() { return rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.util.OfficeInstallationDirectories" ) ); } //========================================================================= uno::Reference< uno::XInterface > SAL_CALL OfficeInstallationDirectories_createInstance( const uno::Reference< lang::XMultiServiceFactory > & xSMgr ) throw( uno::Exception ) { OSL_ENSURE( xSMgr.is(), "No service manager!" ); uno::Reference< uno::XComponentContext > xCtx; uno::Reference< beans::XPropertySet > xPropSet( xSMgr, uno::UNO_QUERY ); if ( xPropSet.is() ) { xPropSet->getPropertyValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "DefaultContext" ) ) ) >>= xCtx; } if ( !xCtx.is() ) { throw uno::RuntimeException( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Unable to obtain component context from service manager!" ) ), uno::Reference< uno::XInterface >() ); } return static_cast< cppu::OWeakObject * >( new OfficeInstallationDirectories( xCtx ) ); } //========================================================================= static bool makeCanonicalFileURL( rtl::OUString & rURL ) { OSL_ENSURE( rURL.matchAsciiL( "file:", sizeof( "file:" ) - 1 , 0 ) , "File URL expected!" ); rtl::OUString aNormalizedURL; if ( osl::FileBase::getAbsoluteFileURL( rtl::OUString(), rURL, aNormalizedURL ) == osl::DirectoryItem::E_None ) { osl::DirectoryItem aDirItem; if ( osl::DirectoryItem::get( aNormalizedURL, aDirItem ) == osl::DirectoryItem::E_None ) { osl::FileStatus aFileStatus( FileStatusMask_FileURL ); if ( aDirItem.getFileStatus( aFileStatus ) == osl::DirectoryItem::E_None ) { aNormalizedURL = aFileStatus.getFileURL(); if ( aNormalizedURL.getLength() > 0 ) { if ( aNormalizedURL .getStr()[ aNormalizedURL.getLength() - 1 ] != sal_Unicode( '/' ) ) rURL = aNormalizedURL; else rURL = aNormalizedURL .copy( 0, aNormalizedURL.getLength() - 1 ); return true; } } } } return false; } //========================================================================= //========================================================================= // // OfficeInstallationDirectories Implementation. // //========================================================================= //========================================================================= OfficeInstallationDirectories::OfficeInstallationDirectories( const uno::Reference< uno::XComponentContext > & xCtx ) : m_aOfficeDirMacro( RTL_CONSTASCII_USTRINGPARAM( "$(baseinsturl)" ) ), m_aUserDirMacro( RTL_CONSTASCII_USTRINGPARAM( "$(userdataurl)" ) ), m_xCtx( xCtx ), m_pOfficeDir( 0 ), m_pUserDir( 0 ) { } //========================================================================= // virtual OfficeInstallationDirectories::~OfficeInstallationDirectories() { } //========================================================================= // util::XOfficeInstallationDirectories //========================================================================= // virtual rtl::OUString SAL_CALL OfficeInstallationDirectories::getOfficeInstallationDirectoryURL() throw ( uno::RuntimeException ) { // late init m_pOfficeDir and m_pUserDir initDirs(); return rtl::OUString( *m_pOfficeDir ); } //========================================================================= // virtual rtl::OUString SAL_CALL OfficeInstallationDirectories::getOfficeUserDataDirectoryURL() throw ( uno::RuntimeException ) { // late init m_pOfficeDir and m_pUserDir initDirs(); return rtl::OUString( *m_pUserDir ); } //========================================================================= // virtual rtl::OUString SAL_CALL OfficeInstallationDirectories::makeRelocatableURL( const rtl::OUString& URL ) throw ( uno::RuntimeException ) { if ( URL.getLength() > 0 ) { // late init m_pOfficeDir and m_pUserDir initDirs(); rtl::OUString aCanonicalURL( URL ); makeCanonicalFileURL( aCanonicalURL ); sal_Int32 nIndex = aCanonicalURL.indexOf( *m_pOfficeDir ); if ( nIndex != -1 ) { return rtl::OUString( URL.replaceAt( nIndex, m_pOfficeDir->getLength(), m_aOfficeDirMacro ) ); } else { sal_Int32 nIndex = aCanonicalURL.indexOf( *m_pUserDir ); if ( nIndex != -1 ) { return rtl::OUString( URL.replaceAt( nIndex, m_pUserDir->getLength(), m_aUserDirMacro ) ); } } } return rtl::OUString( URL ); } //========================================================================= // virtual rtl::OUString SAL_CALL OfficeInstallationDirectories::makeAbsoluteURL( const rtl::OUString& URL ) throw ( uno::RuntimeException ) { if ( URL.getLength() > 0 ) { sal_Int32 nIndex = URL.indexOf( m_aOfficeDirMacro ); if ( nIndex != -1 ) { // late init m_pOfficeDir and m_pUserDir initDirs(); return rtl::OUString( URL.replaceAt( nIndex, m_aOfficeDirMacro.getLength(), *m_pOfficeDir ) ); } else { sal_Int32 nIndex = URL.indexOf( m_aUserDirMacro ); if ( nIndex != -1 ) { // late init m_pOfficeDir and m_pUserDir initDirs(); return rtl::OUString( URL.replaceAt( nIndex, m_aUserDirMacro.getLength(), *m_pUserDir ) ); } } } return rtl::OUString( URL ); } //========================================================================= // lang::XServiceInfo //========================================================================= // virtual rtl::OUString SAL_CALL OfficeInstallationDirectories::getImplementationName() throw ( uno::RuntimeException ) { return OfficeInstallationDirectories_getImplementationName(); } //========================================================================= // virtual sal_Bool SAL_CALL OfficeInstallationDirectories::supportsService( const rtl::OUString& ServiceName ) throw ( uno::RuntimeException ) { const uno::Sequence< rtl::OUString > & aNames = OfficeInstallationDirectories_getSupportedServiceNames(); const rtl::OUString * p = aNames.getConstArray(); for ( sal_Int32 nPos = 0; nPos < aNames.getLength(); nPos++ ) { if ( p[ nPos ].equals( ServiceName ) ) return sal_True; } return sal_False; } //========================================================================= // virtual uno::Sequence< ::rtl::OUString > SAL_CALL OfficeInstallationDirectories::getSupportedServiceNames() throw ( uno::RuntimeException ) { return OfficeInstallationDirectories_getSupportedServiceNames(); } //========================================================================= // non-UNO //========================================================================= void OfficeInstallationDirectories::initDirs() { if ( m_pOfficeDir == 0 ) { osl::MutexGuard aGuard( m_aMutex ); if ( m_pOfficeDir == 0 ) { m_pOfficeDir = new rtl::OUString; m_pUserDir = new rtl::OUString; uno::Reference< util::XMacroExpander > xExpander; m_xCtx->getValueByName( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "/singletons/com.sun.star.util.theMacroExpander" ) ) ) >>= xExpander; OSL_ENSURE( xExpander.is(), "Unable to obtain macro expander singleton!" ); if ( xExpander.is() ) { *m_pOfficeDir = xExpander->expandMacros( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "${$SYSBINDIR/" SAL_CONFIGFILE( "bootstrap" ) ":BaseInstallation}" ) ) ); OSL_ENSURE( m_pOfficeDir->getLength() > 0, "Unable to obtain office installation directory!" ); makeCanonicalFileURL( *m_pOfficeDir ); *m_pUserDir = xExpander->expandMacros( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "${$SYSBINDIR/" SAL_CONFIGFILE( "bootstrap" ) ":UserInstallation}" ) ) ); OSL_ENSURE( m_pUserDir->getLength() > 0, "Unable to obtain office user data directory!" ); makeCanonicalFileURL( *m_pUserDir ); } } } } <|endoftext|>
<commit_before>/**********************************************************\ | | | hprose | | | | Official WebSite: http://www.hprose.com/ | | http://www.hprose.net/ | | http://www.hprose.org/ | | | \**********************************************************/ /**********************************************************\ * * * HproseClient.hpp * * * * hprose client class for Cpp. * * * * LastModified: Jul 7, 2015 * * Author: Chen fei <cf@hprose.com> * * * \**********************************************************/ #ifndef HPROSE_CLIENT_HPROSE_CLIENT_HPP #define HPROSE_CLIENT_HPROSE_CLIENT_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1020) #pragma once #endif #include <hprose/io.hpp> #include <boost/thread.hpp> namespace hprose { namespace HproseTags { const char ResultTags[4] = { TagResult, TagArgument, TagError, TagEnd }; // Todo: Remove } // namespace HproseTags class HproseClient { protected: // structors HproseClient() { } HproseClient(const std::string & uri) { UseService(uri); } virtual ~HproseClient() { } protected: virtual void * GetInvokeContext() = 0; virtual void SendData(void * context) = 0; virtual void EndInvoke(void * context) = 0; virtual std::ostream & GetOutputStream(void * context) = 0; virtual std::istream & GetInputStream(void * context) = 0; public: virtual void UseService(const std::string & uri) { this->uri = uri; } template<typename ReturnType> inline ReturnType Invoke(const std::string & name) { std::vector<Any> args; return Invoke<ReturnType>(name, args); } template<typename ReturnType> inline void Invoke(ReturnType & ret, const std::string & name) { std::vector<Any> args; Invoke(ret, name, args); } #ifndef BOOST_NO_INITIALIZER_LISTS template<typename ReturnType, typename ArgType> inline ReturnType Invoke(const std::string & name, const std::initializer_list<ArgType> & args) { return Invoke<ReturnType>(name, args, false); } template<typename ReturnType, typename ArgType> inline void Invoke(ReturnType & ret, const std::string & name, const std::initializer_list<ArgType> & args) { Invoke(ret, name, args, false); } #endif template<typename ReturnType, typename ArgsType> inline ReturnType Invoke(const std::string & name, ArgsType & args, bool ref = false) { ReturnType ret = ReturnType(); Invoke(ret, name, args, ref); return ret; } template<typename ReturnType, typename ArgsType> void Invoke(ReturnType & ret, const std::string & name, ArgsType & args, bool ref = false) { std::string error; void * context = 0; context = GetInvokeContext(); try { DoOutput(name, args, ref, GetOutputStream(context)); SendData(context); DoInput(ret, args, error, GetInputStream(context)); } catch (...) { } EndInvoke(context); if (!error.empty()) { HPROSE_THROW_EXCEPTION(error); } } template<typename ReturnType, typename Functor> inline void AsyncInvoke(const std::string & name, Functor func) { static std::vector<Any> args; AsyncInvoke<ReturnType>(name, args, func, false); } template<typename ReturnType, typename ArgsType, typename Functor> inline void AsyncInvoke(const std::string & name, const ArgsType & args, Functor func, bool ref = false) { boost::thread thread(Async<ReturnType, ArgsType, Functor>(*this, name, args, func, ref)); } template<typename ReturnType, typename ArgsType, typename Functor, size_t ArraySize> inline void AsyncInvoke(const std::string & name, const ArgsType (&args)[ArraySize], Functor func, bool ref = false) { std::vector<ArgsType> newArgs(ArraySize); for (int i = 0; i < ArraySize; ++i) { newArgs[i] = args[i]; } AsyncInvoke<ReturnType>(name, newArgs, func, ref); } private: template<typename ReturnType, typename ArgsType, typename Functor> class Async { public: Async(HproseClient & client, const std::string & name, ArgsType args, Functor func, bool ref) : client(client), name(name), args(args), func(func), ref(ref) { } public: inline void operator()() { ReturnType ret = ReturnType(); client.Invoke(ret, name, args, ref); func(ret, args); } private: HproseClient & client; std::string name; ArgsType args; Functor func; bool ref; }; // class Async private: template<typename ReturnType, typename ArgsType> void DoInput(ReturnType & ret, ArgsType & args, std::string & error, std::istream & stream) { HproseReader reader(stream); while (true) { switch (reader.CheckTags(HproseTags::ResultTags)) { case HproseTags::TagResult: ret = reader.Unserialize<ReturnType>(); break; case HproseTags::TagArgument: //args = reader.ReadList<ArgsType>(); break; case HproseTags::TagError: error = reader.ReadString(); return; case HproseTags::TagEnd: return; } } } template<typename ArgsType> void DoOutput(const std::string & name, ArgsType & args, bool ref, std::ostream & stream) { HproseWriter writer(stream); stream << HproseTags::TagCall; writer.WriteString(name, false); writer.WriteList(args, false); if (ref) { writer.WriteBool(true); } stream << HproseTags::TagEnd; } template<typename ArgsType, size_t ArraySize> void DoOutput(const std::string & name, ArgsType (&args)[ArraySize], bool ref, std::ostream & stream) { HproseWriter writer(stream); stream << HproseTags::TagCall; writer.WriteString(name, false); writer.WriteList(args, false); if (ref) { writer.WriteBool(true); } stream << HproseTags::TagEnd; } protected: std::string uri; }; // class HproseClient } // namespace hprose #endif // HPROSE_CLIENT_HPROSE_CLIENT_HPP <commit_msg>Omit argument list if empty<commit_after>/**********************************************************\ | | | hprose | | | | Official WebSite: http://www.hprose.com/ | | http://www.hprose.net/ | | http://www.hprose.org/ | | | \**********************************************************/ /**********************************************************\ * * * HproseClient.hpp * * * * hprose client class for Cpp. * * * * LastModified: Jul 7, 2015 * * Author: Chen fei <cf@hprose.com> * * * \**********************************************************/ #ifndef HPROSE_CLIENT_HPROSE_CLIENT_HPP #define HPROSE_CLIENT_HPROSE_CLIENT_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1020) #pragma once #endif #include <hprose/io.hpp> #include <boost/thread.hpp> namespace hprose { namespace HproseTags { const char ResultTags[4] = { TagResult, TagArgument, TagError, TagEnd }; // Todo: Remove } // namespace HproseTags class HproseClient { protected: // structors HproseClient() { } HproseClient(const std::string & uri) { UseService(uri); } virtual ~HproseClient() { } protected: virtual void * GetInvokeContext() = 0; virtual void SendData(void * context) = 0; virtual void EndInvoke(void * context) = 0; virtual std::ostream & GetOutputStream(void * context) = 0; virtual std::istream & GetInputStream(void * context) = 0; public: virtual void UseService(const std::string & uri) { this->uri = uri; } template<typename ReturnType> inline ReturnType Invoke(const std::string & name) { std::vector<Any> args; return Invoke<ReturnType>(name, args); } template<typename ReturnType> inline void Invoke(ReturnType & ret, const std::string & name) { std::vector<Any> args; Invoke(ret, name, args); } #ifndef BOOST_NO_INITIALIZER_LISTS template<typename ReturnType, typename ArgType> inline ReturnType Invoke(const std::string & name, const std::initializer_list<ArgType> & args) { return Invoke<ReturnType>(name, args, false); } template<typename ReturnType, typename ArgType> inline void Invoke(ReturnType & ret, const std::string & name, const std::initializer_list<ArgType> & args) { Invoke(ret, name, args, false); } #endif template<typename ReturnType, typename ArgsType> inline ReturnType Invoke(const std::string & name, ArgsType & args, bool ref = false) { ReturnType ret = ReturnType(); Invoke(ret, name, args, ref); return ret; } template<typename ReturnType, typename ArgsType> void Invoke(ReturnType & ret, const std::string & name, ArgsType & args, bool ref = false) { std::string error; void * context = 0; context = GetInvokeContext(); try { DoOutput(name, args, ref, GetOutputStream(context)); SendData(context); DoInput(ret, args, error, GetInputStream(context)); } catch (...) { } EndInvoke(context); if (!error.empty()) { HPROSE_THROW_EXCEPTION(error); } } template<typename ReturnType, typename Functor> inline void AsyncInvoke(const std::string & name, Functor func) { static std::vector<Any> args; AsyncInvoke<ReturnType>(name, args, func, false); } template<typename ReturnType, typename ArgsType, typename Functor> inline void AsyncInvoke(const std::string & name, const ArgsType & args, Functor func, bool ref = false) { boost::thread thread(Async<ReturnType, ArgsType, Functor>(*this, name, args, func, ref)); } template<typename ReturnType, typename ArgsType, typename Functor, size_t ArraySize> inline void AsyncInvoke(const std::string & name, const ArgsType (&args)[ArraySize], Functor func, bool ref = false) { std::vector<ArgsType> newArgs(ArraySize); for (int i = 0; i < ArraySize; ++i) { newArgs[i] = args[i]; } AsyncInvoke<ReturnType>(name, newArgs, func, ref); } private: template<typename ReturnType, typename ArgsType, typename Functor> class Async { public: Async(HproseClient & client, const std::string & name, ArgsType args, Functor func, bool ref) : client(client), name(name), args(args), func(func), ref(ref) { } public: inline void operator()() { ReturnType ret = ReturnType(); client.Invoke(ret, name, args, ref); func(ret, args); } private: HproseClient & client; std::string name; ArgsType args; Functor func; bool ref; }; // class Async private: template<typename ReturnType, typename ArgsType> void DoInput(ReturnType & ret, ArgsType & args, std::string & error, std::istream & stream) { HproseReader reader(stream); while (true) { switch (reader.CheckTags(HproseTags::ResultTags)) { case HproseTags::TagResult: ret = reader.Unserialize<ReturnType>(); break; case HproseTags::TagArgument: //args = reader.ReadList<ArgsType>(); break; case HproseTags::TagError: error = reader.ReadString(); return; case HproseTags::TagEnd: return; } } } template<typename ArgsType> void DoOutput(const std::string & name, ArgsType & args, bool ref, std::ostream & stream) { HproseWriter writer(stream); stream << HproseTags::TagCall; writer.WriteString(name, false); if (!args.empty()) { writer.WriteList(args, false); } if (ref) { writer.WriteBool(true); } stream << HproseTags::TagEnd; } template<typename ArgsType, size_t ArraySize> void DoOutput(const std::string & name, ArgsType (&args)[ArraySize], bool ref, std::ostream & stream) { HproseWriter writer(stream); stream << HproseTags::TagCall; writer.WriteString(name, false); if (!args.empty()) { writer.WriteList(args, false); } if (ref) { writer.WriteBool(true); } stream << HproseTags::TagEnd; } protected: std::string uri; }; // class HproseClient } // namespace hprose #endif // HPROSE_CLIENT_HPROSE_CLIENT_HPP <|endoftext|>
<commit_before>// Copyright (c) 2011 libmv authors. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. #include "ui/tracker/main.h" #include "ui/tracker/tracker.h" #include "ui/tracker/scene.h" #include "libmv/tools/tool.h" #include <QApplication> #include <QFileDialog> #include <QFormLayout> #include <QDockWidget> #include <QToolButton> #include <QSettings> #include <QToolBar> #include <QAction> #include <QCache> #include <QMenu> #include <QTime> void Clip::Open(QString path) { cache_.setMaxCost(64 * 1024 * 1024); if (path.endsWith(".avi")) { // TODO(MatthiasF): load videos using ffmpeg return; } clear(); foreach (QString file, QDir(path).entryList(QStringList("*.jpg") << "*.png", QDir::Files, QDir::Name)) { append( QDir(path).filePath(file) ); } } QImage Clip::Image(int frame) { QImage* image = cache_[frame]; if (!image) { image = new QImage(value(frame)); cache_.insert(frame, image, image->byteCount()); } return *image; } MainWindow::MainWindow() : clip_(new Clip(this)), scene_(new Scene()), tracker_(new Tracker(scene_,scene_)), current_frame_(-1) { setWindowTitle("Tracker"); setCentralWidget(tracker_); connect(tracker_, SIGNAL(trackChanged(QVector<int>)), this, SLOT(updateZooms(QVector<int>))); QToolBar* toolbar = addToolBar("Main Toolbar"); toolbar->setObjectName("mainToolbar"); toolbar->addAction(QIcon(":/open"), "Open a new sequence...", this, SLOT(open())); QAction* tracker_action_ = toolbar->addAction(QIcon(":/view-image"),"Tracker View"); tracker_action_->setCheckable(true); connect(tracker_action_,SIGNAL(triggered(bool)),tracker_,SLOT(setVisible(bool))); QAction* zoom_action_ = toolbar->addAction(QIcon(":/view-zoom"),"Zoom View"); zoom_action_->setCheckable(true); connect(zoom_action_,SIGNAL(triggered(bool)),this,SLOT(toggleZoom(bool))); QDockWidget* scene_dock = new QDockWidget("Scene View"); scene_dock->setObjectName("sceneDock"); addDockWidget(Qt::BottomDockWidgetArea, scene_dock); scene_dock->setWidget(scene_); scene_dock->toggleViewAction()->setIcon(QIcon(":/view-scene")); toolbar->addAction(scene_dock->toggleViewAction()); connect(scene_, SIGNAL(imageChanged(int)), SLOT(seek(int))); connect(scene_, SIGNAL(trackChanged(QVector<int>)), tracker_, SLOT(select(QVector<int>))); toolbar->addSeparator(); QToolButton* delete_button = new QToolButton(); toolbar->addWidget(delete_button); QMenu* delete_popup = new QMenu(); delete_popup->addAction(QIcon(":/delete"), "Delete current marker", tracker_, SLOT(deleteSelectedMarkers())); QAction* delete_track = delete_popup->addAction(QIcon(":/delete-row"), "Delete current track", tracker_, SLOT(deleteSelectedTracks())); delete_button->setMenu(delete_popup); delete_button->setDefaultAction(delete_track); delete_button->setPopupMode(QToolButton::MenuButtonPopup); connect(delete_popup,SIGNAL(triggered(QAction*)), delete_button,SLOT(setDefaultAction(QAction*))); track_action_ = toolbar->addAction(QIcon(":/record"), "Track selected markers"); track_action_->setCheckable(true); connect(track_action_, SIGNAL(triggered(bool)), SLOT(toggleTracking(bool))); connect(tracker_action_, SIGNAL(triggered(bool)), track_action_, SLOT(setVisible(bool))); QAction* add_action = toolbar->addAction(QIcon(":/add"), "Add object", scene_, SLOT(add())); connect(scene_dock->toggleViewAction(), SIGNAL(triggered(bool)), add_action, SLOT(setVisible(bool))); QAction* link_action = toolbar->addAction(QIcon(":/link"), "Link active object to selected bundles", scene_, SLOT(link())); connect(scene_dock->toggleViewAction(), SIGNAL(triggered(bool)), link_action, SLOT(setVisible(bool))); toolbar->addSeparator(); toolbar->addAction(QIcon(":/skip-backward"), "Seek to first frame", this, SLOT(first())); toolbar->addAction(QIcon(":/step-backward"),"Step to previous frame", this, SLOT(previous()))->setShortcut(QKeySequence("Left")); backward_action_ = toolbar->addAction(QIcon(":/play-backward"), "Play sequence backwards"); backward_action_->setCheckable(true); connect(backward_action_, SIGNAL(triggered(bool)), SLOT(toggleBackward(bool))); connect(&previous_timer_, SIGNAL(timeout()), SLOT(previous())); toolbar->addWidget(&spinbox_); connect(&spinbox_, SIGNAL(valueChanged(int)), SLOT(seek(int))); toolbar->addWidget(&slider_); slider_.setOrientation(Qt::Horizontal); connect(&slider_, SIGNAL(valueChanged(int)), SLOT(seek(int))); forward_action_ = toolbar->addAction(QIcon(":/play-forward"), "Play sequence forwards"); forward_action_->setCheckable(true); connect(forward_action_, SIGNAL(triggered(bool)), SLOT(toggleForward(bool))); connect(&next_timer_, SIGNAL(timeout()), SLOT(next())); toolbar->addAction(QIcon(":/step-forward"), "Next Frame",this, SLOT(next())) ->setShortcut(QKeySequence("Right")); toolbar->addAction(QIcon(":/skip-forward"), "Last Frame",this, SLOT(last())); restoreGeometry(QSettings().value("geometry").toByteArray()); restoreState(QSettings().value("windowState").toByteArray()); } void MainWindow::Save(QString name,QByteArray data) { if(data.isEmpty()) return; QFile file(QDir(path_).filePath(name)); if (file.open(QFile::WriteOnly | QIODevice::Truncate)) { file.write(data); } } MainWindow::~MainWindow() { QSettings().setValue("geometry", saveGeometry()); QSettings().setValue("windowState", saveState()); if(clip_->isEmpty()) return; Save("tracks",tracker_->Save()); Save("cameras",scene_->SaveCameras()); Save("bundles",scene_->SaveBundles()); Save("objects",scene_->SaveObjects()); } QByteArray MainWindow::Load(QString name) { QFile file(QDir(path_).filePath(name)); return file.open(QFile::ReadOnly) ? file.readAll() : QByteArray(); } #include <QDebug> void MainWindow::open() { open(QFileDialog::getExistingDirectory(this, "Select sequence folder")); if(clip_->isEmpty()) return; QSize size = clip_->Image(0).size(); QDialog dialog(this); dialog.setWindowTitle("Camera Parameters"); QFormLayout layout( &dialog ); QDoubleSpinBox focal_length; focal_length.setSuffix("px"); // TODO(MatthiasF): extract from EXIF data focal_length.setRange(0,size.width()); focal_length.setValue(1); layout.addRow("Focal Length", &focal_length ); QDoubleSpinBox principal_point_x; principal_point_x.setSuffix("px"); principal_point_x.setRange(0,size.width()); principal_point_x.setValue(size.width()/2); layout.addRow("Principal Point (X)", &principal_point_x ); QDoubleSpinBox principal_point_y; principal_point_y.setSuffix("px"); principal_point_y.setRange(0,size.height()); principal_point_y.setValue(size.height()/2); layout.addRow("Principal Point (Y)", &principal_point_y ); QDoubleSpinBox skew_factor; skew_factor.setRange(0,1); layout.addRow("Skew Factor", &skew_factor ); static const char* order[] = { "1st", "2nd", "3rd", "4th", "5th" }; QDoubleSpinBox radial_distortion_coefficients[5]; for(int i=0; i<5; i++) { layout.addRow(QString(order[i])+" Radial Distortion Coefficient", &radial_distortion_coefficients[i]); } QDoubleSpinBox tangential_distortion_coefficients[2]; for(int i=0; i<2; i++) { layout.addRow(QString(order[i])+" Tangential Distortion Coefficient", &tangential_distortion_coefficients[i]); } dialog.exec(); // TODO(MatthiasF): save and use the calibration data } void MainWindow::open(QString path) { if (path.isEmpty() || !QDir(path).exists()) return; clip_->Open(path); if(clip_->isEmpty()) return; path_ = path; setWindowTitle(QString("Tracker - %1").arg(QDir(path).dirName())); tracker_->Load(Load("tracks")); scene_->LoadCameras(Load("cameras")); scene_->LoadBundles(Load("bundles")); scene_->LoadObjects(Load("objects")); scene_->upload(); spinbox_.setMaximum(clip_->size() - 1); slider_.setMaximum(clip_->size() - 1); first(); } void MainWindow::seek(int frame) { // Bail out if there's nothing to do. if (frame == current_frame_) { return; } if (frame < 0 || frame >= clip_->size()) { stop(); return; } // Track only if the shift is between consecutive frames. if ( frame > current_frame_ + 1 || frame < current_frame_ - 1 ) { track_action_->setChecked(false); } current_frame_ = frame; slider_.setValue(current_frame_); spinbox_.setValue(current_frame_); tracker_->SetImage(current_frame_, clip_->Image(current_frame_), track_action_->isChecked()); } void MainWindow::stop() { backward_action_->setChecked(false); previous_timer_.stop(); forward_action_->setChecked(false); next_timer_.stop(); } void MainWindow::first() { seek(0); } void MainWindow::previous() { seek(current_frame_ - 1); } void MainWindow::next() { seek(current_frame_ + 1); } void MainWindow::last() { seek(clip_->size() - 1); } void MainWindow::toggleTracking(bool track) { stop(); if (track) { backward_action_->setText("Track sequence backwards"); forward_action_->setText("Track sequence forwards"); } else { backward_action_->setText("Play sequence backwards"); forward_action_->setText("Play sequence forwards"); } } void MainWindow::toggleBackward(bool play) { if (play) { forward_action_->setChecked(false); next_timer_.stop(); previous_timer_.start(0); } else { stop(); } } void MainWindow::toggleForward(bool play) { if (play) { backward_action_->setChecked(false); previous_timer_.stop(); next_timer_.start(0); } else { stop(); } } void MainWindow::toggleZoom(bool zoom) { if (zoom) { foreach(QDockWidget* dock, zooms_docks_) { dock->show(); } } else { foreach(QDockWidget* dock, zooms_docks_) { dock->hide(); } } } void MainWindow::updateZooms(QVector<int> tracks) { if(!zooms_docks_.isEmpty() && tracks.size()*zooms_docks_.first()->width() > width()) { tracks.resize(width() / zooms_docks_.first()->width()); } for(int i=tracks.size(); i<zooms_docks_.size(); i++) { removeDockWidget(zooms_docks_[i]); delete zooms_docks_[i]; //zoom widget is owned by dock ? } for(int i=zooms_docks_.size(); i<tracks.size(); i++) { QDockWidget* dock = new QDockWidget(QString("Zoom View #%1").arg(tracks[i])); dock->setObjectName(QString("zoom%1").arg(tracks[i])); addDockWidget(Qt::TopDockWidgetArea, dock); Zoom* zoom = new Zoom(0,tracker_); dock->setWidget(zoom); addDockWidget(Qt::TopDockWidgetArea,dock); zooms_ << zoom; zooms_docks_ << dock; } zooms_docks_.resize(tracks.size()); zooms_.resize(tracks.size()); for(int i=0; i<tracks.size(); i++) { zooms_[i]->SetMarker(current_frame_,tracks[i]); } } int main(int argc, char *argv[]) { libmv::Init("", &argc, &argv); QApplication app(argc, argv); app.setOrganizationName("libmv"); app.setApplicationName("tracker"); MainWindow window; window.show(); window.open(app.arguments().value(1)); return app.exec(); } <commit_msg>Persistent Settings.<commit_after>// Copyright (c) 2011 libmv authors. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. #include "ui/tracker/main.h" #include "ui/tracker/tracker.h" #include "ui/tracker/scene.h" #include "libmv/tools/tool.h" #include <QApplication> #include <QFileDialog> #include <QFormLayout> #include <QDockWidget> #include <QToolButton> #include <QSettings> #include <QToolBar> #include <QAction> #include <QCache> #include <QMenu> #include <QTime> void Clip::Open(QString path) { cache_.setMaxCost(64 * 1024 * 1024); if (path.endsWith(".avi")) { // TODO(MatthiasF): load videos using ffmpeg return; } clear(); foreach (QString file, QDir(path).entryList(QStringList("*.jpg") << "*.png", QDir::Files, QDir::Name)) { append( QDir(path).filePath(file) ); } } QImage Clip::Image(int frame) { QImage* image = cache_[frame]; if (!image) { image = new QImage(value(frame)); cache_.insert(frame, image, image->byteCount()); } return *image; } MainWindow::MainWindow() : clip_(new Clip(this)), scene_(new Scene()), tracker_(new Tracker(scene_,scene_)), current_frame_(-1) { setWindowTitle("Tracker"); setCentralWidget(tracker_); connect(tracker_, SIGNAL(trackChanged(QVector<int>)), this, SLOT(updateZooms(QVector<int>))); QToolBar* toolbar = addToolBar("Main Toolbar"); toolbar->setObjectName("mainToolbar"); toolbar->addAction(QIcon(":/open"), "Open a new sequence...", this, SLOT(open())); QAction* tracker_action_ = toolbar->addAction(QIcon(":/view-image"),"Tracker View"); tracker_action_->setCheckable(true); connect(tracker_action_,SIGNAL(triggered(bool)),tracker_,SLOT(setVisible(bool))); QAction* zoom_action_ = toolbar->addAction(QIcon(":/view-zoom"),"Zoom View"); zoom_action_->setCheckable(true); connect(zoom_action_,SIGNAL(triggered(bool)),this,SLOT(toggleZoom(bool))); QDockWidget* scene_dock = new QDockWidget("Scene View"); scene_dock->setObjectName("sceneDock"); addDockWidget(Qt::BottomDockWidgetArea, scene_dock); scene_dock->setWidget(scene_); scene_dock->toggleViewAction()->setIcon(QIcon(":/view-scene")); toolbar->addAction(scene_dock->toggleViewAction()); connect(scene_, SIGNAL(imageChanged(int)), SLOT(seek(int))); connect(scene_, SIGNAL(trackChanged(QVector<int>)), tracker_, SLOT(select(QVector<int>))); toolbar->addSeparator(); QToolButton* delete_button = new QToolButton(); toolbar->addWidget(delete_button); QMenu* delete_popup = new QMenu(); delete_popup->addAction(QIcon(":/delete"), "Delete current marker", tracker_, SLOT(deleteSelectedMarkers())); QAction* delete_track = delete_popup->addAction(QIcon(":/delete-row"), "Delete current track", tracker_, SLOT(deleteSelectedTracks())); delete_button->setMenu(delete_popup); delete_button->setDefaultAction(delete_track); delete_button->setPopupMode(QToolButton::MenuButtonPopup); connect(delete_popup,SIGNAL(triggered(QAction*)), delete_button,SLOT(setDefaultAction(QAction*))); track_action_ = toolbar->addAction(QIcon(":/record"), "Track selected markers"); track_action_->setCheckable(true); connect(track_action_, SIGNAL(triggered(bool)), SLOT(toggleTracking(bool))); connect(tracker_action_, SIGNAL(triggered(bool)), track_action_, SLOT(setVisible(bool))); QAction* add_action = toolbar->addAction(QIcon(":/add"), "Add object", scene_, SLOT(add())); connect(scene_dock->toggleViewAction(), SIGNAL(triggered(bool)), add_action, SLOT(setVisible(bool))); QAction* link_action = toolbar->addAction(QIcon(":/link"), "Link active object to selected bundles", scene_, SLOT(link())); connect(scene_dock->toggleViewAction(), SIGNAL(triggered(bool)), link_action, SLOT(setVisible(bool))); toolbar->addSeparator(); toolbar->addAction(QIcon(":/skip-backward"), "Seek to first frame", this, SLOT(first())); toolbar->addAction(QIcon(":/step-backward"),"Step to previous frame", this, SLOT(previous()))->setShortcut(QKeySequence("Left")); backward_action_ = toolbar->addAction(QIcon(":/play-backward"), "Play sequence backwards"); backward_action_->setCheckable(true); connect(backward_action_, SIGNAL(triggered(bool)), SLOT(toggleBackward(bool))); connect(&previous_timer_, SIGNAL(timeout()), SLOT(previous())); toolbar->addWidget(&spinbox_); connect(&spinbox_, SIGNAL(valueChanged(int)), SLOT(seek(int))); toolbar->addWidget(&slider_); slider_.setOrientation(Qt::Horizontal); connect(&slider_, SIGNAL(valueChanged(int)), SLOT(seek(int))); forward_action_ = toolbar->addAction(QIcon(":/play-forward"), "Play sequence forwards"); forward_action_->setCheckable(true); connect(forward_action_, SIGNAL(triggered(bool)), SLOT(toggleForward(bool))); connect(&next_timer_, SIGNAL(timeout()), SLOT(next())); toolbar->addAction(QIcon(":/step-forward"), "Next Frame",this, SLOT(next())) ->setShortcut(QKeySequence("Right")); toolbar->addAction(QIcon(":/skip-forward"), "Last Frame",this, SLOT(last())); restoreGeometry(QSettings().value("geometry").toByteArray()); restoreState(QSettings().value("windowState").toByteArray()); } void MainWindow::Save(QString name,QByteArray data) { if(data.isEmpty()) return; QFile file(QDir(path_).filePath(name)); if (file.open(QFile::WriteOnly | QIODevice::Truncate)) { file.write(data); } } MainWindow::~MainWindow() { QSettings().setValue("geometry", saveGeometry()); QSettings().setValue("windowState", saveState()); if(clip_->isEmpty()) return; Save("tracks",tracker_->Save()); Save("cameras",scene_->SaveCameras()); Save("bundles",scene_->SaveBundles()); Save("objects",scene_->SaveObjects()); } QByteArray MainWindow::Load(QString name) { QFile file(QDir(path_).filePath(name)); return file.open(QFile::ReadOnly) ? file.readAll() : QByteArray(); } struct Parameter { const char* name; const char* suffix; double min; double max; double value; }; void MainWindow::open() { open(QFileDialog::getExistingDirectory(this, "Select sequence folder")); if(clip_->isEmpty()) return; QSize size = clip_->Image(0).size(); QDialog dialog(this); dialog.setWindowTitle("Camera Parameters"); QFormLayout layout( &dialog ); const Parameter parameters[] = { {"Focal Length", "px", 0, size.width(), 1 }, {"Principal Point (X)", "px", 0, size.width(), size.width()/2 }, {"Principal Point (Y)", "px", 0, size.height(), size.height()/2 }, {"Skew Factor", "", 0, 1, 0 }, {"1st Radial Distortion", "", 0, 1, 0 }, {"2nd Radial Distortion", "", 0, 1, 0 }, {"3rd Radial Distortion", "", 0, 1, 0 }, {"4th Radial Distortion", "", 0, 1, 0 }, {"5th Radial Distortion", "", 0, 1, 0 }, {"1st Tangential Distortion", "", 0, 1, 0 }, {"2nd Tangential Distortion", "", 0, 1, 0 }, }; const int count = sizeof(parameters)/sizeof(Parameter); QDoubleSpinBox spinbox[count]; QByteArray data = Load("settings"); data.reserve(count*sizeof(float)); float* values = (float*)data.data(); for(int i=0; i<count; i++) { Parameter parameter = parameters[i]; spinbox[i].setSuffix(parameter.suffix); spinbox[i].setRange(parameter.min,parameter.max); if(data.isEmpty()) { spinbox[i].setValue(parameter.value); } else { spinbox[i].setValue(values[i]); } layout.addRow(parameter.name,&spinbox[i]); } dialog.exec(); data.resize(count*sizeof(float)); for(int i=0; i<count; i++) { values[i]=spinbox[i].value(); } Save("settings",data); // TODO(MatthiasF): use the calibration data } void MainWindow::open(QString path) { if (path.isEmpty() || !QDir(path).exists()) return; clip_->Open(path); if(clip_->isEmpty()) return; path_ = path; setWindowTitle(QString("Tracker - %1").arg(QDir(path).dirName())); tracker_->Load(Load("tracks")); scene_->LoadCameras(Load("cameras")); scene_->LoadBundles(Load("bundles")); scene_->LoadObjects(Load("objects")); scene_->upload(); spinbox_.setMaximum(clip_->size() - 1); slider_.setMaximum(clip_->size() - 1); first(); } void MainWindow::seek(int frame) { // Bail out if there's nothing to do. if (frame == current_frame_) { return; } if (frame < 0 || frame >= clip_->size()) { stop(); return; } // Track only if the shift is between consecutive frames. if ( frame > current_frame_ + 1 || frame < current_frame_ - 1 ) { track_action_->setChecked(false); } current_frame_ = frame; slider_.setValue(current_frame_); spinbox_.setValue(current_frame_); tracker_->SetImage(current_frame_, clip_->Image(current_frame_), track_action_->isChecked()); } void MainWindow::stop() { backward_action_->setChecked(false); previous_timer_.stop(); forward_action_->setChecked(false); next_timer_.stop(); } void MainWindow::first() { seek(0); } void MainWindow::previous() { seek(current_frame_ - 1); } void MainWindow::next() { seek(current_frame_ + 1); } void MainWindow::last() { seek(clip_->size() - 1); } void MainWindow::toggleTracking(bool track) { stop(); if (track) { backward_action_->setText("Track sequence backwards"); forward_action_->setText("Track sequence forwards"); } else { backward_action_->setText("Play sequence backwards"); forward_action_->setText("Play sequence forwards"); } } void MainWindow::toggleBackward(bool play) { if (play) { forward_action_->setChecked(false); next_timer_.stop(); previous_timer_.start(0); } else { stop(); } } void MainWindow::toggleForward(bool play) { if (play) { backward_action_->setChecked(false); previous_timer_.stop(); next_timer_.start(0); } else { stop(); } } void MainWindow::toggleZoom(bool zoom) { if (zoom) { foreach(QDockWidget* dock, zooms_docks_) { dock->show(); } } else { foreach(QDockWidget* dock, zooms_docks_) { dock->hide(); } } } void MainWindow::updateZooms(QVector<int> tracks) { if(!zooms_docks_.isEmpty() && tracks.size()*zooms_docks_.first()->width() > width()) { tracks.resize(width() / zooms_docks_.first()->width()); } for(int i=tracks.size(); i<zooms_docks_.size(); i++) { removeDockWidget(zooms_docks_[i]); delete zooms_docks_[i]; //zoom widget is owned by dock ? } for(int i=zooms_docks_.size(); i<tracks.size(); i++) { QDockWidget* dock = new QDockWidget(QString("Zoom View #%1").arg(tracks[i])); dock->setObjectName(QString("zoom%1").arg(tracks[i])); addDockWidget(Qt::TopDockWidgetArea, dock); Zoom* zoom = new Zoom(0,tracker_); dock->setWidget(zoom); addDockWidget(Qt::TopDockWidgetArea,dock); zooms_ << zoom; zooms_docks_ << dock; } zooms_docks_.resize(tracks.size()); zooms_.resize(tracks.size()); for(int i=0; i<tracks.size(); i++) { zooms_[i]->SetMarker(current_frame_,tracks[i]); } } int main(int argc, char *argv[]) { libmv::Init("", &argc, &argv); QApplication app(argc, argv); app.setOrganizationName("libmv"); app.setApplicationName("tracker"); MainWindow window; window.show(); window.open(app.arguments().value(1)); return app.exec(); } <|endoftext|>
<commit_before>// test_helpers.cpp : functions to aid in testing and test reporting // // Copyright (C) 2017-2020 Stillwater Supercomputing, Inc. // // This file is part of the universal numbers project, which is released under an MIT Open Source license. // test reporting helper int ReportTestResult(int nrOfFailedTests, std::string description, std::string test_operation) { if (nrOfFailedTests > 0) { std::cout << description << " " << test_operation << " FAIL " << nrOfFailedTests << " failed test cases" << std::endl; } else { std::cout << description << " " << test_operation << " PASS" << std::endl; } return nrOfFailedTests; } <commit_msg>performance fix passing std::string as const reference<commit_after>// test_helpers.cpp : functions to aid in testing and test reporting // // Copyright (C) 2017-2020 Stillwater Supercomputing, Inc. // // This file is part of the universal numbers project, which is released under an MIT Open Source license. // test reporting helper int ReportTestResult(int nrOfFailedTests, const std::string& description, const std::string& test_operation) { if (nrOfFailedTests > 0) { std::cout << description << " " << test_operation << " FAIL " << nrOfFailedTests << " failed test cases" << std::endl; } else { std::cout << description << " " << test_operation << " PASS" << std::endl; } return nrOfFailedTests; } <|endoftext|>
<commit_before>/* * Copyright 2013 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkRTConf.h" #include "SkOSFile.h" SkRTConfRegistry::SkRTConfRegistry(): fConfs(100) { SkFILE *fp = sk_fopen(configFileLocation(), kRead_SkFILE_Flag); if (!fp) { return; } char line[1024]; while (!sk_feof(fp)) { if (!sk_fgets(line, sizeof(line), fp)) { break; } char *commentptr = strchr(line, '#'); if (commentptr == line) { continue; } if (NULL != commentptr) { *commentptr = '\0'; } char sep[] = " \t\r\n"; char *keyptr = strtok(line, sep); if (!keyptr) { continue; } char *valptr = strtok(NULL, sep); if (!valptr) { continue; } SkString* key = new SkString(keyptr); SkString* val = new SkString(valptr); fConfigFileKeys.append(1, &key); fConfigFileValues.append(1, &val); } sk_fclose(fp); } const char *SkRTConfRegistry::configFileLocation() const { return "skia.conf"; // for now -- should probably do something fancier like home directories or whatever. } // dump all known runtime config options to the file with their default values. // to trigger this, make a config file of zero size. void SkRTConfRegistry::possiblyDumpFile() const { const char *path = configFileLocation(); SkFILE *fp = sk_fopen(path, kRead_SkFILE_Flag); if (!fp) { return; } size_t configFileSize = sk_fgetsize(fp); if (configFileSize == 0) { printAll(path); } sk_fclose(fp); } // Run through every provided configuration option and print a warning if the user hasn't // declared a correponding configuration object somewhere. void SkRTConfRegistry::validate() const { for (int i = 0 ; i < fConfigFileKeys.count() ; i++) { if (fConfs.find(fConfigFileKeys[i]->c_str())) { SkDebugf("WARNING: You have config value %s in your configuration file, but I've never heard of that.\n", fConfigFileKeys[i]->c_str()); } } } void SkRTConfRegistry::printAll(const char *fname) const { SkWStream *o; if (NULL != fname) { o = new SkFILEWStream(fname); } else { o = new SkDebugWStream(); } ConfMap::Iter iter(fConfs); SkTDArray<SkRTConfBase *> *confArray; while (iter.next(&confArray)) { if (confArray->getAt(0)->isDefault()) { o->writeText("# "); } confArray->getAt(0)->print(o); o->newline(); } delete o; } void SkRTConfRegistry::printNonDefault(const char *fname) const { SkWStream *o; if (NULL != fname) { o = new SkFILEWStream(fname); } else { o = new SkDebugWStream(); } ConfMap::Iter iter(fConfs); SkTDArray<SkRTConfBase *> *confArray; while (iter.next(&confArray)) { if (!confArray->getAt(0)->isDefault()) { confArray->getAt(0)->print(o); o->newline(); } } delete o; } // register a configuration variable after its value has been set by the parser. // we maintain a vector of these things instead of just a single one because the // user might set the value after initialization time and we need to have // all the pointers lying around, not just one. void SkRTConfRegistry::registerConf(SkRTConfBase *conf) { SkTDArray<SkRTConfBase *> *confArray; if (fConfs.find(conf->getName(), &confArray)) { if (!conf->equals(confArray->getAt(0))) { SkDebugf("WARNING: Skia config \"%s\" was registered more than once in incompatible ways.\n", conf->getName()); } else { confArray->append(1, &conf); } } else { confArray = new SkTDArray<SkRTConfBase *>; confArray->append(1, &conf); fConfs.set(conf->getName(),confArray); } } template <typename T> T doParse(const char *, bool *success ) { SkDebugf("WARNING: Invoked non-specialized doParse function...\n"); if (success) { *success = false; } return (T) 0; } template<> bool doParse<bool>(const char *s, bool *success) { if (success) { *success = true; } if (!strcmp(s,"1") || !strcmp(s,"true")) { return true; } if (!strcmp(s,"0") || !strcmp(s,"false")) { return false; } if (success) { *success = false; } return false; } template<> const char * doParse<const char *>(const char * s, bool *success) { if (success) { *success = true; } return s; } template<> int doParse<int>(const char * s, bool *success) { if (success) { *success = true; } return atoi(s); } template<> unsigned int doParse<unsigned int>(const char * s, bool *success) { if (success) { *success = true; } return (unsigned int) atoi(s); } template<> float doParse<float>(const char * s, bool *success) { if (success) { *success = true; } return (float) atof(s); } template<> double doParse<double>(const char * s, bool *success) { if (success) { *success = true; } return atof(s); } static inline void str_replace(char *s, char search, char replace) { for (char *ptr = s ; *ptr ; ptr++) { if (*ptr == search) { *ptr = replace; } } } template<typename T> bool SkRTConfRegistry::parse(const char *name, T* value) { SkString *str = NULL; for (int i = 0 ; i < fConfigFileKeys.count() ; i++) { if (fConfigFileKeys[i]->equals(name)) { str = fConfigFileValues[i]; } } SkString environment_variable("skia."); environment_variable.append(name); const char *environment_value = getenv(environment_variable.c_str()); if (environment_value) { str->set(environment_value); } else { // apparently my shell doesn't let me have environment variables that // have periods in them, so also let the user substitute underscores. SkString underscore_environment_variable("skia_"); char *underscore_name = SkStrDup(name); str_replace(underscore_name,'.','_'); underscore_environment_variable.append(underscore_name); sk_free(underscore_name); environment_value = getenv(underscore_environment_variable.c_str()); if (environment_value) { str->set(environment_value); } } if (!str) { return false; } bool success; T new_value = doParse<T>(str->c_str(),&success); if (success) { *value = new_value; } else { SkDebugf("WARNING: Couldn't parse value \'%s\' for variable \'%s\'\n", str->c_str(), name); } return success; } // need to explicitly instantiate the parsing function for every config type we might have... template bool SkRTConfRegistry::parse(const char *name, bool *value); template bool SkRTConfRegistry::parse(const char *name, int *value); template bool SkRTConfRegistry::parse(const char *name, unsigned int *value); template bool SkRTConfRegistry::parse(const char *name, float *value); template bool SkRTConfRegistry::parse(const char *name, double *value); template bool SkRTConfRegistry::parse(const char *name, const char **value); template <typename T> void SkRTConfRegistry::set(const char *name, T value) { SkTDArray<SkRTConfBase *> *confArray; if (!fConfs.find(name, &confArray)) { SkDebugf("WARNING: Attempting to set configuration value \"%s\", but I've never heard of that.\n", name); return; } for (SkRTConfBase **confBase = confArray->begin(); confBase != confArray->end(); confBase++) { // static_cast here is okay because there's only one kind of child class. SkRTConf<T> *concrete = static_cast<SkRTConf<T> *>(*confBase); if (concrete) { concrete->set(value); } } } template void SkRTConfRegistry::set(const char *name, bool value); template void SkRTConfRegistry::set(const char *name, int value); template void SkRTConfRegistry::set(const char *name, unsigned int value); template void SkRTConfRegistry::set(const char *name, float value); template void SkRTConfRegistry::set(const char *name, double value); template void SkRTConfRegistry::set(const char *name, char * value); SkRTConfRegistry &skRTConfRegistry() { static SkRTConfRegistry r; return r; } <commit_msg>fix boolean check for unknown rtconf variables in files.<commit_after>/* * Copyright 2013 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkRTConf.h" #include "SkOSFile.h" SkRTConfRegistry::SkRTConfRegistry(): fConfs(100) { SkFILE *fp = sk_fopen(configFileLocation(), kRead_SkFILE_Flag); if (!fp) { return; } char line[1024]; while (!sk_feof(fp)) { if (!sk_fgets(line, sizeof(line), fp)) { break; } char *commentptr = strchr(line, '#'); if (commentptr == line) { continue; } if (NULL != commentptr) { *commentptr = '\0'; } char sep[] = " \t\r\n"; char *keyptr = strtok(line, sep); if (!keyptr) { continue; } char *valptr = strtok(NULL, sep); if (!valptr) { continue; } SkString* key = new SkString(keyptr); SkString* val = new SkString(valptr); fConfigFileKeys.append(1, &key); fConfigFileValues.append(1, &val); } sk_fclose(fp); } const char *SkRTConfRegistry::configFileLocation() const { return "skia.conf"; // for now -- should probably do something fancier like home directories or whatever. } // dump all known runtime config options to the file with their default values. // to trigger this, make a config file of zero size. void SkRTConfRegistry::possiblyDumpFile() const { const char *path = configFileLocation(); SkFILE *fp = sk_fopen(path, kRead_SkFILE_Flag); if (!fp) { return; } size_t configFileSize = sk_fgetsize(fp); if (configFileSize == 0) { printAll(path); } sk_fclose(fp); } // Run through every provided configuration option and print a warning if the user hasn't // declared a correponding configuration object somewhere. void SkRTConfRegistry::validate() const { for (int i = 0 ; i < fConfigFileKeys.count() ; i++) { if (!fConfs.find(fConfigFileKeys[i]->c_str())) { SkDebugf("WARNING: You have config value %s in your configuration file, but I've never heard of that.\n", fConfigFileKeys[i]->c_str()); } } } void SkRTConfRegistry::printAll(const char *fname) const { SkWStream *o; if (NULL != fname) { o = new SkFILEWStream(fname); } else { o = new SkDebugWStream(); } ConfMap::Iter iter(fConfs); SkTDArray<SkRTConfBase *> *confArray; while (iter.next(&confArray)) { if (confArray->getAt(0)->isDefault()) { o->writeText("# "); } confArray->getAt(0)->print(o); o->newline(); } delete o; } void SkRTConfRegistry::printNonDefault(const char *fname) const { SkWStream *o; if (NULL != fname) { o = new SkFILEWStream(fname); } else { o = new SkDebugWStream(); } ConfMap::Iter iter(fConfs); SkTDArray<SkRTConfBase *> *confArray; while (iter.next(&confArray)) { if (!confArray->getAt(0)->isDefault()) { confArray->getAt(0)->print(o); o->newline(); } } delete o; } // register a configuration variable after its value has been set by the parser. // we maintain a vector of these things instead of just a single one because the // user might set the value after initialization time and we need to have // all the pointers lying around, not just one. void SkRTConfRegistry::registerConf(SkRTConfBase *conf) { SkTDArray<SkRTConfBase *> *confArray; if (fConfs.find(conf->getName(), &confArray)) { if (!conf->equals(confArray->getAt(0))) { SkDebugf("WARNING: Skia config \"%s\" was registered more than once in incompatible ways.\n", conf->getName()); } else { confArray->append(1, &conf); } } else { confArray = new SkTDArray<SkRTConfBase *>; confArray->append(1, &conf); fConfs.set(conf->getName(),confArray); } } template <typename T> T doParse(const char *, bool *success ) { SkDebugf("WARNING: Invoked non-specialized doParse function...\n"); if (success) { *success = false; } return (T) 0; } template<> bool doParse<bool>(const char *s, bool *success) { if (success) { *success = true; } if (!strcmp(s,"1") || !strcmp(s,"true")) { return true; } if (!strcmp(s,"0") || !strcmp(s,"false")) { return false; } if (success) { *success = false; } return false; } template<> const char * doParse<const char *>(const char * s, bool *success) { if (success) { *success = true; } return s; } template<> int doParse<int>(const char * s, bool *success) { if (success) { *success = true; } return atoi(s); } template<> unsigned int doParse<unsigned int>(const char * s, bool *success) { if (success) { *success = true; } return (unsigned int) atoi(s); } template<> float doParse<float>(const char * s, bool *success) { if (success) { *success = true; } return (float) atof(s); } template<> double doParse<double>(const char * s, bool *success) { if (success) { *success = true; } return atof(s); } static inline void str_replace(char *s, char search, char replace) { for (char *ptr = s ; *ptr ; ptr++) { if (*ptr == search) { *ptr = replace; } } } template<typename T> bool SkRTConfRegistry::parse(const char *name, T* value) { SkString *str = NULL; for (int i = 0 ; i < fConfigFileKeys.count() ; i++) { if (fConfigFileKeys[i]->equals(name)) { str = fConfigFileValues[i]; } } SkString environment_variable("skia."); environment_variable.append(name); const char *environment_value = getenv(environment_variable.c_str()); if (environment_value) { str->set(environment_value); } else { // apparently my shell doesn't let me have environment variables that // have periods in them, so also let the user substitute underscores. SkString underscore_environment_variable("skia_"); char *underscore_name = SkStrDup(name); str_replace(underscore_name,'.','_'); underscore_environment_variable.append(underscore_name); sk_free(underscore_name); environment_value = getenv(underscore_environment_variable.c_str()); if (environment_value) { str->set(environment_value); } } if (!str) { return false; } bool success; T new_value = doParse<T>(str->c_str(),&success); if (success) { *value = new_value; } else { SkDebugf("WARNING: Couldn't parse value \'%s\' for variable \'%s\'\n", str->c_str(), name); } return success; } // need to explicitly instantiate the parsing function for every config type we might have... template bool SkRTConfRegistry::parse(const char *name, bool *value); template bool SkRTConfRegistry::parse(const char *name, int *value); template bool SkRTConfRegistry::parse(const char *name, unsigned int *value); template bool SkRTConfRegistry::parse(const char *name, float *value); template bool SkRTConfRegistry::parse(const char *name, double *value); template bool SkRTConfRegistry::parse(const char *name, const char **value); template <typename T> void SkRTConfRegistry::set(const char *name, T value) { SkTDArray<SkRTConfBase *> *confArray; if (!fConfs.find(name, &confArray)) { SkDebugf("WARNING: Attempting to set configuration value \"%s\", but I've never heard of that.\n", name); return; } for (SkRTConfBase **confBase = confArray->begin(); confBase != confArray->end(); confBase++) { // static_cast here is okay because there's only one kind of child class. SkRTConf<T> *concrete = static_cast<SkRTConf<T> *>(*confBase); if (concrete) { concrete->set(value); } } } template void SkRTConfRegistry::set(const char *name, bool value); template void SkRTConfRegistry::set(const char *name, int value); template void SkRTConfRegistry::set(const char *name, unsigned int value); template void SkRTConfRegistry::set(const char *name, float value); template void SkRTConfRegistry::set(const char *name, double value); template void SkRTConfRegistry::set(const char *name, char * value); SkRTConfRegistry &skRTConfRegistry() { static SkRTConfRegistry r; return r; } <|endoftext|>
<commit_before>#pragma once #include "exception.hpp" #include "debug.hpp" #include <memory> namespace utki{ /** * @brief Intrusive singleton base class. * This is a basic intrusive singleton template. * Template params: T - your singletone class type, T_InstanceOwner - class which owns the static 'instance' variable. * In most cases T_InstanceOwner is the same as T. * Usage as follows: * @code * class my_singleton : public utki::intrusive_singleton<my_singleton, my_singleton>{ * friend class utki::intrusive_singleton<my_singleton, my_singleton>; * static utki::intrusive_singleton<my_singleton, my_singleton>::T_Instance instance; * * public: * void do_something(){ * //... * } * }; * * //define the static variable somewhere in .cpp file. * utki::intrusive_singleton<my_singleton, my_singleton>::T_Instance my_singleton::instance; * * int main(int, char**){ * my_singleton my_singleton_instance; * * my_singleton::inst().do_something(); * } * @endcode */ template <class T, class T_InstanceOwner = T> class intrusive_singleton{ protected://use only as a base class intrusive_singleton(){ if(T_InstanceOwner::instance){ throw utki::invalid_state("Singleton::Singleton(): instance is already created"); } T_InstanceOwner::instance.reset(static_cast<T*>(this)); } typedef intrusive_singleton<T> T_Singleton; //Use unique_ptr because it is automatically initialized to nullptr. Automatic object destruction is not used. typedef std::unique_ptr<T> T_Instance; public: intrusive_singleton(const intrusive_singleton&) = delete; intrusive_singleton& operator=(const intrusive_singleton&) = delete; public: /** * @brief tells if singleton object is created or not. * Note, this function is not thread safe. * @return true if object is created. * @return false otherwise. */ static bool is_created(){ return T_InstanceOwner::instance.operator bool(); } //TODO: deprecated, remove. static bool isCreated(){ return is_created(); } /** * @brief get singleton instance. * @return reference to singleton object instance. */ static T& inst(){ ASSERT_INFO(is_created(), "intrusive_singleton::inst(): singleton object is not created") return *T_InstanceOwner::instance; } virtual ~intrusive_singleton()noexcept{ ASSERT(T_InstanceOwner::instance.operator->() == static_cast<T*>(this)) T_InstanceOwner::instance.release(); } }; /** * @brief Singleton base class. * This is a basic non-intrusive singleton template. * Note, that Singleton inherits the IntrusiveSingleton class, so it inherits all * its static methods, the most important one is Inst(). * Usage as follows: * @code * class my_singleton : public utki::singleton<my_singleton>{ * public: * void do_something(){ * //... * } * }; * * int main(int, char**){ * my_singleton my_singleton_instance; * * my_singleton::inst().do_something(); * } * @endcode */ template <class T> class singleton : public intrusive_singleton<T, singleton<T> >{ friend class intrusive_singleton<T, singleton<T> >; protected: singleton(){} public: singleton(const singleton&) = delete; singleton& operator=(const singleton&) = delete; private: static typename intrusive_singleton<T, singleton<T> >::T_Instance instance; }; template <class T> typename utki::intrusive_singleton<T, singleton<T> >::T_Instance utki::singleton<T>::instance; } <commit_msg>minor formatting corrections<commit_after>#pragma once #include "exception.hpp" #include "debug.hpp" #include <memory> namespace utki{ /** * @brief Intrusive singleton base class. * This is a basic intrusive singleton template. * Template params: T - your singletone class type, T_InstanceOwner - class which owns the static 'instance' variable. * In most cases T_InstanceOwner is the same as T. * Usage as follows: * @code * class my_singleton : public utki::intrusive_singleton<my_singleton, my_singleton>{ * friend class utki::intrusive_singleton<my_singleton, my_singleton>; * static utki::intrusive_singleton<my_singleton, my_singleton>::T_Instance instance; * * public: * void do_something(){ * //... * } * }; * * //define the static variable somewhere in .cpp file. * utki::intrusive_singleton<my_singleton, my_singleton>::T_Instance my_singleton::instance; * * int main(int, char**){ * my_singleton my_singleton_instance; * * my_singleton::inst().do_something(); * } * @endcode */ template <class T, class T_InstanceOwner = T> class intrusive_singleton{ protected: // use only as a base class intrusive_singleton(){ if(T_InstanceOwner::instance){ throw utki::invalid_state("singleton::singleton(): instance is already created"); } T_InstanceOwner::instance.reset(static_cast<T*>(this)); } typedef intrusive_singleton<T> T_Singleton; // use unique_ptr because it is automatically initialized to nullptr. Automatic object destruction is not used. typedef std::unique_ptr<T> T_Instance; public: intrusive_singleton(const intrusive_singleton&) = delete; intrusive_singleton& operator=(const intrusive_singleton&) = delete; public: /** * @brief tells if singleton object is created or not. * Note, this function is not thread safe. * @return true if object is created. * @return false otherwise. */ static bool is_created(){ return T_InstanceOwner::instance.operator bool(); } // TODO: deprecated, remove. static bool isCreated(){ return is_created(); } /** * @brief get singleton instance. * @return reference to singleton object instance. */ static T& inst(){ ASSERT_INFO(is_created(), "intrusive_singleton::inst(): singleton object is not created") return *T_InstanceOwner::instance; } virtual ~intrusive_singleton()noexcept{ ASSERT(T_InstanceOwner::instance.operator->() == static_cast<T*>(this)) T_InstanceOwner::instance.release(); } }; /** * @brief Singleton base class. * This is a basic non-intrusive singleton template. * Note, that Singleton inherits the IntrusiveSingleton class, so it inherits all * its static methods, the most important one is Inst(). * Usage as follows: * @code * class my_singleton : public utki::singleton<my_singleton>{ * public: * void do_something(){ * //... * } * }; * * int main(int, char**){ * my_singleton my_singleton_instance; * * my_singleton::inst().do_something(); * } * @endcode */ template <class T> class singleton : public intrusive_singleton<T, singleton<T> >{ friend class intrusive_singleton<T, singleton<T> >; protected: singleton(){} public: singleton(const singleton&) = delete; singleton& operator=(const singleton&) = delete; private: static typename intrusive_singleton<T, singleton<T> >::T_Instance instance; }; template <class T> typename utki::intrusive_singleton<T, singleton<T> >::T_Instance utki::singleton<T>::instance; } <|endoftext|>
<commit_before>/* Q Light Controller Plus main.cpp Copyright (c) Massimo Callegari Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.txt Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include <QApplication> #include <QCommandLineParser> #include <QQmlApplicationEngine> #include "app.h" #include "qlcconfig.h" void debugMessageHandler(QtMsgType type, const QMessageLogContext &context, const QString &msg) { Q_UNUSED(context) Q_UNUSED(type) QByteArray localMsg = msg.toLocal8Bit(); //if (type >= QtSystemMsg) { fprintf(stderr, "%s\n", localMsg.constData()); fflush(stderr); } } int main(int argc, char *argv[]) { QApplication app(argc, argv); QApplication::setOrganizationName("qlcplus"); QApplication::setOrganizationDomain("org.qlcplus"); QApplication::setApplicationName(APPNAME); QApplication::setApplicationVersion(QString(APPVERSION)); QCommandLineParser parser; parser.setApplicationDescription("Q Light Controller Plus"); parser.addHelpOption(); parser.addVersionOption(); QCommandLineOption debugOption(QStringList() << "d" << "debug", "Enable debug messages."); parser.addOption(debugOption); QCommandLineOption openFileOption(QStringList() << "o" << "open", "Specify a file to open.", "filename", ""); parser.addOption(openFileOption); parser.process(app); if (parser.isSet(debugOption)) qInstallMessageHandler(debugMessageHandler); App qlcplusApp; qlcplusApp.startup(); qlcplusApp.show(); QString filename = parser.value(openFileOption); if (filename.isEmpty() == false) qlcplusApp.loadWorkspace(filename); return app.exec(); } <commit_msg>qmlui: fixed wrong organization domain<commit_after>/* Q Light Controller Plus main.cpp Copyright (c) Massimo Callegari Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.txt Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include <QApplication> #include <QCommandLineParser> #include <QQmlApplicationEngine> #include "app.h" #include "qlcconfig.h" void debugMessageHandler(QtMsgType type, const QMessageLogContext &context, const QString &msg) { Q_UNUSED(context) Q_UNUSED(type) QByteArray localMsg = msg.toLocal8Bit(); //if (type >= QtSystemMsg) { fprintf(stderr, "%s\n", localMsg.constData()); fflush(stderr); } } int main(int argc, char *argv[]) { QApplication app(argc, argv); QApplication::setOrganizationName("qlcplus"); QApplication::setOrganizationDomain("org"); QApplication::setApplicationName(APPNAME); QApplication::setApplicationVersion(QString(APPVERSION)); QCommandLineParser parser; parser.setApplicationDescription("Q Light Controller Plus"); parser.addHelpOption(); parser.addVersionOption(); QCommandLineOption debugOption(QStringList() << "d" << "debug", "Enable debug messages."); parser.addOption(debugOption); QCommandLineOption openFileOption(QStringList() << "o" << "open", "Specify a file to open.", "filename", ""); parser.addOption(openFileOption); parser.process(app); if (parser.isSet(debugOption)) qInstallMessageHandler(debugMessageHandler); App qlcplusApp; qlcplusApp.startup(); qlcplusApp.show(); QString filename = parser.value(openFileOption); if (filename.isEmpty() == false) qlcplusApp.loadWorkspace(filename); return app.exec(); } <|endoftext|>
<commit_before>#include <gtest/gtest.h> #include <Unittests/unittests_common.hh> #include <iostream> namespace { class OpenMeshVectorTest : public testing::Test { protected: // This function is called before each test is run virtual void SetUp() { // Do some initial stuff with the member data here... } // This function is called after all tests are through virtual void TearDown() { // Do some final stuff with the member data here... } }; /* * ==================================================================== * Define tests below * ==================================================================== */ /* Compute surface area via cross product */ TEST_F(OpenMeshVectorTest, ComputeTriangleSurfaceWithCrossProduct) { // // vec1 // x // | // | // | // x------>x vec2 // OpenMesh::Vec3d vec1(0.0,1.0,0.0); OpenMesh::Vec3d vec2(1.0,0.0,0.0); double area = 0.5 * cross(vec1,vec2).norm(); EXPECT_EQ(0.5f , area ) << "Wrong area in cross product function"; area = 0.5 * ( vec1 % vec2 ).norm(); EXPECT_EQ(0.5f , area ) << "Wrong area in cross product operator"; } /* Check OpenMesh Vector type abs function */ TEST_F(OpenMeshVectorTest, AbsTest) { OpenMesh::Vec3d vec1(0.5,0.5,-0.5); EXPECT_EQ( vec1.l8_norm() , 0.5f ) << "Wrong l8norm computation"; } /* Compute surface area via cross product */ TEST_F(OpenMeshVectorTest, VectorCasting) { OpenMesh::Vec3d vecd(1.0,2.0,3.0); OpenMesh::Vec3f vecf = OpenMesh::vector_cast<OpenMesh::Vec3f>(vecd); EXPECT_EQ(1.f, vecf[0]) << "vector type cast failed on component 0"; EXPECT_EQ(2.f, vecf[1]) << "vector type cast failed on component 1"; EXPECT_EQ(3.f, vecf[2]) << "vector type cast failed on component 2"; OpenMesh::Vec4d vecd4(40.0,30.0,20.0,10.0); vecd = OpenMesh::vector_cast<OpenMesh::Vec3d>(vecd4); EXPECT_EQ(40.0, vecd[0]) << "vector dimension cast failed on component 0"; EXPECT_EQ(30.0, vecd[1]) << "vector dimension cast failed on component 1"; EXPECT_EQ(20.0, vecd[2]) << "vector dimension cast failed on component 2"; } #if __cplusplus > 199711L || defined(__GXX_EXPERIMENTAL_CXX0X__) TEST_F(OpenMeshVectorTest, cpp11_constructors) { OpenMesh::Vec3d vec1 { 1.2, 2.0, 3.0 }; EXPECT_EQ(1.2, vec1[0]); EXPECT_EQ(2.0, vec1[1]); EXPECT_EQ(3.0, vec1[2]); OpenMesh::Vec4f vec2 { 1.2f, 3.5f, 1.0f, 0.0f }; EXPECT_EQ(1.2f, vec2[0]); EXPECT_EQ(3.5f, vec2[1]); EXPECT_EQ(1.0f, vec2[2]); EXPECT_EQ(0.0f, vec2[3]); OpenMesh::Vec4f vec2b { vec2 }; EXPECT_EQ(1.2f, vec2b[0]); EXPECT_EQ(3.5f, vec2b[1]); EXPECT_EQ(1.0f, vec2b[2]); EXPECT_EQ(0.0f, vec2b[3]); OpenMesh::Vec4d vec4d { 1.23 }; EXPECT_EQ(1.23, vec4d[0]); EXPECT_EQ(1.23, vec4d[1]); EXPECT_EQ(1.23, vec4d[2]); EXPECT_EQ(1.23, vec4d[3]); } TEST_F(OpenMeshVectorTest, cpp11_htmlColorLiteral) { static constexpr OpenMesh::Vec4f rose = 0xFFC7F1FF_htmlColor; EXPECT_EQ(0xFFC7F1FF_htmlColor, rose); const OpenMesh::Vec4f light_blue = 0x1FCFFFFF_htmlColor; EXPECT_LE((OpenMesh::Vec4f(0.1215686274f, 0.8117647058f, 1.0f, 1.0f) - light_blue).sqrnorm(), 1e-10); const auto light_blue_2 = 0x1FCFFFFF_htmlColor; // Check whether auto type deduction works as expected. static_assert(std::is_same<decltype(light_blue_2), decltype(light_blue)> ::value, "Bad type deduced from _htmlColor literal."); EXPECT_EQ(light_blue, light_blue_2); } namespace { class C { public: C() {} C(const C &rhs) { ADD_FAILURE() << "Copy constructor used."; } C(C &&rhs) { ++copy_con; } C &operator= (const C &rhs) { ADD_FAILURE() << "Copy assignemnt used."; return *this; } C &operator= (C &&rhs) { ++copy_ass; return *this; } static int copy_con; static int copy_ass; }; int C::copy_con = 0; int C::copy_ass = 0; } /** * Checks two things: * 1) Whether VectorT works with a non-arithmetic type. * 2) Whether move construction and assignment works. */ TEST_F(OpenMeshVectorTest, move_constructor_assignment) { C::copy_con = 0; C::copy_ass = 0; // Test move assigning. OpenMesh::VectorT<C, 3> x, y; x = std::move(y); EXPECT_EQ(3, C::copy_ass); EXPECT_EQ(0, C::copy_con); // Test move constructing. OpenMesh::VectorT<C, 3> z(std::move(x)); EXPECT_EQ(3, C::copy_ass); EXPECT_EQ(3, C::copy_con); } #endif // C++11 TEST_F(OpenMeshVectorTest, BasicLinearAlgebra) { OpenMesh::Vec3d v(1, 2, 3); EXPECT_EQ(v[0], 1.0); EXPECT_EQ(v[1], 2.0); EXPECT_EQ(v[2], 3.0); EXPECT_EQ(OpenMesh::Vec3d(-1, -2, -3), -v); EXPECT_EQ(3, OpenMesh::Vec3d(1, 3, 2).max()); EXPECT_EQ(3, OpenMesh::Vec3d(1, 2, 3).max()); EXPECT_EQ(3, OpenMesh::Vec3d(1, 3, -4).max()); EXPECT_EQ(3, OpenMesh::Vec3d(-4, 2, 3).max()); EXPECT_EQ(4, OpenMesh::Vec3d(1, 3, -4).max_abs()); EXPECT_EQ(4, OpenMesh::Vec3d(-4, 2, 3).max_abs()); EXPECT_EQ(1, OpenMesh::Vec3d(1, 3, 2).min()); EXPECT_EQ(1, OpenMesh::Vec3d(1, 2, 3).min()); EXPECT_EQ(-4, OpenMesh::Vec3d(1, 3, -4).min()); EXPECT_EQ(-4, OpenMesh::Vec3d(-4, 2, 3).min()); EXPECT_EQ(1, OpenMesh::Vec3d(1, 3, -4).min_abs()); EXPECT_EQ(2, OpenMesh::Vec3d(-4, 2, 3).min_abs()); EXPECT_NEAR(14, OpenMesh::Vec3d(1, 2, 3) | OpenMesh::Vec3d(1, 2, 3), 1e-6); EXPECT_NEAR(-14, OpenMesh::Vec3d(1, 2, 3) | OpenMesh::Vec3d(-1, -2, -3), 1e-6); EXPECT_NEAR(14, OpenMesh::Vec3d(-1, -2, -3) | OpenMesh::Vec3d(-1, -2, -3), 1e-6); } TEST_F(OpenMeshVectorTest, normalized_cond) { OpenMesh::Vec3d v1(1, -2, 3), v2(0, 0, 0); EXPECT_EQ(OpenMesh::Vec3d(0, 0, 0), v2.normalize_cond()); const auto r1 = OpenMesh::Vec3d(0.2672612419124244, -0.5345224838248488, 0.8017837257372732) - v1.normalize_cond(); EXPECT_NEAR(r1[0], 0.0, 1e-12); EXPECT_NEAR(r1[1], 0.0, 1e-12); EXPECT_NEAR(r1[2], 0.0, 1e-12); } TEST_F(OpenMeshVectorTest, size_dim) { OpenMesh::Vec3d v3d(1, 2, 3); OpenMesh::Vec3f v3f(1, 2, 3); OpenMesh::Vec2i v2i(1, 2); EXPECT_EQ(3u, v3d.size()); EXPECT_EQ(3, v3d.dim()); EXPECT_EQ(3u, v3f.size()); EXPECT_EQ(3, v3f.dim()); EXPECT_EQ(2u, v2i.size()); EXPECT_EQ(2, v2i.dim()); } } <commit_msg>C++11: Made a unit test C++98 compatible.<commit_after>#include <gtest/gtest.h> #include <Unittests/unittests_common.hh> #include <iostream> namespace { class OpenMeshVectorTest : public testing::Test { protected: // This function is called before each test is run virtual void SetUp() { // Do some initial stuff with the member data here... } // This function is called after all tests are through virtual void TearDown() { // Do some final stuff with the member data here... } }; /* * ==================================================================== * Define tests below * ==================================================================== */ /* Compute surface area via cross product */ TEST_F(OpenMeshVectorTest, ComputeTriangleSurfaceWithCrossProduct) { // // vec1 // x // | // | // | // x------>x vec2 // OpenMesh::Vec3d vec1(0.0,1.0,0.0); OpenMesh::Vec3d vec2(1.0,0.0,0.0); double area = 0.5 * cross(vec1,vec2).norm(); EXPECT_EQ(0.5f , area ) << "Wrong area in cross product function"; area = 0.5 * ( vec1 % vec2 ).norm(); EXPECT_EQ(0.5f , area ) << "Wrong area in cross product operator"; } /* Check OpenMesh Vector type abs function */ TEST_F(OpenMeshVectorTest, AbsTest) { OpenMesh::Vec3d vec1(0.5,0.5,-0.5); EXPECT_EQ( vec1.l8_norm() , 0.5f ) << "Wrong l8norm computation"; } /* Compute surface area via cross product */ TEST_F(OpenMeshVectorTest, VectorCasting) { OpenMesh::Vec3d vecd(1.0,2.0,3.0); OpenMesh::Vec3f vecf = OpenMesh::vector_cast<OpenMesh::Vec3f>(vecd); EXPECT_EQ(1.f, vecf[0]) << "vector type cast failed on component 0"; EXPECT_EQ(2.f, vecf[1]) << "vector type cast failed on component 1"; EXPECT_EQ(3.f, vecf[2]) << "vector type cast failed on component 2"; OpenMesh::Vec4d vecd4(40.0,30.0,20.0,10.0); vecd = OpenMesh::vector_cast<OpenMesh::Vec3d>(vecd4); EXPECT_EQ(40.0, vecd[0]) << "vector dimension cast failed on component 0"; EXPECT_EQ(30.0, vecd[1]) << "vector dimension cast failed on component 1"; EXPECT_EQ(20.0, vecd[2]) << "vector dimension cast failed on component 2"; } #if __cplusplus > 199711L || defined(__GXX_EXPERIMENTAL_CXX0X__) TEST_F(OpenMeshVectorTest, cpp11_constructors) { OpenMesh::Vec3d vec1 { 1.2, 2.0, 3.0 }; EXPECT_EQ(1.2, vec1[0]); EXPECT_EQ(2.0, vec1[1]); EXPECT_EQ(3.0, vec1[2]); OpenMesh::Vec4f vec2 { 1.2f, 3.5f, 1.0f, 0.0f }; EXPECT_EQ(1.2f, vec2[0]); EXPECT_EQ(3.5f, vec2[1]); EXPECT_EQ(1.0f, vec2[2]); EXPECT_EQ(0.0f, vec2[3]); OpenMesh::Vec4f vec2b { vec2 }; EXPECT_EQ(1.2f, vec2b[0]); EXPECT_EQ(3.5f, vec2b[1]); EXPECT_EQ(1.0f, vec2b[2]); EXPECT_EQ(0.0f, vec2b[3]); OpenMesh::Vec4d vec4d { 1.23 }; EXPECT_EQ(1.23, vec4d[0]); EXPECT_EQ(1.23, vec4d[1]); EXPECT_EQ(1.23, vec4d[2]); EXPECT_EQ(1.23, vec4d[3]); } TEST_F(OpenMeshVectorTest, cpp11_htmlColorLiteral) { static constexpr OpenMesh::Vec4f rose = 0xFFC7F1FF_htmlColor; EXPECT_EQ(0xFFC7F1FF_htmlColor, rose); const OpenMesh::Vec4f light_blue = 0x1FCFFFFF_htmlColor; EXPECT_LE((OpenMesh::Vec4f(0.1215686274f, 0.8117647058f, 1.0f, 1.0f) - light_blue).sqrnorm(), 1e-10); const auto light_blue_2 = 0x1FCFFFFF_htmlColor; // Check whether auto type deduction works as expected. static_assert(std::is_same<decltype(light_blue_2), decltype(light_blue)> ::value, "Bad type deduced from _htmlColor literal."); EXPECT_EQ(light_blue, light_blue_2); } namespace { class C { public: C() {} C(const C &rhs) { ADD_FAILURE() << "Copy constructor used."; } C(C &&rhs) { ++copy_con; } C &operator= (const C &rhs) { ADD_FAILURE() << "Copy assignemnt used."; return *this; } C &operator= (C &&rhs) { ++copy_ass; return *this; } static int copy_con; static int copy_ass; }; int C::copy_con = 0; int C::copy_ass = 0; } /** * Checks two things: * 1) Whether VectorT works with a non-arithmetic type. * 2) Whether move construction and assignment works. */ TEST_F(OpenMeshVectorTest, move_constructor_assignment) { C::copy_con = 0; C::copy_ass = 0; // Test move assigning. OpenMesh::VectorT<C, 3> x, y; x = std::move(y); EXPECT_EQ(3, C::copy_ass); EXPECT_EQ(0, C::copy_con); // Test move constructing. OpenMesh::VectorT<C, 3> z(std::move(x)); EXPECT_EQ(3, C::copy_ass); EXPECT_EQ(3, C::copy_con); } #endif // C++11 TEST_F(OpenMeshVectorTest, BasicLinearAlgebra) { OpenMesh::Vec3d v(1, 2, 3); EXPECT_EQ(v[0], 1.0); EXPECT_EQ(v[1], 2.0); EXPECT_EQ(v[2], 3.0); EXPECT_EQ(OpenMesh::Vec3d(-1, -2, -3), -v); EXPECT_EQ(3, OpenMesh::Vec3d(1, 3, 2).max()); EXPECT_EQ(3, OpenMesh::Vec3d(1, 2, 3).max()); EXPECT_EQ(3, OpenMesh::Vec3d(1, 3, -4).max()); EXPECT_EQ(3, OpenMesh::Vec3d(-4, 2, 3).max()); EXPECT_EQ(4, OpenMesh::Vec3d(1, 3, -4).max_abs()); EXPECT_EQ(4, OpenMesh::Vec3d(-4, 2, 3).max_abs()); EXPECT_EQ(1, OpenMesh::Vec3d(1, 3, 2).min()); EXPECT_EQ(1, OpenMesh::Vec3d(1, 2, 3).min()); EXPECT_EQ(-4, OpenMesh::Vec3d(1, 3, -4).min()); EXPECT_EQ(-4, OpenMesh::Vec3d(-4, 2, 3).min()); EXPECT_EQ(1, OpenMesh::Vec3d(1, 3, -4).min_abs()); EXPECT_EQ(2, OpenMesh::Vec3d(-4, 2, 3).min_abs()); EXPECT_NEAR(14, OpenMesh::Vec3d(1, 2, 3) | OpenMesh::Vec3d(1, 2, 3), 1e-6); EXPECT_NEAR(-14, OpenMesh::Vec3d(1, 2, 3) | OpenMesh::Vec3d(-1, -2, -3), 1e-6); EXPECT_NEAR(14, OpenMesh::Vec3d(-1, -2, -3) | OpenMesh::Vec3d(-1, -2, -3), 1e-6); } TEST_F(OpenMeshVectorTest, normalized_cond) { OpenMesh::Vec3d v1(1, -2, 3), v2(0, 0, 0); EXPECT_EQ(OpenMesh::Vec3d(0, 0, 0), v2.normalize_cond()); const OpenMesh::Vec3d r1 = OpenMesh::Vec3d( 0.2672612419124244, -0.5345224838248488, 0.8017837257372732) - v1.normalize_cond(); EXPECT_NEAR(r1[0], 0.0, 1e-12); EXPECT_NEAR(r1[1], 0.0, 1e-12); EXPECT_NEAR(r1[2], 0.0, 1e-12); } TEST_F(OpenMeshVectorTest, size_dim) { OpenMesh::Vec3d v3d(1, 2, 3); OpenMesh::Vec3f v3f(1, 2, 3); OpenMesh::Vec2i v2i(1, 2); EXPECT_EQ(3u, v3d.size()); EXPECT_EQ(3, v3d.dim()); EXPECT_EQ(3u, v3f.size()); EXPECT_EQ(3, v3f.dim()); EXPECT_EQ(2u, v2i.size()); EXPECT_EQ(2, v2i.dim()); } } <|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 "remoting/jingle_glue/jingle_client.h" #include "base/logging.h" #include "base/message_loop.h" #include "jingle/notifier/communicator/gaia_token_pre_xmpp_auth.h" #include "remoting/jingle_glue/iq_request.h" #include "remoting/jingle_glue/jingle_thread.h" #include "remoting/jingle_glue/relay_port_allocator.h" #include "remoting/jingle_glue/xmpp_socket_adapter.h" #include "third_party/libjingle/source/talk/base/asyncsocket.h" #include "third_party/libjingle/source/talk/base/ssladapter.h" #include "third_party/libjingle/source/talk/p2p/base/sessionmanager.h" #include "third_party/libjingle/source/talk/p2p/base/transport.h" #include "third_party/libjingle/source/talk/p2p/client/sessionmanagertask.h" #include "third_party/libjingle/source/talk/session/tunnel/tunnelsessionclient.h" #include "third_party/libjingle/source/talk/xmpp/prexmppauth.h" #include "third_party/libjingle/source/talk/xmpp/saslcookiemechanism.h" namespace remoting { JingleClient::JingleClient(JingleThread* thread) : thread_(thread), callback_(NULL), client_(NULL), state_(START), initialized_(false), closed_(false) { } JingleClient::~JingleClient() { AutoLock auto_lock(state_lock_); DCHECK(!initialized_ || closed_); } void JingleClient::Init( const std::string& username, const std::string& auth_token, const std::string& auth_token_service, Callback* callback) { DCHECK_NE(username, ""); { AutoLock auto_lock(state_lock_); DCHECK(!initialized_ && !closed_); initialized_ = true; DCHECK(callback != NULL); callback_ = callback; } message_loop()->PostTask( FROM_HERE, NewRunnableMethod(this, &JingleClient::DoInitialize, username, auth_token, auth_token_service)); } void JingleClient::DoInitialize(const std::string& username, const std::string& auth_token, const std::string& auth_token_service) { DCHECK_EQ(message_loop(), MessageLoop::current()); buzz::Jid login_jid(username); buzz::XmppClientSettings settings; settings.set_user(login_jid.node()); settings.set_host(login_jid.domain()); settings.set_resource("chromoting"); settings.set_use_tls(true); settings.set_token_service(auth_token_service); settings.set_auth_cookie(auth_token); settings.set_server(talk_base::SocketAddress("talk.google.com", 5222)); client_ = new buzz::XmppClient(thread_->task_pump()); client_->SignalStateChange.connect( this, &JingleClient::OnConnectionStateChanged); buzz::AsyncSocket* socket = new XmppSocketAdapter(settings, false); client_->Connect(settings, "", socket, CreatePreXmppAuth(settings)); client_->Start(); network_manager_.reset(new talk_base::NetworkManager()); RelayPortAllocator* port_allocator = new RelayPortAllocator(network_manager_.get(), "transp2"); port_allocator_.reset(port_allocator); port_allocator->SetJingleInfo(client_); session_manager_.reset(new cricket::SessionManager(port_allocator_.get())); cricket::SessionManagerTask* receiver = new cricket::SessionManagerTask(client_, session_manager_.get()); receiver->EnableOutgoingMessages(); receiver->Start(); } void JingleClient::Close() { Close(NULL); } void JingleClient::Close(Task* closed_task) { { AutoLock auto_lock(state_lock_); // If the client is already closed then don't close again. if (closed_) { if (closed_task) thread_->message_loop()->PostTask(FROM_HERE, closed_task); return; } closed_task_.reset(closed_task); closed_ = true; } message_loop()->PostTask( FROM_HERE, NewRunnableMethod(this, &JingleClient::DoClose)); } void JingleClient::DoClose() { DCHECK_EQ(message_loop(), MessageLoop::current()); DCHECK(closed_); session_manager_.reset(); port_allocator_.reset(); network_manager_.reset(); if (client_) { client_->Disconnect(); // Client is deleted by TaskRunner. client_ = NULL; } if (closed_task_.get()) { closed_task_->Run(); closed_task_.reset(); } } std::string JingleClient::GetFullJid() { AutoLock auto_lock(full_jid_lock_); return full_jid_; } IqRequest* JingleClient::CreateIqRequest() { return new IqRequest(this); } MessageLoop* JingleClient::message_loop() { return thread_->message_loop(); } cricket::SessionManager* JingleClient::session_manager() { DCHECK_EQ(message_loop(), MessageLoop::current()); return session_manager_.get(); } void JingleClient::OnConnectionStateChanged(buzz::XmppEngine::State state) { switch (state) { case buzz::XmppEngine::STATE_START: UpdateState(START); break; case buzz::XmppEngine::STATE_OPENING: UpdateState(CONNECTING); break; case buzz::XmppEngine::STATE_OPEN: SetFullJid(client_->jid().Str()); UpdateState(CONNECTED); break; case buzz::XmppEngine::STATE_CLOSED: UpdateState(CLOSED); break; default: NOTREACHED(); break; } } void JingleClient::SetFullJid(const std::string& full_jid) { AutoLock auto_lock(full_jid_lock_); full_jid_ = full_jid; } void JingleClient::UpdateState(State new_state) { if (new_state != state_) { state_ = new_state; { // We have to have the lock held, otherwise we cannot be sure that // the client hasn't been closed when we call the callback. AutoLock auto_lock(state_lock_); if (!closed_) callback_->OnStateChange(this, new_state); } } } buzz::PreXmppAuth* JingleClient::CreatePreXmppAuth( const buzz::XmppClientSettings& settings) { buzz::Jid jid(settings.user(), settings.host(), buzz::STR_EMPTY); return new notifier::GaiaTokenPreXmppAuth(jid.Str(), settings.auth_cookie(), settings.token_service()); } } // namespace remoting <commit_msg>Fix crash when shutting down xmpp connection.<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 "remoting/jingle_glue/jingle_client.h" #include "base/logging.h" #include "base/message_loop.h" #include "jingle/notifier/communicator/gaia_token_pre_xmpp_auth.h" #include "remoting/jingle_glue/iq_request.h" #include "remoting/jingle_glue/jingle_thread.h" #include "remoting/jingle_glue/relay_port_allocator.h" #include "remoting/jingle_glue/xmpp_socket_adapter.h" #include "third_party/libjingle/source/talk/base/asyncsocket.h" #include "third_party/libjingle/source/talk/base/ssladapter.h" #include "third_party/libjingle/source/talk/p2p/base/sessionmanager.h" #include "third_party/libjingle/source/talk/p2p/base/transport.h" #include "third_party/libjingle/source/talk/p2p/client/sessionmanagertask.h" #include "third_party/libjingle/source/talk/session/tunnel/tunnelsessionclient.h" #include "third_party/libjingle/source/talk/xmpp/prexmppauth.h" #include "third_party/libjingle/source/talk/xmpp/saslcookiemechanism.h" namespace remoting { JingleClient::JingleClient(JingleThread* thread) : thread_(thread), callback_(NULL), client_(NULL), state_(START), initialized_(false), closed_(false) { } JingleClient::~JingleClient() { AutoLock auto_lock(state_lock_); DCHECK(!initialized_ || closed_); } void JingleClient::Init( const std::string& username, const std::string& auth_token, const std::string& auth_token_service, Callback* callback) { DCHECK_NE(username, ""); { AutoLock auto_lock(state_lock_); DCHECK(!initialized_ && !closed_); initialized_ = true; DCHECK(callback != NULL); callback_ = callback; } message_loop()->PostTask( FROM_HERE, NewRunnableMethod(this, &JingleClient::DoInitialize, username, auth_token, auth_token_service)); } void JingleClient::DoInitialize(const std::string& username, const std::string& auth_token, const std::string& auth_token_service) { DCHECK_EQ(message_loop(), MessageLoop::current()); buzz::Jid login_jid(username); buzz::XmppClientSettings settings; settings.set_user(login_jid.node()); settings.set_host(login_jid.domain()); settings.set_resource("chromoting"); settings.set_use_tls(true); settings.set_token_service(auth_token_service); settings.set_auth_cookie(auth_token); settings.set_server(talk_base::SocketAddress("talk.google.com", 5222)); client_ = new buzz::XmppClient(thread_->task_pump()); client_->SignalStateChange.connect( this, &JingleClient::OnConnectionStateChanged); buzz::AsyncSocket* socket = new XmppSocketAdapter(settings, false); client_->Connect(settings, "", socket, CreatePreXmppAuth(settings)); client_->Start(); network_manager_.reset(new talk_base::NetworkManager()); RelayPortAllocator* port_allocator = new RelayPortAllocator(network_manager_.get(), "transp2"); port_allocator_.reset(port_allocator); port_allocator->SetJingleInfo(client_); session_manager_.reset(new cricket::SessionManager(port_allocator_.get())); cricket::SessionManagerTask* receiver = new cricket::SessionManagerTask(client_, session_manager_.get()); receiver->EnableOutgoingMessages(); receiver->Start(); } void JingleClient::Close() { Close(NULL); } void JingleClient::Close(Task* closed_task) { { AutoLock auto_lock(state_lock_); // If the client is already closed then don't close again. if (closed_) { if (closed_task) thread_->message_loop()->PostTask(FROM_HERE, closed_task); return; } closed_task_.reset(closed_task); closed_ = true; } message_loop()->PostTask( FROM_HERE, NewRunnableMethod(this, &JingleClient::DoClose)); } void JingleClient::DoClose() { DCHECK_EQ(message_loop(), MessageLoop::current()); DCHECK(closed_); session_manager_.reset(); port_allocator_.reset(); network_manager_.reset(); if (client_) { client_->Disconnect(); // Client is deleted by TaskRunner. client_ = NULL; } if (closed_task_.get()) { closed_task_->Run(); closed_task_.reset(); } } std::string JingleClient::GetFullJid() { AutoLock auto_lock(full_jid_lock_); return full_jid_; } IqRequest* JingleClient::CreateIqRequest() { return new IqRequest(this); } MessageLoop* JingleClient::message_loop() { return thread_->message_loop(); } cricket::SessionManager* JingleClient::session_manager() { DCHECK_EQ(message_loop(), MessageLoop::current()); return session_manager_.get(); } void JingleClient::OnConnectionStateChanged(buzz::XmppEngine::State state) { switch (state) { case buzz::XmppEngine::STATE_START: UpdateState(START); break; case buzz::XmppEngine::STATE_OPENING: UpdateState(CONNECTING); break; case buzz::XmppEngine::STATE_OPEN: SetFullJid(client_->jid().Str()); UpdateState(CONNECTED); break; case buzz::XmppEngine::STATE_CLOSED: UpdateState(CLOSED); // Client is destroyed by the TaskRunner after the client is // closed. Reset the pointer so we don't try to use it later. client_ = NULL; break; default: NOTREACHED(); break; } } void JingleClient::SetFullJid(const std::string& full_jid) { AutoLock auto_lock(full_jid_lock_); full_jid_ = full_jid; } void JingleClient::UpdateState(State new_state) { if (new_state != state_) { state_ = new_state; { // We have to have the lock held, otherwise we cannot be sure that // the client hasn't been closed when we call the callback. AutoLock auto_lock(state_lock_); if (!closed_) callback_->OnStateChange(this, new_state); } } } buzz::PreXmppAuth* JingleClient::CreatePreXmppAuth( const buzz::XmppClientSettings& settings) { buzz::Jid jid(settings.user(), settings.host(), buzz::STR_EMPTY); return new notifier::GaiaTokenPreXmppAuth(jid.Str(), settings.auth_cookie(), settings.token_service()); } } // namespace remoting <|endoftext|>
<commit_before>#include "tile.h" #include "animation.h" #include "camera.h" #include "util/bitmap.h" #include "util/debug.h" #include "util/load_exception.h" #include "util/token.h" using namespace std; using namespace Platformer; Tile::Tile(): row(0), column(0){ } Tile::Tile(const Token * token, std::map< std::string, Animation *> & animations): row(0), column(0){ TokenView view = token->view(); while (view.hasMore()){ try{ const Token * tok; view >> tok; if (*tok == "image"){ std::string name; tok->view() >> name; animation = animations[name]; } else if (*tok == "position"){ tok->view() >> row >> column; } else { Global::debug( 3 ) << "Unhandled Tile attribute: "<< endl; if (Global::getDebug() >= 3){ token->print(" "); } } } catch ( const TokenException & ex ) { throw LoadException(__FILE__, __LINE__, ex, "Tile parse error"); } catch ( const LoadException & ex ) { throw ex; } } } Tile::~Tile(){ } void Tile::act(){ } void Tile::draw(int x, int y, const Bitmap & bmp){ if (animation){ animation->draw(x, y, bmp); } } void Tile::setAnimation(Animation * anim){ } TileManager::TileManager(const Token * token, std::map< std::string, Animation *> & animations): tileX(0), tileY(0), dimensionsX(0), dimensionsY(0){ TokenView view = token->view(); while (view.hasMore()){ try{ const Token * tok; view >> tok; if (*tok == "tile-size"){ tok->view() >> tileX >> tileY; } else if (*tok == "dimensions"){ tok->view() >> dimensionsX >> dimensionsY; } else if (*tok == "tile"){ Tile * tile = new Tile(tok, animations); const int row = tile->getRow(); const int col = tile->getColumn(); // Do first one tiles[tile->getRow()][tile->getColumn()] = tile; // Check repeatables int times = 0; if (tok->match("_/repeat-up", times)){ for (int i = row-1; i >= (row - times); --i){ if (i < 0){ break; } tiles[i][tile->getColumn()] = tile; } } if (tok->match("_/repeat-down", times)){ for (int i = row+1; i <= row + times; ++i){ if (i > dimensionsY){ break; } tiles[i][tile->getColumn()] = tile; } } if (tok->match("_/repeat-left", times)){ for (int i = col-1; i >= (col - times); --i){ if (i < 0){ break; } tiles[tile->getRow()][i] = tile; } } if (tok->match("_/repeat-right", times)){ for (int i = col+1; i <= col + times; ++i){ if (i > dimensionsX){ break; } tiles[tile->getRow()][i] = tile; } } } else { Global::debug( 3 ) << "Unhandled Tilemap attribute: "<< endl; if (Global::getDebug() >= 3){ token->print(" "); } } } catch ( const TokenException & ex ) { throw LoadException(__FILE__, __LINE__, ex, "Tilemap parse error"); } catch ( const LoadException & ex ) { throw ex; } } } TileManager::~TileManager(){ for (tileMap::iterator i = tiles.begin(); i != tiles.end(); ++i){ for (std::map< int, Tile *>::iterator j = i->second.begin(); j != i->second.end(); j++){ if (j->second){ delete j->second; } } } } void TileManager::act(){ } void TileManager::draw(const Camera & camera){ // Render tiles const int x = (int)((camera.getX())/tileX); const int y = (int)((camera.getY())/tileY); const int w = x + (int)(camera.getWindow().getWidth()/tileX) + 1; const int h = y + (int)(camera.getWindow().getHeight()/tileY); int posy = y * tileY - camera.getY(); for(int row = y; row < h; ++row){ int posx = x * tileX - camera.getX(); for(int column = x; column < w; ++column){ Tile * tile = tiles[row][column]; if (tile){ tile->draw(posx, posy, camera.getWindow()); } posx+=tileX; } posy+=tileY; } } <commit_msg>Change image to animation to correctly reflect the object.<commit_after>#include "tile.h" #include "animation.h" #include "camera.h" #include "util/bitmap.h" #include "util/debug.h" #include "util/load_exception.h" #include "util/token.h" using namespace std; using namespace Platformer; Tile::Tile(): row(0), column(0){ } Tile::Tile(const Token * token, std::map< std::string, Animation *> & animations): row(0), column(0){ TokenView view = token->view(); while (view.hasMore()){ try{ const Token * tok; view >> tok; if (*tok == "animation"){ std::string name; tok->view() >> name; animation = animations[name]; } else if (*tok == "position"){ tok->view() >> row >> column; } else { Global::debug( 3 ) << "Unhandled Tile attribute: "<< endl; if (Global::getDebug() >= 3){ token->print(" "); } } } catch ( const TokenException & ex ) { throw LoadException(__FILE__, __LINE__, ex, "Tile parse error"); } catch ( const LoadException & ex ) { throw ex; } } } Tile::~Tile(){ } void Tile::act(){ } void Tile::draw(int x, int y, const Bitmap & bmp){ if (animation){ animation->draw(x, y, bmp); } } void Tile::setAnimation(Animation * anim){ } TileManager::TileManager(const Token * token, std::map< std::string, Animation *> & animations): tileX(0), tileY(0), dimensionsX(0), dimensionsY(0){ TokenView view = token->view(); while (view.hasMore()){ try{ const Token * tok; view >> tok; if (*tok == "tile-size"){ tok->view() >> tileX >> tileY; } else if (*tok == "dimensions"){ tok->view() >> dimensionsX >> dimensionsY; } else if (*tok == "tile"){ Tile * tile = new Tile(tok, animations); const int row = tile->getRow(); const int col = tile->getColumn(); // Do first one tiles[tile->getRow()][tile->getColumn()] = tile; // Check repeatables int times = 0; if (tok->match("_/repeat-up", times)){ for (int i = row-1; i >= (row - times); --i){ if (i < 0){ break; } tiles[i][tile->getColumn()] = tile; } } if (tok->match("_/repeat-down", times)){ for (int i = row+1; i <= row + times; ++i){ if (i > dimensionsY){ break; } tiles[i][tile->getColumn()] = tile; } } if (tok->match("_/repeat-left", times)){ for (int i = col-1; i >= (col - times); --i){ if (i < 0){ break; } tiles[tile->getRow()][i] = tile; } } if (tok->match("_/repeat-right", times)){ for (int i = col+1; i <= col + times; ++i){ if (i > dimensionsX){ break; } tiles[tile->getRow()][i] = tile; } } } else { Global::debug( 3 ) << "Unhandled Tilemap attribute: "<< endl; if (Global::getDebug() >= 3){ token->print(" "); } } } catch ( const TokenException & ex ) { throw LoadException(__FILE__, __LINE__, ex, "Tilemap parse error"); } catch ( const LoadException & ex ) { throw ex; } } } TileManager::~TileManager(){ for (tileMap::iterator i = tiles.begin(); i != tiles.end(); ++i){ for (std::map< int, Tile *>::iterator j = i->second.begin(); j != i->second.end(); j++){ if (j->second){ delete j->second; } } } } void TileManager::act(){ } void TileManager::draw(const Camera & camera){ // Render tiles const int x = (int)((camera.getX())/tileX); const int y = (int)((camera.getY())/tileY); const int w = x + (int)(camera.getWindow().getWidth()/tileX) + 1; const int h = y + (int)(camera.getWindow().getHeight()/tileY); int posy = y * tileY - camera.getY(); for(int row = y; row < h; ++row){ int posx = x * tileX - camera.getX(); for(int column = x; column < w; ++column){ Tile * tile = tiles[row][column]; if (tile){ tile->draw(posx, posy, camera.getWindow()); } posx+=tileX; } posy+=tileY; } } <|endoftext|>
<commit_before>/* video_resource.cpp This file is part of: GAME PENCIL ENGINE https://create.pawbyte.com Copyright (c) 2014-2020 Nathan Hurde, Chase Lee. Copyright (c) 2014-2020 PawByte LLC. Copyright (c) 2014-2020 Game Pencil Engine contributors ( Contributors Page ) 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. -Game Pencil Engine <https://create.pawbyte.com> */ #include "video_resource.h" #include "gpe_editor_settings.h" std::string SUPPORTED_VIDEO_EXT[SUPPORTED_VIDEO_FORMAT_COUNT]; videoResource::videoResource(GPE_GeneralResourceContainer * pFolder) { projectParentFolder = pFolder; resourceFileName = " "; resourceName = " "; for( int i = 0; i < SUPPORTED_VIDEO_FORMAT_COUNT; i++) { videoFileName[i] = ""; } videoId = -1; videoType = 0; videoEditorMainNote = new GPE_Label_Text("Video playback in editor not supported.","Video playback in editor not supported."); videoGroupName = new GPE_TextInputBasic("","default=blank"); videoGroupName->set_label("Video Group"); defaultVolume = new GPE_TextInputNumber("100",true,0,100); defaultVolume->set_string("100"); defaultVolume->set_label("Default Volume:"); openExternalEditorButton = new GPE_ToolIconButton( APP_DIRECTORY_NAME+"resources/gfx/iconpacks/fontawesome/rocket.png","Opens Audio In External Editor"); refreshResourceDataButton = new GPE_ToolIconButton( APP_DIRECTORY_NAME+"resources/gfx/iconpacks/fontawesome/refresh.png","Refreshes this resource's media files"); } videoResource::~videoResource() { if( videoEditorMainNote!=NULL) { delete videoEditorMainNote; videoEditorMainNote = NULL; } if( defaultVolume!=NULL) { delete defaultVolume; defaultVolume = NULL; } if( videoGroupName!=NULL) { delete videoGroupName; videoGroupName = NULL; } if( openExternalEditorButton!=NULL) { delete openExternalEditorButton; openExternalEditorButton = NULL; } if( refreshResourceDataButton!=NULL) { delete refreshResourceDataButton; refreshResourceDataButton = NULL; } } bool videoResource::build_intohtml5_file(std::ofstream * fileTarget, int leftTabAmount) { if( fileTarget!=NULL && fileTarget->is_open() ) { std::string nestedTabsStr = generate_tabs( leftTabAmount ); std::string nestedTabsStrObjFunc = generate_tabs( leftTabAmount +1 ); std::string html5SpShName = get_name(); *fileTarget << nestedTabsStr << "var " + html5SpShName + " = GPE.rsm.add_video("; *fileTarget << int_to_string (exportBuildGlobalId ) + ","; *fileTarget << "'"+html5SpShName + "',"; for( int i = 0; i < SUPPORTED_VIDEO_FORMAT_COUNT; i++) { if( (int)videoFileName[i].size() > 3) { *fileTarget << "'resources/videos/"+get_short_filename( videoFileName[i] )+"',"; } else { *fileTarget << "'',"; } } if( videoGroupName!=NULL) { *fileTarget << "'"+videoGroupName->get_string()+"',"; } else { *fileTarget << "'',"; } if( defaultVolume!=NULL) { *fileTarget << defaultVolume->get_held_number() << ""; } else { *fileTarget << "100"; } *fileTarget << "); \n"; return true; } return false; } bool videoResource::build_intocpp_file(std::ofstream * fileTarget, int leftTabAmount ) { return true; } void videoResource::compile_cpp() { } bool videoResource::copy_video_source(std::string outDirectoryName) { std::string copyDestinationStr = ""; bool copyErrorFound = false; for( int i = 0; i < SUPPORTED_VIDEO_FORMAT_COUNT ; i++) { if((int)videoFileName[i].size() > 0) { copyDestinationStr = outDirectoryName+"/"+ get_short_filename(videoFileName[i],true); GPE_Report(videoFileName[i]+" attempted to copy to "+copyDestinationStr); if( copy_file(videoFileName[i],copyDestinationStr )==false) { copyErrorFound = true; } } } return copyErrorFound; } bool videoResource::include_local_files( std::string pBuildDir , int buildType ) { appendToFile(get_user_settings_folder()+"resources_check.txt", get_name() +"..."); return true; } void videoResource::load_video(std::string newFileName) { if( (int) newFileName.size()>0 ) { bool isvideoFile = true; std::string newFileExt = get_file_ext(newFileName); if( newFileExt=="mp4") { videoFileName[mp4FileName] = newFileName; } else if( newFileExt=="ogg") { videoFileName[oggVideoFileName] = newFileName; } else if( newFileExt=="webm") { videoFileName[webmFileName] = newFileName; } else { display_user_alert("[Alert - "+resourceName+"]","Unsupported file type added."); } if( isvideoFile) { copy_video_source( file_to_dir(parentProjectName)+"/gpe_project/resources/videos" ); } } } void videoResource::preprocess_self(std::string alternatePath) { if( resourcePostProcessed == false || file_exists(alternatePath) ) { if( GPE_LOADER != NULL ) { GPE_LOADER->update_submessages( "Processing Video",resourceName ); } std::string otherColContainerName = ""; std::string newFileIn =""; std::string soughtDir = file_to_dir(parentProjectName)+"/gpe_project/resources/videos/"; if( file_exists(alternatePath) ) { newFileIn = alternatePath; soughtDir = get_path_from_file(newFileIn); } else { newFileIn = soughtDir + resourceName+".gpf"; } std::ifstream gameResourceFileIn( newFileIn.c_str() ); GPE_Report("Loading video - "+newFileIn); //If the level file could be loaded if( !gameResourceFileIn.fail() && gameResourceFileIn.is_open()) { int equalPos = 0; std::string firstChar=""; std::string keyString=""; std::string valString=""; std::string subValString=""; std::string currLine=""; std::string currLineToBeProcessed; float foundFileVersion = 0; std::string fFontFile = ""; while ( gameResourceFileIn.good() ) { getline (gameResourceFileIn,currLine); //gets the next line of the file currLineToBeProcessed = trim_left_inplace(currLine); currLineToBeProcessed = trim_right_inplace(currLineToBeProcessed); if( foundFileVersion <=0) { //Empty Line skipping is only allowed at the top of the file if(!currLineToBeProcessed.empty() ) { //Comment skipping is only allowed at the top of the file if( currLineToBeProcessed[0]!= '#' && currLineToBeProcessed[0]!='/' ) { //searches for an equal character and parses through the variable equalPos=currLineToBeProcessed.find_first_of("="); if(equalPos!=(int)std::string::npos) { //if the equalPos is present, then parse on through and carryon keyString = currLineToBeProcessed.substr(0,equalPos); valString = currLineToBeProcessed.substr(equalPos+1,currLineToBeProcessed.length()); if( keyString=="Version") { foundFileVersion = string_to_float(valString); } } } } } else if( foundFileVersion <= 2) { //Begin processing the file. if(!currLineToBeProcessed.empty() ) { equalPos=currLineToBeProcessed.find_first_of("="); if(equalPos!=(int)std::string::npos) { //if the equalPos is present, then parse on through and carryon keyString = currLineToBeProcessed.substr(0,equalPos); valString = currLineToBeProcessed.substr(equalPos+1,currLineToBeProcessed.length()); if( keyString=="ResourceName") { renameBox->set_string(valString); } else if( keyString=="videoFileLocation") { load_video( soughtDir+valString ); } else if( keyString=="VideoGroup") { videoGroupName->set_string(valString); } else if( keyString=="DefaultVolume") { defaultVolume->set_number(string_to_int(valString,100)); } else { for(int i = 0; i < SUPPORTED_VIDEO_FORMAT_COUNT; i++) { if( keyString=="videoFile["+SUPPORTED_VIDEO_EXT[i]+"]") { if( (int)valString.size() > 3) { load_video( soughtDir+valString ); } } } } } } } else { GPE_Report("Invalid FoundFileVersion ="+float_to_string(foundFileVersion)+"."); } } if( GPE_LOADER != NULL ) { GPE_LOADER->increment_and_update( "Video resource processed",resourceName ); } } else { if( GPE_LOADER != NULL ) { GPE_LOADER->increment_and_update( "Video resource processingg error occurred",resourceName ); } } } } void videoResource::prerender_self() { standardEditableGameResource::prerender_self(); } void videoResource::process_self(GPE_Rect * viewedSpace,GPE_Rect * cam ) { viewedSpace = GPE_find_camera(viewedSpace); cam = GPE_find_camera(cam); if(cam!=NULL && viewedSpace!=NULL && PANEL_GENERAL_EDITOR!=NULL) { PANEL_GENERAL_EDITOR->clear_panel(); PANEL_GENERAL_EDITOR->add_gui_element(videoEditorMainNote,true); PANEL_GENERAL_EDITOR->add_gui_element(renameBox,true); PANEL_GENERAL_EDITOR->add_gui_element(refreshResourceDataButton,false ); PANEL_GENERAL_EDITOR->add_gui_element(loadResourceButton,false ); PANEL_GENERAL_EDITOR->add_gui_element(openExternalEditorButton,true); PANEL_GENERAL_EDITOR->add_gui_element(videoGroupName, true); PANEL_GENERAL_EDITOR->add_gui_element(defaultVolume,true); PANEL_GENERAL_EDITOR->add_gui_element(confirmResourceButton,true); PANEL_GENERAL_EDITOR->add_gui_element(cancelResourceButton,true); //PANEL_GENERAL_EDITOR->set_maxed_out_width(); PANEL_GENERAL_EDITOR->process_self(NULL, NULL); if( loadResourceButton!=NULL && loadResourceButton->is_clicked() ) { std::string newFileName = GPE_GetOpenFileName("Load In an video File","Video",MAIN_GUI_SETTINGS->fileOpenVideoDir); load_video(newFileName); } else if( confirmResourceButton!=NULL && confirmResourceButton->is_clicked() ) { save_resource(); } else if( cancelResourceButton->is_clicked() ) { resourcePostProcessed = false; preprocess_self(); } else if( openExternalEditorButton!=NULL && openExternalEditorButton->is_clicked() ) { bool hasFileToOpen = false; int ii = 0; for( ii = 0; ii < SUPPORTED_VIDEO_FORMAT_COUNT; ii++) { if( (int)videoFileName[ii].size() > 0) { hasFileToOpen = true; break; } } if( hasFileToOpen ) { GPE_open_context_menu(-1,-1,256); MAIN_CONTEXT_MENU->set_width(openExternalEditorButton->get_width() ); for( ii = 0; ii < SUPPORTED_VIDEO_FORMAT_COUNT; ii++) { if( (int)videoFileName[ii].size() > 0) { MAIN_CONTEXT_MENU->add_menu_option("Edit "+SUPPORTED_VIDEO_EXT[ii],ii); } } int menuSelection = GPE_Get_Context_Result(); if( menuSelection >=0 && menuSelection < SUPPORTED_VIDEO_FORMAT_COUNT) { std::string fileToEdit = videoFileName[menuSelection]; if( MAIN_EDITOR_SETTINGS!=NULL && MAIN_EDITOR_SETTINGS->pencilExternalEditorsFile[GPE_EXTERNAL_EDITOR_VID]!=NULL) { GPE_OpenProgram(MAIN_EDITOR_SETTINGS->pencilExternalEditorsFile[GPE_EXTERNAL_EDITOR_VID]->get_string(),fileToEdit, true ); } else { GPE_OpenURL(fileToEdit); } /* fileToEdit = "\"C:/Program Files (x86)/Audacity/audacity.exe\" \""+fileToEdit+"\""; GPE_OpenURL(fileToEdit);*/ appendToFile(get_user_settings_folder()+"gpe_error_log2.txt","Attempting to edit ["+fileToEdit+"]..."); } } } else if( refreshResourceDataButton!=NULL && refreshResourceDataButton->is_clicked() ) { resourcePostProcessed = false; preprocess_self(); } } } void videoResource::render_self(GPE_Rect * viewedSpace,GPE_Rect *cam ) { viewedSpace = GPE_find_camera(viewedSpace); cam = GPE_find_camera(cam); if( cam!=NULL && viewedSpace!=NULL) { for( int i = 0; i < SUPPORTED_VIDEO_FORMAT_COUNT; i++) { if( videoFileName[i].size()> 0) { gfs->render_text( viewedSpace->w-GENERAL_GPE_GUI_PADDING*3,GENERAL_GPE_GUI_PADDING+GPE_AVERAGE_LINE_HEIGHT*i,SUPPORTED_VIDEO_EXT[i]+" is attatched",GPE_MAIN_THEME->Main_Box_Font_Highlight_Color,GPE_DEFAULT_FONT,FA_RIGHT,FA_TOP); } else { gfs->render_text( viewedSpace->w-GENERAL_GPE_GUI_PADDING*3,GENERAL_GPE_GUI_PADDING+GPE_AVERAGE_LINE_HEIGHT*i,SUPPORTED_VIDEO_EXT[i]+" not attatched",GPE_MAIN_THEME->Main_Box_Font_Color,GPE_DEFAULT_FONT,FA_RIGHT,FA_TOP); } } gfs->render_text( viewedSpace->w/2, viewedSpace->h-32, "HTML5 Feature. Currently not supported in C++/Native runtime",GPE_MAIN_THEME->Main_Box_Font_Color,GPE_DEFAULT_FONT, FA_CENTER, FA_BOTTOM, 255); } // } void videoResource::save_resource(std::string alternatePath, int backupId) { if( GPE_LOADER != NULL ) { GPE_LOADER->update_submessages( "Saving Game video", resourceName ); } bool usingAltSaveSource = false; std::string newFileOut =""; std::string soughtDir = get_path_from_file(alternatePath); if( path_exists(soughtDir) ) { newFileOut = alternatePath; usingAltSaveSource= true; } else { soughtDir = file_to_dir(parentProjectName)+"/gpe_project/resources/videos/"; newFileOut = soughtDir + resourceName+".gpf"; } std::ofstream newSaveDataFile( newFileOut.c_str() ); //If the scene file could be saved if( !newSaveDataFile.fail() && newSaveDataFile.is_open() ) { write_header_on_file(&newSaveDataFile); std::string resFileLocation = ""; std::string resFileCopySrc; std::string resFileCopyDest; for(int i = 0; i < SUPPORTED_VIDEO_FORMAT_COUNT; i++) { if( (int)videoFileName[i].size() > 3) { resFileLocation = get_short_filename (videoFileName[i],true ); newSaveDataFile << "videoFile["+SUPPORTED_VIDEO_EXT[i]+"]="+resFileLocation+"\n"; if( (int)resFileLocation.size() > 0 && usingAltSaveSource ) { resFileCopySrc = file_to_dir(parentProjectName)+"/gpe_project/resources/video/"+resFileLocation; resFileCopyDest = soughtDir+resFileLocation; if( file_exists(resFileCopyDest) ) { /* if( GPE_Display_Basic_Prompt("[WARNING]Video File Already exists?","Are you sure you will like to overwrite your ["+resFileLocation+"] Video file? This action is irreversible!")==DISPLAY_QUERY_YES) { copy_file(resFileCopySrc,resFileCopyDest); } */ } else { copy_file(resFileCopySrc,resFileCopyDest); } } } } if( defaultVolume!=NULL) { newSaveDataFile << "DefaultVolume="+int_to_string(defaultVolume->get_held_number() )+"\n"; } if( videoGroupName!=NULL) { newSaveDataFile << "VideoGroup="+videoGroupName->get_string()+"\n"; } newSaveDataFile.close(); if( !usingAltSaveSource) { isModified = false; } if( GPE_LOADER != NULL ) { GPE_LOADER->increment_and_update( "Video resource saved",resourceName ); } return; } GPE_Main_Logs->log_general_error("Unable to save file ["+newFileOut+"]"); if( GPE_LOADER != NULL ) { GPE_LOADER->increment_and_update( "Video resource unable to save",resourceName ); } } bool videoResource::write_data_into_projectfile(std::ofstream * fileTarget, int nestedFoldersIn) { if( fileTarget!=NULL) { if( fileTarget->is_open() ) { std::string nestedTabsStr = generate_tabs( nestedFoldersIn ); *fileTarget << nestedTabsStr << "video=" << resourceName << "," << get_global_rid() << ",\n"; return true; } } return false; } <commit_msg>Delete video_resource.cpp<commit_after><|endoftext|>
<commit_before>/********************************************************************************* * * Inviwo - Interactive Visualization Workshop * * Copyright (c) 2014-2017 Inviwo Foundation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * *********************************************************************************/ #include <pybind11/pybind11.h> #include <modules/python3/python3module.h> #include <modules/python3/pythoninterpreter.h> #include <modules/python3/pythonexecutionoutputobservable.h> #include <modules/python3/processors/numpymandelbrot.h> #include <modules/python3/processors/numpyvolume.h> #include <modules/python3/processors/numpymeshcreatetest.h> #include <inviwo/core/common/inviwoapplication.h> #include <inviwo/core/util/commandlineparser.h> #include <inviwo/core/util/filesystem.h> #include <modules/python3/pythonscript.h> #include <modules/python3/pythonlogger.h> namespace inviwo { Python3Module::Python3Module(InviwoApplication* app) : InviwoModule(app, "Python3") , pythonInterpreter_(util::make_unique<PythonInterpreter>(this)) , pythonScriptArg_("p", "pythonScript", "Specify a python script to run at startup", false, "", "Path to the file containing the script") { registerProcessor<NumPyVolume>(); registerProcessor<NumpyMandelbrot>(); registerProcessor<NumPyMeshCreateTest>(); pythonInterpreter_->addObserver(&pythonLogger_); app->getCommandLineParser().add( &pythonScriptArg_, [this]() { auto filename = pythonScriptArg_.getValue(); if (!filesystem::fileExists(filename)) { LogWarn("Could not run script, file does not exist: " << filename); return; } PythonScriptDisk s(filename); s.run(); }, 100); app->dispatchFront([&]() { pythonInterpreter_->runString("import inviwopy"); // we need to import inviwopy to trigger // the initialization code in // inviwopy.cpp, this is needed to be // able to cast cpp/inviwo objects to // python objects //PythonScriptDisk(getPath() + "/scripts/documentgenerator.py").run(); }); } Python3Module::~Python3Module() { pythonInterpreter_->removeObserver(&pythonLogger_); } void Python3Module::registerPythonInitCallback(PythonInitCallback callback) { callbackObjects_.push_back(callback); } void Python3Module::invokePythonInitCallbacks(pybind11::module* objects) { for (auto& c : callbackObjects_) { c(objects); } } } // namespace <commit_msg>Python3: use post module registration hook<commit_after>/********************************************************************************* * * Inviwo - Interactive Visualization Workshop * * Copyright (c) 2014-2017 Inviwo Foundation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * *********************************************************************************/ #include <pybind11/pybind11.h> #include <modules/python3/python3module.h> #include <modules/python3/pythoninterpreter.h> #include <modules/python3/pythonexecutionoutputobservable.h> #include <modules/python3/processors/numpymandelbrot.h> #include <modules/python3/processors/numpyvolume.h> #include <modules/python3/processors/numpymeshcreatetest.h> #include <inviwo/core/common/inviwoapplication.h> #include <inviwo/core/util/commandlineparser.h> #include <inviwo/core/util/filesystem.h> #include <modules/python3/pythonscript.h> #include <modules/python3/pythonlogger.h> namespace inviwo { Python3Module::Python3Module(InviwoApplication* app) : InviwoModule(app, "Python3") , pythonInterpreter_(util::make_unique<PythonInterpreter>(this)) , pythonScriptArg_("p", "pythonScript", "Specify a python script to run at startup", false, "", "Path to the file containing the script") { registerProcessor<NumPyVolume>(); registerProcessor<NumpyMandelbrot>(); registerProcessor<NumPyMeshCreateTest>(); pythonInterpreter_->addObserver(&pythonLogger_); app->getCommandLineParser().add( &pythonScriptArg_, [this]() { auto filename = pythonScriptArg_.getValue(); if (!filesystem::fileExists(filename)) { LogWarn("Could not run script, file does not exist: " << filename); return; } PythonScriptDisk s(filename); s.run(); }, 100); app->addPostModulesRegistrationCallback([&]() { pythonInterpreter_->runString("import inviwopy"); // we need to import inviwopy to trigger // the initialization code in // inviwopy.cpp, this is needed to be // able to cast cpp/inviwo objects to // python objects //PythonScriptDisk(getPath() + "/scripts/documentgenerator.py").run(); }); } Python3Module::~Python3Module() { pythonInterpreter_->removeObserver(&pythonLogger_); } void Python3Module::registerPythonInitCallback(PythonInitCallback callback) { callbackObjects_.push_back(callback); } void Python3Module::invokePythonInitCallbacks(pybind11::module* objects) { for (auto& c : callbackObjects_) { c(objects); } } } // namespace <|endoftext|>
<commit_before>#include <igvc/SerialPort.h> #include <iostream> using namespace std; using namespace boost::asio; SerialPort::SerialPort(string device, int baud) : port(ioservice), path(device) { try { port.open(device); } catch(...){} if( !port.is_open() ) { throw runtime_error("Could not open serial port " + device); } try { port.set_option(boost::asio::serial_port_base::baud_rate(baud)); port.set_option(boost::asio::serial_port_base::parity(boost::asio::serial_port_base::parity::none)); port.set_option(boost::asio::serial_port_base::stop_bits(boost::asio::serial_port_base::stop_bits::one)); } catch(...) { throw runtime_error("Could not open serial port " + device); } } void SerialPort::flush() { ::tcflush(port.lowest_layer().native_handle(), TCIOFLUSH); } SerialPort::~SerialPort() { port.close(); } bool SerialPort::isOpen() { return port.is_open(); } void SerialPort::write(string msg) { if(port.is_open()) boost::asio::write(port, boost::asio::buffer(msg.c_str(),msg.length())); } void SerialPort::write(char *buffer, int length) { boost::asio::write(port, boost::asio::buffer(buffer, length)); } void SerialPort::write(unsigned char *buffer, int length) { if(port.is_open()) boost::asio::write(port, boost::asio::buffer(buffer, length)); } char SerialPort::read() { if(!port.is_open()) return -1; char in; try { boost::asio::read(port, buffer(&in, 1)); } catch (boost::exception_detail::clone_impl<boost::exception_detail::error_info_injector<boost::system::system_error> >& err) { throw runtime_error("Error reading serial port"); } return in; } char* SerialPort::read(int numBytes) { if(!port.is_open()) return (char*)""; char* bytes = new char[numBytes]; for(int i = 0; i < numBytes; i++) bytes[i] = read(); return bytes; } string SerialPort::readln() { string line = ""; while(true) { char in = read(); if(in == '\n') return line; if(in == '\r') return line; line = line + in; } } string SerialPort::devicePath() { return path; } <commit_msg>added serial port close before throwing errors<commit_after>#include <igvc/SerialPort.h> #include <iostream> using namespace std; using namespace boost::asio; SerialPort::SerialPort(string device, int baud) : port(ioservice), path(device) { try { port.open(device); } catch(...){} if( !port.is_open() ) { throw runtime_error("Could not open serial port " + device); } try { port.set_option(boost::asio::serial_port_base::baud_rate(baud)); port.set_option(boost::asio::serial_port_base::parity(boost::asio::serial_port_base::parity::none)); port.set_option(boost::asio::serial_port_base::stop_bits(boost::asio::serial_port_base::stop_bits::one)); } catch(...) { port.close(); throw runtime_error("Could not open serial port " + device); } } void SerialPort::flush() { ::tcflush(port.lowest_layer().native_handle(), TCIOFLUSH); } SerialPort::~SerialPort() { port.close(); } bool SerialPort::isOpen() { return port.is_open(); } void SerialPort::write(string msg) { if(port.is_open()) boost::asio::write(port, boost::asio::buffer(msg.c_str(),msg.length())); } void SerialPort::write(char *buffer, int length) { boost::asio::write(port, boost::asio::buffer(buffer, length)); } void SerialPort::write(unsigned char *buffer, int length) { if(port.is_open()) boost::asio::write(port, boost::asio::buffer(buffer, length)); } char SerialPort::read() { if(!port.is_open()) return -1; char in; try { boost::asio::read(port, buffer(&in, 1)); } catch (boost::exception_detail::clone_impl<boost::exception_detail::error_info_injector<boost::system::system_error> >& err) { port.close(); throw runtime_error("Error reading serial port"); } return in; } char* SerialPort::read(int numBytes) { if(!port.is_open()) return (char*)""; char* bytes = new char[numBytes]; for(int i = 0; i < numBytes; i++) bytes[i] = read(); return bytes; } string SerialPort::readln() { string line = ""; while(true) { char in = read(); if(in == '\n') return line; if(in == '\r') return line; line = line + in; } } string SerialPort::devicePath() { return path; } <|endoftext|>
<commit_before><commit_msg>sat: fixup schedule_requests_sat.cc<commit_after><|endoftext|>
<commit_before>#pragma once /////////////////////////////////////////////////////////////////////////////// /// @file DBBackend.hpp /// @author BrainlessLabs /// @version 0.3 /// @brief Implements the database backend. /////////////////////////////////////////////////////////////////////////////// #include <soci/soci.h> #include "blib/utils/Singleton.hpp" #include "blib/bun/DbLogger.hpp" #include <memory> #define BUN_SQLITE #ifdef BUN_SQLITE #include <soci/sqlite3/soci-sqlite3.h> #elif BUN_POSTGRES #include <soci/postgresql/soci-postgresql.h> #elif BUN_MYSQL #include <soci/mysql/soci-mysql.h> #endif namespace blib { namespace bun { namespace __private { struct DbGenericType{ }; struct DbTypeSqlite : DbGenericType{ }; struct DbTypePostgres : DbGenericType{ }; struct DbTypeMySql : DbGenericType{ }; template<typename T = DbGenericType> class DbBackend : public blib::Singleton<DbBackend<T>> { private: bool _ok; soci::session _sql_session; //DbBackend() = default; public: bool ok() const { return _ok; } bool connect(std::string const &in_params) { const soci::backend_factory backend_factory = #ifdef BUN_SQLITE soci::sqlite3; #elif BUN_POSTGRES soci::postgresql; #elif BUN_MYSQL soci::mysql; #endif try { _sql_session.open(backend_factory, in_params); _ok = true; } catch (std::exception const &except) { _ok = false; } } soci::session &session() { return _sql_session; } }; ///////////////////////////////////////////////// /// @class ConvertToSOCIType /// @brief Convert a basic type to a type available for soci. /// @details Supported type can be found in http://soci.sourceforge.net/doc/master/types/ /// So all basic C++ types will be converted to closest type. By default same type is returned. ///////////////////////////////////////////////// template<typename T> struct ConvertToSOCIType { using type = T; }; template<> struct ConvertToSOCIType<float> { using type = double; }; template<typename T> typename ConvertToSOCIType<T>::type convertToSOCIType(T const & val) { return static_cast<ConvertToSOCIType<T>::type>(val); } } } } <commit_msg>Adding string conversion<commit_after>#pragma once /////////////////////////////////////////////////////////////////////////////// /// @file DBBackend.hpp /// @author BrainlessLabs /// @version 0.3 /// @brief Implements the database backend. /////////////////////////////////////////////////////////////////////////////// #include <soci/soci.h> #include "blib/utils/Singleton.hpp" #include "blib/bun/DbLogger.hpp" #include <memory> #define BUN_SQLITE #ifdef BUN_SQLITE #include <soci/sqlite3/soci-sqlite3.h> #elif BUN_POSTGRES #include <soci/postgresql/soci-postgresql.h> #elif BUN_MYSQL #include <soci/mysql/soci-mysql.h> #endif namespace blib { namespace bun { namespace __private { struct DbGenericType{ }; struct DbTypeSqlite : DbGenericType{ }; struct DbTypePostgres : DbGenericType{ }; struct DbTypeMySql : DbGenericType{ }; template<typename T = DbGenericType> class DbBackend : public blib::Singleton<DbBackend<T>> { private: bool _ok; soci::session _sql_session; //DbBackend() = default; public: bool ok() const { return _ok; } bool connect(std::string const &in_params) { const soci::backend_factory backend_factory = #ifdef BUN_SQLITE soci::sqlite3; #elif BUN_POSTGRES soci::postgresql; #elif BUN_MYSQL soci::mysql; #endif try { _sql_session.open(backend_factory, in_params); _ok = true; } catch (std::exception const &except) { _ok = false; } } soci::session &session() { return _sql_session; } }; ///////////////////////////////////////////////// /// @class ConvertToSOCIType /// @brief Convert a basic type to a type available for soci. /// @details Supported type can be found in http://soci.sourceforge.net/doc/master/types/ /// So all basic C++ types will be converted to closest type. By default same type is returned. ///////////////////////////////////////////////// template<typename T> struct ConvertToSOCIType { using type = T; }; template<> struct ConvertToSOCIType<float> { using type = double; }; /// @brief Works for all stuff where the default type conversion operator is overloaded. template<typename T> typename ConvertToSOCIType<T>::type convertToSOCIType(T const & val) { return (ConvertToSOCIType<T>::type)(val); } std::string convertToSOCIType( char const* val) { std::string ret = val; return std::move(ret); } } } } <|endoftext|>
<commit_before>/* * Launch WAS child processes. * * author: Max Kellermann <mk@cm4all.com> */ #include "was_launch.hxx" #include "system/fd_util.h" #include "system/fd-util.h" #include "system/sigutil.h" #include "spawn/Spawn.hxx" #include "spawn/Prepared.hxx" #include "spawn/ChildOptions.hxx" #include "gerrno.h" #include "util/ConstBuffer.hxx" #include <daemon/log.h> #include <inline/compiler.h> #include <sys/socket.h> #include <stdio.h> #include <unistd.h> #include <string.h> #ifdef __linux #include <sched.h> #endif void WasProcess::Close() { if (control_fd >= 0) { close(control_fd); control_fd = -1; } if (input_fd >= 0) { close(input_fd); input_fd = -1; } if (output_fd >= 0) { close(output_fd); output_fd = -1; } } struct was_run_args { sigset_t signals; PreparedChildProcess child; }; gcc_noreturn static int was_run(void *ctx) { struct was_run_args *args = (struct was_run_args *)ctx; install_default_signal_handlers(); leave_signal_section(&args->signals); Exec(std::move(args->child)); } bool was_launch(WasProcess *process, const char *executable_path, ConstBuffer<const char *> args, const ChildOptions &options, GError **error_r) { int control_fds[2], input_fds[2], output_fds[2]; if (socketpair_cloexec(AF_UNIX, SOCK_STREAM, 0, control_fds) < 0) { set_error_errno_msg(error_r, "failed to create socket pair"); return false; } if (pipe_cloexec(input_fds) < 0) { set_error_errno_msg(error_r, "failed to create first pipe"); close(control_fds[0]); close(control_fds[1]); return false; } if (pipe_cloexec(output_fds) < 0) { set_error_errno_msg(error_r, "failed to create second pipe"); close(control_fds[0]); close(control_fds[1]); close(input_fds[0]); close(input_fds[1]); return false; } struct was_run_args run_args; run_args.child.stdin_fd = output_fds[0]; run_args.child.stdout_fd = input_fds[1]; /* fd2 is retained */ run_args.child.control_fd = control_fds[1]; run_args.child.Append(executable_path); for (auto i : args) run_args.child.Append(i); if (!options.CopyTo(run_args.child, true, nullptr, error_r)) { close(control_fds[0]); close(input_fds[0]); close(output_fds[1]); return false; } int clone_flags = SIGCHLD; clone_flags = options.ns.GetCloneFlags(clone_flags); /* avoid race condition due to libevent signal handler in child process */ enter_signal_section(&run_args.signals); char stack[8192]; long pid = clone(was_run, stack + sizeof(stack), clone_flags, &run_args); if (pid < 0) { leave_signal_section(&run_args.signals); set_error_errno_msg(error_r, "clone() failed"); close(control_fds[0]); close(input_fds[0]); close(output_fds[1]); return false; } leave_signal_section(&run_args.signals); fd_set_nonblock(input_fds[0], true); fd_set_nonblock(output_fds[1], true); process->pid = pid; process->control_fd = control_fds[0]; process->input_fd = input_fds[0]; process->output_fd = output_fds[1]; return true; } <commit_msg>was/launch: use SpawnChildProcess()<commit_after>/* * Launch WAS child processes. * * author: Max Kellermann <mk@cm4all.com> */ #include "was_launch.hxx" #include "system/fd_util.h" #include "system/fd-util.h" #include "spawn/Spawn.hxx" #include "spawn/Prepared.hxx" #include "spawn/ChildOptions.hxx" #include "gerrno.h" #include "util/ConstBuffer.hxx" #include <daemon/log.h> #include <inline/compiler.h> #include <sys/socket.h> #include <unistd.h> void WasProcess::Close() { if (control_fd >= 0) { close(control_fd); control_fd = -1; } if (input_fd >= 0) { close(input_fd); input_fd = -1; } if (output_fd >= 0) { close(output_fd); output_fd = -1; } } bool was_launch(WasProcess *process, const char *executable_path, ConstBuffer<const char *> args, const ChildOptions &options, GError **error_r) { int control_fds[2], input_fds[2], output_fds[2]; if (socketpair_cloexec(AF_UNIX, SOCK_STREAM, 0, control_fds) < 0) { set_error_errno_msg(error_r, "failed to create socket pair"); return false; } if (pipe_cloexec(input_fds) < 0) { set_error_errno_msg(error_r, "failed to create first pipe"); close(control_fds[0]); close(control_fds[1]); return false; } if (pipe_cloexec(output_fds) < 0) { set_error_errno_msg(error_r, "failed to create second pipe"); close(control_fds[0]); close(control_fds[1]); close(input_fds[0]); close(input_fds[1]); return false; } PreparedChildProcess p; p.stdin_fd = output_fds[0]; p.stdout_fd = input_fds[1]; /* fd2 is retained */ p.control_fd = control_fds[1]; p.Append(executable_path); for (auto i : args) p.Append(i); if (!options.CopyTo(p, true, nullptr, error_r)) { close(control_fds[0]); close(input_fds[0]); close(output_fds[1]); return false; } pid_t pid = SpawnChildProcess(std::move(p)); if (pid < 0) { set_error_errno_msg2(error_r, -pid, "clone() failed"); close(control_fds[0]); close(input_fds[0]); close(output_fds[1]); return false; } fd_set_nonblock(input_fds[0], true); fd_set_nonblock(output_fds[1], true); process->pid = pid; process->control_fd = control_fds[0]; process->input_fd = input_fds[0]; process->output_fd = output_fds[1]; return true; } <|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 . */ #ifndef SVX_BORDERLINE_HXX #define SVX_BORDERLINE_HXX #include <com/sun/star/table/BorderLineStyle.hpp> #include <tools/color.hxx> #include <svl/poolitem.hxx> #include <editeng/editengdllapi.h> #include <svtools/ctrlbox.hxx> // Line defaults in twips (former Writer defaults): #define DEF_LINE_WIDTH_0 1 #define DEF_LINE_WIDTH_1 20 #define DEF_LINE_WIDTH_2 50 #define DEF_LINE_WIDTH_3 80 #define DEF_LINE_WIDTH_4 100 #define DEF_LINE_WIDTH_5 10 // ============================================================================ namespace editeng { // values from ::com::sun::star::table::BorderLineStyle typedef sal_Int16 SvxBorderStyle; // convert border style between Word formats and LO SvxBorderStyle EDITENG_DLLPUBLIC ConvertBorderStyleFromWord(int); /// convert border width in twips between Word formats and LO double EDITENG_DLLPUBLIC ConvertBorderWidthToWord(SvxBorderStyle, double); double EDITENG_DLLPUBLIC ConvertBorderWidthFromWord(SvxBorderStyle, double, int); class EDITENG_DLLPUBLIC SvxBorderLine { protected: Color aColor; long m_nWidth; bool m_bMirrorWidths; BorderWidthImpl m_aWidthImpl; long m_nMult; long m_nDiv; SvxBorderStyle m_nStyle; sal_uInt16 nOutWidth; sal_uInt16 nInWidth; sal_uInt16 nDistance; bool m_bUseLeftTop; Color (*m_pColorOutFn)( Color ); Color (*m_pColorInFn)( Color ); Color (*m_pColorGapFn)( Color ); public: SvxBorderLine( const Color *pCol = 0, long nWidth = 0, SvxBorderStyle nStyle = ::com::sun::star::table::BorderLineStyle::SOLID, bool bUseLeftTop = false, Color (*pColorOutFn)( Color ) = &darkColor, Color (*pColorInFn)( Color ) = &darkColor, Color (*pColorGapFn)( Color ) = NULL ); SvxBorderLine( const SvxBorderLine& r ); SvxBorderLine& operator=( const SvxBorderLine& r ); const Color& GetColor() const { return aColor; } Color GetColorOut( bool bLeftOrTop = true ) const; Color GetColorIn( bool bLeftOrTop = true ) const; bool HasGapColor() const { return m_pColorGapFn != NULL; } Color GetColorGap() const; void SetWidth( long nWidth = 0 ) { m_nWidth = nWidth; } /** Guess the style and width from the three lines widths values. When the value of nStyle is SvxBorderLine::DOUBLE, the style set will be guessed using the three values to match the best possible style among the following: - SvxBorderLine::DOUBLE - SvxBorderLine::THINTHICK_SMALLGAP - SvxBorderLine::THINTHICK_MEDIUMGAP - SvxBorderLine::THINTHICK_LARGEGAP - SvxBorderLine::THICKTHIN_SMALLGAP - SvxBorderLine::THICKTHIN_MEDIUMGAP - SvxBorderLine::THICKTHIN_LARGEGAP If no styles matches the width, then the width is set to 0. There is one known case that could fit several styles: \a nIn = \a nDist = 0.75 pt, \a nOut = 1.5 pt. This case fits SvxBorderLine::THINTHICK_SMALLGAP and SvxBorderLine::THINTHICK_MEDIUMGAP with a 1.5 pt width and SvxBorderLine::THINTHICK_LARGEGAP with a 0.75 pt width. The same case happens also for thick-thin styles. \param nStyle the border style used to guess the width. \param nIn the width of the inner line in 1th pt \param nOut the width of the outer line in 1th pt \param nDist the width of the gap between the lines in 1th pt */ void GuessLinesWidths( SvxBorderStyle nStyle, sal_uInt16 nOut, sal_uInt16 nIn = 0, sal_uInt16 nDist = 0 ); // TODO Hacky method to mirror lines in only a few cases void SetMirrorWidths( bool bMirror = true ) { m_bMirrorWidths = bMirror; } long GetWidth( ) const { return m_nWidth; } sal_uInt16 GetOutWidth() const; sal_uInt16 GetInWidth() const; sal_uInt16 GetDistance() const; SvxBorderStyle GetBorderLineStyle() const { return m_nStyle; } void SetColor( const Color &rColor ) { aColor = rColor; } void SetColorOutFn( Color (*pColorOutFn)( Color ) ) { m_pColorOutFn = pColorOutFn; } void SetColorInFn( Color (*pColorInFn)( Color ) ) { m_pColorInFn = pColorInFn; } void SetColorGapFn( Color (*pColorGapFn)( Color ) ) { m_pColorGapFn = pColorGapFn; } void SetUseLeftTop( bool bUseLeftTop ) { m_bUseLeftTop = bUseLeftTop; } void SetBorderLineStyle( SvxBorderStyle nNew ); void ScaleMetrics( long nMult, long nDiv ); sal_Bool operator==( const SvxBorderLine &rCmp ) const; OUString GetValueString( SfxMapUnit eSrcUnit, SfxMapUnit eDestUnit, const IntlWrapper* pIntl, sal_Bool bMetricStr = sal_False ) const; bool HasPriority( const SvxBorderLine& rOtherLine ) const; bool isEmpty() const { return m_aWidthImpl.IsEmpty() || m_nStyle == ::com::sun::star::table::BorderLineStyle::NONE || m_nWidth == 0; } bool isDouble() const { return m_aWidthImpl.IsDouble(); } sal_uInt16 GetScaledWidth() const { return GetOutWidth() + GetInWidth() + GetDistance(); } static Color darkColor( Color aMain ); static Color lightColor( Color aMain ); static Color threeDLightColor( Color aMain ); static Color threeDMediumColor( Color aMain ); static Color threeDDarkColor( Color aMain ); static BorderWidthImpl getWidthImpl( SvxBorderStyle nStyle ); }; EDITENG_DLLPUBLIC bool operator!=( const SvxBorderLine& rLeft, const SvxBorderLine& rRight ); } // namespace editeng #endif /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>Remove unused width members from BorderLine class<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 . */ #ifndef SVX_BORDERLINE_HXX #define SVX_BORDERLINE_HXX #include <com/sun/star/table/BorderLineStyle.hpp> #include <tools/color.hxx> #include <svl/poolitem.hxx> #include <editeng/editengdllapi.h> #include <svtools/ctrlbox.hxx> // Line defaults in twips (former Writer defaults): #define DEF_LINE_WIDTH_0 1 #define DEF_LINE_WIDTH_1 20 #define DEF_LINE_WIDTH_2 50 #define DEF_LINE_WIDTH_3 80 #define DEF_LINE_WIDTH_4 100 #define DEF_LINE_WIDTH_5 10 // ============================================================================ namespace editeng { // values from ::com::sun::star::table::BorderLineStyle typedef sal_Int16 SvxBorderStyle; // convert border style between Word formats and LO SvxBorderStyle EDITENG_DLLPUBLIC ConvertBorderStyleFromWord(int); /// convert border width in twips between Word formats and LO double EDITENG_DLLPUBLIC ConvertBorderWidthToWord(SvxBorderStyle, double); double EDITENG_DLLPUBLIC ConvertBorderWidthFromWord(SvxBorderStyle, double, int); class EDITENG_DLLPUBLIC SvxBorderLine { protected: Color aColor; long m_nWidth; bool m_bMirrorWidths; BorderWidthImpl m_aWidthImpl; long m_nMult; long m_nDiv; SvxBorderStyle m_nStyle; bool m_bUseLeftTop; Color (*m_pColorOutFn)( Color ); Color (*m_pColorInFn)( Color ); Color (*m_pColorGapFn)( Color ); public: SvxBorderLine( const Color *pCol = 0, long nWidth = 0, SvxBorderStyle nStyle = ::com::sun::star::table::BorderLineStyle::SOLID, bool bUseLeftTop = false, Color (*pColorOutFn)( Color ) = &darkColor, Color (*pColorInFn)( Color ) = &darkColor, Color (*pColorGapFn)( Color ) = NULL ); SvxBorderLine( const SvxBorderLine& r ); SvxBorderLine& operator=( const SvxBorderLine& r ); const Color& GetColor() const { return aColor; } Color GetColorOut( bool bLeftOrTop = true ) const; Color GetColorIn( bool bLeftOrTop = true ) const; bool HasGapColor() const { return m_pColorGapFn != NULL; } Color GetColorGap() const; void SetWidth( long nWidth = 0 ) { m_nWidth = nWidth; } /** Guess the style and width from the three lines widths values. When the value of nStyle is SvxBorderLine::DOUBLE, the style set will be guessed using the three values to match the best possible style among the following: - SvxBorderLine::DOUBLE - SvxBorderLine::THINTHICK_SMALLGAP - SvxBorderLine::THINTHICK_MEDIUMGAP - SvxBorderLine::THINTHICK_LARGEGAP - SvxBorderLine::THICKTHIN_SMALLGAP - SvxBorderLine::THICKTHIN_MEDIUMGAP - SvxBorderLine::THICKTHIN_LARGEGAP If no styles matches the width, then the width is set to 0. There is one known case that could fit several styles: \a nIn = \a nDist = 0.75 pt, \a nOut = 1.5 pt. This case fits SvxBorderLine::THINTHICK_SMALLGAP and SvxBorderLine::THINTHICK_MEDIUMGAP with a 1.5 pt width and SvxBorderLine::THINTHICK_LARGEGAP with a 0.75 pt width. The same case happens also for thick-thin styles. \param nStyle the border style used to guess the width. \param nIn the width of the inner line in 1th pt \param nOut the width of the outer line in 1th pt \param nDist the width of the gap between the lines in 1th pt */ void GuessLinesWidths( SvxBorderStyle nStyle, sal_uInt16 nOut, sal_uInt16 nIn = 0, sal_uInt16 nDist = 0 ); // TODO Hacky method to mirror lines in only a few cases void SetMirrorWidths( bool bMirror = true ) { m_bMirrorWidths = bMirror; } long GetWidth( ) const { return m_nWidth; } sal_uInt16 GetOutWidth() const; sal_uInt16 GetInWidth() const; sal_uInt16 GetDistance() const; SvxBorderStyle GetBorderLineStyle() const { return m_nStyle; } void SetColor( const Color &rColor ) { aColor = rColor; } void SetColorOutFn( Color (*pColorOutFn)( Color ) ) { m_pColorOutFn = pColorOutFn; } void SetColorInFn( Color (*pColorInFn)( Color ) ) { m_pColorInFn = pColorInFn; } void SetColorGapFn( Color (*pColorGapFn)( Color ) ) { m_pColorGapFn = pColorGapFn; } void SetUseLeftTop( bool bUseLeftTop ) { m_bUseLeftTop = bUseLeftTop; } void SetBorderLineStyle( SvxBorderStyle nNew ); void ScaleMetrics( long nMult, long nDiv ); sal_Bool operator==( const SvxBorderLine &rCmp ) const; OUString GetValueString( SfxMapUnit eSrcUnit, SfxMapUnit eDestUnit, const IntlWrapper* pIntl, sal_Bool bMetricStr = sal_False ) const; bool HasPriority( const SvxBorderLine& rOtherLine ) const; bool isEmpty() const { return m_aWidthImpl.IsEmpty() || m_nStyle == ::com::sun::star::table::BorderLineStyle::NONE || m_nWidth == 0; } bool isDouble() const { return m_aWidthImpl.IsDouble(); } sal_uInt16 GetScaledWidth() const { return GetOutWidth() + GetInWidth() + GetDistance(); } static Color darkColor( Color aMain ); static Color lightColor( Color aMain ); static Color threeDLightColor( Color aMain ); static Color threeDMediumColor( Color aMain ); static Color threeDDarkColor( Color aMain ); static BorderWidthImpl getWidthImpl( SvxBorderStyle nStyle ); }; EDITENG_DLLPUBLIC bool operator!=( const SvxBorderLine& rLeft, const SvxBorderLine& rRight ); } // namespace editeng #endif /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>#ifndef GHULBUS_LIBRARY_INCLUDE_GUARD_BASE_LOG_HANDLERS_HPP #define GHULBUS_LIBRARY_INCLUDE_GUARD_BASE_LOG_HANDLERS_HPP /** @file * * @brief Log Handlers. * @author Andreas Weis (der_ghulbus@ghulbus-inc.de) */ #include <gbBase/config.hpp> #include <gbBase/Log.hpp> #include <condition_variable> #include <deque> #include <fstream> #include <mutex> #include <thread> #include <tuple> namespace GHULBUS_BASE_NAMESPACE { namespace Log { /** Handlers for use with Ghulbus::Log::setLogHandler(). */ namespace Handlers { /** Simple, unsynchronized logging to `std::cout` and `std::cerr`. * Log messages of Ghulbus::LogLevel::Error or higher go to `std::cerr`, all others to `std::cout`. * Logging is not synchronized, so logging concurrently from multiple threads is not safe with this handler. * Use one of the \ref log_handler_adapters "thread-safe adapters" LogSynchronizeMutex or LogAsync if you need to * log from more than one thread. * @note Logging to the console is usually quite slow and can slow down an application significantly if many log * messages are produces. Use the LogAsync adapter if performance is an issue. */ GHULBUS_BASE_API void logToCout(LogLevel log_level, std::stringstream&& log_stream); #ifdef WIN32 /** Logs to an attached debugger via the OutputDebugString() Win32 API function. */ GHULBUS_BASE_API void logToWindowsDebugger(LogLevel log_level, std::stringstream&& log_stream); #endif /** Unsynchronized file logging. * All log messages will be appended to the given log file. %Log messages may be buffered in memory but will be * flushed upon destruction of the handler object. * Logging is not synchronized, so logging concurrently from multiple threads is not safe with this handler. * Use one of the \ref log_handler_adapters "thread-safe adapters" LogSynchronizeMutex or LogAsync if you need to * log from more than one thread. * @note This handler uses `std::fstream` for file I/O which might perform less than ideal on certain * (*cough* Windows) implementations. * Use the LogAsync adapter if performance is an issue. */ class LogToFile { private: std::ofstream m_logFile; public: /** Construct a logger for logging to a file. * @param[in] filename Path to the log file. This file will be opened in append mode. * @throw Exceptions::IOError If file could not be opened for writing. */ GHULBUS_BASE_API LogToFile(char const* filename); /** Convert to a LogHandler function to pass to Ghulbus::Log::setLogHandler(). * @attention Note that an object must not be destroyed while it is set as log handler. */ GHULBUS_BASE_API operator LogHandler(); }; /** @defgroup log_handler_adapters Handler adapters. * A handler adapter is not a full handler by itself, but rather wraps around a downstream handler to add * additional functionality (like thread safety). * @{ */ /** Simple synchronization. * The mutex adapter synchronizes concurrent access to the downstream handler via a mutex. * The resulting handler is thread safe. */ class LogSynchronizeMutex { private: std::mutex m_mutex; LogHandler m_downstreamHandler; public: /** Adapting Constructor. * @param[in] downstream_handler The log handler that is to be wrapped. * The downstream handler need not be thread safe. * The downstream handler must not be empty. If the downstream handler dies before * this adapter, the behavior is undefined. */ GHULBUS_BASE_API LogSynchronizeMutex(LogHandler downstream_handler); /** Convert to a LogHandler function to pass to Ghulbus::Log::setLogHandler(). * @attention Note that an object must not be destroyed while it is set as log handler. */ GHULBUS_BASE_API operator LogHandler(); }; /** Asynchronous logging. * This adapter defers execution of the downstream handler in a separate thread. This allows the logging thread * to continue immediately after assembling the log message without having to wait for the log I/O to complete. * The impact on the runtime of the logging thread is far lower than with the other handlers. The downside is * that async logging requires spawning an additional I/O thread to execute the downstream handler. * Note that all access to the downstream handler is serialized through this I/O thread, so you can use a thread * unsafe handler as downstream handler. * * @note Messages will be queued in memory for processing. If an application produces log messages faster than the * adapted handler can process them, this can in theory consume all available memory on the machine. Be careful * not to overload the logging thread in this way. * * @note While the async handler works very well with small numbers of threads, it still requires concurrent access * to the single queue of log messages. If you need highly concurrent logging, consider using an adapter that * uses several thread-local queues instead. */ class LogAsync { private: typedef std::tuple<LogLevel, std::stringstream> QueueElement; private: std::mutex m_mutex; ///< mutex protexting access to the m_queue std::deque<QueueElement> m_queue; ///< queue of log messages bool m_stopRequested; ///< flag indicating that the user called stop() to stop the I/O thread std::condition_variable m_condvar; ///< signal that a message was pushed to the queue or stop was requested LogHandler m_downstreamHandler; std::thread m_ioThread; public: /** @copydoc LogSynchronizeMutex::LogSynchronizeMutex(LogHandler) */ GHULBUS_BASE_API LogAsync(LogHandler downstream_handler); /** Start the I/O thread. * Invoking the log handler obtained from this class will put the respective log message to an in-memory queue. * This function will spawn a thread that waits for messages to be put into that queue and forwards them to the * downstream handler. Note that while that thread is not running, messages will just keep piling up in memory, * so it is best to start the adapter *before* setting it as the active log handler. * Note that the object must not be destroyed while the I/O thread is running. * @see stop() * @pre The I/O thread is not already running. * @note This function is thread-safe. */ GHULBUS_BASE_API void start(); /** Stop the I/O thread. * Processes all outstanding log messages still in the queue and then joins the I/O thread. * %Log messages arriving after stop() has started executing will remain unprocessed. So you will probably want * to remove the adapter from active log handler before calling stop(). * @see start() * @pre The I/O thread is currently running. * @note This function is thread-safe. */ GHULBUS_BASE_API void stop(); /** Convert to a LogHandler function to pass to Ghulbus::Log::setLogHandler(). * @note Note that the handler needs to be \ref start() "started" for any log messages to be processed. * @attention Note that an object must not be destroyed while it is set as log handler. */ GHULBUS_BASE_API operator LogHandler(); }; /** Forwards each log message to two downstream handlers. * Use this if you want to log to two different sinks, for instance to a log file and the console. * @note This handler will duplicate the log message before passing it on to the downstream handlers, * which is potentially expensive. When combining the LogMultiSink with the LogAsync it is * therefore desirable to have the LogMultiSink as the downstream and the LogAsync as the * top-level handler. */ class LogMultiSink { private: LogHandler m_downstreamHandlers[2]; public: /** Adapting Constructor. * @param[in] first_downstream_handler The first log handler that is to be wrapped. * @param[in] first_downstream_handler The second log handler that is to be wrapped. */ GHULBUS_BASE_API LogMultiSink(LogHandler first_downstream_handler, LogHandler second_downstream_handler); /** Convert to a LogHandler function to pass to Ghulbus::Log::setLogHandler(). * @attention Note that an object must not be destroyed while it is set as log handler. */ GHULBUS_BASE_API operator LogHandler(); }; /** @} */ } } } #endif <commit_msg>clarified documentation<commit_after>#ifndef GHULBUS_LIBRARY_INCLUDE_GUARD_BASE_LOG_HANDLERS_HPP #define GHULBUS_LIBRARY_INCLUDE_GUARD_BASE_LOG_HANDLERS_HPP /** @file * * @brief Log Handlers. * @author Andreas Weis (der_ghulbus@ghulbus-inc.de) */ #include <gbBase/config.hpp> #include <gbBase/Log.hpp> #include <condition_variable> #include <deque> #include <fstream> #include <mutex> #include <thread> #include <tuple> namespace GHULBUS_BASE_NAMESPACE { namespace Log { /** Handlers for use with Ghulbus::Log::setLogHandler(). */ namespace Handlers { /** Simple, unsynchronized logging to `std::cout` and `std::cerr`. * Log messages of Ghulbus::LogLevel::Error or higher go to `std::cerr`, all others to `std::cout`. * Logging is not synchronized, so logging concurrently from multiple threads is not safe with this handler. * Use one of the \ref log_handler_adapters "thread-safe adapters" LogSynchronizeMutex or LogAsync if you need to * log from more than one thread. * @note Logging to the console is usually quite slow and can slow down an application significantly if many log * messages are produces. Use the LogAsync adapter if performance is an issue. */ GHULBUS_BASE_API void logToCout(LogLevel log_level, std::stringstream&& log_stream); #ifdef WIN32 /** Logs to an attached debugger via the OutputDebugString() Win32 API function. */ GHULBUS_BASE_API void logToWindowsDebugger(LogLevel log_level, std::stringstream&& log_stream); #endif /** Unsynchronized file logging. * All log messages will be appended to the given log file. %Log messages may be buffered in memory but will be * flushed upon destruction of the handler object. * Logging is not synchronized, so logging concurrently from multiple threads is not safe with this handler. * Use one of the \ref log_handler_adapters "thread-safe adapters" LogSynchronizeMutex or LogAsync if you need to * log from more than one thread. * @note This handler uses `std::fstream` for file I/O which might perform less than ideal on certain * (*cough* Windows) implementations. * Use the LogAsync adapter if performance is an issue. */ class LogToFile { private: std::ofstream m_logFile; public: /** Construct a logger for logging to a file. * @param[in] filename Path to the log file. This file will be opened in append mode. * @throw Exceptions::IOError If file could not be opened for writing. */ GHULBUS_BASE_API LogToFile(char const* filename); /** Convert to a LogHandler function to pass to Ghulbus::Log::setLogHandler(). * @attention Note that an object must not be destroyed while it is set as log handler. */ GHULBUS_BASE_API operator LogHandler(); }; /** @defgroup log_handler_adapters Handler adapters. * A handler adapter is not a full handler by itself, but rather wraps around a downstream handler to add * additional functionality (like thread safety). * @{ */ /** Simple synchronization. * The mutex adapter synchronizes concurrent access to the downstream handler via a mutex. * The resulting handler is thread safe. */ class LogSynchronizeMutex { private: std::mutex m_mutex; LogHandler m_downstreamHandler; public: /** Adapting Constructor. * @param[in] downstream_handler The log handler that is to be wrapped. * The downstream handler need not be thread safe. * The downstream handler must not be empty. If the downstream handler dies before * this adapter, the behavior is undefined. */ GHULBUS_BASE_API LogSynchronizeMutex(LogHandler downstream_handler); /** Convert to a LogHandler function to pass to Ghulbus::Log::setLogHandler(). * @attention Note that an object must not be destroyed while it is set as log handler. */ GHULBUS_BASE_API operator LogHandler(); }; /** Asynchronous logging. * This adapter defers execution of the downstream handler in a separate thread. This allows the logging thread * to continue immediately after assembling the log message without having to wait for the log I/O to complete. * The impact on the runtime of the logging thread is far lower than with the other handlers. The downside is * that async logging requires spawning an additional I/O thread to execute the downstream handler. * Note that all access to the downstream handler is serialized through this I/O thread, so you can use a thread * unsafe handler as downstream handler. * * @note Messages will be queued in memory for processing. If an application produces log messages faster than the * adapted handler can process them, this can in theory consume all available memory on the machine. Be careful * not to overload the logging thread in this way. * * @note While the async handler works very well with small numbers of threads, it still requires concurrent access * to the single queue of log messages. If you need highly concurrent logging, consider using an adapter that * uses several thread-local queues instead. */ class LogAsync { private: typedef std::tuple<LogLevel, std::stringstream> QueueElement; private: std::mutex m_mutex; ///< mutex protexting access to the m_queue std::deque<QueueElement> m_queue; ///< queue of log messages bool m_stopRequested; ///< flag indicating that the user called stop() to stop the I/O thread std::condition_variable m_condvar; ///< signal that a message was pushed to the queue or stop was requested LogHandler m_downstreamHandler; std::thread m_ioThread; public: /** @copydoc LogSynchronizeMutex::LogSynchronizeMutex(LogHandler) */ GHULBUS_BASE_API LogAsync(LogHandler downstream_handler); /** Start the I/O thread. * Invoking the log handler obtained from this class will put the respective log message to an in-memory queue. * This function will spawn a thread that waits for messages to be put into that queue and forwards them to the * downstream handler. Note that while that thread is not running, messages will just keep piling up in memory, * so it is best to start the adapter *before* setting it as the active log handler. * Note that the object must not be destroyed while the I/O thread is running. * @see stop() * @pre The I/O thread is not already running. * @note This function is thread-safe. */ GHULBUS_BASE_API void start(); /** Stop the I/O thread. * Processes all outstanding log messages still in the queue and then joins the I/O thread. * %Log messages arriving after stop() has started executing will remain unprocessed. So you will probably want * to remove the adapter from active log handler before calling stop(). * @see start() * @pre The I/O thread is currently running. * @note This function is thread-safe. */ GHULBUS_BASE_API void stop(); /** Convert to a LogHandler function to pass to Ghulbus::Log::setLogHandler(). * @note Note that the handler needs to be \ref start() "started" for any log messages to be processed. * @attention Note that an object must not be destroyed while it is set as log handler. */ GHULBUS_BASE_API operator LogHandler(); }; /** Forwards each log message to two downstream handlers. * Use this if you want to log to two different sinks, for instance to a log file and the console. * @note This handler will duplicate the log message before passing it on to the downstream handlers, * which is potentially expensive. When combining the LogMultiSink with the LogAsync it is * therefore desirable to have the LogMultiSink as the downstream and the LogAsync as the * top-level handler. */ class LogMultiSink { private: LogHandler m_downstreamHandlers[2]; public: /** Adapting Constructor. * Neither of the downstream handlers shall be empty. * @param[in] first_downstream_handler The first log handler that is to be wrapped. * @param[in] second_downstream_handler The second log handler that is to be wrapped. */ GHULBUS_BASE_API LogMultiSink(LogHandler first_downstream_handler, LogHandler second_downstream_handler); /** Convert to a LogHandler function to pass to Ghulbus::Log::setLogHandler(). * @attention Note that an object must not be destroyed while it is set as log handler. */ GHULBUS_BASE_API operator LogHandler(); }; /** @} */ } } } #endif <|endoftext|>
<commit_before>// // Copyright (c) 2014 CNRS // Authors: Florent Lamiraux // // This file is part of hpp-core // hpp-core 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 // 3 of the License, or (at your option) any later version. // // hpp-core 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 Lesser Public License for more details. You should have // received a copy of the GNU Lesser General Public License along with // hpp-core If not, see // <http://www.gnu.org/licenses/>. #ifndef HPP_CORE_LOCKED_DOF_HH # define HPP_CORE_LOCKED_DOF_HH # include <roboptim/core/differentiable-function.hh> # include <hpp/core/constraint-set.hh> namespace hpp { namespace core { /// Constraint that locks a degree of freedom to a constant value. class HPP_CORE_DLLAPI LockedDof : public Constraint { public: /// Return shared pointer to new object static LockedDofPtr_t create (const std::string& name, size_type index, value_type value) { LockedDof* ptr = new LockedDof (name, index, value); LockedDofPtr_t shPtr (ptr); ptr->init (shPtr); return shPtr; } /// Get index of the locked degree of freedom in the configuration vector. std::size_t index () const { return index_; } /// Get the value of the configuration locked component. value_type value () const { return value_; } protected: LockedDof (const std::string& name, size_type index, value_type value) : Constraint (name), index_ (index), value_ (value) { } void init (const LockedDofPtr_t& self) { weak_ = self; } bool impl_compute (Configuration_t& configuration) { configuration [index_] = value_; return true; } private: virtual std::ostream& print (std::ostream& os) const { os << "Locked degree of freedom " << name () << ": index = " << index_ << ", value = " << value_ << std::endl; return os; } virtual void addToConstraintSet (const ConstraintSetPtr_t& constraintSet) { constraintSet->addLockedDof (weak_.lock ()); constraintSet->hasLockedDofs_ = true; Constraint::addToConstraintSet (constraintSet); } std::size_t index_; value_type value_; /// Weak pointer to itself LockedDofWkPtr weak_; }; // class LockedDof } // namespace core } // namespace hpp #endif // HPP_CORE_LOCKED_DOF_HH <commit_msg>Give access to reference of the value of a locked dof.<commit_after>// // Copyright (c) 2014 CNRS // Authors: Florent Lamiraux // // This file is part of hpp-core // hpp-core 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 // 3 of the License, or (at your option) any later version. // // hpp-core 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 Lesser Public License for more details. You should have // received a copy of the GNU Lesser General Public License along with // hpp-core If not, see // <http://www.gnu.org/licenses/>. #ifndef HPP_CORE_LOCKED_DOF_HH # define HPP_CORE_LOCKED_DOF_HH # include <roboptim/core/differentiable-function.hh> # include <hpp/core/constraint-set.hh> namespace hpp { namespace core { /// Constraint that locks a degree of freedom to a constant value. class HPP_CORE_DLLAPI LockedDof : public Constraint { public: /// Return shared pointer to new object static LockedDofPtr_t create (const std::string& name, size_type index, value_type value) { LockedDof* ptr = new LockedDof (name, index, value); LockedDofPtr_t shPtr (ptr); ptr->init (shPtr); return shPtr; } /// Get index of the locked degree of freedom in the configuration vector. std::size_t index () const { return index_; } /// Get the value of the configuration locked component. const value_type& value () const { return value_; } /// Get the value of the configuration locked component. value_type& value () { return value_; } protected: LockedDof (const std::string& name, size_type index, value_type value) : Constraint (name), index_ (index), value_ (value) { } void init (const LockedDofPtr_t& self) { weak_ = self; } bool impl_compute (Configuration_t& configuration) { configuration [index_] = value_; return true; } private: virtual std::ostream& print (std::ostream& os) const { os << "Locked degree of freedom " << name () << ": index = " << index_ << ", value = " << value_ << std::endl; return os; } virtual void addToConstraintSet (const ConstraintSetPtr_t& constraintSet) { constraintSet->addLockedDof (weak_.lock ()); constraintSet->hasLockedDofs_ = true; Constraint::addToConstraintSet (constraintSet); } std::size_t index_; value_type value_; /// Weak pointer to itself LockedDofWkPtr weak_; }; // class LockedDof } // namespace core } // namespace hpp #endif // HPP_CORE_LOCKED_DOF_HH <|endoftext|>
<commit_before>/******************************************************************************* * include/huffman/huff_merge.hpp * * Copyright (C) 2017 Marvin Löbel <loebel.marvin@gmail.com> * * All rights reserved. Published under the BSD-2 license in the LICENSE file. ******************************************************************************/ #pragma once #include <cassert> #include <climits> #include <omp.h> #include "huffman/huff_bit_vectors.hpp" #include "util/common.hpp" #include "util/macros.hpp" #include "construction/merge.hpp" template<typename ContextType, typename Rho> inline auto huff_merge_bit_vectors(std::vector<uint64_t> const& level_sizes, uint64_t const shards, const std::vector<ContextType>& src_ctxs, const Rho& rho) { assert(shards == src_ctxs.size()); assert(shards > 1); uint64_t const levels = level_sizes.size(); // Allocate data structures centrally struct MergeLevelCtx { std::vector<uint64_t> read_offsets; uint64_t initial_read_offset; uint64_t first_read_block; uint64_t write_end_offset; }; struct MergeCtx { std::vector<MergeLevelCtx> levels; }; auto ctxs = std::vector<MergeCtx> { shards, { std::vector<MergeLevelCtx> { levels, { std::vector<uint64_t>(shards), 0, 0, 0, } }, } }; /* Visualization of ctxs for levels = 2 and shards = 2: ┌──────────────┬───────────────────────┐ │ctxs: MergeCtx│ x shards │ │ ┌────────────┴────────┬──────────────┤ │ │levels: MergeLevelCtx│ x levels │ │ │ ┌───────────────────┴──────────────┤ │ │ │write_end_offset: uint64_t │ │ │ ├──────────────────────────────────┤ │ │ │initial_read_offset: uint64_t │ │ │ ├──────────────────────────────────┤ │ │ │first_read_block: uint64_t │ │ │ ├──────────────────────┬───────────┤ │ │ │read_offsets: uint64_t│ x shards │ │ │ │ ┌────────────────────┴───────────┤ │ │ │ │ │ │ │ │ ╞════════════════════════════════╡ │ │ │ │ │ │ │ ╞═╧════════════════════════════════╡ │ │ │initial_read_offset: uint64_t │ │ │ ├──────────────────────────────────┤ │ │ │first_read_block: uint64_t │ │ │ ├──────────────────────┬───────────┤ │ │ │read_offsets: uint64_t│ x shards │ │ │ │ ┌────────────────────┴───────────┤ │ │ │ │ │ │ │ │ ╞════════════════════════════════╡ │ │ │ │ │ │ ╞═╧═╧════════════════════════════════╡ │ │levels: MergeLevelCtx│ x levels │ │ │ ┌───────────────────┴──────────────┤ │ │ │write_end_offset: uint64_t │ │ │ ├──────────────────────────────────┤ │ │ │initial_read_offset: uint64_t │ │ │ ├──────────────────────────────────┤ │ │ │first_read_block: uint64_t │ │ │ ├──────────────────────┬───────────┤ │ │ │read_offsets: uint64_t│ x shards │ │ │ │ ┌────────────────────┴───────────┤ │ │ │ │ │ │ │ │ ╞════════════════════════════════╡ │ │ │ │ │ │ │ ╞═╧════════════════════════════════╡ │ │ │initial_read_offset: uint64_t │ │ │ ├──────────────────────────────────┤ │ │ │first_read_block: uint64_t │ │ │ ├──────────────────────┬───────────┤ │ │ │read_offsets: uint64_t│ x shards │ │ │ │ ┌────────────────────┴───────────┤ │ │ │ │ │ │ │ │ ╞════════════════════════════════╡ │ │ │ │ │ └─┴─┴─┴────────────────────────────────┘ */ // Calculate end bit offset per merge shard (thread). // It is an multiple of 64, to ensure no interference // in writing bits to the left or right of it in parallel for(size_t level = 0; level < levels; level++) { const size_t size = level_sizes[level]; for (size_t shard = 1; shard < shards; shard++) { const uint64_t offset = (shard * (word_size(size) / shards)) + std::min<uint64_t>(shard, word_size(size) % shards); ctxs[shard - 1].levels[level].write_end_offset = std::min<uint64_t>(offset * 64ull, size); } ctxs[shards - 1].levels[level].write_end_offset = std::min<uint64_t>(word_size(size) * 64ull, size); } for(size_t level = 0; level < levels; level++) { // number of tree nodes on the current level const size_t blocks = 1ull << level; size_t write_offset = 0; // bit offset in destination bv size_t merge_shard = 0; // index of merge thread // iterate over all blocks of all shards on the current level // // this gradually assigns the bits of the // blocks to each of the aviable merge shards of the current level: // // | read_shard | read_shard | // +---------------+---------------+ // | block | block | // | block | block | block | block | <- current level // +----------+----------+---------+ // | m. shard | m. shard |m. shard | // for(size_t i = 0; i < blocks * shards; i++) { // std::cout << "[offsets] i: " << i << "\n"; // returns merge level context of merge_shard auto lctx = [&level, &ctxs](auto merge_shard) -> MergeLevelCtx& { return ctxs[merge_shard].levels[level]; }; // returns merge level context of merge_shard+1 auto nxt_lctx = [&level, &ctxs](auto merge_shard) -> MergeLevelCtx& { return ctxs[merge_shard + 1].levels[level]; }; // which block (node on current level of tree) const auto block = i / shards; // which shard to read from const auto read_shard = i % shards; // map logical block index to // actual block index (rho depends on WT vs WM) const auto permuted_block = rho(level, block); // block size == number of entries in the block on this level auto block_size = src_ctxs[read_shard].hist(level, permuted_block); // advance global write offset by the number of bits assigned for // this block write_offset += block_size; // advance local read offset of next merge shard // for the curent read shard // // this way, all merge shard start reading // at different offsets from the read shards nxt_lctx(merge_shard).read_offsets[read_shard] += block_size; // If we passed the current right border, split up the block if (write_offset > lctx(merge_shard).write_end_offset) { // Take back the last step write_offset -= block_size; nxt_lctx(merge_shard).read_offsets[read_shard] -= block_size; uint64_t initial_read_offset = 0; do { // Split up the block like this: // [ left_block_size | right_block_size ] // ^ ^ ^ // (write_offset) | | // (ctxs[merge_shard].write_end_offset) | // (write_offset + block_size) // // this loop iterates multiple times, to ensure right_block_size // did not also overlap the next write_end_offset auto const left_block_size = lctx(merge_shard).write_end_offset - write_offset; // advance global and local read offsets to end exactly at // write_end_offset write_offset += left_block_size; nxt_lctx(merge_shard).read_offsets[read_shard] += left_block_size; initial_read_offset += left_block_size; // from which offset in which block to start reading nxt_lctx(merge_shard).initial_read_offset = initial_read_offset; nxt_lctx(merge_shard).first_read_block = i; // if there is a merge_shard to the right // of the next merge shard, intialize // its local read offsets with those of the next shard if (merge_shard + 2 < shards) { for(size_t s = 0; s < shards; s++) { nxt_lctx(merge_shard + 1).read_offsets[s] = nxt_lctx(merge_shard).read_offsets[s]; } } merge_shard++; // Once we have calculated the offsets for all merge threads, // break out of the whole nested loop if (merge_shard + 1 == shards) { goto triple_loop_exit; } // Iterate on remaining block, because one block might // span multiple threads block_size -= left_block_size; } while ((write_offset + block_size) > lctx(merge_shard).write_end_offset); // Process remainder of block write_offset += block_size; nxt_lctx(merge_shard).read_offsets[read_shard] += block_size; assert(write_offset <= lctx(merge_shard).write_end_offset); } } triple_loop_exit:; // we are done } // TODO: remove redundant argument auto r = huff_bit_vectors(levels, level_sizes); auto& _bv = r; // TODO: Bugs //#pragma omp parallel for(size_t merge_shard = 0; merge_shard < shards; merge_shard++) { auto& ctx = ctxs[merge_shard]; for (size_t level = 0; level < levels; level++) { const auto target_right = std::min( ctx.levels[level].write_end_offset, level_sizes[level]); const auto target_left = std::min( (merge_shard > 0 ? ctxs[merge_shard - 1].levels[level].write_end_offset : 0), target_right); // std::cout << "\n"; // std::cout << "[merge] target_{left,right}: " << target_left; // std::cout << ", " << target_right << "\n"; auto i = ctx.levels[level].first_read_block; uint64_t write_offset = target_left; auto copy_next_block = [&](size_t const initial_read_offset) { // std::cout << "\n"; // std::cout << "[merge] i: " << i << "\n"; // std::cout << "[merge] write_offset: " << write_offset << "\n"; // std::cout << "[merge] initial_read_offset: " << initial_read_offset << "\n"; const auto block = i / shards; const auto read_shard = i % shards; i++; // std::cout << "[merge] block: " << block << "\n"; // std::cout << "[merge] read_shard: " << read_shard << "\n"; const auto& local_bv = src_ctxs[read_shard].bv()[level]; const auto& h = src_ctxs[read_shard]; auto const permuted_block = rho(level, block); uint64_t block_size = h.hist(level, permuted_block) - initial_read_offset; uint64_t distance_to_end = target_right - write_offset; // std::cout << "[merge] block_size: " << block_size << "\n"; // std::cout << "[merge] distance_to_end: " << distance_to_end << "\n"; uint64_t copy_size; if (PWM_LIKELY(block_size <= distance_to_end)) { copy_size = block_size; } else { copy_size = distance_to_end; } auto& local_cursor = ctx.levels[level].read_offsets[read_shard]; // std::cout << "[merge] copy_bits(" // << "write_offset=" << write_offset << ", " // << "local_cursor=" << local_cursor << ", " // << "copy_size=" << copy_size << ")" // << "\n"; copy_bits<uint64_t>( _bv[level].data(), local_bv.data(), write_offset, local_cursor, copy_size ); }; if (write_offset < target_right) { // the first block might start somewhere in the middle copy_next_block(ctx.levels[level].initial_read_offset); } while (write_offset < target_right) { // other blocks start at 0 copy_next_block(0); } assert(write_offset == target_right); } } return r; } /******************************************************************************/ <commit_msg>FIx parallelism in huff_merge<commit_after>/******************************************************************************* * include/huffman/huff_merge.hpp * * Copyright (C) 2017 Marvin Löbel <loebel.marvin@gmail.com> * * All rights reserved. Published under the BSD-2 license in the LICENSE file. ******************************************************************************/ #pragma once #include <cassert> #include <climits> #include <omp.h> #include "huffman/huff_bit_vectors.hpp" #include "util/common.hpp" #include "util/macros.hpp" #include "construction/merge.hpp" template<typename ContextType, typename Rho> inline auto huff_merge_bit_vectors(std::vector<uint64_t> const& level_sizes, uint64_t const shards, const std::vector<ContextType>& src_ctxs, const Rho& rho) { assert(shards == src_ctxs.size()); assert(shards > 1); uint64_t const levels = level_sizes.size(); // Allocate data structures centrally struct MergeLevelCtx { std::vector<uint64_t> read_offsets; uint64_t initial_read_offset; uint64_t first_read_block; uint64_t write_end_offset; }; struct MergeCtx { std::vector<MergeLevelCtx> levels; }; auto ctxs = std::vector<MergeCtx> { shards, { std::vector<MergeLevelCtx> { levels, { std::vector<uint64_t>(shards), 0, 0, 0, } }, } }; /* Visualization of ctxs for levels = 2 and shards = 2: ┌──────────────┬───────────────────────┐ │ctxs: MergeCtx│ x shards │ │ ┌────────────┴────────┬──────────────┤ │ │levels: MergeLevelCtx│ x levels │ │ │ ┌───────────────────┴──────────────┤ │ │ │write_end_offset: uint64_t │ │ │ ├──────────────────────────────────┤ │ │ │initial_read_offset: uint64_t │ │ │ ├──────────────────────────────────┤ │ │ │first_read_block: uint64_t │ │ │ ├──────────────────────┬───────────┤ │ │ │read_offsets: uint64_t│ x shards │ │ │ │ ┌────────────────────┴───────────┤ │ │ │ │ │ │ │ │ ╞════════════════════════════════╡ │ │ │ │ │ │ │ ╞═╧════════════════════════════════╡ │ │ │initial_read_offset: uint64_t │ │ │ ├──────────────────────────────────┤ │ │ │first_read_block: uint64_t │ │ │ ├──────────────────────┬───────────┤ │ │ │read_offsets: uint64_t│ x shards │ │ │ │ ┌────────────────────┴───────────┤ │ │ │ │ │ │ │ │ ╞════════════════════════════════╡ │ │ │ │ │ │ ╞═╧═╧════════════════════════════════╡ │ │levels: MergeLevelCtx│ x levels │ │ │ ┌───────────────────┴──────────────┤ │ │ │write_end_offset: uint64_t │ │ │ ├──────────────────────────────────┤ │ │ │initial_read_offset: uint64_t │ │ │ ├──────────────────────────────────┤ │ │ │first_read_block: uint64_t │ │ │ ├──────────────────────┬───────────┤ │ │ │read_offsets: uint64_t│ x shards │ │ │ │ ┌────────────────────┴───────────┤ │ │ │ │ │ │ │ │ ╞════════════════════════════════╡ │ │ │ │ │ │ │ ╞═╧════════════════════════════════╡ │ │ │initial_read_offset: uint64_t │ │ │ ├──────────────────────────────────┤ │ │ │first_read_block: uint64_t │ │ │ ├──────────────────────┬───────────┤ │ │ │read_offsets: uint64_t│ x shards │ │ │ │ ┌────────────────────┴───────────┤ │ │ │ │ │ │ │ │ ╞════════════════════════════════╡ │ │ │ │ │ └─┴─┴─┴────────────────────────────────┘ */ // Calculate end bit offset per merge shard (thread). // It is an multiple of 64, to ensure no interference // in writing bits to the left or right of it in parallel for(size_t level = 0; level < levels; level++) { const size_t size = level_sizes[level]; for (size_t shard = 1; shard < shards; shard++) { const uint64_t offset = (shard * (word_size(size) / shards)) + std::min<uint64_t>(shard, word_size(size) % shards); ctxs[shard - 1].levels[level].write_end_offset = std::min<uint64_t>(offset * 64ull, size); } ctxs[shards - 1].levels[level].write_end_offset = std::min<uint64_t>(word_size(size) * 64ull, size); } for(size_t level = 0; level < levels; level++) { // number of tree nodes on the current level const size_t blocks = 1ull << level; size_t write_offset = 0; // bit offset in destination bv size_t merge_shard = 0; // index of merge thread // iterate over all blocks of all shards on the current level // // this gradually assigns the bits of the // blocks to each of the aviable merge shards of the current level: // // | read_shard | read_shard | // +---------------+---------------+ // | block | block | // | block | block | block | block | <- current level // +----------+----------+---------+ // | m. shard | m. shard |m. shard | // for(size_t i = 0; i < blocks * shards; i++) { // std::cout << "[offsets] i: " << i << "\n"; // returns merge level context of merge_shard auto lctx = [&level, &ctxs](auto merge_shard) -> MergeLevelCtx& { return ctxs[merge_shard].levels[level]; }; // returns merge level context of merge_shard+1 auto nxt_lctx = [&level, &ctxs](auto merge_shard) -> MergeLevelCtx& { return ctxs[merge_shard + 1].levels[level]; }; // which block (node on current level of tree) const auto block = i / shards; // which shard to read from const auto read_shard = i % shards; // map logical block index to // actual block index (rho depends on WT vs WM) const auto permuted_block = rho(level, block); // block size == number of entries in the block on this level auto block_size = src_ctxs[read_shard].hist(level, permuted_block); // advance global write offset by the number of bits assigned for // this block write_offset += block_size; // advance local read offset of next merge shard // for the curent read shard // // this way, all merge shard start reading // at different offsets from the read shards nxt_lctx(merge_shard).read_offsets[read_shard] += block_size; // If we passed the current right border, split up the block if (write_offset > lctx(merge_shard).write_end_offset) { // Take back the last step write_offset -= block_size; nxt_lctx(merge_shard).read_offsets[read_shard] -= block_size; uint64_t initial_read_offset = 0; do { // Split up the block like this: // [ left_block_size | right_block_size ] // ^ ^ ^ // (write_offset) | | // (ctxs[merge_shard].write_end_offset) | // (write_offset + block_size) // // this loop iterates multiple times, to ensure right_block_size // did not also overlap the next write_end_offset auto const left_block_size = lctx(merge_shard).write_end_offset - write_offset; // advance global and local read offsets to end exactly at // write_end_offset write_offset += left_block_size; nxt_lctx(merge_shard).read_offsets[read_shard] += left_block_size; initial_read_offset += left_block_size; // from which offset in which block to start reading nxt_lctx(merge_shard).initial_read_offset = initial_read_offset; nxt_lctx(merge_shard).first_read_block = i; // if there is a merge_shard to the right // of the next merge shard, intialize // its local read offsets with those of the next shard if (merge_shard + 2 < shards) { for(size_t s = 0; s < shards; s++) { nxt_lctx(merge_shard + 1).read_offsets[s] = nxt_lctx(merge_shard).read_offsets[s]; } } merge_shard++; // Once we have calculated the offsets for all merge threads, // break out of the whole nested loop if (merge_shard + 1 == shards) { goto triple_loop_exit; } // Iterate on remaining block, because one block might // span multiple threads block_size -= left_block_size; } while ((write_offset + block_size) > lctx(merge_shard).write_end_offset); // Process remainder of block write_offset += block_size; nxt_lctx(merge_shard).read_offsets[read_shard] += block_size; assert(write_offset <= lctx(merge_shard).write_end_offset); } } triple_loop_exit:; // we are done } // TODO: remove redundant argument auto r = huff_bit_vectors(levels, level_sizes); auto& _bv = r; #pragma omp parallel for for(size_t merge_shard = 0; merge_shard < shards; merge_shard++) { for (size_t level = 0; level < levels; level++) { auto& lctx = ctxs[merge_shard].levels[level]; const auto target_right = std::min( lctx.write_end_offset, level_sizes[level]); const auto target_left = std::min( (merge_shard > 0 ? ctxs[merge_shard - 1].levels[level].write_end_offset : 0), target_right); uint64_t i = lctx.first_read_block; uint64_t write_offset = target_left; auto copy_next_block = [&](size_t const initial_read_offset) { const auto block = i / shards; const auto read_shard = i % shards; i++; const auto& local_bv = src_ctxs[read_shard].bv()[level]; const auto& h = src_ctxs[read_shard]; auto const permuted_block = rho(level, block); uint64_t block_size = h.hist(level, permuted_block) - initial_read_offset; uint64_t distance_to_end = target_right - write_offset; uint64_t copy_size; if (PWM_LIKELY(block_size <= distance_to_end)) { copy_size = block_size; } else { copy_size = distance_to_end; } auto& local_cursor = lctx.read_offsets[read_shard]; copy_bits<uint64_t>( _bv[level].data(), local_bv.data(), write_offset, local_cursor, copy_size ); }; if (write_offset < target_right) { // the first block might start somewhere in the middle copy_next_block(lctx.initial_read_offset); } while (write_offset < target_right) { // other blocks start at 0 copy_next_block(0); } assert(write_offset == target_right); } } return r; } /******************************************************************************/ <|endoftext|>
<commit_before>//======================================================================= // Copyright (c) 2014 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #ifndef MNIST_READER_HPP #define MNIST_READER_HPP #include <fstream> #include <iostream> #include <vector> #include <cstdint> #include <memory> namespace mnist { template<template<typename...> class Container = std::vector, template<typename...> class Sub = std::vector, typename Pixel = uint8_t, typename Label = uint8_t> struct MNIST_dataset { Container<Sub<Pixel>> training_images; Container<Sub<Pixel>> test_images; Container<Label> training_labels; Container<Label> test_labels; void resize_training(std::size_t new_size){ if(training_images.size() > new_size){ training_images.resize(new_size); training_labels.resize(new_size); } } void resize_test(std::size_t new_size){ if(test_images.size() > new_size){ test_images.resize(new_size); test_labels.resize(new_size); } } }; inline uint32_t read_header(const std::unique_ptr<char[]>& buffer, size_t position){ auto header = reinterpret_cast<uint32_t*>(buffer.get()); auto value = *(header + position); return (value << 24) | ((value << 8) & 0x00FF0000) | ((value >> 8) & 0X0000FF00) | (value >> 24); } template<template<typename...> class Container = std::vector, template<typename...> class Sub = std::vector, typename Pixel = uint8_t> Container<Sub<Pixel>> read_mnist_image_file(const std::string& path, std::size_t limit = 0){ std::ifstream file; file.open(path, std::ios::in | std::ios::binary | std::ios::ate); if(!file){ std::cout << "Error opening file" << std::endl; } else { auto size = file.tellg(); std::unique_ptr<char[]> buffer(new char[size]); //Read the entire file at once file.seekg(0, std::ios::beg); file.read(buffer.get(), size); file.close(); auto magic = read_header(buffer, 0); if(magic != 0x803){ std::cout << "Invalid magic number, probably not a MNIST file" << std::endl; } else { auto count = read_header(buffer, 1); auto rows = read_header(buffer, 2); auto columns = read_header(buffer, 3); if(size < count * rows * columns + 16){ std::cout << "The file is not large enough to hold all the data, probably corrupted" << std::endl; } else { //Skip the header //Cast to unsigned char is necessary cause signedness of char is //platform-specific auto image_buffer = reinterpret_cast<unsigned char*>(buffer.get() + 16); if(limit > 0 && count > limit){ count = limit; } Container<Sub<Pixel>> images; images.reserve(count); for(size_t i = 0; i < count; ++i){ images.emplace_back(rows * columns); for(size_t j = 0; j < rows * columns; ++j){ auto pixel = *image_buffer++; images[i][j] = static_cast<Pixel>(pixel); } } return images; } } } return {}; } template<template<typename...> class Container = std::vector, typename Label = uint8_t> Container<Label> read_mnist_label_file(const std::string& path, std::size_t limit = 0){ std::ifstream file; file.open(path, std::ios::in | std::ios::binary | std::ios::ate); if(!file){ std::cout << "Error opening file" << std::endl; } else { auto size = file.tellg(); std::unique_ptr<char[]> buffer(new char[size]); //Read the entire file at once file.seekg(0, std::ios::beg); file.read(buffer.get(), size); file.close(); auto magic = read_header(buffer, 0); if(magic != 0x801){ std::cout << "Invalid magic number, probably not a MNIST file" << std::endl; } else { auto count = read_header(buffer, 1); if(size < count + 8){ std::cout << "The file is not large enough to hold all the data, probably corrupted" << std::endl; } else { //Skip the header //Cast to unsigned char is necessary cause signedness of char is //platform-specific auto label_buffer = reinterpret_cast<unsigned char*>(buffer.get() + 8); if(limit > 0 && count > limit){ count = limit; } Container<Label> labels(count); for(size_t i = 0; i < count; ++i){ auto label = *label_buffer++; labels[i] = static_cast<Label>(label); } return labels; } } } return {}; } template<template<typename...> class Container = std::vector, template<typename...> class Sub = std::vector, typename Pixel = uint8_t> Container<Sub<Pixel>> read_training_images(std::size_t limit = 0){ return read_mnist_image_file<Container,Sub,Pixel>("mnist/train-images-idx3-ubyte", limit); } template<template<typename...> class Container = std::vector, template<typename...> class Sub = std::vector, typename Pixel = uint8_t> Container<Sub<Pixel>> read_test_images(std::size_t limit = 0){ return read_mnist_image_file<Container,Sub,Pixel>("mnist/t10k-images-idx3-ubyte", limit); } template<template<typename...> class Container = std::vector, typename Label = uint8_t> Container<Label> read_training_labels(std::size_t limit = 0){ return read_mnist_label_file<Container, Label>("mnist/train-labels-idx1-ubyte", limit); } template<template<typename...> class Container = std::vector, typename Label = uint8_t> Container<Label> read_test_labels(std::size_t limit = 0){ return read_mnist_label_file<Container, Label>("mnist/t10k-labels-idx1-ubyte", limit); } template<template<typename...> class Container = std::vector, template<typename...> class Sub = std::vector, typename Pixel = uint8_t, typename Label = uint8_t> MNIST_dataset<Container, Sub, Pixel, Label> read_dataset(std::size_t training_limit = 0, std::size_t test_limit = 0){ MNIST_dataset<Container, Sub, Pixel, Label> dataset; dataset.training_images = read_training_images<Container, Sub, Pixel>(training_limit); dataset.training_labels = read_training_labels<Container, Label>(training_limit); dataset.test_images = read_test_images<Container, Sub, Pixel>(test_limit); dataset.test_labels = read_test_labels<Container, Label>(test_limit); return dataset; } } //end of namespace mnist #endif <commit_msg>Make the types more flexible<commit_after>//======================================================================= // Copyright (c) 2014 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #ifndef MNIST_READER_HPP #define MNIST_READER_HPP #include <fstream> #include <iostream> #include <vector> #include <cstdint> #include <memory> namespace mnist { template<template<typename...> class Container, typename Image, typename Label> struct MNIST_dataset { Container<Image> training_images; Container<Image> test_images; Container<Label> training_labels; Container<Label> test_labels; void resize_training(std::size_t new_size){ if(training_images.size() > new_size){ training_images.resize(new_size); training_labels.resize(new_size); } } void resize_test(std::size_t new_size){ if(test_images.size() > new_size){ test_images.resize(new_size); test_labels.resize(new_size); } } }; inline uint32_t read_header(const std::unique_ptr<char[]>& buffer, size_t position){ auto header = reinterpret_cast<uint32_t*>(buffer.get()); auto value = *(header + position); return (value << 24) | ((value << 8) & 0x00FF0000) | ((value >> 8) & 0X0000FF00) | (value >> 24); } template<template<typename...> class Container = std::vector, typename Image> Container<Image> read_mnist_image_file(const std::string& path, std::size_t limit = 0){ std::ifstream file; file.open(path, std::ios::in | std::ios::binary | std::ios::ate); if(!file){ std::cout << "Error opening file" << std::endl; } else { auto size = file.tellg(); std::unique_ptr<char[]> buffer(new char[size]); //Read the entire file at once file.seekg(0, std::ios::beg); file.read(buffer.get(), size); file.close(); auto magic = read_header(buffer, 0); if(magic != 0x803){ std::cout << "Invalid magic number, probably not a MNIST file" << std::endl; } else { auto count = read_header(buffer, 1); auto rows = read_header(buffer, 2); auto columns = read_header(buffer, 3); if(size < count * rows * columns + 16){ std::cout << "The file is not large enough to hold all the data, probably corrupted" << std::endl; } else { //Skip the header //Cast to unsigned char is necessary cause signedness of char is //platform-specific auto image_buffer = reinterpret_cast<unsigned char*>(buffer.get() + 16); if(limit > 0 && count > limit){ count = limit; } Container<Image> images; images.reserve(count); for(size_t i = 0; i < count; ++i){ images.emplace_back(rows * columns); for(size_t j = 0; j < rows * columns; ++j){ auto pixel = *image_buffer++; images[i][j] = static_cast<typename Image::value_type>(pixel); } } return std::move(images); } } } return {}; } template<template<typename...> class Container = std::vector, typename Label = uint8_t> Container<Label> read_mnist_label_file(const std::string& path, std::size_t limit = 0){ std::ifstream file; file.open(path, std::ios::in | std::ios::binary | std::ios::ate); if(!file){ std::cout << "Error opening file" << std::endl; } else { auto size = file.tellg(); std::unique_ptr<char[]> buffer(new char[size]); //Read the entire file at once file.seekg(0, std::ios::beg); file.read(buffer.get(), size); file.close(); auto magic = read_header(buffer, 0); if(magic != 0x801){ std::cout << "Invalid magic number, probably not a MNIST file" << std::endl; } else { auto count = read_header(buffer, 1); if(size < count + 8){ std::cout << "The file is not large enough to hold all the data, probably corrupted" << std::endl; } else { //Skip the header //Cast to unsigned char is necessary cause signedness of char is //platform-specific auto label_buffer = reinterpret_cast<unsigned char*>(buffer.get() + 8); if(limit > 0 && count > limit){ count = limit; } Container<Label> labels(count); for(size_t i = 0; i < count; ++i){ auto label = *label_buffer++; labels[i] = static_cast<Label>(label); } return std::move(labels); } } } return {}; } template<template<typename...> class Container = std::vector, typename Image> Container<Image> read_training_images(std::size_t limit = 0){ return read_mnist_image_file<Container, Image>("mnist/train-images-idx3-ubyte", limit); } template<template<typename...> class Container = std::vector, typename Image> Container<Image> read_test_images(std::size_t limit = 0){ return read_mnist_image_file<Container, Image>("mnist/t10k-images-idx3-ubyte", limit); } template<template<typename...> class Container = std::vector, typename Label = uint8_t> Container<Label> read_training_labels(std::size_t limit = 0){ return read_mnist_label_file<Container, Label>("mnist/train-labels-idx1-ubyte", limit); } template<template<typename...> class Container = std::vector, typename Label = uint8_t> Container<Label> read_test_labels(std::size_t limit = 0){ return read_mnist_label_file<Container, Label>("mnist/t10k-labels-idx1-ubyte", limit); } template<template<typename...> class Container, typename Image, typename Label = uint8_t> MNIST_dataset<Container, Image, Label> read_dataset_direct(std::size_t training_limit = 0, std::size_t test_limit = 0){ MNIST_dataset<Container, Image, Label> dataset; dataset.training_images = read_training_images<Container, Image>(training_limit); dataset.training_labels = read_training_labels<Container, Label>(training_limit); dataset.test_images = read_test_images<Container, Image>(test_limit); dataset.test_labels = read_test_labels<Container, Label>(test_limit); return dataset; } template<template<typename...> class Container = std::vector, template<typename...> class Sub = std::vector, typename Pixel = uint8_t, typename Label = uint8_t> MNIST_dataset<Container, Sub<Pixel>, Label> read_dataset(std::size_t training_limit = 0, std::size_t test_limit = 0){ return read_dataset_direct<Container, Sub<Pixel>>(training_limit, test_limit); } } //end of namespace mnist #endif <|endoftext|>
<commit_before>#pragma once #include <utility> #include <stdexcept> #include <vector> #include <array_view.hpp> #include "reflection_info.hpp" #include "api_types.hpp" #include "info_iterators.hpp" namespace shadow { namespace reflection_initialization_detail { // used to handle cases where reflection_manager is initialized with nullptrs // (ie empty) instead of arrays template <class T> struct array_selector { static helene::array_view<std::remove_pointer_t<std::remove_const_t<T>>> initialize(T) { return helene::array_view< std::remove_pointer_t<std::remove_const_t<T>>>(); } }; template <class I, std::size_t N> struct array_selector<I[N]> { static helene::array_view<I> initialize(I (&arr)[N]) { return helene::make_array_view(arr); } }; } // namespace reflection_initialization_detail // point of interaction with the reflection system class reflection_manager { public: typedef info_iterator_<const type_info, type_tag> const_type_iterator; typedef indexed_info_iterator_<const type_info, type_tag> const_indexed_type_iterator; typedef info_iterator_<const constructor_info, constructor_tag> const_constructor_iterator; typedef info_iterator_<const conversion_info, conversion_tag> const_conversion_iterator; typedef info_iterator_<const free_function_info, free_function_tag> const_free_function_iterator; public: template <class TypeInfoArray, class ConstructorInfoArray, class ConversionInfoArray, class FreeFunctionArray, class MemberFunctionArray, class MemberVariableArray, class StringSerializationArray> reflection_manager(TypeInfoArray& ti_arr, ConstructorInfoArray& ci_arr, ConversionInfoArray& cv_arr, FreeFunctionArray& ff_arr, MemberFunctionArray& mf_arr, MemberVariableArray& mv_arr, StringSerializationArray& ss_arr); // queries on types std::pair<const_type_iterator, const_type_iterator> types() const; std::string type_name(const type_tag& tag) const; std::size_t type_size(const type_tag& tag) const; // returns range of all constructors available std::pair<const_constructor_iterator, const_constructor_iterator> constructors() const; // returns the type that the given constructor belongs to type_tag constructor_type(const constructor_tag& tag) const; // returns range of the types of the parameters of the given constructor std::pair<const_indexed_type_iterator, const_indexed_type_iterator> constructor_parameter_types(const constructor_tag& tag) const; template <class Iterator> object construct_object(const constructor_tag& tag, Iterator first, Iterator last) const; // type conversion functions std::pair<const_conversion_iterator, const_conversion_iterator> conversions() const; std::pair<type_tag, type_tag> conversion_types(const conversion_tag& tag) const; object convert(const conversion_tag& tag, const object& val) const; // returns range of tags to all free functions available std::pair<const_free_function_iterator, const_free_function_iterator> free_functions() const; // returns name of function associated with the free_function_tag std::string free_function_name(const free_function_tag& tag) const; // returns return type of function associated with the free_function_tag type_tag free_function_return_type(const free_function_tag& tag) const; // return range of type tags of parameters of free function associated with // the tag std::pair<const_indexed_type_iterator, const_indexed_type_iterator> free_function_parameter_types(const free_function_tag& tag) const; template <class Iterator> object call_free_function(const free_function_tag& tag, Iterator first, Iterator last) const; public: // unchecked operations template <class T> T& get(object& obj) const; template <class T> const T& get(const object& obj) const; private: template <class Iterator, class InfoType> bool check_arguments(Iterator first, Iterator last, const InfoType& info) const; bool compare_type(const type_tag& tag, std::size_t index) const; template <class Iterator, class OutputIterator, class InfoType> void construct_argument_array(Iterator first, Iterator last, OutputIterator out, const InfoType& info) const; private: // array_views of reflection information generated at compile time helene::array_view<const type_info> type_info_view_; helene::array_view<const constructor_info> constructor_info_view_; helene::array_view<const conversion_info> conversion_info_view_; helene::array_view<const free_function_info> free_function_info_view_; helene::array_view<const member_function_info> member_function_info_view_; helene::array_view<const member_variable_info> member_variable_info_view_; helene::array_view<const string_serialization_info> string_serialization_info_view_; }; } // namespace shadow namespace shadow { template <class TypeInfoArray, class ConstructorInfoArray, class ConversionInfoArray, class FreeFunctionArray, class MemberFunctionArray, class MemberVariableArray, class StringSerializationArray> inline reflection_manager::reflection_manager(TypeInfoArray& ti_arr, ConstructorInfoArray& ci_arr, ConversionInfoArray& cv_arr, FreeFunctionArray& ff_arr, MemberFunctionArray& mf_arr, MemberVariableArray& mv_arr, StringSerializationArray& ss_arr) : type_info_view_(reflection_initialization_detail::array_selector< TypeInfoArray>::initialize(ti_arr)), constructor_info_view_(reflection_initialization_detail::array_selector< ConstructorInfoArray>::initialize(ci_arr)), conversion_info_view_(reflection_initialization_detail::array_selector< ConversionInfoArray>::initialize(cv_arr)), free_function_info_view_(reflection_initialization_detail::array_selector< FreeFunctionArray>::initialize(ff_arr)), member_function_info_view_( reflection_initialization_detail::array_selector< MemberFunctionArray>::initialize(mf_arr)), member_variable_info_view_( reflection_initialization_detail::array_selector< MemberVariableArray>::initialize(mv_arr)), string_serialization_info_view_( reflection_initialization_detail::array_selector< StringSerializationArray>::initialize(ss_arr)) { } inline std::pair<typename reflection_manager::const_type_iterator, typename reflection_manager::const_type_iterator> reflection_manager::types() const { return std::make_pair(const_type_iterator(type_info_view_.cbegin()), const_type_iterator(type_info_view_.cend())); } inline std::string reflection_manager::type_name(const type_tag& tag) const { return tag.name(); } inline std::size_t reflection_manager::type_size(const type_tag& tag) const { return tag.size(); } inline std::pair<typename reflection_manager::const_constructor_iterator, typename reflection_manager::const_constructor_iterator> reflection_manager::constructors() const { return std::make_pair( const_constructor_iterator(constructor_info_view_.cbegin()), const_constructor_iterator(constructor_info_view_.cend())); } inline type_tag reflection_manager::constructor_type(const constructor_tag& tag) const { return type_tag(type_info_view_[tag.info_ptr_->type_index]); } inline std::pair<reflection_manager::const_indexed_type_iterator, reflection_manager::const_indexed_type_iterator> reflection_manager::constructor_parameter_types( const constructor_tag& tag) const { auto index_buffer = tag.info_ptr_->parameter_type_indices; auto data_buffer = type_info_view_.data(); return std::make_pair( const_indexed_type_iterator(0, index_buffer, data_buffer), const_indexed_type_iterator( tag.info_ptr_->num_parameters, index_buffer, data_buffer)); } inline bool reflection_manager::compare_type(const type_tag& tag, std::size_t index) const { type_tag tag_from_index(type_info_view_[index]); return tag == tag_from_index; } template <class Iterator, class InfoType> inline bool reflection_manager::check_arguments(Iterator first, Iterator last, const InfoType& info) const { if(info.num_parameters != std::distance(first, last)) { return false; } for(auto index_ptr = info.parameter_type_indices; first != last; ++index_ptr, ++first) { if(compare_type(first->type(), *index_ptr) == false) { return false; } } return true; } template <class Iterator, class OutputIterator, class InfoType> inline void reflection_manager::construct_argument_array(Iterator first, Iterator last, OutputIterator out, const InfoType& info) const { for(auto pointer_flag_ptr = info.parameter_pointer_flags; first != last; ++pointer_flag_ptr, ++first, ++out) { if(*pointer_flag_ptr) { // construct any with pointer to value auto address_bind_point = first->type_info_->address_of_bind_point; out = address_bind_point(first->value_); } else { out = first->value_; } } } template <class Iterator> inline object reflection_manager::construct_object(const constructor_tag& tag, Iterator first, Iterator last) const { if(check_arguments(first, last, *tag.info_ptr_) == false) { throw std::runtime_error("wrong argument types"); } std::vector<any> arg_vec; arg_vec.reserve(std::distance(first, last)); construct_argument_array( first, last, std::back_inserter(arg_vec), *tag.info_ptr_); auto return_value = tag.info_ptr_->bind_point(arg_vec.data()); return object( return_value, type_info_view_.data() + tag.info_ptr_->type_index, this); } inline std::pair<reflection_manager::const_conversion_iterator, reflection_manager::const_conversion_iterator> reflection_manager::conversions() const { return std::make_pair( const_conversion_iterator(conversion_info_view_.cbegin()), const_conversion_iterator(conversion_info_view_.cend())); } inline std::pair<type_tag, type_tag> reflection_manager::conversion_types(const conversion_tag& tag) const { return std::make_pair( type_tag(type_info_view_[tag.info_ptr_->from_type_index]), type_tag(type_info_view_[tag.info_ptr_->to_type_index])); } inline object reflection_manager::convert(const conversion_tag& tag, const object& val) const { if(val.type() != type_tag(type_info_view_[tag.info_ptr_->from_type_index])) { throw std::runtime_error( "type of object doesn't match conversion binding"); } return object(tag.info_ptr_->bind_point(val.value_), type_info_view_.data() + tag.info_ptr_->to_type_index, this); } template <class T> inline T& reflection_manager::get(object& obj) const { return obj.value_.get<T>(); } template <class T> inline const T& reflection_manager::get(const object& obj) const { return obj.value_.get<T>(); } inline std::pair<reflection_manager::const_free_function_iterator, reflection_manager::const_free_function_iterator> reflection_manager::free_functions() const { return std::make_pair( const_free_function_iterator(free_function_info_view_.cbegin()), const_free_function_iterator(free_function_info_view_.cend())); } inline std::string reflection_manager::free_function_name(const free_function_tag& tag) const { return std::string(tag.info_ptr_->name); } inline type_tag reflection_manager::free_function_return_type( const free_function_tag& tag) const { return type_tag(type_info_view_[tag.info_ptr_->return_type_index]); } inline std::pair<reflection_manager::const_indexed_type_iterator, reflection_manager::const_indexed_type_iterator> reflection_manager::free_function_parameter_types( const free_function_tag& tag) const { return std::make_pair( const_indexed_type_iterator( 0, tag.info_ptr_->parameter_type_indices, type_info_view_.data()), const_indexed_type_iterator(tag.info_ptr_->num_parameters, tag.info_ptr_->parameter_type_indices, type_info_view_.data())); } template <class Iterator> inline object reflection_manager::call_free_function(const free_function_tag& tag, Iterator first, Iterator last) const { if(!check_arguments(first, last, *tag.info_ptr_)) { throw std::runtime_error( "attempting to call free function with arguments of wrong type"); } std::vector<shadow::any> args; args.reserve(std::distance(first, last)); construct_argument_array( first, last, std::back_inserter(args), *tag.info_ptr_); auto return_value = tag.info_ptr_->bind_point(args.data()); return object(return_value, type_info_view_.data() + tag.info_ptr_->return_type_index, this); } } // namespace shadow <commit_msg>Fix passing parameters out in case of out parameters. modified: include/reflection_manager.hpp<commit_after>#pragma once #include <utility> #include <stdexcept> #include <vector> #include <array_view.hpp> #include "reflection_info.hpp" #include "api_types.hpp" #include "info_iterators.hpp" namespace shadow { namespace reflection_initialization_detail { // used to handle cases where reflection_manager is initialized with nullptrs // (ie empty) instead of arrays template <class T> struct array_selector { static helene::array_view<std::remove_pointer_t<std::remove_const_t<T>>> initialize(T) { return helene::array_view< std::remove_pointer_t<std::remove_const_t<T>>>(); } }; template <class I, std::size_t N> struct array_selector<I[N]> { static helene::array_view<I> initialize(I (&arr)[N]) { return helene::make_array_view(arr); } }; } // namespace reflection_initialization_detail // point of interaction with the reflection system class reflection_manager { public: typedef info_iterator_<const type_info, type_tag> const_type_iterator; typedef indexed_info_iterator_<const type_info, type_tag> const_indexed_type_iterator; typedef info_iterator_<const constructor_info, constructor_tag> const_constructor_iterator; typedef info_iterator_<const conversion_info, conversion_tag> const_conversion_iterator; typedef info_iterator_<const free_function_info, free_function_tag> const_free_function_iterator; public: template <class TypeInfoArray, class ConstructorInfoArray, class ConversionInfoArray, class FreeFunctionArray, class MemberFunctionArray, class MemberVariableArray, class StringSerializationArray> reflection_manager(TypeInfoArray& ti_arr, ConstructorInfoArray& ci_arr, ConversionInfoArray& cv_arr, FreeFunctionArray& ff_arr, MemberFunctionArray& mf_arr, MemberVariableArray& mv_arr, StringSerializationArray& ss_arr); // queries on types std::pair<const_type_iterator, const_type_iterator> types() const; std::string type_name(const type_tag& tag) const; std::size_t type_size(const type_tag& tag) const; // returns range of all constructors available std::pair<const_constructor_iterator, const_constructor_iterator> constructors() const; // returns the type that the given constructor belongs to type_tag constructor_type(const constructor_tag& tag) const; // returns range of the types of the parameters of the given constructor std::pair<const_indexed_type_iterator, const_indexed_type_iterator> constructor_parameter_types(const constructor_tag& tag) const; template <class Iterator> object construct_object(const constructor_tag& tag, Iterator first, Iterator last) const; // type conversion functions std::pair<const_conversion_iterator, const_conversion_iterator> conversions() const; std::pair<type_tag, type_tag> conversion_types(const conversion_tag& tag) const; object convert(const conversion_tag& tag, const object& val) const; // returns range of tags to all free functions available std::pair<const_free_function_iterator, const_free_function_iterator> free_functions() const; // returns name of function associated with the free_function_tag std::string free_function_name(const free_function_tag& tag) const; // returns return type of function associated with the free_function_tag type_tag free_function_return_type(const free_function_tag& tag) const; // return range of type tags of parameters of free function associated with // the tag std::pair<const_indexed_type_iterator, const_indexed_type_iterator> free_function_parameter_types(const free_function_tag& tag) const; template <class Iterator> object call_free_function(const free_function_tag& tag, Iterator first, Iterator last) const; public: // unchecked operations template <class T> T& get(object& obj) const; template <class T> const T& get(const object& obj) const; private: template <class Iterator, class InfoType> bool check_arguments(Iterator first, Iterator last, const InfoType& info) const; bool compare_type(const type_tag& tag, std::size_t index) const; template <class Iterator, class OutputIterator, class InfoType> void construct_argument_array(Iterator first, Iterator last, OutputIterator out, const InfoType& info) const; template <class Iterator, class OutputIterator, class InfoType> void pass_parameters_out(Iterator first, Iterator last, OutputIterator out, const InfoType& info) const; private: // array_views of reflection information generated at compile time helene::array_view<const type_info> type_info_view_; helene::array_view<const constructor_info> constructor_info_view_; helene::array_view<const conversion_info> conversion_info_view_; helene::array_view<const free_function_info> free_function_info_view_; helene::array_view<const member_function_info> member_function_info_view_; helene::array_view<const member_variable_info> member_variable_info_view_; helene::array_view<const string_serialization_info> string_serialization_info_view_; }; } // namespace shadow namespace shadow { template <class TypeInfoArray, class ConstructorInfoArray, class ConversionInfoArray, class FreeFunctionArray, class MemberFunctionArray, class MemberVariableArray, class StringSerializationArray> inline reflection_manager::reflection_manager(TypeInfoArray& ti_arr, ConstructorInfoArray& ci_arr, ConversionInfoArray& cv_arr, FreeFunctionArray& ff_arr, MemberFunctionArray& mf_arr, MemberVariableArray& mv_arr, StringSerializationArray& ss_arr) : type_info_view_(reflection_initialization_detail::array_selector< TypeInfoArray>::initialize(ti_arr)), constructor_info_view_(reflection_initialization_detail::array_selector< ConstructorInfoArray>::initialize(ci_arr)), conversion_info_view_(reflection_initialization_detail::array_selector< ConversionInfoArray>::initialize(cv_arr)), free_function_info_view_(reflection_initialization_detail::array_selector< FreeFunctionArray>::initialize(ff_arr)), member_function_info_view_( reflection_initialization_detail::array_selector< MemberFunctionArray>::initialize(mf_arr)), member_variable_info_view_( reflection_initialization_detail::array_selector< MemberVariableArray>::initialize(mv_arr)), string_serialization_info_view_( reflection_initialization_detail::array_selector< StringSerializationArray>::initialize(ss_arr)) { } inline std::pair<typename reflection_manager::const_type_iterator, typename reflection_manager::const_type_iterator> reflection_manager::types() const { return std::make_pair(const_type_iterator(type_info_view_.cbegin()), const_type_iterator(type_info_view_.cend())); } inline std::string reflection_manager::type_name(const type_tag& tag) const { return tag.name(); } inline std::size_t reflection_manager::type_size(const type_tag& tag) const { return tag.size(); } inline std::pair<typename reflection_manager::const_constructor_iterator, typename reflection_manager::const_constructor_iterator> reflection_manager::constructors() const { return std::make_pair( const_constructor_iterator(constructor_info_view_.cbegin()), const_constructor_iterator(constructor_info_view_.cend())); } inline type_tag reflection_manager::constructor_type(const constructor_tag& tag) const { return type_tag(type_info_view_[tag.info_ptr_->type_index]); } inline std::pair<reflection_manager::const_indexed_type_iterator, reflection_manager::const_indexed_type_iterator> reflection_manager::constructor_parameter_types( const constructor_tag& tag) const { auto index_buffer = tag.info_ptr_->parameter_type_indices; auto data_buffer = type_info_view_.data(); return std::make_pair( const_indexed_type_iterator(0, index_buffer, data_buffer), const_indexed_type_iterator( tag.info_ptr_->num_parameters, index_buffer, data_buffer)); } inline bool reflection_manager::compare_type(const type_tag& tag, std::size_t index) const { type_tag tag_from_index(type_info_view_[index]); return tag == tag_from_index; } template <class Iterator, class InfoType> inline bool reflection_manager::check_arguments(Iterator first, Iterator last, const InfoType& info) const { if(info.num_parameters != std::distance(first, last)) { return false; } for(auto index_ptr = info.parameter_type_indices; first != last; ++index_ptr, ++first) { if(compare_type(first->type(), *index_ptr) == false) { return false; } } return true; } template <class Iterator, class OutputIterator, class InfoType> inline void reflection_manager::construct_argument_array(Iterator first, Iterator last, OutputIterator out, const InfoType& info) const { for(auto pointer_flag_ptr = info.parameter_pointer_flags; first != last; ++pointer_flag_ptr, ++first, ++out) { if(*pointer_flag_ptr) { // construct any with pointer to value auto address_bind_point = first->type_info_->address_of_bind_point; out = address_bind_point(first->value_); } else { out = first->value_; } } } template <class Iterator, class OutputIterator, class InfoType> inline void reflection_manager::pass_parameters_out(Iterator first, Iterator last, OutputIterator out, const InfoType& info) const { for(auto ptr_flags = info.parameter_pointer_flags; first != last; ++first, ++out, ++ptr_flags) { if(*ptr_flags) { auto dereference_binding = out->type_info_->dereference_bind_point; out->value_ = dereference_binding(*first); } else { out->value_ = *first; } } } template <class Iterator> inline object reflection_manager::construct_object(const constructor_tag& tag, Iterator first, Iterator last) const { if(check_arguments(first, last, *tag.info_ptr_) == false) { throw std::runtime_error("wrong argument types"); } std::vector<any> arg_vec; arg_vec.reserve(std::distance(first, last)); construct_argument_array( first, last, std::back_inserter(arg_vec), *tag.info_ptr_); auto return_value = tag.info_ptr_->bind_point(arg_vec.data()); return object( return_value, type_info_view_.data() + tag.info_ptr_->type_index, this); } inline std::pair<reflection_manager::const_conversion_iterator, reflection_manager::const_conversion_iterator> reflection_manager::conversions() const { return std::make_pair( const_conversion_iterator(conversion_info_view_.cbegin()), const_conversion_iterator(conversion_info_view_.cend())); } inline std::pair<type_tag, type_tag> reflection_manager::conversion_types(const conversion_tag& tag) const { return std::make_pair( type_tag(type_info_view_[tag.info_ptr_->from_type_index]), type_tag(type_info_view_[tag.info_ptr_->to_type_index])); } inline object reflection_manager::convert(const conversion_tag& tag, const object& val) const { if(val.type() != type_tag(type_info_view_[tag.info_ptr_->from_type_index])) { throw std::runtime_error( "type of object doesn't match conversion binding"); } return object(tag.info_ptr_->bind_point(val.value_), type_info_view_.data() + tag.info_ptr_->to_type_index, this); } template <class T> inline T& reflection_manager::get(object& obj) const { return obj.value_.get<T>(); } template <class T> inline const T& reflection_manager::get(const object& obj) const { return obj.value_.get<T>(); } inline std::pair<reflection_manager::const_free_function_iterator, reflection_manager::const_free_function_iterator> reflection_manager::free_functions() const { return std::make_pair( const_free_function_iterator(free_function_info_view_.cbegin()), const_free_function_iterator(free_function_info_view_.cend())); } inline std::string reflection_manager::free_function_name(const free_function_tag& tag) const { return std::string(tag.info_ptr_->name); } inline type_tag reflection_manager::free_function_return_type( const free_function_tag& tag) const { return type_tag(type_info_view_[tag.info_ptr_->return_type_index]); } inline std::pair<reflection_manager::const_indexed_type_iterator, reflection_manager::const_indexed_type_iterator> reflection_manager::free_function_parameter_types( const free_function_tag& tag) const { return std::make_pair( const_indexed_type_iterator( 0, tag.info_ptr_->parameter_type_indices, type_info_view_.data()), const_indexed_type_iterator(tag.info_ptr_->num_parameters, tag.info_ptr_->parameter_type_indices, type_info_view_.data())); } template <class Iterator> inline object reflection_manager::call_free_function(const free_function_tag& tag, Iterator first, Iterator last) const { if(!check_arguments(first, last, *tag.info_ptr_)) { throw std::runtime_error( "attempting to call free function with arguments of wrong type"); } std::vector<shadow::any> args; args.reserve(std::distance(first, last)); construct_argument_array( first, last, std::back_inserter(args), *tag.info_ptr_); auto return_value = tag.info_ptr_->bind_point(args.data()); pass_parameters_out(args.begin(), args.end(), first, *tag.info_ptr_); return object(return_value, type_info_view_.data() + tag.info_ptr_->return_type_index, this); } } // namespace shadow <|endoftext|>
<commit_before>/* * type.hpp * * Copyright (c) 2015 Masatoshi Hanai * * This software is released under MIT License. * See LICENSE. * */ #ifndef SCALESIM_UTIL_TYPE_HPP_ #define SCALESIM_UTIL_TYPE_HPP_ #include <vector> #include <boost/unordered_set.hpp> #include <boost/shared_ptr.hpp> #include <boost/unordered_map.hpp> template<class App> using event = typename App::Event; template<class App> using state = typename App::State; template<class App> using ev_ptr = boost::shared_ptr<const event<App> >; template<class App> using st_ptr = boost::shared_ptr<const state<App> >; template<class App> using ev_vec = std::vector<ev_ptr<App> >; template<class App> using st_vec = std::vector<st_ptr<App> >; using parti_ptr = boost::shared_ptr<std::vector<long> >; using parti_indx = boost::unordered_multimap<long, long>; using parti_indx_ptr = boost::shared_ptr<parti_indx>; #endif /* SCALESIM_UTIL_TYPE_HPP_ */ <commit_msg>Add comment<commit_after>/* * type.hpp * * Copyright (c) 2015 Masatoshi Hanai * * This software is released under MIT License. * See LICENSE. * */ #ifndef SCALESIM_UTIL_TYPE_HPP_ #define SCALESIM_UTIL_TYPE_HPP_ #include <vector> #include <boost/unordered_set.hpp> #include <boost/shared_ptr.hpp> #include <boost/unordered_map.hpp> template<class App> using event = typename App::Event; template<class App> using state = typename App::State; template<class App> using ev_ptr = boost::shared_ptr<const event<App> >; template<class App> using st_ptr = boost::shared_ptr<const state<App> >; template<class App> using ev_vec = std::vector<ev_ptr<App> >; template<class App> using st_vec = std::vector<st_ptr<App> >; /* partition is a table from id to partition number */ using parti_ptr = boost::shared_ptr<std::vector<long> >; /* partition index is a table from partition to involving ids */ using parti_indx = boost::unordered_multimap<long, long>; using parti_indx_ptr = boost::shared_ptr<parti_indx>; #endif /* SCALESIM_UTIL_TYPE_HPP_ */ <|endoftext|>
<commit_before>#include "sherwood_mex.h" #if USE_OPENMP == 1 #include <omp.h> #endif using namespace MicrosoftResearch::Cambridge::Sherwood; template<typename F> class FeatureFactory: public IFeatureResponseFactory<F> { public: FeatureFactory(unsigned int dimensions, std::vector<Stats> featureStats) : dimensions(dimensions), featureStats(featureStats) {}; F CreateRandom(Random& random) { return F::CreateRandom(random, dimensions, featureStats); } private: unsigned int dimensions; std::vector<Stats> featureStats; }; // F: Feature Response // S: StatisticsAggregator template<typename F, typename S> void sherwood_train(int nlhs, /* number of expected outputs */ mxArray *plhs[], /* mxArray output pointer array */ int nrhs, /* number of inputs */ const mxArray *prhs[], /* mxArray input pointer array */ Options options) { unsigned int curarg = 0; // Features along rows // Examples along columns const matrix<float> features = prhs[curarg++]; const matrix<unsigned char> labels = prhs[curarg++]; // Supervised classification TrainingParameters trainingParameters; trainingParameters.MaxDecisionLevels = options.MaxDecisionLevels; trainingParameters.NumberOfCandidateFeatures = options.NumberOfCandidateFeatures; trainingParameters.NumberOfCandidateThresholdsPerFeature = options.NumberOfCandidateThresholdsPerFeature; trainingParameters.NumberOfTrees = options.NumberOfTrees; trainingParameters.Verbose = false; // Point class DataPointCollection trainingData(features,labels); if (options.Verbose) { mexPrintf("Training data has: %d features %d classes and %d examples.\n", trainingData.Dimensions(), trainingData.CountClasses(), trainingData.Count()); } Random random; // The range for each feature std::vector<Stats> featureStats; featureStats.reserve(trainingData.Dimensions()); if (!options.FeatureScaling) { mexPrintf("No feature scaling is performed: make sure your features are scaled. \n"); } else { for (unsigned int d = 0; d < trainingData.Dimensions(); ++d) { featureStats.push_back(trainingData.GetStats(d)); if (options.Verbose) { mexPrintf("Feature: %d mean: %f stdev: %f. \n", d, featureStats[d].mean, featureStats[d].stdev); } } } FeatureFactory<F> featureFactory(trainingData.Dimensions(), featureStats); ClassificationTrainingContext<F> classificationContext(trainingData.CountClasses(), &featureFactory); // Without OPENMP no multi threading. #if USE_OPENMP == 0 if (options.MaxThreads > 1) { mexPrintf("Compiled without OpenMP flags, falling back to single thread code.\n"); } options.MaxThreads = 1; #endif std::auto_ptr<Forest<F, S> > forest ; // Create forest if (options.MaxThreads == 1) { ProgressStream progressStream(std::cout, Silent); mexPrintf("Using 1 thread.\n"); forest = ForestTrainer<F, S>::TrainForest (random, trainingParameters, classificationContext, trainingData, &progressStream ); } // Parallel // ParallelForestTrainer.h segfaults using gcc. else { #if USE_OPENMP == 1 omp_set_num_threads(options.MaxThreads); unsigned int current_num_threads = 0; if (options.Verbose) { int current_num_threads; #pragma omp parallel current_num_threads = omp_get_num_threads(); mexPrintf("Using OpenMP with %d threads (maximum %d) \n ",current_num_threads,omp_get_max_threads()); } forest = std::auto_ptr<Forest<F,S> >(new Forest<F,S>()); omp_lock_t writelock; omp_init_lock(&writelock); #pragma omp parallel for for (int t = 0; t < trainingParameters.NumberOfTrees; t++) { std::auto_ptr<Tree<F,S> > tree = TreeTrainer<F,S>::TrainTree(random, classificationContext, trainingParameters, trainingData); omp_set_lock(&writelock); forest->AddTree(tree); omp_unset_lock(&writelock); } omp_destroy_lock(&writelock); #endif } // Saving the forest std::ofstream o(options.ForestName.c_str(), std::ios_base::binary); forest->Serialize(o); } void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { MexParams params(1, prhs+2); Options options(params); if (!options.WeakLearner.compare("axis-aligned-hyperplane") && !options.FeatureScaling) sherwood_train<AxisAlignedFeatureResponse, HistogramAggregator>(nlhs, plhs, nrhs, prhs, options); else if (!options.WeakLearner.compare("axis-aligned-hyperplane") && options.FeatureScaling) sherwood_train<AxisAlignedFeatureResponseNormalized, HistogramAggregator>(nlhs, plhs, nrhs, prhs, options); else if (!options.WeakLearner.compare("random-hyperplane") && !options.FeatureScaling) sherwood_train<RandomHyperplaneFeatureResponse, HistogramAggregator>(nlhs, plhs, nrhs, prhs, options); else if (!options.WeakLearner.compare("random-hyperplane") && options.FeatureScaling) sherwood_train<RandomHyperplaneFeatureResponseNormalized, HistogramAggregator>(nlhs, plhs, nrhs, prhs, options); else mexErrMsgTxt("Unknown weak learner. Supported are: axis-aligned-hyperplane and random-hyperplane"); }<commit_msg>Suppressing some output.<commit_after>#include "sherwood_mex.h" #if USE_OPENMP == 1 #include <omp.h> #endif using namespace MicrosoftResearch::Cambridge::Sherwood; template<typename F> class FeatureFactory: public IFeatureResponseFactory<F> { public: FeatureFactory(unsigned int dimensions, std::vector<Stats> featureStats) : dimensions(dimensions), featureStats(featureStats) {}; F CreateRandom(Random& random) { return F::CreateRandom(random, dimensions, featureStats); } private: unsigned int dimensions; std::vector<Stats> featureStats; }; // F: Feature Response // S: StatisticsAggregator template<typename F, typename S> void sherwood_train(int nlhs, /* number of expected outputs */ mxArray *plhs[], /* mxArray output pointer array */ int nrhs, /* number of inputs */ const mxArray *prhs[], /* mxArray input pointer array */ Options options) { unsigned int curarg = 0; // Features along rows // Examples along columns const matrix<float> features = prhs[curarg++]; const matrix<unsigned char> labels = prhs[curarg++]; // Supervised classification TrainingParameters trainingParameters; trainingParameters.MaxDecisionLevels = options.MaxDecisionLevels; trainingParameters.NumberOfCandidateFeatures = options.NumberOfCandidateFeatures; trainingParameters.NumberOfCandidateThresholdsPerFeature = options.NumberOfCandidateThresholdsPerFeature; trainingParameters.NumberOfTrees = options.NumberOfTrees; trainingParameters.Verbose = false; // Point class DataPointCollection trainingData(features,labels); if (options.Verbose) { mexPrintf("Training data has: %d features %d classes and %d examples.\n", trainingData.Dimensions(), trainingData.CountClasses(), trainingData.Count()); } Random random; // The range for each feature std::vector<Stats> featureStats; featureStats.reserve(trainingData.Dimensions()); if (!options.FeatureScaling) { if (options.Verbose) { mexPrintf("No feature scaling is performed: make sure your features are scaled. \n"); } } else { for (unsigned int d = 0; d < trainingData.Dimensions(); ++d) { featureStats.push_back(trainingData.GetStats(d)); if (options.Verbose) { mexPrintf("Feature: %d mean: %f stdev: %f. \n", d, featureStats[d].mean, featureStats[d].stdev); } } } FeatureFactory<F> featureFactory(trainingData.Dimensions(), featureStats); ClassificationTrainingContext<F> classificationContext(trainingData.CountClasses(), &featureFactory); // Without OPENMP no multi threading. #if USE_OPENMP == 0 if (options.MaxThreads > 1) { mexPrintf("Compiled without OpenMP flags, falling back to single thread code.\n"); } options.MaxThreads = 1; #endif std::auto_ptr<Forest<F, S> > forest ; // Create forest if (options.MaxThreads == 1) { ProgressStream progressStream(std::cout, Silent); mexPrintf("Using 1 thread.\n"); forest = ForestTrainer<F, S>::TrainForest (random, trainingParameters, classificationContext, trainingData, &progressStream ); } // Parallel // ParallelForestTrainer.h segfaults using gcc. else { #if USE_OPENMP == 1 omp_set_num_threads(options.MaxThreads); unsigned int current_num_threads = 0; if (options.Verbose) { int current_num_threads; #pragma omp parallel current_num_threads = omp_get_num_threads(); mexPrintf("Using OpenMP with %d threads (maximum %d) \n ",current_num_threads,omp_get_max_threads()); } forest = std::auto_ptr<Forest<F,S> >(new Forest<F,S>()); omp_lock_t writelock; omp_init_lock(&writelock); #pragma omp parallel for for (int t = 0; t < trainingParameters.NumberOfTrees; t++) { std::auto_ptr<Tree<F,S> > tree = TreeTrainer<F,S>::TrainTree(random, classificationContext, trainingParameters, trainingData); omp_set_lock(&writelock); forest->AddTree(tree); omp_unset_lock(&writelock); } omp_destroy_lock(&writelock); #endif } // Saving the forest std::ofstream o(options.ForestName.c_str(), std::ios_base::binary); forest->Serialize(o); } void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { MexParams params(1, prhs+2); Options options(params); if (!options.WeakLearner.compare("axis-aligned-hyperplane") && !options.FeatureScaling) sherwood_train<AxisAlignedFeatureResponse, HistogramAggregator>(nlhs, plhs, nrhs, prhs, options); else if (!options.WeakLearner.compare("axis-aligned-hyperplane") && options.FeatureScaling) sherwood_train<AxisAlignedFeatureResponseNormalized, HistogramAggregator>(nlhs, plhs, nrhs, prhs, options); else if (!options.WeakLearner.compare("random-hyperplane") && !options.FeatureScaling) sherwood_train<RandomHyperplaneFeatureResponse, HistogramAggregator>(nlhs, plhs, nrhs, prhs, options); else if (!options.WeakLearner.compare("random-hyperplane") && options.FeatureScaling) sherwood_train<RandomHyperplaneFeatureResponseNormalized, HistogramAggregator>(nlhs, plhs, nrhs, prhs, options); else mexErrMsgTxt("Unknown weak learner. Supported are: axis-aligned-hyperplane and random-hyperplane"); }<|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 . */ #ifndef INCLUDED_SVX_SDRPAINTWINDOW_HXX #define INCLUDED_SVX_SDRPAINTWINDOW_HXX #include <rtl/ref.hxx> #include <vcl/virdev.hxx> #include <svx/svxdllapi.h> class SdrPaintView; namespace sdr { namespace overlay { class OverlayManager; } } #ifdef _MSC_VER // broken msvc template instantiation #include <svx/sdr/overlay/overlaymanager.hxx> #endif /// paint the transparent children of rWin that overlap rPixelRect /// (for example, transparent form controls like check boxes) void SVX_DLLPUBLIC PaintTransparentChildren(vcl::Window & rWindow, Rectangle const& rPixelRect); class SdrPreRenderDevice { // The original OutputDevice OutputDevice& mrOutputDevice; // The VirtualDevice for PreRendering VclPtr<VirtualDevice> mpPreRenderDevice; public: explicit SdrPreRenderDevice(OutputDevice& rOriginal); ~SdrPreRenderDevice(); void PreparePreRenderDevice(); void OutputPreRenderDevice(const vcl::Region& rExpandedRegion); OutputDevice& GetOriginalOutputDevice() const { return mrOutputDevice; } OutputDevice& GetPreRenderDevice() { return *mpPreRenderDevice.get(); } }; class SVX_DLLPUBLIC SdrPaintWindow { private: // the OutputDevice this window represents OutputDevice& mrOutputDevice; /// In case mrOutputDevice is a buffer for a vcl::Window, this is the window. vcl::Window* mpWindow; // the SdrPaintView this window belongs to SdrPaintView& mrPaintView; // the new OverlayManager for the new OverlayObjects. Test add here, will // replace the IAOManager as soon as it works. rtl::Reference< sdr::overlay::OverlayManager > mxOverlayManager; // The PreRenderDevice for PreRendering SdrPreRenderDevice* mpPreRenderDevice; // The RedrawRegion used for rendering vcl::Region maRedrawRegion; // bitfield // #i72889# flag if this is only a temporary target for repaint, default is false bool mbTemporaryTarget : 1; /** Remember whether the mxOverlayManager supports buffering. Using this flags expensive dynamic_casts on mxOverlayManager in order to detect this. */ bool mbUseBuffer; // helpers void impCreateOverlayManager(); public: SdrPaintWindow(SdrPaintView& rNewPaintView, OutputDevice& rOut, vcl::Window* pWindow = 0); ~SdrPaintWindow(); // data read accesses SdrPaintView& GetPaintView() const { return mrPaintView; } OutputDevice& GetOutputDevice() const { return mrOutputDevice; } vcl::Window* GetWindow() const { return mpWindow; } // OVERLAYMANAGER rtl::Reference< sdr::overlay::OverlayManager > GetOverlayManager() const; // #i73602# add flag if buffer shall be used void DrawOverlay(const vcl::Region& rRegion); // calculate visible area and return Rectangle GetVisibleArea() const; // Is OutDev a printer? bool OutputToPrinter() const { return (OUTDEV_PRINTER == mrOutputDevice.GetOutDevType()); } // Is OutDev a window? bool OutputToWindow() const { return (OUTDEV_WINDOW == mrOutputDevice.GetOutDevType()); } // Is OutDev a VirtualDevice? bool OutputToVirtualDevice() const { return (OUTDEV_VIRDEV == mrOutputDevice.GetOutDevType()); } // Is OutDev a recording MetaFile? bool OutputToRecordingMetaFile() const; // prepare PreRendering (evtl.) void PreparePreRenderDevice(); void DestroyPreRenderDevice(); void OutputPreRenderDevice(const vcl::Region& rExpandedRegion); SdrPreRenderDevice* GetPreRenderDevice() const { return mpPreRenderDevice; } // RedrawRegion const vcl::Region& GetRedrawRegion() const { return maRedrawRegion;} void SetRedrawRegion(const vcl::Region& rNew); // #i72889# read/write access to TempoparyTarget bool getTemporaryTarget() const { return (bool)mbTemporaryTarget; } void setTemporaryTarget(bool bNew) { mbTemporaryTarget = bNew; } // #i72889# get target output device, take into account output buffering OutputDevice& GetTargetOutputDevice() { if(mpPreRenderDevice) return mpPreRenderDevice->GetPreRenderDevice(); else return mrOutputDevice; } }; // typedefs for a list of SdrPaintWindows typedef ::std::vector< SdrPaintWindow* > SdrPaintWindowVector; #endif // INCLUDED_SVX_SDRPAINTWINDOW_HXX /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>loplugin:vclwidgets<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 . */ #ifndef INCLUDED_SVX_SDRPAINTWINDOW_HXX #define INCLUDED_SVX_SDRPAINTWINDOW_HXX #include <rtl/ref.hxx> #include <vcl/virdev.hxx> #include <svx/svxdllapi.h> class SdrPaintView; namespace sdr { namespace overlay { class OverlayManager; } } #ifdef _MSC_VER // broken msvc template instantiation #include <svx/sdr/overlay/overlaymanager.hxx> #endif /// paint the transparent children of rWin that overlap rPixelRect /// (for example, transparent form controls like check boxes) void SVX_DLLPUBLIC PaintTransparentChildren(vcl::Window & rWindow, Rectangle const& rPixelRect); class SdrPreRenderDevice { // The original OutputDevice OutputDevice& mrOutputDevice; // The VirtualDevice for PreRendering VclPtr<VirtualDevice> mpPreRenderDevice; public: explicit SdrPreRenderDevice(OutputDevice& rOriginal); ~SdrPreRenderDevice(); void PreparePreRenderDevice(); void OutputPreRenderDevice(const vcl::Region& rExpandedRegion); OutputDevice& GetOriginalOutputDevice() const { return mrOutputDevice; } OutputDevice& GetPreRenderDevice() { return *mpPreRenderDevice.get(); } }; class SVX_DLLPUBLIC SdrPaintWindow { private: // the OutputDevice this window represents OutputDevice& mrOutputDevice; /// In case mrOutputDevice is a buffer for a vcl::Window, this is the window. VclPtr<vcl::Window> mpWindow; // the SdrPaintView this window belongs to SdrPaintView& mrPaintView; // the new OverlayManager for the new OverlayObjects. Test add here, will // replace the IAOManager as soon as it works. rtl::Reference< sdr::overlay::OverlayManager > mxOverlayManager; // The PreRenderDevice for PreRendering SdrPreRenderDevice* mpPreRenderDevice; // The RedrawRegion used for rendering vcl::Region maRedrawRegion; // bitfield // #i72889# flag if this is only a temporary target for repaint, default is false bool mbTemporaryTarget : 1; /** Remember whether the mxOverlayManager supports buffering. Using this flags expensive dynamic_casts on mxOverlayManager in order to detect this. */ bool mbUseBuffer; // helpers void impCreateOverlayManager(); public: SdrPaintWindow(SdrPaintView& rNewPaintView, OutputDevice& rOut, vcl::Window* pWindow = 0); ~SdrPaintWindow(); // data read accesses SdrPaintView& GetPaintView() const { return mrPaintView; } OutputDevice& GetOutputDevice() const { return mrOutputDevice; } vcl::Window* GetWindow() const { return mpWindow; } // OVERLAYMANAGER rtl::Reference< sdr::overlay::OverlayManager > GetOverlayManager() const; // #i73602# add flag if buffer shall be used void DrawOverlay(const vcl::Region& rRegion); // calculate visible area and return Rectangle GetVisibleArea() const; // Is OutDev a printer? bool OutputToPrinter() const { return (OUTDEV_PRINTER == mrOutputDevice.GetOutDevType()); } // Is OutDev a window? bool OutputToWindow() const { return (OUTDEV_WINDOW == mrOutputDevice.GetOutDevType()); } // Is OutDev a VirtualDevice? bool OutputToVirtualDevice() const { return (OUTDEV_VIRDEV == mrOutputDevice.GetOutDevType()); } // Is OutDev a recording MetaFile? bool OutputToRecordingMetaFile() const; // prepare PreRendering (evtl.) void PreparePreRenderDevice(); void DestroyPreRenderDevice(); void OutputPreRenderDevice(const vcl::Region& rExpandedRegion); SdrPreRenderDevice* GetPreRenderDevice() const { return mpPreRenderDevice; } // RedrawRegion const vcl::Region& GetRedrawRegion() const { return maRedrawRegion;} void SetRedrawRegion(const vcl::Region& rNew); // #i72889# read/write access to TempoparyTarget bool getTemporaryTarget() const { return (bool)mbTemporaryTarget; } void setTemporaryTarget(bool bNew) { mbTemporaryTarget = bNew; } // #i72889# get target output device, take into account output buffering OutputDevice& GetTargetOutputDevice() { if(mpPreRenderDevice) return mpPreRenderDevice->GetPreRenderDevice(); else return mrOutputDevice; } }; // typedefs for a list of SdrPaintWindows typedef ::std::vector< SdrPaintWindow* > SdrPaintWindowVector; #endif // INCLUDED_SVX_SDRPAINTWINDOW_HXX /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>#ifndef TWISTEDCPP_REACTOR_HPP #define TWISTEDCPP_REACTOR_HPP #include "exception.hpp" #include "sockets.hpp" #include "ssl_options.hpp" #include <boost/asio/io_service.hpp> #include <boost/asio/ip/tcp.hpp> #include <boost/asio/ssl.hpp> #include <boost/asio/spawn.hpp> #include <boost/system/system_error.hpp> #include <iostream> #include <memory> #include <iterator> namespace twisted { class reactor { public: void run() { _io_service.run(); } void stop() { _io_service.stop(); } template <typename ProtocolFactory> void listen_tcp(int port, ProtocolFactory factory) { run_impl_tcp(port, std::move(factory)); } template <typename ProtocolFactory> void listen_ssl(int port, ProtocolFactory factory, ssl_options ssl_ops) { run_impl_ssl(port, std::move(factory), std::move(ssl_ops)); } private: template <typename ProtocolFactory> void run_impl_tcp(int port, ProtocolFactory factory) { boost::asio::spawn(_io_service, [=](boost::asio::yield_context yield) { using boost::asio::ip::tcp; tcp::acceptor acceptor(_io_service, tcp::endpoint(tcp::v4(), port)); run_impl_tcp_core(acceptor, factory, yield); }); } template <typename ProtocolFactory> void run_impl_ssl(int port, ProtocolFactory factory, ssl_options ssl_ops) { boost::asio::spawn(_io_service, [=](boost::asio::yield_context yield) { using boost::asio::ip::tcp; tcp::acceptor acceptor(_io_service, tcp::endpoint(tcp::v4(), port)); run_impl_ssl_core(acceptor, factory, yield, ssl_ops); }); } template <typename ProtocolFactory> void run_impl_tcp_core(boost::asio::ip::tcp::acceptor& acceptor, ProtocolFactory factory, boost::asio::yield_context yield) { auto socket_factory = [=]() { return std::unique_ptr<detail::tcp_socket>( new detail::tcp_socket(_io_service)); }; run_loop(acceptor, std::move(factory), yield, socket_factory); } template <typename ProtocolFactory> void run_impl_ssl_core(boost::asio::ip::tcp::acceptor& acceptor, ProtocolFactory factory, boost::asio::yield_context yield, ssl_options ssl_ops) { using boost::asio::ip::tcp; auto socket_factory = [=] { boost::asio::ssl::context _context(boost::asio::ssl::context::sslv23_server); _context.set_options( boost::asio::ssl::context::default_workarounds | boost::asio::ssl::context::no_sslv2 | boost::asio::ssl::context::single_dh_use); _context.set_password_callback([=]( std::size_t /* max_length */, boost::asio::ssl::context::password_purpose /* purpose */) { return ssl_ops.password(); }); _context.use_certificate_chain_file(ssl_ops.certificate()); _context.use_private_key_file(ssl_ops.key(), boost::asio::ssl::context::pem); return std::unique_ptr<detail::ssl_socket>( new detail::ssl_socket(_io_service, _context)); }; run_loop(acceptor, std::move(factory), yield, socket_factory); } template <typename ProtocolFactory, typename SocketFactory> void run_loop(boost::asio::ip::tcp::acceptor& acceptor, ProtocolFactory factory, boost::asio::yield_context yield, SocketFactory socket_factory) { for (;;) { boost::system::error_code ec; auto socket = socket_factory(); acceptor.async_accept(socket->lowest_layer(), yield[ec]); if (ec) { throw boost::system::system_error(ec); } auto new_client = std::make_shared<decltype(factory())>(factory()); // lazy init to avoid clutter in protocol constructors new_client->set_socket(std::move(socket)); new_client->run_protocol(); } } boost::asio::io_service _io_service; }; } // namespace twisted #endif <commit_msg>switched from error code in excep in reactor<commit_after>#ifndef TWISTEDCPP_REACTOR_HPP #define TWISTEDCPP_REACTOR_HPP #include "exception.hpp" #include "sockets.hpp" #include "ssl_options.hpp" #include <boost/asio/io_service.hpp> #include <boost/asio/ip/tcp.hpp> #include <boost/asio/ssl.hpp> #include <boost/asio/spawn.hpp> #include <boost/system/system_error.hpp> #include <iostream> #include <memory> #include <iterator> namespace twisted { class reactor { public: void run() { _io_service.run(); } void stop() { _io_service.stop(); } template <typename ProtocolFactory> void listen_tcp(int port, ProtocolFactory factory) { run_impl_tcp(port, std::move(factory)); } template <typename ProtocolFactory> void listen_ssl(int port, ProtocolFactory factory, ssl_options ssl_ops) { run_impl_ssl(port, std::move(factory), std::move(ssl_ops)); } private: template <typename ProtocolFactory> void run_impl_tcp(int port, ProtocolFactory factory) { boost::asio::spawn(_io_service, [=](boost::asio::yield_context yield) { using boost::asio::ip::tcp; tcp::acceptor acceptor(_io_service, tcp::endpoint(tcp::v4(), port)); run_impl_tcp_core(acceptor, factory, yield); }); } template <typename ProtocolFactory> void run_impl_ssl(int port, ProtocolFactory factory, ssl_options ssl_ops) { boost::asio::spawn(_io_service, [=](boost::asio::yield_context yield) { using boost::asio::ip::tcp; tcp::acceptor acceptor(_io_service, tcp::endpoint(tcp::v4(), port)); run_impl_ssl_core(acceptor, factory, yield, ssl_ops); }); } template <typename ProtocolFactory> void run_impl_tcp_core(boost::asio::ip::tcp::acceptor& acceptor, ProtocolFactory factory, boost::asio::yield_context yield) { auto socket_factory = [=]() { return std::unique_ptr<detail::tcp_socket>( new detail::tcp_socket(_io_service)); }; run_loop(acceptor, std::move(factory), yield, socket_factory); } template <typename ProtocolFactory> void run_impl_ssl_core(boost::asio::ip::tcp::acceptor& acceptor, ProtocolFactory factory, boost::asio::yield_context yield, ssl_options ssl_ops) { using boost::asio::ip::tcp; auto socket_factory = [=] { boost::asio::ssl::context _context(boost::asio::ssl::context::sslv23_server); _context.set_options( boost::asio::ssl::context::default_workarounds | boost::asio::ssl::context::no_sslv2 | boost::asio::ssl::context::single_dh_use); _context.set_password_callback([=]( std::size_t /* max_length */, boost::asio::ssl::context::password_purpose /* purpose */) { return ssl_ops.password(); }); _context.use_certificate_chain_file(ssl_ops.certificate()); _context.use_private_key_file(ssl_ops.key(), boost::asio::ssl::context::pem); return std::unique_ptr<detail::ssl_socket>( new detail::ssl_socket(_io_service, _context)); }; run_loop(acceptor, std::move(factory), yield, socket_factory); } template <typename ProtocolFactory, typename SocketFactory> void run_loop(boost::asio::ip::tcp::acceptor& acceptor, ProtocolFactory factory, boost::asio::yield_context yield, SocketFactory socket_factory) { for (;;) { auto socket = socket_factory(); acceptor.async_accept(socket->lowest_layer(), yield); auto new_client = std::make_shared<decltype(factory())>(factory()); // lazy init to avoid clutter in protocol constructors new_client->set_socket(std::move(socket)); new_client->run_protocol(); } } boost::asio::io_service _io_service; }; } // namespace twisted #endif <|endoftext|>