text
stringlengths
54
60.6k
<commit_before>/* * Copyright (c) 2010 Matthew Iselin * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "GPTimer.h" #include "Prcm.h" #include <processor/PhysicalMemoryManager.h> #include <processor/VirtualAddressSpace.h> #include <processor/Processor.h> #include <Log.h> #include <machine/Machine.h> SyncTimer g_SyncTimer; void SyncTimer::initialise(uintptr_t base) { // Map in the base if(!PhysicalMemoryManager::instance().allocateRegion(m_MmioBase, 1, PhysicalMemoryManager::continuous, VirtualAddressSpace::Write | VirtualAddressSpace::KernelMode, base)) { // Failed to allocate the region! return; } // Dump the hardware revision uint32_t hardwareRevision = *reinterpret_cast<volatile uint32_t*>(m_MmioBase.virtualAddress()); NOTICE("32-kHz sync timer at " << Hex << reinterpret_cast<uintptr_t>(m_MmioBase.virtualAddress()) << " - revision " << Dec << ((hardwareRevision >> 4) & 0xF) << "." << (hardwareRevision & 0xF) << Hex); } uint32_t SyncTimer::getTickCount() { if(!m_MmioBase) return 0; return reinterpret_cast<uint32_t*>(m_MmioBase.virtualAddress())[4]; } void GPTimer::initialise(size_t timer, uintptr_t base) { // Map in the base if(!PhysicalMemoryManager::instance().allocateRegion(m_MmioBase, 1, PhysicalMemoryManager::continuous, VirtualAddressSpace::Write | VirtualAddressSpace::KernelMode, base)) { // Failed to allocate the region! return; } if(timer > 0) { // Use the SYS_CLK as our time source during reset Prcm::instance().SelectClockPER(timer, Prcm::SYS_CLK); // Enable the interface clock for the timer Prcm::instance().SetIfaceClockPER(timer, true); // Enable the functional clock for the timer Prcm::instance().SetFuncClockPER(timer, true); } volatile uint32_t *registers = reinterpret_cast<volatile uint32_t*>(m_MmioBase.virtualAddress()); // Reset the timer registers[TIOCP_CFG] = 2; registers[TSICR] = 2; while(!(registers[TISTAT] & 1)); if(timer > 0) { // Reset the clock source to the 32 kHz functional clock Prcm::instance().SelectClockPER(timer, Prcm::FCLK_32K); } // Dump the hardware revision uint32_t hardwareRevision = registers[TIDR]; NOTICE("General Purpose timer at " << Hex << reinterpret_cast<uintptr_t>(m_MmioBase.virtualAddress()) << " - revision " << Dec << ((hardwareRevision >> 4) & 0xF) << "." << (hardwareRevision & 0xF) << Hex); // Section 16.2.4.2.1 in the OMAP35xx manual, page 2573 registers[TPIR] = 232000; registers[TNIR] = -768000; registers[TLDR] = 0xFFFFFFE0; registers[TTGR] = 1; // Trigger after one interval // Clear existing interrupts registers[TISR] = 7; // Set the IRQ number for future reference m_Irq = 37 + timer; // Enable the overflow interrupt registers[TIER] = 2; // Enable the timer in the right mode registers[TCLR] = 3; // Autoreload and timer started } bool GPTimer::registerHandler(TimerHandler *handler) { // Find a spare spot and install size_t nHandler; for(nHandler = 0; nHandler < MAX_TIMER_HANDLERS; nHandler++) { if(m_Handlers[nHandler] == 0) { m_Handlers[nHandler] = handler; if(!m_bIrqInstalled && m_Irq) { Spinlock install; install.acquire(); m_bIrqInstalled = InterruptManager::instance().registerInterruptHandler(m_Irq, this); install.release(); } return true; } } // No room! return false; } bool GPTimer::unregisterHandler(TimerHandler *handler) { size_t nHandler; for(nHandler = 0; nHandler < MAX_TIMER_HANDLERS; nHandler++) { if(m_Handlers[nHandler] == handler) { m_Handlers[nHandler] = 0; return true; } } return false; } void GPTimer::addAlarm(class Event *pEvent, size_t alarmSecs, size_t alarmUsecs) { #ifdef THREADS Alarm *pAlarm = new Alarm(pEvent, alarmSecs*1000000+alarmUsecs+getTickCount(), Processor::information().getCurrentThread()); m_Alarms.pushBack(pAlarm); #endif } void GPTimer::removeAlarm(class Event *pEvent) { #ifdef THREADS for (List<Alarm*>::Iterator it = m_Alarms.begin(); it != m_Alarms.end(); it++) { if ( (*it)->m_pEvent == pEvent ) { m_Alarms.erase(it); return; } } #endif } size_t GPTimer::removeAlarm(class Event *pEvent, bool bRetZero) { #ifdef THREADS size_t currTime = getTickCount(); for (List<Alarm*>::Iterator it = m_Alarms.begin(); it != m_Alarms.end(); it++) { if ( (*it)->m_pEvent == pEvent ) { size_t ret = 0; if(!bRetZero) { size_t alarmEndTime = (*it)->m_Time; // Is it later than the end of the alarm? if(alarmEndTime < currTime) ret = 0; else { size_t diff = alarmEndTime - currTime; ret = (diff / 1000) + 1; } } m_Alarms.erase(it); return ret; } } return 0; #else return 0; #endif } void GPTimer::interrupt(size_t nInterruptnumber, InterruptState &state) { m_TickCount++; // Call handlers size_t nHandler; for(nHandler = 0; nHandler < MAX_TIMER_HANDLERS; nHandler++) { // Timer delta is in nanoseconds if(m_Handlers[nHandler]) m_Handlers[nHandler]->timer(1000000, state); } // Ack the interrupt source volatile uint32_t *registers = reinterpret_cast<volatile uint32_t*>(m_MmioBase.virtualAddress()); registers[TISR] = registers[TISR]; } <commit_msg>ARM Beagle: fix/add Alarm dispatch<commit_after>/* * Copyright (c) 2010 Matthew Iselin * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "GPTimer.h" #include "Prcm.h" #include <processor/PhysicalMemoryManager.h> #include <processor/VirtualAddressSpace.h> #include <processor/Processor.h> #include <Log.h> #include <machine/Machine.h> SyncTimer g_SyncTimer; void SyncTimer::initialise(uintptr_t base) { // Map in the base if(!PhysicalMemoryManager::instance().allocateRegion(m_MmioBase, 1, PhysicalMemoryManager::continuous, VirtualAddressSpace::Write | VirtualAddressSpace::KernelMode, base)) { // Failed to allocate the region! return; } // Dump the hardware revision uint32_t hardwareRevision = *reinterpret_cast<volatile uint32_t*>(m_MmioBase.virtualAddress()); NOTICE("32-kHz sync timer at " << Hex << reinterpret_cast<uintptr_t>(m_MmioBase.virtualAddress()) << " - revision " << Dec << ((hardwareRevision >> 4) & 0xF) << "." << (hardwareRevision & 0xF) << Hex); } uint32_t SyncTimer::getTickCount() { if(!m_MmioBase) return 0; return reinterpret_cast<uint32_t*>(m_MmioBase.virtualAddress())[4]; } void GPTimer::initialise(size_t timer, uintptr_t base) { // Map in the base if(!PhysicalMemoryManager::instance().allocateRegion(m_MmioBase, 1, PhysicalMemoryManager::continuous, VirtualAddressSpace::Write | VirtualAddressSpace::KernelMode, base)) { // Failed to allocate the region! return; } if(timer > 0) { // Use the SYS_CLK as our time source during reset Prcm::instance().SelectClockPER(timer, Prcm::SYS_CLK); // Enable the interface clock for the timer Prcm::instance().SetIfaceClockPER(timer, true); // Enable the functional clock for the timer Prcm::instance().SetFuncClockPER(timer, true); } volatile uint32_t *registers = reinterpret_cast<volatile uint32_t*>(m_MmioBase.virtualAddress()); // Reset the timer registers[TIOCP_CFG] = 2; registers[TSICR] = 2; while(!(registers[TISTAT] & 1)); if(timer > 0) { // Reset the clock source to the 32 kHz functional clock Prcm::instance().SelectClockPER(timer, Prcm::FCLK_32K); } // Dump the hardware revision uint32_t hardwareRevision = registers[TIDR]; NOTICE("General Purpose timer at " << Hex << reinterpret_cast<uintptr_t>(m_MmioBase.virtualAddress()) << " - revision " << Dec << ((hardwareRevision >> 4) & 0xF) << "." << (hardwareRevision & 0xF) << Hex); // Section 16.2.4.2.1 in the OMAP35xx manual, page 2573 registers[TPIR] = 232000; registers[TNIR] = -768000; registers[TLDR] = 0xFFFFFFE0; registers[TTGR] = 1; // Trigger after one interval // Clear existing interrupts registers[TISR] = 7; // Set the IRQ number for future reference m_Irq = 37 + timer; // Enable the overflow interrupt registers[TIER] = 2; // Enable the timer in the right mode registers[TCLR] = 3; // Autoreload and timer started } bool GPTimer::registerHandler(TimerHandler *handler) { // Find a spare spot and install size_t nHandler; for(nHandler = 0; nHandler < MAX_TIMER_HANDLERS; nHandler++) { if(m_Handlers[nHandler] == 0) { m_Handlers[nHandler] = handler; if(!m_bIrqInstalled && m_Irq) { Spinlock install; install.acquire(); m_bIrqInstalled = InterruptManager::instance().registerInterruptHandler(m_Irq, this); install.release(); } return true; } } // No room! return false; } bool GPTimer::unregisterHandler(TimerHandler *handler) { size_t nHandler; for(nHandler = 0; nHandler < MAX_TIMER_HANDLERS; nHandler++) { if(m_Handlers[nHandler] == handler) { m_Handlers[nHandler] = 0; return true; } } return false; } void GPTimer::addAlarm(class Event *pEvent, size_t alarmSecs, size_t alarmUsecs) { #ifdef THREADS size_t time = (alarmSecs * 1000) + (alarmUsecs / 1000) + m_TickCount; Alarm *pAlarm = new Alarm(pEvent, time, Processor::information().getCurrentThread()); m_Alarms.pushBack(pAlarm); #endif } void GPTimer::removeAlarm(class Event *pEvent) { #ifdef THREADS for (List<Alarm*>::Iterator it = m_Alarms.begin(); it != m_Alarms.end(); it++) { if ( (*it)->m_pEvent == pEvent ) { m_Alarms.erase(it); return; } } #endif } size_t GPTimer::removeAlarm(class Event *pEvent, bool bRetZero) { #ifdef THREADS size_t currTime = getTickCount(); for (List<Alarm*>::Iterator it = m_Alarms.begin(); it != m_Alarms.end(); it++) { if ( (*it)->m_pEvent == pEvent ) { size_t ret = 0; if(!bRetZero) { size_t alarmEndTime = (*it)->m_Time; // Is it later than the end of the alarm? if(alarmEndTime < currTime) ret = 0; else { size_t diff = alarmEndTime - currTime; ret = (diff / 1000) + 1; } } m_Alarms.erase(it); return ret; } } return 0; #else return 0; #endif } void GPTimer::interrupt(size_t nInterruptnumber, InterruptState &state) { m_TickCount++; // Call handlers size_t nHandler; for(nHandler = 0; nHandler < MAX_TIMER_HANDLERS; nHandler++) { // Timer delta is in nanoseconds if(m_Handlers[nHandler]) m_Handlers[nHandler]->timer(1000000, state); } // Check for alarms. while (true) { bool bDispatched = false; for (List<Alarm*>::Iterator it = m_Alarms.begin(); it != m_Alarms.end(); it++) { Alarm *pA = *it; if ( pA->m_Time <= m_TickCount ) { pA->m_pThread->sendEvent(pA->m_pEvent); m_Alarms.erase(it); bDispatched = true; break; } } if (!bDispatched) break; } // Ack the interrupt source volatile uint32_t *registers = reinterpret_cast<volatile uint32_t*>(m_MmioBase.virtualAddress()); registers[TISR] = registers[TISR]; } <|endoftext|>
<commit_before>/* -*- c++ -*- attachmentstrategy.cpp This file is part of KMail, the KDE mail client. Copyright (c) 2003 Marc Mutz <mutz@kde.org> KMail is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License, version 2, as published by the Free Software Foundation. KMail 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #include "attachmentstrategy.h" #include "partNode.h" #include "kmmsgpart.h" #include <QString> #include <kdebug.h> namespace KMail { // // IconicAttachmentStrategy: // show everything but the first text/plain body as icons // class IconicAttachmentStrategy : public AttachmentStrategy { friend class ::KMail::AttachmentStrategy; protected: IconicAttachmentStrategy() : AttachmentStrategy() {} virtual ~IconicAttachmentStrategy() {} public: const char * name() const { return "iconic"; } const AttachmentStrategy * next() const { return smart(); } const AttachmentStrategy * prev() const { return hidden(); } bool inlineNestedMessages() const { return false; } Display defaultDisplay( const partNode * node ) const { if ( node->type() == DwMime::kTypeText && node->msgPart().fileName().trimmed().isEmpty() && node->msgPart().name().trimmed().isEmpty() ) // text/* w/o filename parameter: return Inline; return AsIcon; } }; // // SmartAttachmentStrategy: // in addition to Iconic, show all body parts // with content-disposition == "inline" and // all text parts without a filename or name parameter inline // class SmartAttachmentStrategy : public AttachmentStrategy { friend class ::KMail::AttachmentStrategy; protected: SmartAttachmentStrategy() : AttachmentStrategy() {} virtual ~SmartAttachmentStrategy() {} public: const char * name() const { return "smart"; } const AttachmentStrategy * next() const { return inlined(); } const AttachmentStrategy * prev() const { return iconic(); } bool inlineNestedMessages() const { return true; } Display defaultDisplay( const partNode * node ) const { if ( node->hasContentDispositionInline() ) // explict "inline" disposition: return Inline; if ( node->isAttachment() ) // explicit "attachment" disposition: return AsIcon; if ( node->type() == DwMime::kTypeText && node->msgPart().fileName().trimmed().isEmpty() && node->msgPart().name().trimmed().isEmpty() ) // text/* w/o filename parameter: return Inline; return AsIcon; } }; // // InlinedAttachmentStrategy: // show everything possible inline // class InlinedAttachmentStrategy : public AttachmentStrategy { friend class ::KMail::AttachmentStrategy; protected: InlinedAttachmentStrategy() : AttachmentStrategy() {} virtual ~InlinedAttachmentStrategy() {} public: const char * name() const { return "inlined"; } const AttachmentStrategy * next() const { return hidden(); } const AttachmentStrategy * prev() const { return smart(); } bool inlineNestedMessages() const { return true; } Display defaultDisplay( const partNode * ) const { return Inline; } }; // // HiddenAttachmentStrategy // show nothing except the first text/plain body part _at all_ // class HiddenAttachmentStrategy : public AttachmentStrategy { friend class ::KMail::AttachmentStrategy; protected: HiddenAttachmentStrategy() : AttachmentStrategy() {} virtual ~HiddenAttachmentStrategy() {} public: const char * name() const { return "hidden"; } const AttachmentStrategy * next() const { return iconic(); } const AttachmentStrategy * prev() const { return inlined(); } bool inlineNestedMessages() const { return false; } Display defaultDisplay( const partNode * node ) const { if ( node->type() == DwMime::kTypeText && node->msgPart().fileName().trimmed().isEmpty() && node->msgPart().name().trimmed().isEmpty() ) // text/* w/o filename parameter: return Inline; if ( node->parentNode()->type() == DwMime::kTypeMultipart && node->parentNode()->subType() == DwMime::kSubtypeRelated ) return Inline; return None; } }; // // AttachmentStrategy abstract base: // AttachmentStrategy::AttachmentStrategy() { } AttachmentStrategy::~AttachmentStrategy() { } const AttachmentStrategy * AttachmentStrategy::create( Type type ) { switch ( type ) { case Iconic: return iconic(); case Smart: return smart(); case Inlined: return inlined(); case Hidden: return hidden(); } kFatal() << "Unknown attachment startegy ( type ==" << (int)type << ") requested!"; return 0; // make compiler happy } const AttachmentStrategy * AttachmentStrategy::create( const QString & type ) { QString lowerType = type.toLower(); if ( lowerType == "iconic" ) return iconic(); //if ( lowerType == "smart" ) return smart(); // not needed, see below if ( lowerType == "inlined" ) return inlined(); if ( lowerType == "hidden" ) return hidden(); // don't kFatal here, b/c the strings are user-provided // (KConfig), so fail gracefully to the default: return smart(); } static const AttachmentStrategy * iconicStrategy = 0; static const AttachmentStrategy * smartStrategy = 0; static const AttachmentStrategy * inlinedStrategy = 0; static const AttachmentStrategy * hiddenStrategy = 0; const AttachmentStrategy * AttachmentStrategy::iconic() { if ( !iconicStrategy ) iconicStrategy = new IconicAttachmentStrategy(); return iconicStrategy; } const AttachmentStrategy * AttachmentStrategy::smart() { if ( !smartStrategy ) smartStrategy = new SmartAttachmentStrategy(); return smartStrategy; } const AttachmentStrategy * AttachmentStrategy::inlined() { if ( !inlinedStrategy ) inlinedStrategy = new InlinedAttachmentStrategy(); return inlinedStrategy; } const AttachmentStrategy * AttachmentStrategy::hidden() { if ( !hiddenStrategy ) hiddenStrategy = new HiddenAttachmentStrategy(); return hiddenStrategy; } } // namespace KMail <commit_msg>Fix crash when header strategy is hidden Apply patch from BR.<commit_after>/* -*- c++ -*- attachmentstrategy.cpp This file is part of KMail, the KDE mail client. Copyright (c) 2003 Marc Mutz <mutz@kde.org> KMail is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License, version 2, as published by the Free Software Foundation. KMail 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #include "attachmentstrategy.h" #include "partNode.h" #include "kmmsgpart.h" #include <QString> #include <kdebug.h> namespace KMail { // // IconicAttachmentStrategy: // show everything but the first text/plain body as icons // class IconicAttachmentStrategy : public AttachmentStrategy { friend class ::KMail::AttachmentStrategy; protected: IconicAttachmentStrategy() : AttachmentStrategy() {} virtual ~IconicAttachmentStrategy() {} public: const char * name() const { return "iconic"; } const AttachmentStrategy * next() const { return smart(); } const AttachmentStrategy * prev() const { return hidden(); } bool inlineNestedMessages() const { return false; } Display defaultDisplay( const partNode * node ) const { if ( node->type() == DwMime::kTypeText && node->msgPart().fileName().trimmed().isEmpty() && node->msgPart().name().trimmed().isEmpty() ) // text/* w/o filename parameter: return Inline; return AsIcon; } }; // // SmartAttachmentStrategy: // in addition to Iconic, show all body parts // with content-disposition == "inline" and // all text parts without a filename or name parameter inline // class SmartAttachmentStrategy : public AttachmentStrategy { friend class ::KMail::AttachmentStrategy; protected: SmartAttachmentStrategy() : AttachmentStrategy() {} virtual ~SmartAttachmentStrategy() {} public: const char * name() const { return "smart"; } const AttachmentStrategy * next() const { return inlined(); } const AttachmentStrategy * prev() const { return iconic(); } bool inlineNestedMessages() const { return true; } Display defaultDisplay( const partNode * node ) const { if ( node->hasContentDispositionInline() ) // explict "inline" disposition: return Inline; if ( node->isAttachment() ) // explicit "attachment" disposition: return AsIcon; if ( node->type() == DwMime::kTypeText && node->msgPart().fileName().trimmed().isEmpty() && node->msgPart().name().trimmed().isEmpty() ) // text/* w/o filename parameter: return Inline; return AsIcon; } }; // // InlinedAttachmentStrategy: // show everything possible inline // class InlinedAttachmentStrategy : public AttachmentStrategy { friend class ::KMail::AttachmentStrategy; protected: InlinedAttachmentStrategy() : AttachmentStrategy() {} virtual ~InlinedAttachmentStrategy() {} public: const char * name() const { return "inlined"; } const AttachmentStrategy * next() const { return hidden(); } const AttachmentStrategy * prev() const { return smart(); } bool inlineNestedMessages() const { return true; } Display defaultDisplay( const partNode * ) const { return Inline; } }; // // HiddenAttachmentStrategy // show nothing except the first text/plain body part _at all_ // class HiddenAttachmentStrategy : public AttachmentStrategy { friend class ::KMail::AttachmentStrategy; protected: HiddenAttachmentStrategy() : AttachmentStrategy() {} virtual ~HiddenAttachmentStrategy() {} public: const char * name() const { return "hidden"; } const AttachmentStrategy * next() const { return iconic(); } const AttachmentStrategy * prev() const { return inlined(); } bool inlineNestedMessages() const { return false; } Display defaultDisplay( const partNode * node ) const { if ( node->type() == DwMime::kTypeText && node->msgPart().fileName().trimmed().isEmpty() && node->msgPart().name().trimmed().isEmpty() ) // text/* w/o filename parameter: return Inline; if (!node->parentNode()) return Inline; if ( node->parentNode()->type() == DwMime::kTypeMultipart && node->parentNode()->subType() == DwMime::kSubtypeRelated ) return Inline; return None; } }; // // AttachmentStrategy abstract base: // AttachmentStrategy::AttachmentStrategy() { } AttachmentStrategy::~AttachmentStrategy() { } const AttachmentStrategy * AttachmentStrategy::create( Type type ) { switch ( type ) { case Iconic: return iconic(); case Smart: return smart(); case Inlined: return inlined(); case Hidden: return hidden(); } kFatal() << "Unknown attachment startegy ( type ==" << (int)type << ") requested!"; return 0; // make compiler happy } const AttachmentStrategy * AttachmentStrategy::create( const QString & type ) { QString lowerType = type.toLower(); if ( lowerType == "iconic" ) return iconic(); //if ( lowerType == "smart" ) return smart(); // not needed, see below if ( lowerType == "inlined" ) return inlined(); if ( lowerType == "hidden" ) return hidden(); // don't kFatal here, b/c the strings are user-provided // (KConfig), so fail gracefully to the default: return smart(); } static const AttachmentStrategy * iconicStrategy = 0; static const AttachmentStrategy * smartStrategy = 0; static const AttachmentStrategy * inlinedStrategy = 0; static const AttachmentStrategy * hiddenStrategy = 0; const AttachmentStrategy * AttachmentStrategy::iconic() { if ( !iconicStrategy ) iconicStrategy = new IconicAttachmentStrategy(); return iconicStrategy; } const AttachmentStrategy * AttachmentStrategy::smart() { if ( !smartStrategy ) smartStrategy = new SmartAttachmentStrategy(); return smartStrategy; } const AttachmentStrategy * AttachmentStrategy::inlined() { if ( !inlinedStrategy ) inlinedStrategy = new InlinedAttachmentStrategy(); return inlinedStrategy; } const AttachmentStrategy * AttachmentStrategy::hidden() { if ( !hiddenStrategy ) hiddenStrategy = new HiddenAttachmentStrategy(); return hiddenStrategy; } } // namespace KMail <|endoftext|>
<commit_before>/* kopete.cpp Kopete Instant Messenger Main Class Copyright (c) 2001-2002 by Duncan Mac-Vicar Prett <duncan@kde.org> Copyright (c) 2002-2003 by Martijn Klingens <klingens@kde.org> Kopete (c) 2001-2003 by the Kopete developers <kopete-devel@kde.org> ************************************************************************* * * * 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. * * * ************************************************************************* */ #include "kopeteapplication.h" #include <qtimer.h> #include <qregexp.h> #include <kconfig.h> #include <kdebug.h> #include <kglobal.h> #include <klocale.h> #include <kcmdlineargs.h> #include <kmessagebox.h> #include "addaccountwizard.h" #include "kabcpersistence.h" #include "kopeteaccount.h" #include "kopeteaccountmanager.h" #include "kopetebehaviorsettings.h" #include "kopetecommandhandler.h" #include "kopetecontactlist.h" #include "kopeteglobal.h" #include "kopetefileengine.h" #include "kopetemimetypehandler.h" #include "kopetepluginmanager.h" #include "kopeteprotocol.h" #include "kopetestdaction.h" #include "kopeteuiglobal.h" #include "kopetewindow.h" #include "kopeteviewmanager.h" #include "kopeteidentitymanager.h" KopeteApplication::KopeteApplication() : KUniqueApplication( true, true ) { m_isShuttingDown = false; m_mainWindow = new KopeteWindow( 0, "mainWindow" ); Kopete::PluginManager::self(); Kopete::UI::Global::setMainWidget( m_mainWindow ); //Create the identity manager Kopete::IdentityManager::self()->load(); /* * FIXME: This is a workaround for a quite odd problem: * When starting up kopete and the msn plugin gets loaded it can bring up * a messagebox, in case the msg configuration is missing. This messagebox * will result in a QApplication::enter_loop() call, an event loop is * created. At this point however the loop_level is 0, because this is all * still inside the KopeteApplication constructor, before the exec() call from main. * When the messagebox is finished the loop_level will drop down to zero and * QApplication thinks the application shuts down (this is usually the case * when the loop_level goes down to zero) . So it emits aboutToQuit(), to * which KApplication is connected and re-emits shutdown() , to which again * KXmlGuiWindow (a KopeteWindow instance exists already) is connected. KXmlGuiWindow's * shuttingDown() slot calls queryExit() which results in KopeteWindow::queryExit() * calling unloadPlugins() . This of course is wrong and just shouldn't happen. * The workaround is to simply delay the initialization of all this to a point * where the loop_level is already > 0 . That is why I moved all the code from * the constructor to the initialize() method and added this single-shot-timer * setup. (Simon) * * Additionally, it makes the GUI appear less 'blocking' during startup, so * there is a secondary benefit as well here. (Martijn) */ QTimer::singleShot( 0, this, SLOT( slotLoadPlugins() ) ); m_fileEngineHandler = new Kopete::FileEngineHandler(); //Create the emoticon installer m_emoticonHandler = new Kopete::EmoticonMimeTypeHandler; } KopeteApplication::~KopeteApplication() { kDebug( 14000 ) ; delete m_fileEngineHandler; delete m_emoticonHandler; delete m_mainWindow; //kDebug( 14000 ) << "Done"; } void KopeteApplication::slotLoadPlugins() { // we have to load the address book early, because calling this enters the Qt event loop when there are remote resources. // The plugin manager is written with the assumption that Kopete will not reenter the event loop during plugin load, // otherwise lots of things break as plugins are loaded, then contacts are added to incompletely initialised MCLVIs Kopete::KABCPersistence::self()->addressBook(); //Create the command handler (looks silly) Kopete::CommandHandler::commandHandler(); //Create the view manager KopeteViewManager::viewManager(); // the account manager should be created after the identity manager is created Kopete::AccountManager::self()->load(); Kopete::ContactList::self()->load(); KSharedConfig::Ptr config = KGlobal::config(); // Parse command-line arguments KCmdLineArgs *args = KCmdLineArgs::parsedArgs(); bool showConfigDialog = false; KConfigGroup pluginsGroup = config->group( "Plugins" ); /* FIXME: This is crap, if something purged that groups but your accounts * are still working kopete will load the necessary plugins but still show the * stupid accounts dialog (of course empty at that time because account data * gets loaded later on). [mETz - 29.05.2004] */ if ( !pluginsGroup.exists() ) showConfigDialog = true; // Listen to arguments /* // TODO: conflicts with emoticon installer and the general meaning // of %U in kopete.desktop if ( args->count() > 0 ) { showConfigDialog = false; for ( int i = 0; i < args->count(); i++ ) Kopete::PluginManager::self()->setPluginEnabled( args->arg( i ), true ); } */ // Prevent plugins from loading? (--disable=foo,bar) foreach ( const QString &disableArg, args->getOption( "disable" ).split( ',' )) { showConfigDialog = false; Kopete::PluginManager::self()->setPluginEnabled( disableArg, false ); } // Load some plugins exclusively? (--load-plugins=foo,bar) if ( args->isSet( "load-plugins" ) ) { pluginsGroup.deleteGroup( KConfigBase::Global ); showConfigDialog = false; foreach ( const QString &plugin, args->getOption( "load-plugins" ).split( ',' )) Kopete::PluginManager::self()->setPluginEnabled( plugin, true ); } config->sync(); // Disable plugins altogether? (--noplugins) if ( !args->isSet( "plugins" ) ) { // If anybody reenables this I'll get a sword and make a nice chop-suy out // of your body :P [mETz - 29.05.2004] // This screws up kopeterc because there is no way to get the Plugins group back! //config->deleteGroup( "Plugins", true ); showConfigDialog = false; // pretend all plugins were loaded :) QTimer::singleShot(0, this, SLOT( slotAllPluginsLoaded() )); } else { Kopete::PluginManager::self()->loadAllPlugins(); } connect( Kopete::PluginManager::self(), SIGNAL( allPluginsLoaded() ), this, SLOT( slotAllPluginsLoaded() )); if( showConfigDialog ) { // No plugins specified. Show the config dialog. // FIXME: Although it's a bit stupid it is theoretically possible that a user // explicitly configured Kopete to not load plugins on startup. In this // case we don't want this dialog. We need some other config setting // like a bool hasRunKopeteBefore or so to trigger the loading of the // wizard. Maybe using the last run version number is more useful even // as it also allows for other features. - Martijn // FIXME: Possibly we need to influence the showConfigDialog bool based on the // command line arguments processed below. But how exactly? - Martijn // NB: the command line args are completely broken atm. // I don't want to fix them for 3.5 as plugin loading will change for KDE4. - Will AddAccountWizard *m_addwizard = new AddAccountWizard( Kopete::UI::Global::mainWidget(), true ); m_addwizard->exec(); Kopete::AccountManager::self()->save(); } } void KopeteApplication::slotAllPluginsLoaded() { KCmdLineArgs *args = KCmdLineArgs::parsedArgs(); //FIXME: this should probably ask for the identities to connect instead of all accounts // --noconnect not specified? if ( args->isSet( "connect" ) && Kopete::BehaviorSettings::self()->autoConnect() ) Kopete::AccountManager::self()->connectAll(); QStringList connectArgs = args->getOptionList( "autoconnect" ); for ( QStringList::ConstIterator i = connectArgs.begin(); i != connectArgs.end(); ++i ) { foreach ( const QString connectArg, (*i).split(',')) connectArgs.append( connectArg ); } for ( QStringList::ConstIterator i = connectArgs.begin(); i != connectArgs.end(); ++i ) { QRegExp rx( QLatin1String( "([^\\|]*)\\|\\|(.*)" ) ); rx.indexIn( *i ); QString protocolId = rx.cap( 1 ); QString accountId = rx.cap( 2 ); if ( accountId.isEmpty() ) { if ( protocolId.isEmpty() ) accountId = *i; else continue; } QListIterator<Kopete::Account *> it( Kopete::AccountManager::self()->accounts() ); Kopete::Account *account; while ( it.hasNext() ) { account = it.next(); if ( ( account->accountId() == accountId ) ) { if ( protocolId.isEmpty() || account->protocol()->pluginId() == protocolId ) { account->connect(); break; } } } } // Parse any passed URLs/files handleURLArgs(); } int KopeteApplication::newInstance() { // kDebug(14000) ; handleURLArgs(); return KUniqueApplication::newInstance(); } void KopeteApplication::handleURLArgs() { KCmdLineArgs *args = KCmdLineArgs::parsedArgs(); // kDebug(14000) << "called with " << args->count() << " arguments to handle."; if ( args->count() > 0 ) { for ( int i = 0; i < args->count(); i++ ) { KUrl u( args->url( i ) ); if ( !u.isValid() ) continue; Kopete::MimeTypeHandler::dispatchURL( u ); } // END for() } // END args->count() > 0 } void KopeteApplication::quitKopete() { kDebug( 14000 ) ; m_isShuttingDown = true; // close all windows QList<KMainWindow*> members = KMainWindow::memberList(); QList<KMainWindow*>::iterator it, itEnd = members.end(); for ( it = members.begin(); it != itEnd; ++it) { if ( (*it)->close() ) { m_isShuttingDown = false; break; } } } void KopeteApplication::commitData( QSessionManager &sm ) { m_isShuttingDown = true; KUniqueApplication::commitData( sm ); } #include "kopeteapplication.moc" // vim: set noet ts=4 sts=4 sw=4: <commit_msg>Do not quit when last window is closed (fixes some crashes)<commit_after>/* kopete.cpp Kopete Instant Messenger Main Class Copyright (c) 2001-2002 by Duncan Mac-Vicar Prett <duncan@kde.org> Copyright (c) 2002-2003 by Martijn Klingens <klingens@kde.org> Kopete (c) 2001-2003 by the Kopete developers <kopete-devel@kde.org> ************************************************************************* * * * 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. * * * ************************************************************************* */ #include "kopeteapplication.h" #include <qtimer.h> #include <qregexp.h> #include <kconfig.h> #include <kdebug.h> #include <kglobal.h> #include <klocale.h> #include <kcmdlineargs.h> #include <kmessagebox.h> #include "addaccountwizard.h" #include "kabcpersistence.h" #include "kopeteaccount.h" #include "kopeteaccountmanager.h" #include "kopetebehaviorsettings.h" #include "kopetecommandhandler.h" #include "kopetecontactlist.h" #include "kopeteglobal.h" #include "kopetefileengine.h" #include "kopetemimetypehandler.h" #include "kopetepluginmanager.h" #include "kopeteprotocol.h" #include "kopetestdaction.h" #include "kopeteuiglobal.h" #include "kopetewindow.h" #include "kopeteviewmanager.h" #include "kopeteidentitymanager.h" KopeteApplication::KopeteApplication() : KUniqueApplication( true, true ) { setQuitOnLastWindowClosed( false ); m_isShuttingDown = false; m_mainWindow = new KopeteWindow( 0, "mainWindow" ); Kopete::PluginManager::self(); Kopete::UI::Global::setMainWidget( m_mainWindow ); //Create the identity manager Kopete::IdentityManager::self()->load(); /* * FIXME: This is a workaround for a quite odd problem: * When starting up kopete and the msn plugin gets loaded it can bring up * a messagebox, in case the msg configuration is missing. This messagebox * will result in a QApplication::enter_loop() call, an event loop is * created. At this point however the loop_level is 0, because this is all * still inside the KopeteApplication constructor, before the exec() call from main. * When the messagebox is finished the loop_level will drop down to zero and * QApplication thinks the application shuts down (this is usually the case * when the loop_level goes down to zero) . So it emits aboutToQuit(), to * which KApplication is connected and re-emits shutdown() , to which again * KXmlGuiWindow (a KopeteWindow instance exists already) is connected. KXmlGuiWindow's * shuttingDown() slot calls queryExit() which results in KopeteWindow::queryExit() * calling unloadPlugins() . This of course is wrong and just shouldn't happen. * The workaround is to simply delay the initialization of all this to a point * where the loop_level is already > 0 . That is why I moved all the code from * the constructor to the initialize() method and added this single-shot-timer * setup. (Simon) * * Additionally, it makes the GUI appear less 'blocking' during startup, so * there is a secondary benefit as well here. (Martijn) */ QTimer::singleShot( 0, this, SLOT( slotLoadPlugins() ) ); m_fileEngineHandler = new Kopete::FileEngineHandler(); //Create the emoticon installer m_emoticonHandler = new Kopete::EmoticonMimeTypeHandler; } KopeteApplication::~KopeteApplication() { kDebug( 14000 ) ; delete m_fileEngineHandler; delete m_emoticonHandler; delete m_mainWindow; //kDebug( 14000 ) << "Done"; } void KopeteApplication::slotLoadPlugins() { // we have to load the address book early, because calling this enters the Qt event loop when there are remote resources. // The plugin manager is written with the assumption that Kopete will not reenter the event loop during plugin load, // otherwise lots of things break as plugins are loaded, then contacts are added to incompletely initialised MCLVIs Kopete::KABCPersistence::self()->addressBook(); //Create the command handler (looks silly) Kopete::CommandHandler::commandHandler(); //Create the view manager KopeteViewManager::viewManager(); // the account manager should be created after the identity manager is created Kopete::AccountManager::self()->load(); Kopete::ContactList::self()->load(); KSharedConfig::Ptr config = KGlobal::config(); // Parse command-line arguments KCmdLineArgs *args = KCmdLineArgs::parsedArgs(); bool showConfigDialog = false; KConfigGroup pluginsGroup = config->group( "Plugins" ); /* FIXME: This is crap, if something purged that groups but your accounts * are still working kopete will load the necessary plugins but still show the * stupid accounts dialog (of course empty at that time because account data * gets loaded later on). [mETz - 29.05.2004] */ if ( !pluginsGroup.exists() ) showConfigDialog = true; // Listen to arguments /* // TODO: conflicts with emoticon installer and the general meaning // of %U in kopete.desktop if ( args->count() > 0 ) { showConfigDialog = false; for ( int i = 0; i < args->count(); i++ ) Kopete::PluginManager::self()->setPluginEnabled( args->arg( i ), true ); } */ // Prevent plugins from loading? (--disable=foo,bar) foreach ( const QString &disableArg, args->getOption( "disable" ).split( ',' )) { showConfigDialog = false; Kopete::PluginManager::self()->setPluginEnabled( disableArg, false ); } // Load some plugins exclusively? (--load-plugins=foo,bar) if ( args->isSet( "load-plugins" ) ) { pluginsGroup.deleteGroup( KConfigBase::Global ); showConfigDialog = false; foreach ( const QString &plugin, args->getOption( "load-plugins" ).split( ',' )) Kopete::PluginManager::self()->setPluginEnabled( plugin, true ); } config->sync(); // Disable plugins altogether? (--noplugins) if ( !args->isSet( "plugins" ) ) { // If anybody reenables this I'll get a sword and make a nice chop-suy out // of your body :P [mETz - 29.05.2004] // This screws up kopeterc because there is no way to get the Plugins group back! //config->deleteGroup( "Plugins", true ); showConfigDialog = false; // pretend all plugins were loaded :) QTimer::singleShot(0, this, SLOT( slotAllPluginsLoaded() )); } else { Kopete::PluginManager::self()->loadAllPlugins(); } connect( Kopete::PluginManager::self(), SIGNAL( allPluginsLoaded() ), this, SLOT( slotAllPluginsLoaded() )); if( showConfigDialog ) { // No plugins specified. Show the config dialog. // FIXME: Although it's a bit stupid it is theoretically possible that a user // explicitly configured Kopete to not load plugins on startup. In this // case we don't want this dialog. We need some other config setting // like a bool hasRunKopeteBefore or so to trigger the loading of the // wizard. Maybe using the last run version number is more useful even // as it also allows for other features. - Martijn // FIXME: Possibly we need to influence the showConfigDialog bool based on the // command line arguments processed below. But how exactly? - Martijn // NB: the command line args are completely broken atm. // I don't want to fix them for 3.5 as plugin loading will change for KDE4. - Will AddAccountWizard *m_addwizard = new AddAccountWizard( Kopete::UI::Global::mainWidget(), true ); m_addwizard->exec(); Kopete::AccountManager::self()->save(); } } void KopeteApplication::slotAllPluginsLoaded() { KCmdLineArgs *args = KCmdLineArgs::parsedArgs(); //FIXME: this should probably ask for the identities to connect instead of all accounts // --noconnect not specified? if ( args->isSet( "connect" ) && Kopete::BehaviorSettings::self()->autoConnect() ) Kopete::AccountManager::self()->connectAll(); QStringList connectArgs = args->getOptionList( "autoconnect" ); for ( QStringList::ConstIterator i = connectArgs.begin(); i != connectArgs.end(); ++i ) { foreach ( const QString connectArg, (*i).split(',')) connectArgs.append( connectArg ); } for ( QStringList::ConstIterator i = connectArgs.begin(); i != connectArgs.end(); ++i ) { QRegExp rx( QLatin1String( "([^\\|]*)\\|\\|(.*)" ) ); rx.indexIn( *i ); QString protocolId = rx.cap( 1 ); QString accountId = rx.cap( 2 ); if ( accountId.isEmpty() ) { if ( protocolId.isEmpty() ) accountId = *i; else continue; } QListIterator<Kopete::Account *> it( Kopete::AccountManager::self()->accounts() ); Kopete::Account *account; while ( it.hasNext() ) { account = it.next(); if ( ( account->accountId() == accountId ) ) { if ( protocolId.isEmpty() || account->protocol()->pluginId() == protocolId ) { account->connect(); break; } } } } // Parse any passed URLs/files handleURLArgs(); } int KopeteApplication::newInstance() { // kDebug(14000) ; handleURLArgs(); return KUniqueApplication::newInstance(); } void KopeteApplication::handleURLArgs() { KCmdLineArgs *args = KCmdLineArgs::parsedArgs(); // kDebug(14000) << "called with " << args->count() << " arguments to handle."; if ( args->count() > 0 ) { for ( int i = 0; i < args->count(); i++ ) { KUrl u( args->url( i ) ); if ( !u.isValid() ) continue; Kopete::MimeTypeHandler::dispatchURL( u ); } // END for() } // END args->count() > 0 } void KopeteApplication::quitKopete() { kDebug( 14000 ) ; m_isShuttingDown = true; // close all windows QList<KMainWindow*> members = KMainWindow::memberList(); QList<KMainWindow*>::iterator it, itEnd = members.end(); for ( it = members.begin(); it != itEnd; ++it) { if ( (*it)->close() ) { m_isShuttingDown = false; break; } } } void KopeteApplication::commitData( QSessionManager &sm ) { m_isShuttingDown = true; KUniqueApplication::commitData( sm ); } #include "kopeteapplication.moc" // vim: set noet ts=4 sts=4 sw=4: <|endoftext|>
<commit_before>#ifndef CORE_HPP #define CORE_HPP #include "CallBackWrapper.hpp" class IOService; class IONotifier; namespace org_pqrs_Karabiner { class ParamsUnion; namespace Core { void start(void); void stop(void); // ---------------------------------------------------------------------- bool IOHIKeyboard_gIOMatchedNotification_callback(void* target, void* refCon, IOService* newService, IONotifier* notifier); bool IOHIKeyboard_gIOTerminatedNotification_callback(void* target, void* refCon, IOService* newService, IONotifier* notifier); bool IOHIPointing_gIOMatchedNotification_callback(void* target, void* refCon, IOService* newService, IONotifier* notifier); bool IOHIPointing_gIOTerminatedNotification_callback(void* target, void* refCon, IOService* newService, IONotifier* notifier); // ---------------------------------------------------------------------- void remap_KeyboardEventCallback(const Params_Base& paramsBase); void remap_KeyboardSpecialEventCallback(const Params_Base& paramsBase); void remap_RelativePointerEventCallback(const Params_Base& paramsBase); void remap_ScrollWheelEventCallback(const Params_Base& paramsBase); }; } #endif <commit_msg>clean up<commit_after>#ifndef CORE_HPP #define CORE_HPP #include "CallBackWrapper.hpp" class IOService; class IONotifier; namespace org_pqrs_Karabiner { namespace Core { void start(void); void stop(void); // ---------------------------------------------------------------------- bool IOHIKeyboard_gIOMatchedNotification_callback(void* target, void* refCon, IOService* newService, IONotifier* notifier); bool IOHIKeyboard_gIOTerminatedNotification_callback(void* target, void* refCon, IOService* newService, IONotifier* notifier); bool IOHIPointing_gIOMatchedNotification_callback(void* target, void* refCon, IOService* newService, IONotifier* notifier); bool IOHIPointing_gIOTerminatedNotification_callback(void* target, void* refCon, IOService* newService, IONotifier* notifier); // ---------------------------------------------------------------------- void remap_KeyboardEventCallback(const Params_Base& paramsBase); void remap_KeyboardSpecialEventCallback(const Params_Base& paramsBase); void remap_RelativePointerEventCallback(const Params_Base& paramsBase); void remap_ScrollWheelEventCallback(const Params_Base& paramsBase); }; } #endif <|endoftext|>
<commit_before>/** * @file * @brief Implementation of logger * * @copyright MIT License */ #include "log.h" #include <algorithm> #include <array> #include <chrono> #include <exception> #include <iomanip> #include <iostream> #include <ostream> #include <string> #include <unistd.h> using namespace allpix; // Last name used while printing (for identifying process logs) std::string DefaultLogger::last_identifier_; // Last message send used to check if extra spaces are needed std::string DefaultLogger::last_message_; /** * The logger will save the number of uncaught exceptions during construction to compare that with the number of exceptions * during destruction later. */ DefaultLogger::DefaultLogger() : exception_count_(get_uncaught_exceptions(true)) {} /** * The output is written to the streams as soon as the logger gets out-of-scope and desctructed. The destructor checks * specifically if an exception is thrown while output is written to the stream. In that case the log stream will not be * forwarded to the output streams and the message will be discarded. */ DefaultLogger::~DefaultLogger() { // Check if an exception is thrown while adding output to the stream if(exception_count_ != get_uncaught_exceptions(false)) { return; } // TODO [doc] any extra exceptions here need to be catched // Get output string std::string out(os.str()); // Replace every newline by indented code if necessary auto start_pos = out.find('\n'); if(start_pos != std::string::npos) { std::string spcs(indent_count_ + 1, ' '); spcs[0] = '\n'; do { out.replace(start_pos, 1, spcs); start_pos += spcs.length(); } while((start_pos = out.find('\n', start_pos)) != std::string::npos); } // Add extra spaces if necessary size_t extra_spaces = 0; if(!identifier_.empty() && last_identifier_ == identifier_) { // Put carriage return for process logs out = '\r' + out; // Set extra spaces to fully cover previous message if(last_message_.size() > out.size()) { extra_spaces = last_message_.size() - out.size(); } } else if(!last_identifier_.empty()) { // End process log and continue normal logging out = '\n' + out; } last_identifier_ = identifier_; // Save last message last_message_ = out; last_message_ += " "; // Add extra spaces if required if(extra_spaces > 0) { out += std::string(extra_spaces, ' '); } // Add final newline if not a progress log if(identifier_.empty()) { out += '\n'; } // Create a version without any special terminal characters std::string out_no_special; size_t prev = 0, pos = 0; while((pos = out.find("\x1B[", prev)) != std::string::npos) { out_no_special += out.substr(prev, pos - prev); prev = out.find("m", pos) + 1; if(prev == std::string::npos) break; } out_no_special += out.substr(prev); // Print output to streams for(auto stream : get_streams()) { if(is_terminal(*stream)) { (*stream) << out; } else { (*stream) << out_no_special; } (*stream).flush(); } } /** * @warning No other log message should be send after this method * @note Does not close the streams */ void DefaultLogger::finish() { if(!last_identifier_.empty()) { // Flush final line if necessary for(auto stream : get_streams()) { (*stream) << std::endl; (*stream).flush(); } } last_identifier_ = ""; last_message_ = ""; // Enable cursor again if stream supports it for(auto stream : get_streams()) { if(is_terminal(*stream)) { (*stream) << "\x1B[?25h"; } } } /** * This method is typically automatically called by the \ref LOG macro to return a stream after constructing the logger. The * header of the stream is added before returning the output stream. */ std::ostringstream& DefaultLogger::getStream(LogLevel level, const std::string& file, const std::string& function, uint32_t line) { // Add date in all except short format if(get_format() != LogFormat::SHORT) { os << "\x1B[1m"; // BOLD os << "|" << get_current_date() << "| "; os << "\x1B[0m"; // RESET } // Set color for log level if(level == LogLevel::FATAL || level == LogLevel::ERROR) { os << "\x1B[31;1m"; // RED } else if(level == LogLevel::WARNING) { os << "\x1B[33;1m"; // YELLOW } else if(level == LogLevel::TRACE || level == LogLevel::DEBUG) { os << "\x1B[36m"; // NON-BOLD CYAN } else { os << "\x1B[36;1m"; // CYAN } // Add log level (shortly in the short format) if(get_format() != LogFormat::SHORT) { std::string level_str = "("; level_str += getStringFromLevel(level); level_str += ")"; os << std::setw(9) << level_str << " "; } else { os << "(" << getStringFromLevel(level).substr(0, 1) << ") "; } os << "\x1B[0m"; // RESET // Add section if available if(!get_section().empty()) { os << "\x1B[1m"; // BOLD os << "[" << get_section() << "] "; os << "\x1B[0m"; // RESET } // Print function name and line number information in debug format if(get_format() == LogFormat::LONG) { os << "\x1B[1m"; // BOLD os << "<" << file << "/" << function << ":L" << line << "> "; os << "\x1B[0m"; // RESET } // Save the indent count to fix with newlines indent_count_ = static_cast<unsigned int>(os.str().size()); return os; } /** * @throws std::invalid_argument If an empty identifier is provided * * This method is typically automatically called by the \ref LOG_PROCESS macro. */ std::ostringstream& DefaultLogger::getProcessStream( const std::string& identifier, LogLevel level, const std::string& file, const std::string& function, uint32_t line) { // Get the standard process stream std::ostringstream& stream = getStream(level, file, function, line); // Save the identifier to indicate a progress log if(identifier.empty()) { throw std::invalid_argument("the process log identifier cannot be empty"); } identifier_ = identifier; return stream; } // Getter and setters for the reporting level LogLevel& DefaultLogger::get_reporting_level() { static LogLevel reporting_level = LogLevel::INFO; return reporting_level; } void DefaultLogger::setReportingLevel(LogLevel level) { get_reporting_level() = level; } LogLevel DefaultLogger::getReportingLevel() { return get_reporting_level(); } // String to LogLevel conversions and vice versa std::string DefaultLogger::getStringFromLevel(LogLevel level) { static const std::array<std::string, 7> type = {{"FATAL", "QUIET", "ERROR", "WARNING", "INFO", "DEBUG", "TRACE"}}; return type.at(static_cast<decltype(type)::size_type>(level)); } /** * @throws std::invalid_argument If the string does not correspond with an existing log level */ LogLevel DefaultLogger::getLevelFromString(const std::string& level) { if(level == "TRACE") { return LogLevel::TRACE; } if(level == "DEBUG") { return LogLevel::DEBUG; } if(level == "INFO") { return LogLevel::INFO; } if(level == "WARNING") { return LogLevel::WARNING; } if(level == "ERROR") { return LogLevel::ERROR; } if(level == "QUIET") { return LogLevel::QUIET; } if(level == "FATAL") { return LogLevel::FATAL; } throw std::invalid_argument("unknown log level"); } // Getter and setters for the format LogFormat& DefaultLogger::get_format() { static LogFormat reporting_level = LogFormat::DEFAULT; return reporting_level; } void DefaultLogger::setFormat(LogFormat level) { get_format() = level; } LogFormat DefaultLogger::getFormat() { return get_format(); } // Convert string to log format and vice versa std::string DefaultLogger::getStringFromFormat(LogFormat format) { static const std::array<std::string, 3> type = {{"SHORT", "DEFAULT", "LONG"}}; return type.at(static_cast<decltype(type)::size_type>(format)); } /** * @throws std::invalid_argument If the string does not correspond with an existing log format */ LogFormat DefaultLogger::getFormatFromString(const std::string& format) { if(format == "SHORT") { return LogFormat::SHORT; } if(format == "DEFAULT") { return LogFormat::DEFAULT; } if(format == "LONG") { return LogFormat::LONG; } throw std::invalid_argument("unknown log format"); } /** * The streams are shared by all logger instantiations. */ const std::vector<std::ostream*>& DefaultLogger::getStreams() { return get_streams(); } std::vector<std::ostream*>& DefaultLogger::get_streams() { static std::vector<std::ostream*> streams; return streams; } void DefaultLogger::clearStreams() { get_streams().clear(); } /** * The caller has to make sure that the added ostream exists for as long log messages may be written. The std::cout stream is * added automatically to the list of streams and does not need to be added itself. * * @note Streams cannot be individually removed at the moment and only all at once using \ref clearStreams(). */ void DefaultLogger::addStream(std::ostream& stream) { // Disable cursor if stream supports it if(is_terminal(stream)) { stream << "\x1B[?25l"; } get_streams().push_back(&stream); } // Getters and setters for the section header std::string& DefaultLogger::get_section() { static std::string section; return section; } void DefaultLogger::setSection(std::string section) { get_section() = std::move(section); } std::string DefaultLogger::getSection() { return get_section(); } /** * The date is returned in the hh:mm:ss.ms format */ std::string DefaultLogger::get_current_date() { // FIXME: revise this to get microseconds in a better way auto now = std::chrono::system_clock::now(); auto in_time_t = std::chrono::system_clock::to_time_t(now); std::stringstream ss; ss << std::put_time(std::localtime(&in_time_t), "%X"); auto seconds_from_epoch = std::chrono::duration_cast<std::chrono::seconds>(now.time_since_epoch()); auto millis = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch() - seconds_from_epoch).count(); ss << "."; ss << std::setfill('0') << std::setw(3); ss << millis; return ss.str(); } /* * It is impossible to know for sure a terminal has support for all extra terminal features, but every modern terminal has * this so we just assume it. */ bool DefaultLogger::is_terminal(std::ostream& stream) { if(&std::cout == &stream) { return isatty(fileno(stdout)); } else if(&std::cerr == &stream) { return isatty(fileno(stderr)); } return false; } /** * The number of uncaught exceptions can only be properly determined in C++17. In earlier versions it is only possible to * check if there is at least a single exception thrown and that function is used instead. This means a return value of zero * corresponds to no exception and one to at least one exception. */ int DefaultLogger::get_uncaught_exceptions(bool cons = false) { #if __cplusplus > 201402L // we can only do this fully correctly in C++17 return std::uncaught_exceptions(); #else if(cons) { return 0; } return static_cast<int>(std::uncaught_exception()); #endif } <commit_msg>fix indent from logger<commit_after>/** * @file * @brief Implementation of logger * * @copyright MIT License */ #include "log.h" #include <algorithm> #include <array> #include <chrono> #include <exception> #include <iomanip> #include <iostream> #include <ostream> #include <string> #include <unistd.h> using namespace allpix; // Last name used while printing (for identifying process logs) std::string DefaultLogger::last_identifier_; // Last message send used to check if extra spaces are needed std::string DefaultLogger::last_message_; /** * The logger will save the number of uncaught exceptions during construction to compare that with the number of exceptions * during destruction later. */ DefaultLogger::DefaultLogger() : exception_count_(get_uncaught_exceptions(true)) {} /** * The output is written to the streams as soon as the logger gets out-of-scope and desctructed. The destructor checks * specifically if an exception is thrown while output is written to the stream. In that case the log stream will not be * forwarded to the output streams and the message will be discarded. */ DefaultLogger::~DefaultLogger() { // Check if an exception is thrown while adding output to the stream if(exception_count_ != get_uncaught_exceptions(false)) { return; } // TODO [doc] any extra exceptions here need to be catched // Get output string std::string out(os.str()); // Replace every newline by indented code if necessary auto start_pos = out.find('\n'); if(start_pos != std::string::npos) { std::string spcs(indent_count_ + 1, ' '); spcs[0] = '\n'; do { out.replace(start_pos, 1, spcs); start_pos += spcs.length(); } while((start_pos = out.find('\n', start_pos)) != std::string::npos); } // Add extra spaces if necessary size_t extra_spaces = 0; if(!identifier_.empty() && last_identifier_ == identifier_) { // Put carriage return for process logs out = '\r' + out; // Set extra spaces to fully cover previous message if(last_message_.size() > out.size()) { extra_spaces = last_message_.size() - out.size(); } } else if(!last_identifier_.empty()) { // End process log and continue normal logging out = '\n' + out; } last_identifier_ = identifier_; // Save last message last_message_ = out; last_message_ += " "; // Add extra spaces if required if(extra_spaces > 0) { out += std::string(extra_spaces, ' '); } // Add final newline if not a progress log if(identifier_.empty()) { out += '\n'; } // Create a version without any special terminal characters std::string out_no_special; size_t prev = 0, pos = 0; while((pos = out.find("\x1B[", prev)) != std::string::npos) { out_no_special += out.substr(prev, pos - prev); prev = out.find("m", pos) + 1; if(prev == std::string::npos) { break; } } out_no_special += out.substr(prev); // Print output to streams for(auto stream : get_streams()) { if(is_terminal(*stream)) { (*stream) << out; } else { (*stream) << out_no_special; } (*stream).flush(); } } /** * @warning No other log message should be send after this method * @note Does not close the streams */ void DefaultLogger::finish() { if(!last_identifier_.empty()) { // Flush final line if necessary for(auto stream : get_streams()) { (*stream) << std::endl; (*stream).flush(); } } last_identifier_ = ""; last_message_ = ""; // Enable cursor again if stream supports it for(auto stream : get_streams()) { if(is_terminal(*stream)) { (*stream) << "\x1B[?25h"; } } } /** * This method is typically automatically called by the \ref LOG macro to return a stream after constructing the logger. The * header of the stream is added before returning the output stream. */ std::ostringstream& DefaultLogger::getStream(LogLevel level, const std::string& file, const std::string& function, uint32_t line) { // Add date in all except short format if(get_format() != LogFormat::SHORT) { os << "\x1B[1m"; // BOLD os << "|" << get_current_date() << "| "; os << "\x1B[0m"; // RESET } // Set color for log level if(level == LogLevel::FATAL || level == LogLevel::ERROR) { os << "\x1B[31;1m"; // RED } else if(level == LogLevel::WARNING) { os << "\x1B[33;1m"; // YELLOW } else if(level == LogLevel::TRACE || level == LogLevel::DEBUG) { os << "\x1B[36m"; // NON-BOLD CYAN } else { os << "\x1B[36;1m"; // CYAN } // Add log level (shortly in the short format) if(get_format() != LogFormat::SHORT) { std::string level_str = "("; level_str += getStringFromLevel(level); level_str += ")"; os << std::setw(9) << level_str << " "; } else { os << "(" << getStringFromLevel(level).substr(0, 1) << ") "; } os << "\x1B[0m"; // RESET // Add section if available if(!get_section().empty()) { os << "\x1B[1m"; // BOLD os << "[" << get_section() << "] "; os << "\x1B[0m"; // RESET } // Print function name and line number information in debug format if(get_format() == LogFormat::LONG) { os << "\x1B[1m"; // BOLD os << "<" << file << "/" << function << ":L" << line << "> "; os << "\x1B[0m"; // RESET } // Save the indent count to fix with newlines size_t prev = 0, pos = 0; std::string out = os.str(); while((pos = out.find("\x1B[", prev)) != std::string::npos) { indent_count_ += static_cast<unsigned int>(pos - prev); prev = out.find("m", pos) + 1; if(prev == std::string::npos) { break; } } return os; } /** * @throws std::invalid_argument If an empty identifier is provided * * This method is typically automatically called by the \ref LOG_PROCESS macro. */ std::ostringstream& DefaultLogger::getProcessStream( const std::string& identifier, LogLevel level, const std::string& file, const std::string& function, uint32_t line) { // Get the standard process stream std::ostringstream& stream = getStream(level, file, function, line); // Save the identifier to indicate a progress log if(identifier.empty()) { throw std::invalid_argument("the process log identifier cannot be empty"); } identifier_ = identifier; return stream; } // Getter and setters for the reporting level LogLevel& DefaultLogger::get_reporting_level() { static LogLevel reporting_level = LogLevel::INFO; return reporting_level; } void DefaultLogger::setReportingLevel(LogLevel level) { get_reporting_level() = level; } LogLevel DefaultLogger::getReportingLevel() { return get_reporting_level(); } // String to LogLevel conversions and vice versa std::string DefaultLogger::getStringFromLevel(LogLevel level) { static const std::array<std::string, 7> type = {{"FATAL", "QUIET", "ERROR", "WARNING", "INFO", "DEBUG", "TRACE"}}; return type.at(static_cast<decltype(type)::size_type>(level)); } /** * @throws std::invalid_argument If the string does not correspond with an existing log level */ LogLevel DefaultLogger::getLevelFromString(const std::string& level) { if(level == "TRACE") { return LogLevel::TRACE; } if(level == "DEBUG") { return LogLevel::DEBUG; } if(level == "INFO") { return LogLevel::INFO; } if(level == "WARNING") { return LogLevel::WARNING; } if(level == "ERROR") { return LogLevel::ERROR; } if(level == "QUIET") { return LogLevel::QUIET; } if(level == "FATAL") { return LogLevel::FATAL; } throw std::invalid_argument("unknown log level"); } // Getter and setters for the format LogFormat& DefaultLogger::get_format() { static LogFormat reporting_level = LogFormat::DEFAULT; return reporting_level; } void DefaultLogger::setFormat(LogFormat level) { get_format() = level; } LogFormat DefaultLogger::getFormat() { return get_format(); } // Convert string to log format and vice versa std::string DefaultLogger::getStringFromFormat(LogFormat format) { static const std::array<std::string, 3> type = {{"SHORT", "DEFAULT", "LONG"}}; return type.at(static_cast<decltype(type)::size_type>(format)); } /** * @throws std::invalid_argument If the string does not correspond with an existing log format */ LogFormat DefaultLogger::getFormatFromString(const std::string& format) { if(format == "SHORT") { return LogFormat::SHORT; } if(format == "DEFAULT") { return LogFormat::DEFAULT; } if(format == "LONG") { return LogFormat::LONG; } throw std::invalid_argument("unknown log format"); } /** * The streams are shared by all logger instantiations. */ const std::vector<std::ostream*>& DefaultLogger::getStreams() { return get_streams(); } std::vector<std::ostream*>& DefaultLogger::get_streams() { static std::vector<std::ostream*> streams; return streams; } void DefaultLogger::clearStreams() { get_streams().clear(); } /** * The caller has to make sure that the added ostream exists for as long log messages may be written. The std::cout stream is * added automatically to the list of streams and does not need to be added itself. * * @note Streams cannot be individually removed at the moment and only all at once using \ref clearStreams(). */ void DefaultLogger::addStream(std::ostream& stream) { // Disable cursor if stream supports it if(is_terminal(stream)) { stream << "\x1B[?25l"; } get_streams().push_back(&stream); } // Getters and setters for the section header std::string& DefaultLogger::get_section() { static std::string section; return section; } void DefaultLogger::setSection(std::string section) { get_section() = std::move(section); } std::string DefaultLogger::getSection() { return get_section(); } /** * The date is returned in the hh:mm:ss.ms format */ std::string DefaultLogger::get_current_date() { // FIXME: revise this to get microseconds in a better way auto now = std::chrono::system_clock::now(); auto in_time_t = std::chrono::system_clock::to_time_t(now); std::stringstream ss; ss << std::put_time(std::localtime(&in_time_t), "%X"); auto seconds_from_epoch = std::chrono::duration_cast<std::chrono::seconds>(now.time_since_epoch()); auto millis = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch() - seconds_from_epoch).count(); ss << "."; ss << std::setfill('0') << std::setw(3); ss << millis; return ss.str(); } /* * It is impossible to know for sure a terminal has support for all extra terminal features, but every modern terminal has * this so we just assume it. */ bool DefaultLogger::is_terminal(std::ostream& stream) { if(&std::cout == &stream) { return isatty(fileno(stdout)); } else if(&std::cerr == &stream) { return isatty(fileno(stderr)); } return false; } /** * The number of uncaught exceptions can only be properly determined in C++17. In earlier versions it is only possible to * check if there is at least a single exception thrown and that function is used instead. This means a return value of zero * corresponds to no exception and one to at least one exception. */ int DefaultLogger::get_uncaught_exceptions(bool cons = false) { #if __cplusplus > 201402L // we can only do this fully correctly in C++17 return std::uncaught_exceptions(); #else if(cons) { return 0; } return static_cast<int>(std::uncaught_exception()); #endif } <|endoftext|>
<commit_before>#include "connection.hpp" #include <boost/thread.hpp> #include <thread> #include <chrono> using boost::asio::ip::tcp; namespace libircppclient { void connection::connect() { /* * Resolve the host and generate a list of endpoints. * An endpoint is the information used to connect to an address. * An address may have more than one endpoint. */ tcp::resolver r(io_service_); tcp::resolver::query query(addr_, port_); tcp::resolver::iterator endpt_it = r.resolve(query); /* Denotes the end of the list of generated endpoints. */ decltype(endpt_it) end; /* Default error */ boost::system::error_code error = boost::asio::error::host_not_found; /* Iterate until we've reached the end of the list. */ while (endpt_it != end) { if (!error) break; socket_.close(); socket_.connect(*endpt_it++, error); } if (error) throw error; } void connection::connect(const std::string &addr, const std::string &port) { /* Perfect place to implement check of valid data */ addr_ = addr; port_ = port; connect(); } void connection::run() { //std::thread write_handler_thread(write_handler_); std::thread ping_handler_thread(ping_handler); /* * Start an asynchronous read thread going through connection::read(). * Pass the arguments (this, _1, _2) to the handler. */ socket_.async_read_some(boost::asio::buffer(buffer_), boost::bind(&connection::read, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred())); io_service_.run(); /* Remain at this point until we do not need the connection any more. */ ping_handler_thread.join(); } void connection::ping() { using namespace std::literals; while (do_ping) { /* Arbitrary interval decided by mimicing WeeChat. */ std::this_thread::sleep_for(1min + 30s); std::cout << "[info] Pinging " << addr_ << '.' << std::endl; write("PING " + addr_); } } void connection::write(const std::string &content) { /* * The IRC protocol specifies that all messages sent to the server * must be terminated with CR-LF (Carriage Return - Line Feed) */ boost::asio::write(socket_, boost::asio::buffer(content + "\r\n")); } void connection::read(const boost::system::error_code &error, std::size_t length) { if (error) { /* Unable to read from server. */ throw error; } else { /* * Works in synergy with socket::async_read_some(). * * Copy the data within the buffer and the length of it * and pass it to the class' read_handler. */ read_handler_(std::string(buffer_.data(), length)); /* * Start an asynchronous recursive read thread. * * Read data from the IRC server into the buffer, and * call this function again. * * Pass the eventual error and the message length. */ socket_.async_read_some(boost::asio::buffer(buffer_), boost::bind(&connection::read, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); } } void connection::stop() { socket_.close(); io_service_.stop(); } /* ns libircppclient */ } <commit_msg>Placed overloaded connect() above non-overloaded<commit_after>#include "connection.hpp" #include <boost/thread.hpp> #include <thread> #include <chrono> using boost::asio::ip::tcp; namespace libircppclient { void connection::connect(const std::string &addr, const std::string &port) { /* Perfect place to implement check of valid data */ addr_ = addr; port_ = port; connect(); } void connection::connect() { /* * Resolve the host and generate a list of endpoints. * An endpoint is the information used to connect to an address. * An address may have more than one endpoint. */ tcp::resolver r(io_service_); tcp::resolver::query query(addr_, port_); tcp::resolver::iterator endpt_it = r.resolve(query); /* Denotes the end of the list of generated endpoints. */ decltype(endpt_it) end; /* Default error */ boost::system::error_code error = boost::asio::error::host_not_found; /* Iterate until we've reached the end of the list. */ while (endpt_it != end) { if (!error) break; socket_.close(); socket_.connect(*endpt_it++, error); } if (error) throw error; } void connection::run() { //std::thread write_handler_thread(write_handler_); std::thread ping_handler_thread(ping_handler); /* * Start an asynchronous read thread going through connection::read(). * Pass the arguments (this, _1, _2) to the handler. */ socket_.async_read_some(boost::asio::buffer(buffer_), boost::bind(&connection::read, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred())); io_service_.run(); /* Remain at this point until we do not need the connection any more. */ ping_handler_thread.join(); } void connection::ping() { using namespace std::literals; while (do_ping) { /* Arbitrary interval decided by mimicing WeeChat. */ std::this_thread::sleep_for(1min + 30s); std::cout << "[info] Pinging " << addr_ << '.' << std::endl; write("PING " + addr_); } } void connection::write(const std::string &content) { /* * The IRC protocol specifies that all messages sent to the server * must be terminated with CR-LF (Carriage Return - Line Feed) */ boost::asio::write(socket_, boost::asio::buffer(content + "\r\n")); } void connection::read(const boost::system::error_code &error, std::size_t length) { if (error) { /* Unable to read from server. */ throw error; } else { /* * Works in synergy with socket::async_read_some(). * * Copy the data within the buffer and the length of it * and pass it to the class' read_handler. */ read_handler_(std::string(buffer_.data(), length)); /* * Start an asynchronous recursive read thread. * * Read data from the IRC server into the buffer, and * call this function again. * * Pass the eventual error and the message length. */ socket_.async_read_some(boost::asio::buffer(buffer_), boost::bind(&connection::read, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); } } void connection::stop() { socket_.close(); io_service_.stop(); } /* ns libircppclient */ } <|endoftext|>
<commit_before> #include "Logger.h" #include "event_loop.h" #include "client_service.h" #include "kernel.h" #include "Topic.h" #include "IOLoop.h" #include "IOHandle.h" #include "io_connector.h" #include <Logger.h> #include <sstream> #include <condition_variable> #include <mutex> #include <queue> #include <list> #include <iostream> #include <unistd.h> #include <string.h> #include <sys/time.h> #include <getopt.h> /* for getopt_long; standard getopt is in unistd.h */ std::shared_ptr<XXX::router_conn> rconn; XXX::Logger * logger = new XXX::ConsoleLogger(XXX::ConsoleLogger::eStdout, XXX::Logger::eAll, true); std::unique_ptr<XXX::kernel> g_kernel; struct user_options { std::string addr; std::string port; std::string cmd; std::list< std::string > cmdargs; std::list< std::string > subscribe_topics; std::string publish_topic; std::string publish_message; std::string register_procedure; std::string call_procedure; int verbose; user_options() : verbose(0) { } } uopts; //---------------------------------------------------------------------- std::string util_strerror(int e) { std::string retval; char errbuf[256]; memset(errbuf, 0, sizeof(errbuf)); /* TODO: here I should be using the proper feature tests for the XSI implementation of strerror_r . See man page. (_POSIX_C_SOURCE >= 200112L || _XOPEN_SOURCE >= 600) && ! _GNU_SOURCE */ #ifdef _GNU_SOURCE // the GNU implementation might not write to errbuf, so instead, always use // the return value. return ::strerror_r(e, errbuf, sizeof(errbuf)-1); #else // XSI implementation if (::strerror_r(e, errbuf, sizeof(errbuf)-1) == 0) return errbuf; #endif return "unknown"; } std::mutex g_active_session_mutex; std::condition_variable g_active_session_condition; bool g_active_session_notifed = false; enum AdminEvent { eNone, eRPCSent, eReplyReceived, }; std::mutex event_queue_mutex; std::condition_variable event_queue_condition; std::queue< AdminEvent > event_queue; struct callback_t { callback_t(XXX::kernel* s, const char* d) : svc(s), request(d) { } XXX::kernel* svc; const char* request; }; void procedure_cb(XXX::invoke_details& invocation) { const callback_t* cbdata = (callback_t*) invocation.user; /* called when a procedure within a CALLEE is triggered */ auto __logptr = logger; _INFO_ ("CALLEE has procuedure '"<< invocation.uri << "' invoked, args: " << invocation.args.args_list << ", user:" << cbdata->request ); // example of making a call back into the connection object during a callback rconn->publish("call", jalson::json_object(), XXX::wamp_args()); auto my_args = invocation.args; my_args.args_list = jalson::json_array(); jalson::json_array & arr = my_args.args_list.as_array(); arr.push_back("hello"); arr.push_back("back"); invocation.yield_fn(my_args); // now delete // std::cout << "deleting this connection from user space\n"; // rconn.reset(); } void call_cb(XXX::wamp_call_result r) { auto __logptr = logger; const char* msg = ( const char* ) r.user; if (r.was_error) { _INFO_( "received error, error=" << r.error_uri << ", args=" << r.args.args_list << ", cb_user_data: " << msg << ", reqid: " << r.reqid << ", proc:" << r.procedure ); } else { _INFO_( "received result, args=" << r.args.args_list << ", cb_user_data: " << msg << ", reqid: " << r.reqid << ", proc:" << r.procedure ); } std::unique_lock< std::mutex > guard( event_queue_mutex ); event_queue.push( eReplyReceived ); event_queue_condition.notify_one(); } /* called upon subscribed and update events */ void subscribe_cb(XXX::subscription_event_type evtype, const std::string& /* uri */, const jalson::json_object& /* details */, const jalson::json_array& args_list, const jalson::json_object& args_dict, void* /*user*/) { std::cout << "received topic update!!! evtype: " << evtype << ", args_list: " << args_list << ", args_dict:" << args_dict << "\n"; } int g_connect_status = 0; void router_connection_cb(XXX::router_conn* /*router_session*/, int errcode, bool is_open) { std::lock_guard<std::mutex> guard(g_active_session_mutex); auto __logptr = logger; _INFO_ ("router connection is " << (is_open? "open" : "closed") << ", errcode " << errcode); g_connect_status = errcode; g_active_session_notifed = true; g_active_session_condition.notify_all(); } static void die(const char* e) { std::cout << e << std::endl; exit( 1 ); } static void usage() { exit(0); } static void version() { // std::cout << PACKAGE_VERSION << std::endl; exit(0)l exit(0); } static void process_options(int argc, char** argv) { /* struct option { const char *name; int has_arg; int *flag; int val; }; */ // int digit_optind = 0; static struct option long_options[] = { {"help", no_argument, 0, 'h'}, {"version", no_argument, 0, 'v'}, {"subscribe", required_argument, 0, 's'}, {"publish", required_argument, 0, 'p'}, {"register", required_argument, 0, 'r'}, {"call", required_argument, 0, 'c'}, {"msg", required_argument, 0, 'm'}, {NULL, 0, NULL, 0} }; const char* optstr="hvds:p:m:r:c:"; ::opterr=1; while (true) { /* "optind" is the index of the next element to be processed in argv. It is defined in the getopts header, and the system initializes this value to 1. The caller can reset it to 1 to restart scanning of the same argv, or when scanning a new argument vector. */ // take a copy to remember value for after return from getopt_long() //int this_option_optind = ::optind ? ::optind : 1; int long_index = 0; int c = getopt_long(argc, argv, optstr, long_options, &long_index); if (c == -1) break; switch(c) { case 0 : /* got long option */; break; case 'd' : uopts.verbose++; break; case 'h' : usage(); case 'v' : version(); case 's' : uopts.subscribe_topics.push_back(optarg); break; case 'p' : uopts.publish_topic = optarg; break; case 'm' : uopts.publish_message = optarg; break; case 'r' : uopts.register_procedure = optarg; break; case 'c' : uopts.call_procedure = optarg; break; case '?' : exit(1); // invalid option default: { std::cout << "getopt_long() returned (dec) " << (unsigned int)(c) << "\n"; exit(1); } } } //while if (optind < argc) uopts.addr = argv[optind++]; if (optind < argc) uopts.port = argv[optind++]; if (optind < argc) uopts.cmd = argv[optind++]; while (optind < argc) uopts.cmdargs.push_back(argv[optind++]); } std::string get_timestamp() { // get current time timeval now; struct timezone * const tz = NULL; /* not used on Linux */ gettimeofday(&now, tz); struct tm _tm; localtime_r(&now.tv_sec, &_tm); std::ostringstream os; os << _tm.tm_hour << ":" << _tm.tm_min << ":" << _tm.tm_sec; return os.str(); } int main(int argc, char** argv) { process_options(argc, argv); g_kernel.reset( new XXX::kernel(logger) ); g_kernel->start(); // after this, conn will immediately make an attempt to connect. Note the // object is a source of async events (the connect and disconnect call back). std::shared_ptr<XXX::io_connector> conn = g_kernel->get_io()->add_connection("t420", "55555", false); auto connect_fut = conn->get_future(); // TODO: need to delay the IO handle read, before wamp_session is ready to // receive callbacks std::unique_ptr<XXX::IOHandle> up_handle; try { std::future_status status; do { status = connect_fut.wait_for(std::chrono::seconds(5)); if (status == std::future_status::timeout) { std::cout << "timed out when trying to connect, cancelling" << std::endl; conn->async_cancel(); } } while (status != std::future_status::ready); up_handle = connect_fut.get(); if (!up_handle) { std::cout << "connect failed\n"; return 1; } } catch (std::exception & e) { std::cout << "connect failed : " << e.what() << std::endl; return 1; } /* if we reached here, the io handle is available */ //std::unique_ptr<XXX::text_topic> topic; // if (!uopts.publish_topic.empty()) // topic.reset( new XXX::text_topic( uopts.publish_topic ) ); // if (topic) g_kernel->add_topic( topic.get() ); rconn.reset( new XXX::router_conn(g_kernel.get(), "default_realm", router_connection_cb, std::move(up_handle), nullptr ) ); // wait for a connection attempt to complete auto wait_interval = std::chrono::seconds(50); { std::unique_lock<std::mutex> guard(g_active_session_mutex); bool hasevent = g_active_session_condition.wait_for(guard, wait_interval, [](){ return g_active_session_notifed; }); if (!hasevent) die("failed to obtain remote connection"); } if (g_connect_status != 0) { std::cout << "Unable to connect, error " << g_connect_status << ": " << util_strerror(g_connect_status) << "\n"; exit(1); } // TODO: take CALL parameters from command line XXX::wamp_args args; jalson::json_array ja; ja.push_back( "hello" ); ja.push_back( "world" ); args.args_list = ja ; bool long_wait = false; bool wait_reply = false; // now that we are connected, make our requests // subscribe if (! uopts.subscribe_topics.empty()) long_wait = true; for (auto & topic : uopts.subscribe_topics) rconn->subscribe(topic, jalson::json_object(), subscribe_cb, nullptr); // register std::unique_ptr<callback_t> cb1( new callback_t(g_kernel.get(),"my_hello") ); if (!uopts.register_procedure.empty()) { rconn->provide(uopts.register_procedure, jalson::json_object(), procedure_cb, (void*) cb1.get()); long_wait = true; } // publish if (!uopts.publish_topic.empty()) { XXX::wamp_args pub_args; pub_args.args_list = jalson::json_value::make_array(); pub_args.args_list.as_array().push_back(uopts.publish_message); rconn->publish(uopts.publish_topic, jalson::json_object(), pub_args); } // call if (!uopts.call_procedure.empty()) { rconn->call(uopts.call_procedure, jalson::json_object(), args, [](XXX::wamp_call_result r) { call_cb(r);}, (void*)"I_called_the_proc"); wait_reply = true; } while (long_wait || wait_reply) { std::unique_lock< std::mutex > guard( event_queue_mutex ); /*bool hasevent =*/ event_queue_condition.wait_for(guard, wait_interval, [](){ return !event_queue.empty(); }); // if (event_queue.empty()) // { // // TODO: eventually want to suppor tall kinds of errors, ie, no // // connection, no rpc, no rpc reply etc // std::cout << "timeout ... did not find the admin\n"; // break; // } while (!event_queue.empty()) { AdminEvent aev = event_queue.front(); event_queue.pop(); switch (aev) { case eNone : break; case eRPCSent : break; /* resets the timer */ case eReplyReceived : wait_reply = false; ;break; } } } int sleep_time = 3; std::cout << "sleeping for " << sleep_time << " before shutdown\n"; sleep(sleep_time); // TODO: think I need this, to give publish time to complete // orderly shutdown of the wamp_session std::cout << "requesting wamp_session closure\n"; auto fut_closed = rconn->close(); fut_closed.wait(); // while (1) sleep(10); std::cout << "dong rconn reset\n"; rconn.reset(); // TODO: this now causes core dump // remember to free the kernel and logger after all sessions are closed // (sessions might attempt logging during their destruction) g_kernel.reset(); delete logger; return 0; } <commit_msg>more detailed comments<commit_after> #include "Logger.h" #include "event_loop.h" #include "client_service.h" #include "kernel.h" #include "Topic.h" #include "IOLoop.h" #include "IOHandle.h" #include "io_connector.h" #include <Logger.h> #include <sstream> #include <condition_variable> #include <mutex> #include <queue> #include <list> #include <iostream> #include <unistd.h> #include <string.h> #include <sys/time.h> #include <getopt.h> /* for getopt_long; standard getopt is in unistd.h */ std::shared_ptr<XXX::router_conn> rconn; XXX::Logger * logger = new XXX::ConsoleLogger(XXX::ConsoleLogger::eStdout, XXX::Logger::eAll, true); std::unique_ptr<XXX::kernel> g_kernel; struct user_options { std::string addr; std::string port; std::string cmd; std::list< std::string > cmdargs; std::list< std::string > subscribe_topics; std::string publish_topic; std::string publish_message; std::string register_procedure; std::string call_procedure; int verbose; user_options() : verbose(0) { } } uopts; //---------------------------------------------------------------------- std::string util_strerror(int e) { std::string retval; char errbuf[256]; memset(errbuf, 0, sizeof(errbuf)); /* TODO: here I should be using the proper feature tests for the XSI implementation of strerror_r . See man page. (_POSIX_C_SOURCE >= 200112L || _XOPEN_SOURCE >= 600) && ! _GNU_SOURCE */ #ifdef _GNU_SOURCE // the GNU implementation might not write to errbuf, so instead, always use // the return value. return ::strerror_r(e, errbuf, sizeof(errbuf)-1); #else // XSI implementation if (::strerror_r(e, errbuf, sizeof(errbuf)-1) == 0) return errbuf; #endif return "unknown"; } std::mutex g_active_session_mutex; std::condition_variable g_active_session_condition; bool g_active_session_notifed = false; enum AdminEvent { eNone, eRPCSent, eReplyReceived, }; std::mutex event_queue_mutex; std::condition_variable event_queue_condition; std::queue< AdminEvent > event_queue; struct callback_t { callback_t(XXX::kernel* s, const char* d) : svc(s), request(d) { } XXX::kernel* svc; const char* request; }; void procedure_cb(XXX::invoke_details& invocation) { const callback_t* cbdata = (callback_t*) invocation.user; /* called when a procedure within a CALLEE is triggered */ auto __logptr = logger; _INFO_ ("CALLEE has procuedure '"<< invocation.uri << "' invoked, args: " << invocation.args.args_list << ", user:" << cbdata->request ); // example of making a call back into the connection object during a callback rconn->publish("call", jalson::json_object(), XXX::wamp_args()); auto my_args = invocation.args; my_args.args_list = jalson::json_array(); jalson::json_array & arr = my_args.args_list.as_array(); arr.push_back("hello"); arr.push_back("back"); invocation.yield_fn(my_args); // now delete // std::cout << "deleting this connection from user space\n"; // rconn.reset(); } void call_cb(XXX::wamp_call_result r) { auto __logptr = logger; const char* msg = ( const char* ) r.user; if (r.was_error) { _INFO_( "received error, error=" << r.error_uri << ", args=" << r.args.args_list << ", cb_user_data: " << msg << ", reqid: " << r.reqid << ", proc:" << r.procedure ); } else { _INFO_( "received result, args=" << r.args.args_list << ", cb_user_data: " << msg << ", reqid: " << r.reqid << ", proc:" << r.procedure ); } std::unique_lock< std::mutex > guard( event_queue_mutex ); event_queue.push( eReplyReceived ); event_queue_condition.notify_one(); } /* called upon subscribed and update events */ void subscribe_cb(XXX::subscription_event_type evtype, const std::string& /* uri */, const jalson::json_object& /* details */, const jalson::json_array& args_list, const jalson::json_object& args_dict, void* /*user*/) { std::cout << "received topic update!!! evtype: " << evtype << ", args_list: " << args_list << ", args_dict:" << args_dict << "\n"; } int g_connect_status = 0; void router_connection_cb(XXX::router_conn* /*router_session*/, int errcode, bool is_open) { std::lock_guard<std::mutex> guard(g_active_session_mutex); auto __logptr = logger; if (!is_open) std::cout << "WAMP session closed, errcode " << errcode << std::endl; g_connect_status = errcode; g_active_session_notifed = true; g_active_session_condition.notify_all(); } static void die(const char* e) { std::cout << e << std::endl; exit( 1 ); } static void usage() { exit(0); } static void version() { // std::cout << PACKAGE_VERSION << std::endl; exit(0)l exit(0); } static void process_options(int argc, char** argv) { /* struct option { const char *name; int has_arg; int *flag; int val; }; */ // int digit_optind = 0; static struct option long_options[] = { {"help", no_argument, 0, 'h'}, {"version", no_argument, 0, 'v'}, {"subscribe", required_argument, 0, 's'}, {"publish", required_argument, 0, 'p'}, {"register", required_argument, 0, 'r'}, {"call", required_argument, 0, 'c'}, {"msg", required_argument, 0, 'm'}, {NULL, 0, NULL, 0} }; const char* optstr="hvds:p:m:r:c:"; ::opterr=1; while (true) { /* "optind" is the index of the next element to be processed in argv. It is defined in the getopts header, and the system initializes this value to 1. The caller can reset it to 1 to restart scanning of the same argv, or when scanning a new argument vector. */ // take a copy to remember value for after return from getopt_long() //int this_option_optind = ::optind ? ::optind : 1; int long_index = 0; int c = getopt_long(argc, argv, optstr, long_options, &long_index); if (c == -1) break; switch(c) { case 0 : /* got long option */; break; case 'd' : uopts.verbose++; break; case 'h' : usage(); case 'v' : version(); case 's' : uopts.subscribe_topics.push_back(optarg); break; case 'p' : uopts.publish_topic = optarg; break; case 'm' : uopts.publish_message = optarg; break; case 'r' : uopts.register_procedure = optarg; break; case 'c' : uopts.call_procedure = optarg; break; case '?' : exit(1); // invalid option default: { std::cout << "getopt_long() returned (dec) " << (unsigned int)(c) << "\n"; exit(1); } } } //while if (optind < argc) uopts.addr = argv[optind++]; if (optind < argc) uopts.port = argv[optind++]; if (optind < argc) uopts.cmd = argv[optind++]; while (optind < argc) uopts.cmdargs.push_back(argv[optind++]); } std::string get_timestamp() { // get current time timeval now; struct timezone * const tz = NULL; /* not used on Linux */ gettimeofday(&now, tz); struct tm _tm; localtime_r(&now.tv_sec, &_tm); std::ostringstream os; os << _tm.tm_hour << ":" << _tm.tm_min << ":" << _tm.tm_sec; return os.str(); } int main(int argc, char** argv) { process_options(argc, argv); g_kernel.reset( new XXX::kernel(logger) ); g_kernel->start(); /* Create a socket connector. This will immediately make an attempt to * connect to the target end point. The connector object is a source of async * events (the connect and disconnect call back), and so must be managed * asynchronously. */ std::shared_ptr<XXX::io_connector> conn = g_kernel->get_io()->add_connection("t420", "55555", false); auto connect_fut = conn->get_future(); std::unique_ptr<XXX::IOHandle> up_handle; try { /* Wait until the connector has got a result. The result can be successful, * in which case a socket is available, or result could be a failure, in * which case either an exception will be available or a null pointer. */ std::future_status status; do { status = connect_fut.wait_for(std::chrono::seconds(5)); if (status == std::future_status::timeout) { std::cout << "timed out when trying to connect, cancelling" << std::endl; conn->async_cancel(); } } while (status != std::future_status::ready); /* A result is available; our socket connection could be available. */ up_handle = connect_fut.get(); if (!up_handle) { std::cout << "connect failed\n"; return 1; } } catch (std::exception & e) { std::cout << "connect failed : " << e.what() << std::endl; return 1; } /* We have obtained a socket. It's not yet being read from. We now create a * wamp_session that takes ownership of the socket, and initiates socket read * events. The wamp_session will commence the WAMP handshake; connection * success is delivered via the callback. */ rconn.reset( new XXX::router_conn(g_kernel.get(), "default_realm", router_connection_cb, std::move(up_handle), nullptr ) ); /* Wait for the WAMP session to authenticate and become open */ auto wait_interval = std::chrono::seconds(50); { std::unique_lock<std::mutex> guard(g_active_session_mutex); bool hasevent = g_active_session_condition.wait_for(guard, wait_interval, [](){ return g_active_session_notifed; }); if (!hasevent) die("failed to obtain remote connection"); } if (g_connect_status != 0) { std::cout << "Unable to connect, error " << g_connect_status << ": " << util_strerror(g_connect_status) << "\n"; exit(1); } /* WAMP session is now open */ std::cout << "WAMP session open\n"; // TODO: take CALL parameters from command line XXX::wamp_args args; jalson::json_array ja; ja.push_back( "hello" ); ja.push_back( "world" ); args.args_list = ja ; bool long_wait = false; bool wait_reply = false; // subscribe if (! uopts.subscribe_topics.empty()) long_wait = true; for (auto & topic : uopts.subscribe_topics) rconn->subscribe(topic, jalson::json_object(), subscribe_cb, nullptr); // register std::unique_ptr<callback_t> cb1( new callback_t(g_kernel.get(),"my_hello") ); if (!uopts.register_procedure.empty()) { rconn->provide(uopts.register_procedure, jalson::json_object(), procedure_cb, (void*) cb1.get()); long_wait = true; } // publish if (!uopts.publish_topic.empty()) { XXX::wamp_args pub_args; pub_args.args_list = jalson::json_value::make_array(); pub_args.args_list.as_array().push_back(uopts.publish_message); rconn->publish(uopts.publish_topic, jalson::json_object(), pub_args); } // call if (!uopts.call_procedure.empty()) { rconn->call(uopts.call_procedure, jalson::json_object(), args, [](XXX::wamp_call_result r) { call_cb(r);}, (void*)"I_called_the_proc"); wait_reply = true; } while (long_wait || wait_reply) { std::unique_lock< std::mutex > guard( event_queue_mutex ); /*bool hasevent =*/ event_queue_condition.wait_for(guard, wait_interval, [](){ return !event_queue.empty(); }); // if (event_queue.empty()) // { // // TODO: eventually want to suppor tall kinds of errors, ie, no // // connection, no rpc, no rpc reply etc // std::cout << "timeout ... did not find the admin\n"; // break; // } while (!event_queue.empty()) { AdminEvent aev = event_queue.front(); event_queue.pop(); switch (aev) { case eNone : break; case eRPCSent : break; /* resets the timer */ case eReplyReceived : wait_reply = false; ;break; } } } int sleep_time = 3; std::cout << "sleeping for " << sleep_time << " before shutdown\n"; sleep(sleep_time); // TODO: think I need this, to give publish time to complete /* Commence orderly shutdown of the wamp_session. Shutdown is an asychronous * operation so we start the request and then wait for the request to * complete. Once complete, we shall not receive anymore events from the * wamp_session object (and thus is safe to delete). */ std::cout << "requesting wamp_session closure\n"; auto fut_closed = rconn->close(); fut_closed.wait(); // while (1) sleep(10); std::cout << "dong rconn reset\n"; rconn.reset(); // TODO: this now causes core dump /* We must be mindful to free the kernel and logger only after all sessions are closed (e.g. sessions might attempt logging during their destruction) */ g_kernel.reset(); delete logger; return 0; } <|endoftext|>
<commit_before>// Copyright (c) 2009-2017 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 <core_io.h> #include <base58.h> #include <consensus/consensus.h> #include <consensus/validation.h> #include <script/script.h> #include <script/standard.h> #include <serialize.h> #include <streams.h> #include <univalue.h> #include <util.h> #include <utilmoneystr.h> #include <utilstrencodings.h> #include <spentindex.h> #include <blind.h> //extern bool GetSpentIndex(CSpentIndexKey &key, CSpentIndexValue &value); bool (*pCoreWriteGetSpentIndex)(CSpentIndexKey &key, CSpentIndexValue &value) = nullptr; // HACK, alternative is to move GetSpentIndex into common lib void SetCoreWriteGetSpentIndex(bool (*function)(CSpentIndexKey&, CSpentIndexValue&)) { pCoreWriteGetSpentIndex = function; }; UniValue ValueFromAmount(const CAmount& amount) { bool sign = amount < 0; int64_t n_abs = (sign ? -amount : amount); int64_t quotient = n_abs / COIN; int64_t remainder = n_abs % COIN; return UniValue(UniValue::VNUM, strprintf("%s%d.%08d", sign ? "-" : "", quotient, remainder)); } std::string FormatScript(const CScript& script) { std::string ret; CScript::const_iterator it = script.begin(); opcodetype op; while (it != script.end()) { CScript::const_iterator it2 = it; std::vector<unsigned char> vch; if (script.GetOp2(it, op, &vch)) { if (op == OP_0) { ret += "0 "; continue; } else if ((op >= OP_1 && op <= OP_16) || op == OP_1NEGATE) { ret += strprintf("%i ", op - OP_1NEGATE - 1); continue; } else if (op >= OP_NOP && op <= OP_NOP10) { std::string str(GetOpName(op)); if (str.substr(0, 3) == std::string("OP_")) { ret += str.substr(3, std::string::npos) + " "; continue; } } if (vch.size() > 0) { ret += strprintf("0x%x 0x%x ", HexStr(it2, it - vch.size()), HexStr(it - vch.size(), it)); } else { ret += strprintf("0x%x ", HexStr(it2, it)); } continue; } ret += strprintf("0x%x ", HexStr(it2, script.end())); break; } return ret.substr(0, ret.size() - 1); } const std::map<unsigned char, std::string> mapSigHashTypes = { {static_cast<unsigned char>(SIGHASH_ALL), std::string("ALL")}, {static_cast<unsigned char>(SIGHASH_ALL|SIGHASH_ANYONECANPAY), std::string("ALL|ANYONECANPAY")}, {static_cast<unsigned char>(SIGHASH_NONE), std::string("NONE")}, {static_cast<unsigned char>(SIGHASH_NONE|SIGHASH_ANYONECANPAY), std::string("NONE|ANYONECANPAY")}, {static_cast<unsigned char>(SIGHASH_SINGLE), std::string("SINGLE")}, {static_cast<unsigned char>(SIGHASH_SINGLE|SIGHASH_ANYONECANPAY), std::string("SINGLE|ANYONECANPAY")}, }; /** * Create the assembly string representation of a CScript object. * @param[in] script CScript object to convert into the asm string representation. * @param[in] fAttemptSighashDecode Whether to attempt to decode sighash types on data within the script that matches the format * of a signature. Only pass true for scripts you believe could contain signatures. For example, * pass false, or omit the this argument (defaults to false), for scriptPubKeys. */ std::string ScriptToAsmStr(const CScript& script, const bool fAttemptSighashDecode) { std::string str; opcodetype opcode; std::vector<unsigned char> vch; CScript::const_iterator pc = script.begin(); while (pc < script.end()) { if (!str.empty()) { str += " "; } if (!script.GetOp(pc, opcode, vch)) { str += "[error]"; return str; } if (0 <= opcode && opcode <= OP_PUSHDATA4) { if (vch.size() <= static_cast<std::vector<unsigned char>::size_type>(4)) { str += strprintf("%d", CScriptNum(vch, false).getint()); } else { // the IsUnspendable check makes sure not to try to decode OP_RETURN data that may match the format of a signature if (fAttemptSighashDecode && !script.IsUnspendable()) { std::string strSigHashDecode; // goal: only attempt to decode a defined sighash type from data that looks like a signature within a scriptSig. // this won't decode correctly formatted public keys in Pubkey or Multisig scripts due to // the restrictions on the pubkey formats (see IsCompressedOrUncompressedPubKey) being incongruous with the // checks in CheckSignatureEncoding. if (CheckSignatureEncoding(vch, SCRIPT_VERIFY_STRICTENC, nullptr)) { const unsigned char chSigHashType = vch.back(); if (mapSigHashTypes.count(chSigHashType)) { strSigHashDecode = "[" + mapSigHashTypes.find(chSigHashType)->second + "]"; vch.pop_back(); // remove the sighash type byte. it will be replaced by the decode. } } str += HexStr(vch) + strSigHashDecode; } else { str += HexStr(vch); } } } else { str += GetOpName(opcode); } } return str; } std::string EncodeHexTx(const CTransaction& tx, const int serializeFlags) { CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION | serializeFlags); ssTx << tx; return HexStr(ssTx.begin(), ssTx.end()); } void ScriptPubKeyToUniv(const CScript& scriptPubKey, UniValue& out, bool fIncludeHex) { txnouttype type; std::vector<CTxDestination> addresses; int nRequired; out.pushKV("asm", ScriptToAsmStr(scriptPubKey)); if (fIncludeHex) out.pushKV("hex", HexStr(scriptPubKey.begin(), scriptPubKey.end())); if (!ExtractDestinations(scriptPubKey, type, addresses, nRequired)) { out.pushKV("type", GetTxnOutputType(type)); return; } out.pushKV("reqSigs", nRequired); out.pushKV("type", GetTxnOutputType(type)); UniValue a(UniValue::VARR); for (const CTxDestination& addr : addresses) { a.push_back(EncodeDestination(addr)); } out.pushKV("addresses", a); } void AddRangeproof(const std::vector<uint8_t> &vRangeproof, UniValue &entry) { entry.push_back(Pair("rangeproof", HexStr(vRangeproof.begin(), vRangeproof.end()))); if (vRangeproof.size() > 0) { int exponent, mantissa; CAmount min_value, max_value; if (0 == GetRangeProofInfo(vRangeproof, exponent, mantissa, min_value, max_value)) { entry.push_back(Pair("rp_exponent", exponent)); entry.push_back(Pair("rp_mantissa", mantissa)); entry.push_back(Pair("rp_min_value", ValueFromAmount(min_value))); entry.push_back(Pair("rp_max_value", ValueFromAmount(max_value))); }; }; } void OutputToJSON(uint256 &txid, int i, const CTxOutBase *baseOut, UniValue &entry) { bool fCanSpend = false; switch (baseOut->GetType()) { case OUTPUT_STANDARD: { fCanSpend = true; entry.push_back(Pair("type", "standard")); CTxOutStandard *s = (CTxOutStandard*) baseOut; entry.push_back(Pair("value", ValueFromAmount(s->nValue))); entry.push_back(Pair("valueSat", s->nValue)); UniValue o(UniValue::VOBJ); ScriptPubKeyToUniv(s->scriptPubKey, o, true); entry.push_back(Pair("scriptPubKey", o)); } break; case OUTPUT_DATA: { CTxOutData *s = (CTxOutData*) baseOut; entry.push_back(Pair("type", "data")); entry.push_back(Pair("data_hex", HexStr(s->vData.begin(), s->vData.end()))); } break; case OUTPUT_CT: { fCanSpend = true; CTxOutCT *s = (CTxOutCT*) baseOut; entry.push_back(Pair("type", "blind")); entry.push_back(Pair("valueCommitment", HexStr(&s->commitment.data[0], &s->commitment.data[0]+33))); UniValue o(UniValue::VOBJ); ScriptPubKeyToUniv(s->scriptPubKey, o, true); entry.push_back(Pair("scriptPubKey", o)); entry.push_back(Pair("data_hex", HexStr(s->vData.begin(), s->vData.end()))); AddRangeproof(s->vRangeproof, entry); } break; case OUTPUT_RINGCT: { CTxOutRingCT *s = (CTxOutRingCT*) baseOut; entry.push_back(Pair("type", "anon")); entry.push_back(Pair("pubkey", HexStr(s->pk.begin(), s->pk.end()))); entry.push_back(Pair("valueCommitment", HexStr(&s->commitment.data[0], &s->commitment.data[0]+33))); entry.push_back(Pair("data_hex", HexStr(s->vData.begin(), s->vData.end()))); AddRangeproof(s->vRangeproof, entry); } break; default: entry.push_back(Pair("type", "unknown")); break; }; if (fCanSpend) { // Add spent information if spentindex is enabled CSpentIndexValue spentInfo; CSpentIndexKey spentKey(txid, i); if (pCoreWriteGetSpentIndex && pCoreWriteGetSpentIndex(spentKey, spentInfo)) { entry.push_back(Pair("spentTxId", spentInfo.txid.GetHex())); entry.push_back(Pair("spentIndex", (int)spentInfo.inputIndex)); entry.push_back(Pair("spentHeight", spentInfo.blockHeight)); }; }; }; void TxToUniv(const CTransaction& tx, const uint256& hashBlock, UniValue& entry, bool include_hex, int serialize_flags) { uint256 txid = tx.GetHash(); entry.pushKV("txid", txid.GetHex()); entry.pushKV("hash", tx.GetWitnessHash().GetHex()); entry.pushKV("version", tx.nVersion); entry.pushKV("size", (int)::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION)); entry.pushKV("vsize", (GetTransactionWeight(tx) + WITNESS_SCALE_FACTOR - 1) / WITNESS_SCALE_FACTOR); entry.pushKV("locktime", (int64_t)tx.nLockTime); UniValue vin(UniValue::VARR); for (unsigned int i = 0; i < tx.vin.size(); i++) { const CTxIn& txin = tx.vin[i]; UniValue in(UniValue::VOBJ); if (tx.IsCoinBase()) in.pushKV("coinbase", HexStr(txin.scriptSig.begin(), txin.scriptSig.end())); else { in.pushKV("txid", txin.prevout.hash.GetHex()); in.pushKV("vout", (int64_t)txin.prevout.n); UniValue o(UniValue::VOBJ); o.pushKV("asm", ScriptToAsmStr(txin.scriptSig, true)); o.pushKV("hex", HexStr(txin.scriptSig.begin(), txin.scriptSig.end())); in.pushKV("scriptSig", o); if (!tx.vin[i].scriptWitness.IsNull()) { UniValue txinwitness(UniValue::VARR); for (const auto& item : tx.vin[i].scriptWitness.stack) { txinwitness.push_back(HexStr(item.begin(), item.end())); } in.pushKV("txinwitness", txinwitness); } } in.pushKV("sequence", (int64_t)txin.nSequence); vin.push_back(in); } entry.pushKV("vin", vin); UniValue vout(UniValue::VARR); for (unsigned int i = 0; i < tx.vpout.size(); i++) { UniValue out(UniValue::VOBJ); out.push_back(Pair("n", (int64_t)i)); OutputToJSON(txid, i, tx.vpout[i].get(), out); vout.push_back(out); } if (!tx.IsParticlVersion()) for (unsigned int i = 0; i < tx.vout.size(); i++) { const CTxOut& txout = tx.vout[i]; UniValue out(UniValue::VOBJ); out.pushKV("value", ValueFromAmount(txout.nValue)); out.pushKV("n", (int64_t)i); UniValue o(UniValue::VOBJ); ScriptPubKeyToUniv(txout.scriptPubKey, o, true); out.pushKV("scriptPubKey", o); vout.push_back(out); } entry.pushKV("vout", vout); if (!hashBlock.IsNull()) entry.pushKV("blockhash", hashBlock.GetHex()); if (include_hex) { entry.pushKV("hex", EncodeHexTx(tx, serialize_flags)); // the hex-encoded transaction. used the name "hex" to be consistent with the verbose output of "getrawtransaction". } } <commit_msg>Display coldstake address in decoderawtransaction.<commit_after>// Copyright (c) 2009-2017 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 <core_io.h> #include <base58.h> #include <consensus/consensus.h> #include <consensus/validation.h> #include <script/script.h> #include <script/standard.h> #include <serialize.h> #include <streams.h> #include <univalue.h> #include <util.h> #include <utilmoneystr.h> #include <utilstrencodings.h> #include <spentindex.h> #include <blind.h> //extern bool GetSpentIndex(CSpentIndexKey &key, CSpentIndexValue &value); bool (*pCoreWriteGetSpentIndex)(CSpentIndexKey &key, CSpentIndexValue &value) = nullptr; // HACK, alternative is to move GetSpentIndex into common lib void SetCoreWriteGetSpentIndex(bool (*function)(CSpentIndexKey&, CSpentIndexValue&)) { pCoreWriteGetSpentIndex = function; }; UniValue ValueFromAmount(const CAmount& amount) { bool sign = amount < 0; int64_t n_abs = (sign ? -amount : amount); int64_t quotient = n_abs / COIN; int64_t remainder = n_abs % COIN; return UniValue(UniValue::VNUM, strprintf("%s%d.%08d", sign ? "-" : "", quotient, remainder)); } std::string FormatScript(const CScript& script) { std::string ret; CScript::const_iterator it = script.begin(); opcodetype op; while (it != script.end()) { CScript::const_iterator it2 = it; std::vector<unsigned char> vch; if (script.GetOp2(it, op, &vch)) { if (op == OP_0) { ret += "0 "; continue; } else if ((op >= OP_1 && op <= OP_16) || op == OP_1NEGATE) { ret += strprintf("%i ", op - OP_1NEGATE - 1); continue; } else if (op >= OP_NOP && op <= OP_NOP10) { std::string str(GetOpName(op)); if (str.substr(0, 3) == std::string("OP_")) { ret += str.substr(3, std::string::npos) + " "; continue; } } if (vch.size() > 0) { ret += strprintf("0x%x 0x%x ", HexStr(it2, it - vch.size()), HexStr(it - vch.size(), it)); } else { ret += strprintf("0x%x ", HexStr(it2, it)); } continue; } ret += strprintf("0x%x ", HexStr(it2, script.end())); break; } return ret.substr(0, ret.size() - 1); } const std::map<unsigned char, std::string> mapSigHashTypes = { {static_cast<unsigned char>(SIGHASH_ALL), std::string("ALL")}, {static_cast<unsigned char>(SIGHASH_ALL|SIGHASH_ANYONECANPAY), std::string("ALL|ANYONECANPAY")}, {static_cast<unsigned char>(SIGHASH_NONE), std::string("NONE")}, {static_cast<unsigned char>(SIGHASH_NONE|SIGHASH_ANYONECANPAY), std::string("NONE|ANYONECANPAY")}, {static_cast<unsigned char>(SIGHASH_SINGLE), std::string("SINGLE")}, {static_cast<unsigned char>(SIGHASH_SINGLE|SIGHASH_ANYONECANPAY), std::string("SINGLE|ANYONECANPAY")}, }; /** * Create the assembly string representation of a CScript object. * @param[in] script CScript object to convert into the asm string representation. * @param[in] fAttemptSighashDecode Whether to attempt to decode sighash types on data within the script that matches the format * of a signature. Only pass true for scripts you believe could contain signatures. For example, * pass false, or omit the this argument (defaults to false), for scriptPubKeys. */ std::string ScriptToAsmStr(const CScript& script, const bool fAttemptSighashDecode) { std::string str; opcodetype opcode; std::vector<unsigned char> vch; CScript::const_iterator pc = script.begin(); while (pc < script.end()) { if (!str.empty()) { str += " "; } if (!script.GetOp(pc, opcode, vch)) { str += "[error]"; return str; } if (0 <= opcode && opcode <= OP_PUSHDATA4) { if (vch.size() <= static_cast<std::vector<unsigned char>::size_type>(4)) { str += strprintf("%d", CScriptNum(vch, false).getint()); } else { // the IsUnspendable check makes sure not to try to decode OP_RETURN data that may match the format of a signature if (fAttemptSighashDecode && !script.IsUnspendable()) { std::string strSigHashDecode; // goal: only attempt to decode a defined sighash type from data that looks like a signature within a scriptSig. // this won't decode correctly formatted public keys in Pubkey or Multisig scripts due to // the restrictions on the pubkey formats (see IsCompressedOrUncompressedPubKey) being incongruous with the // checks in CheckSignatureEncoding. if (CheckSignatureEncoding(vch, SCRIPT_VERIFY_STRICTENC, nullptr)) { const unsigned char chSigHashType = vch.back(); if (mapSigHashTypes.count(chSigHashType)) { strSigHashDecode = "[" + mapSigHashTypes.find(chSigHashType)->second + "]"; vch.pop_back(); // remove the sighash type byte. it will be replaced by the decode. } } str += HexStr(vch) + strSigHashDecode; } else { str += HexStr(vch); } } } else { str += GetOpName(opcode); } } return str; } std::string EncodeHexTx(const CTransaction& tx, const int serializeFlags) { CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION | serializeFlags); ssTx << tx; return HexStr(ssTx.begin(), ssTx.end()); } void ScriptPubKeyToUniv(const CScript& scriptPubKey, UniValue& out, bool fIncludeHex) { txnouttype type; std::vector<CTxDestination> addresses; int nRequired; out.pushKV("asm", ScriptToAsmStr(scriptPubKey)); if (fIncludeHex) out.pushKV("hex", HexStr(scriptPubKey.begin(), scriptPubKey.end())); if (!ExtractDestinations(scriptPubKey, type, addresses, nRequired)) { out.pushKV("type", GetTxnOutputType(type)); return; } out.pushKV("reqSigs", nRequired); out.pushKV("type", GetTxnOutputType(type)); UniValue a(UniValue::VARR); for (const CTxDestination& addr : addresses) { a.push_back(EncodeDestination(addr)); } out.pushKV("addresses", a); if (HasIsCoinstakeOp(scriptPubKey)) { CScript scriptCS; if (GetCoinstakeScriptPath(scriptPubKey, scriptCS)) if (ExtractDestinations(scriptCS, type, addresses, nRequired)) { UniValue a(UniValue::VARR); for (const CTxDestination& addr : addresses) { a.push_back(EncodeDestination(addr)); }; out.pushKV("stakeaddresses", a); }; }; } void AddRangeproof(const std::vector<uint8_t> &vRangeproof, UniValue &entry) { entry.push_back(Pair("rangeproof", HexStr(vRangeproof.begin(), vRangeproof.end()))); if (vRangeproof.size() > 0) { int exponent, mantissa; CAmount min_value, max_value; if (0 == GetRangeProofInfo(vRangeproof, exponent, mantissa, min_value, max_value)) { entry.push_back(Pair("rp_exponent", exponent)); entry.push_back(Pair("rp_mantissa", mantissa)); entry.push_back(Pair("rp_min_value", ValueFromAmount(min_value))); entry.push_back(Pair("rp_max_value", ValueFromAmount(max_value))); }; }; } void OutputToJSON(uint256 &txid, int i, const CTxOutBase *baseOut, UniValue &entry) { bool fCanSpend = false; switch (baseOut->GetType()) { case OUTPUT_STANDARD: { fCanSpend = true; entry.push_back(Pair("type", "standard")); CTxOutStandard *s = (CTxOutStandard*) baseOut; entry.push_back(Pair("value", ValueFromAmount(s->nValue))); entry.push_back(Pair("valueSat", s->nValue)); UniValue o(UniValue::VOBJ); ScriptPubKeyToUniv(s->scriptPubKey, o, true); entry.push_back(Pair("scriptPubKey", o)); } break; case OUTPUT_DATA: { CTxOutData *s = (CTxOutData*) baseOut; entry.push_back(Pair("type", "data")); entry.push_back(Pair("data_hex", HexStr(s->vData.begin(), s->vData.end()))); } break; case OUTPUT_CT: { fCanSpend = true; CTxOutCT *s = (CTxOutCT*) baseOut; entry.push_back(Pair("type", "blind")); entry.push_back(Pair("valueCommitment", HexStr(&s->commitment.data[0], &s->commitment.data[0]+33))); UniValue o(UniValue::VOBJ); ScriptPubKeyToUniv(s->scriptPubKey, o, true); entry.push_back(Pair("scriptPubKey", o)); entry.push_back(Pair("data_hex", HexStr(s->vData.begin(), s->vData.end()))); AddRangeproof(s->vRangeproof, entry); } break; case OUTPUT_RINGCT: { CTxOutRingCT *s = (CTxOutRingCT*) baseOut; entry.push_back(Pair("type", "anon")); entry.push_back(Pair("pubkey", HexStr(s->pk.begin(), s->pk.end()))); entry.push_back(Pair("valueCommitment", HexStr(&s->commitment.data[0], &s->commitment.data[0]+33))); entry.push_back(Pair("data_hex", HexStr(s->vData.begin(), s->vData.end()))); AddRangeproof(s->vRangeproof, entry); } break; default: entry.push_back(Pair("type", "unknown")); break; }; if (fCanSpend) { // Add spent information if spentindex is enabled CSpentIndexValue spentInfo; CSpentIndexKey spentKey(txid, i); if (pCoreWriteGetSpentIndex && pCoreWriteGetSpentIndex(spentKey, spentInfo)) { entry.push_back(Pair("spentTxId", spentInfo.txid.GetHex())); entry.push_back(Pair("spentIndex", (int)spentInfo.inputIndex)); entry.push_back(Pair("spentHeight", spentInfo.blockHeight)); }; }; }; void TxToUniv(const CTransaction& tx, const uint256& hashBlock, UniValue& entry, bool include_hex, int serialize_flags) { uint256 txid = tx.GetHash(); entry.pushKV("txid", txid.GetHex()); entry.pushKV("hash", tx.GetWitnessHash().GetHex()); entry.pushKV("version", tx.nVersion); entry.pushKV("size", (int)::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION)); entry.pushKV("vsize", (GetTransactionWeight(tx) + WITNESS_SCALE_FACTOR - 1) / WITNESS_SCALE_FACTOR); entry.pushKV("locktime", (int64_t)tx.nLockTime); UniValue vin(UniValue::VARR); for (unsigned int i = 0; i < tx.vin.size(); i++) { const CTxIn& txin = tx.vin[i]; UniValue in(UniValue::VOBJ); if (tx.IsCoinBase()) in.pushKV("coinbase", HexStr(txin.scriptSig.begin(), txin.scriptSig.end())); else { in.pushKV("txid", txin.prevout.hash.GetHex()); in.pushKV("vout", (int64_t)txin.prevout.n); UniValue o(UniValue::VOBJ); o.pushKV("asm", ScriptToAsmStr(txin.scriptSig, true)); o.pushKV("hex", HexStr(txin.scriptSig.begin(), txin.scriptSig.end())); in.pushKV("scriptSig", o); if (!tx.vin[i].scriptWitness.IsNull()) { UniValue txinwitness(UniValue::VARR); for (const auto& item : tx.vin[i].scriptWitness.stack) { txinwitness.push_back(HexStr(item.begin(), item.end())); } in.pushKV("txinwitness", txinwitness); } } in.pushKV("sequence", (int64_t)txin.nSequence); vin.push_back(in); } entry.pushKV("vin", vin); UniValue vout(UniValue::VARR); for (unsigned int i = 0; i < tx.vpout.size(); i++) { UniValue out(UniValue::VOBJ); out.push_back(Pair("n", (int64_t)i)); OutputToJSON(txid, i, tx.vpout[i].get(), out); vout.push_back(out); } if (!tx.IsParticlVersion()) for (unsigned int i = 0; i < tx.vout.size(); i++) { const CTxOut& txout = tx.vout[i]; UniValue out(UniValue::VOBJ); out.pushKV("value", ValueFromAmount(txout.nValue)); out.pushKV("n", (int64_t)i); UniValue o(UniValue::VOBJ); ScriptPubKeyToUniv(txout.scriptPubKey, o, true); out.pushKV("scriptPubKey", o); vout.push_back(out); } entry.pushKV("vout", vout); if (!hashBlock.IsNull()) entry.pushKV("blockhash", hashBlock.GetHex()); if (include_hex) { entry.pushKV("hex", EncodeHexTx(tx, serialize_flags)); // the hex-encoded transaction. used the name "hex" to be consistent with the verbose output of "getrawtransaction". } } <|endoftext|>
<commit_before>// Copyright (c) 2009-2016 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 "core_io.h" #include "base58.h" #include "primitives/transaction.h" #include "script/script.h" #include "script/standard.h" #include "serialize.h" #include "streams.h" #include <univalue.h> #include "util.h" #include "utilmoneystr.h" #include "utilstrencodings.h" #include <boost/assign/list_of.hpp> #include <boost/foreach.hpp> std::string FormatScript(const CScript& script) { std::string ret; CScript::const_iterator it = script.begin(); opcodetype op; while (it != script.end()) { CScript::const_iterator it2 = it; std::vector<unsigned char> vch; if (script.GetOp2(it, op, &vch)) { if (op == OP_0) { ret += "0 "; continue; } else if ((op >= OP_1 && op <= OP_16) || op == OP_1NEGATE) { ret += strprintf("%i ", op - OP_1NEGATE - 1); continue; } else if (op >= OP_NOP && op <= OP_NOP10) { std::string str(GetOpName(op)); if (str.substr(0, 3) == std::string("OP_")) { ret += str.substr(3, std::string::npos) + " "; continue; } } if (vch.size() > 0) { ret += strprintf("0x%x 0x%x ", HexStr(it2, it - vch.size()), HexStr(it - vch.size(), it)); } else { ret += strprintf("0x%x ", HexStr(it2, it)); } continue; } ret += strprintf("0x%x ", HexStr(it2, script.end())); break; } return ret.substr(0, ret.size() - 1); } const std::map<unsigned char, std::string> mapSigHashTypes = boost::assign::map_list_of (static_cast<unsigned char>(SIGHASH_ALL), std::string("ALL")) (static_cast<unsigned char>(SIGHASH_ALL|SIGHASH_ANYONECANPAY), std::string("ALL|ANYONECANPAY")) (static_cast<unsigned char>(SIGHASH_NONE), std::string("NONE")) (static_cast<unsigned char>(SIGHASH_NONE|SIGHASH_ANYONECANPAY), std::string("NONE|ANYONECANPAY")) (static_cast<unsigned char>(SIGHASH_SINGLE), std::string("SINGLE")) (static_cast<unsigned char>(SIGHASH_SINGLE|SIGHASH_ANYONECANPAY), std::string("SINGLE|ANYONECANPAY")) ; /** * Create the assembly string representation of a CScript object. * @param[in] script CScript object to convert into the asm string representation. * @param[in] fAttemptSighashDecode Whether to attempt to decode sighash types on data within the script that matches the format * of a signature. Only pass true for scripts you believe could contain signatures. For example, * pass false, or omit the this argument (defaults to false), for scriptPubKeys. */ std::string ScriptToAsmStr(const CScript& script, const bool fAttemptSighashDecode) { std::string str; opcodetype opcode; std::vector<unsigned char> vch; CScript::const_iterator pc = script.begin(); while (pc < script.end()) { if (!str.empty()) { str += " "; } if (!script.GetOp(pc, opcode, vch)) { str += "[error]"; return str; } if (0 <= opcode && opcode <= OP_PUSHDATA4) { if (vch.size() <= static_cast<std::vector<unsigned char>::size_type>(4)) { str += strprintf("%d", CScriptNum(vch, false).getint()); } else { // the IsUnspendable check makes sure not to try to decode OP_RETURN data that may match the format of a signature if (fAttemptSighashDecode && !script.IsUnspendable()) { std::string strSigHashDecode; // goal: only attempt to decode a defined sighash type from data that looks like a signature within a scriptSig. // this won't decode correctly formatted public keys in Pubkey or Multisig scripts due to // the restrictions on the pubkey formats (see IsCompressedOrUncompressedPubKey) being incongruous with the // checks in CheckSignatureEncoding. if (CheckSignatureEncoding(vch, SCRIPT_VERIFY_STRICTENC, NULL)) { const unsigned char chSigHashType = vch.back(); if (mapSigHashTypes.count(chSigHashType)) { strSigHashDecode = "[" + mapSigHashTypes.find(chSigHashType)->second + "]"; vch.pop_back(); // remove the sighash type byte. it will be replaced by the decode. } } str += HexStr(vch) + strSigHashDecode; } else { str += HexStr(vch); } } } else { str += GetOpName(opcode); } } return str; } std::string EncodeHexTx(const CTransaction& tx, const int serialFlags) { CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION | serialFlags); ssTx << tx; return HexStr(ssTx.begin(), ssTx.end()); } void ScriptPubKeyToUniv(const CScript& scriptPubKey, UniValue& out, bool fIncludeHex) { txnouttype type; std::vector<CTxDestination> addresses; int nRequired; out.pushKV("asm", ScriptToAsmStr(scriptPubKey)); if (fIncludeHex) out.pushKV("hex", HexStr(scriptPubKey.begin(), scriptPubKey.end())); if (!ExtractDestinations(scriptPubKey, type, addresses, nRequired)) { out.pushKV("type", GetTxnOutputType(type)); return; } out.pushKV("reqSigs", nRequired); out.pushKV("type", GetTxnOutputType(type)); UniValue a(UniValue::VARR); BOOST_FOREACH(const CTxDestination& addr, addresses) a.push_back(CBitcoinAddress(addr).ToString()); out.pushKV("addresses", a); } void TxToUniv(const CTransaction& tx, const uint256& hashBlock, UniValue& entry) { entry.pushKV("txid", tx.GetId().GetHex()); entry.pushKV("hash", tx.GetHash().GetHex()); entry.pushKV("version", tx.nVersion); entry.pushKV("locktime", (int64_t)tx.nLockTime); UniValue vin(UniValue::VARR); for (unsigned int i = 0; i < tx.vin.size(); i++) { const CTxIn& txin = tx.vin[i]; UniValue in(UniValue::VOBJ); if (tx.IsCoinBase()) in.pushKV("coinbase", HexStr(txin.scriptSig.begin(), txin.scriptSig.end())); else { in.pushKV("txid", txin.prevout.hash.GetHex()); in.pushKV("vout", (int64_t)txin.prevout.n); UniValue o(UniValue::VOBJ); o.pushKV("asm", ScriptToAsmStr(txin.scriptSig, true)); o.pushKV("hex", HexStr(txin.scriptSig.begin(), txin.scriptSig.end())); in.pushKV("scriptSig", o); } in.pushKV("sequence", (int64_t)txin.nSequence); vin.push_back(in); } entry.pushKV("vin", vin); UniValue vout(UniValue::VARR); for (unsigned int i = 0; i < tx.vout.size(); i++) { const CTxOut& txout = tx.vout[i]; UniValue out(UniValue::VOBJ); UniValue outValue(UniValue::VNUM, FormatMoney(txout.nValue)); out.pushKV("value", outValue); out.pushKV("n", (int64_t)i); UniValue o(UniValue::VOBJ); ScriptPubKeyToUniv(txout.scriptPubKey, o, true); out.pushKV("scriptPubKey", o); vout.push_back(out); } entry.pushKV("vout", vout); if (!hashBlock.IsNull()) entry.pushKV("blockhash", hashBlock.GetHex()); entry.pushKV("hex", EncodeHexTx(tx)); // the hex-encoded transaction. used the name "hex" to be consistent with the verbose output of "getrawtransaction". } <commit_msg>Format core_write.cpp<commit_after>// Copyright (c) 2009-2016 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 "core_io.h" #include "base58.h" #include "primitives/transaction.h" #include "script/script.h" #include "script/standard.h" #include "serialize.h" #include "streams.h" #include "util.h" #include "utilmoneystr.h" #include "utilstrencodings.h" #include <univalue.h> #include <boost/assign/list_of.hpp> #include <boost/foreach.hpp> std::string FormatScript(const CScript &script) { std::string ret; CScript::const_iterator it = script.begin(); opcodetype op; while (it != script.end()) { CScript::const_iterator it2 = it; std::vector<unsigned char> vch; if (script.GetOp2(it, op, &vch)) { if (op == OP_0) { ret += "0 "; continue; } else if ((op >= OP_1 && op <= OP_16) || op == OP_1NEGATE) { ret += strprintf("%i ", op - OP_1NEGATE - 1); continue; } else if (op >= OP_NOP && op <= OP_NOP10) { std::string str(GetOpName(op)); if (str.substr(0, 3) == std::string("OP_")) { ret += str.substr(3, std::string::npos) + " "; continue; } } if (vch.size() > 0) { ret += strprintf("0x%x 0x%x ", HexStr(it2, it - vch.size()), HexStr(it - vch.size(), it)); } else { ret += strprintf("0x%x ", HexStr(it2, it)); } continue; } ret += strprintf("0x%x ", HexStr(it2, script.end())); break; } return ret.substr(0, ret.size() - 1); } const std::map<unsigned char, std::string> mapSigHashTypes = boost::assign::map_list_of(static_cast<unsigned char>(SIGHASH_ALL), std::string("ALL"))( static_cast<unsigned char>(SIGHASH_ALL | SIGHASH_ANYONECANPAY), std::string("ALL|ANYONECANPAY"))( static_cast<unsigned char>(SIGHASH_NONE), std::string("NONE"))( static_cast<unsigned char>(SIGHASH_NONE | SIGHASH_ANYONECANPAY), std::string("NONE|ANYONECANPAY"))( static_cast<unsigned char>(SIGHASH_SINGLE), std::string("SINGLE"))( static_cast<unsigned char>(SIGHASH_SINGLE | SIGHASH_ANYONECANPAY), std::string("SINGLE|ANYONECANPAY")); /** * Create the assembly string representation of a CScript object. * @param[in] script CScript object to convert into the asm string * representation. * @param[in] fAttemptSighashDecode Whether to attempt to decode sighash * types on data within the script that matches the format of a signature. Only * pass true for scripts you believe could contain signatures. For example, pass * false, or omit the this argument (defaults to false), for scriptPubKeys. */ std::string ScriptToAsmStr(const CScript &script, const bool fAttemptSighashDecode) { std::string str; opcodetype opcode; std::vector<unsigned char> vch; CScript::const_iterator pc = script.begin(); while (pc < script.end()) { if (!str.empty()) { str += " "; } if (!script.GetOp(pc, opcode, vch)) { str += "[error]"; return str; } if (0 <= opcode && opcode <= OP_PUSHDATA4) { if (vch.size() <= static_cast<std::vector<unsigned char>::size_type>(4)) { str += strprintf("%d", CScriptNum(vch, false).getint()); } else { // the IsUnspendable check makes sure not to try to decode // OP_RETURN data that may match the format of a signature if (fAttemptSighashDecode && !script.IsUnspendable()) { std::string strSigHashDecode; // goal: only attempt to decode a defined sighash type from // data that looks like a signature within a scriptSig. This // won't decode correctly formatted public keys in Pubkey or // Multisig scripts due to the restrictions on the pubkey // formats (see IsCompressedOrUncompressedPubKey) being // incongruous with the checks in CheckSignatureEncoding. if (CheckSignatureEncoding(vch, SCRIPT_VERIFY_STRICTENC, NULL)) { const unsigned char chSigHashType = vch.back(); if (mapSigHashTypes.count(chSigHashType)) { strSigHashDecode = "[" + mapSigHashTypes.find(chSigHashType)->second + "]"; // remove the sighash type byte. it will be replaced // by the decode. vch.pop_back(); } } str += HexStr(vch) + strSigHashDecode; } else { str += HexStr(vch); } } } else { str += GetOpName(opcode); } } return str; } std::string EncodeHexTx(const CTransaction &tx, const int serialFlags) { CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION | serialFlags); ssTx << tx; return HexStr(ssTx.begin(), ssTx.end()); } void ScriptPubKeyToUniv(const CScript &scriptPubKey, UniValue &out, bool fIncludeHex) { txnouttype type; std::vector<CTxDestination> addresses; int nRequired; out.pushKV("asm", ScriptToAsmStr(scriptPubKey)); if (fIncludeHex) out.pushKV("hex", HexStr(scriptPubKey.begin(), scriptPubKey.end())); if (!ExtractDestinations(scriptPubKey, type, addresses, nRequired)) { out.pushKV("type", GetTxnOutputType(type)); return; } out.pushKV("reqSigs", nRequired); out.pushKV("type", GetTxnOutputType(type)); UniValue a(UniValue::VARR); BOOST_FOREACH (const CTxDestination &addr, addresses) a.push_back(CBitcoinAddress(addr).ToString()); out.pushKV("addresses", a); } void TxToUniv(const CTransaction &tx, const uint256 &hashBlock, UniValue &entry) { entry.pushKV("txid", tx.GetId().GetHex()); entry.pushKV("hash", tx.GetHash().GetHex()); entry.pushKV("version", tx.nVersion); entry.pushKV("locktime", (int64_t)tx.nLockTime); UniValue vin(UniValue::VARR); for (unsigned int i = 0; i < tx.vin.size(); i++) { const CTxIn &txin = tx.vin[i]; UniValue in(UniValue::VOBJ); if (tx.IsCoinBase()) in.pushKV("coinbase", HexStr(txin.scriptSig.begin(), txin.scriptSig.end())); else { in.pushKV("txid", txin.prevout.hash.GetHex()); in.pushKV("vout", (int64_t)txin.prevout.n); UniValue o(UniValue::VOBJ); o.pushKV("asm", ScriptToAsmStr(txin.scriptSig, true)); o.pushKV("hex", HexStr(txin.scriptSig.begin(), txin.scriptSig.end())); in.pushKV("scriptSig", o); } in.pushKV("sequence", (int64_t)txin.nSequence); vin.push_back(in); } entry.pushKV("vin", vin); UniValue vout(UniValue::VARR); for (unsigned int i = 0; i < tx.vout.size(); i++) { const CTxOut &txout = tx.vout[i]; UniValue out(UniValue::VOBJ); UniValue outValue(UniValue::VNUM, FormatMoney(txout.nValue)); out.pushKV("value", outValue); out.pushKV("n", (int64_t)i); UniValue o(UniValue::VOBJ); ScriptPubKeyToUniv(txout.scriptPubKey, o, true); out.pushKV("scriptPubKey", o); vout.push_back(out); } entry.pushKV("vout", vout); if (!hashBlock.IsNull()) entry.pushKV("blockhash", hashBlock.GetHex()); // the hex-encoded transaction. used the name "hex" to be consistent with // the verbose output of "getrawtransaction". entry.pushKV("hex", EncodeHexTx(tx)); } <|endoftext|>
<commit_before>/* * Copyright (C) 2010-2014 Jeremy Lainé * Contact: https://github.com/jlaine/qdjango * * This file is part of the QDjango Library. * * 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. */ #include <QCoreApplication> #include <QDateTime> #include <QDebug> #include <QSqlDriver> #include <QSqlError> #include <QSqlQuery> #include <QStringList> #include <QThread> #include "QDjango.h" static const char *connectionPrefix = "_qdjango_"; QMap<QByteArray, QDjangoMetaModel> globalMetaModels = QMap<QByteArray, QDjangoMetaModel>(); static QDjangoDatabase *globalDatabase = 0; static QDjangoDatabase::DatabaseType globalDatabaseType = QDjangoDatabase::UnknownDB; static bool globalDebugEnabled = false; /// \cond QDjangoDatabase::QDjangoDatabase(QObject *parent) : QObject(parent), connectionId(0) { } void QDjangoDatabase::threadFinished() { QThread *thread = qobject_cast<QThread*>(sender()); if (!thread) return; // cleanup database connection for the thread QMutexLocker locker(&mutex); disconnect(thread, SIGNAL(finished()), this, SLOT(threadFinished())); const QString connectionName = copies.value(thread).connectionName(); copies.remove(thread); if (connectionName.startsWith(QLatin1String(connectionPrefix))) QSqlDatabase::removeDatabase(connectionName); } static void closeDatabase() { delete globalDatabase; } static QDjangoDatabase::DatabaseType getDatabaseType(QSqlDatabase &db) { const QString driverName = db.driverName(); if (driverName == QLatin1String("QMYSQL") || driverName == QLatin1String("QMYSQL3")) return QDjangoDatabase::MySqlServer; else if (driverName == QLatin1String("QSQLITE") || driverName == QLatin1String("QSQLITE2")) return QDjangoDatabase::SQLite; else if (driverName == QLatin1String("QPSQL")) return QDjangoDatabase::PostgreSQL; else if (driverName == QLatin1String("QODBC")) { QSqlQuery query(db); if (query.exec("SELECT sqlite_version()")) return QDjangoDatabase::SQLite; else if (query.exec("SELECT @@version")) return QDjangoDatabase::MSSqlServer; else if (query.exec("SELECT version()") && query.next()) { if (query.value(0).toString().contains("PostgreSQL")) return QDjangoDatabase::PostgreSQL; else return QDjangoDatabase::MySqlServer; } } return QDjangoDatabase::UnknownDB; } static void initDatabase(QSqlDatabase db) { QDjangoDatabase::DatabaseType databaseType = QDjangoDatabase::databaseType(db); if (databaseType == QDjangoDatabase::SQLite) { // enable foreign key constraint handling QDjangoQuery query(db); query.prepare("PRAGMA foreign_keys=on"); query.exec(); } } QDjangoQuery::QDjangoQuery(QSqlDatabase db) : QSqlQuery(db) { } void QDjangoQuery::addBindValue(const QVariant &val, QSql::ParamType paramType) { // this hack is required so that we do not store a mix of local // and UTC times if (val.type() == QVariant::DateTime) QSqlQuery::addBindValue(val.toDateTime().toLocalTime(), paramType); else QSqlQuery::addBindValue(val, paramType); } bool QDjangoQuery::exec() { if (globalDebugEnabled) { qDebug() << "SQL query" << lastQuery(); QMapIterator<QString, QVariant> i(boundValues()); while (i.hasNext()) { i.next(); qDebug() << "SQL " << i.key().toLatin1().data() << "=" << i.value().toString().toLatin1().data(); } } if (!QSqlQuery::exec()) { if (globalDebugEnabled) qWarning() << "SQL error" << lastError(); return false; } return true; } bool QDjangoQuery::exec(const QString &query) { if (globalDebugEnabled) qDebug() << "SQL query" << query; if (!QSqlQuery::exec(query)) { if (globalDebugEnabled) qWarning() << "SQL error" << lastError(); return false; } return true; } /// \endcond /*! Returns the database used by QDjango. If you call this method from any thread but the application's main thread, a new connection to the database will be created. The connection will automatically be torn down once the thread finishes. \sa setDatabase() */ QSqlDatabase QDjango::database() { if (!globalDatabase) return QSqlDatabase(); // if we are in the main thread, return reference connection QThread *thread = QThread::currentThread(); if (thread == globalDatabase->thread()) return globalDatabase->reference; // if we have a connection for this thread, return it QMutexLocker locker(&globalDatabase->mutex); if (globalDatabase->copies.contains(thread)) return globalDatabase->copies[thread]; // create a new connection for this thread QObject::connect(thread, SIGNAL(finished()), globalDatabase, SLOT(threadFinished())); QSqlDatabase db = QSqlDatabase::cloneDatabase(globalDatabase->reference, QLatin1String(connectionPrefix) + QString::number(globalDatabase->connectionId++)); db.open(); initDatabase(db); globalDatabase->copies.insert(thread, db); return db; } /*! Sets the database used by QDjango. You must call this method from your application's main thread. \sa database() */ void QDjango::setDatabase(QSqlDatabase database) { globalDatabaseType = getDatabaseType(database); if (globalDatabaseType == QDjangoDatabase::UnknownDB) { qWarning() << "Unsupported database driver" << database.driverName(); } if (!globalDatabase) { globalDatabase = new QDjangoDatabase(); qAddPostRoutine(closeDatabase); } initDatabase(database); globalDatabase->reference = database; } /*! Returns whether debugging information should be printed. \sa setDebugEnabled() */ bool QDjango::isDebugEnabled() { return globalDebugEnabled; } /*! Sets whether debugging information should be printed. \sa isDebugEnabled() */ void QDjango::setDebugEnabled(bool enabled) { globalDebugEnabled = enabled; } /*! Creates the database tables for all registered models. */ bool QDjango::createTables() { bool ret = true; foreach (const QByteArray &key, globalMetaModels.keys()) if (!globalMetaModels[key].createTable()) ret = false; return ret; } /*! Drops the database tables for all registered models. */ bool QDjango::dropTables() { bool ret = true; foreach (const QByteArray &key, globalMetaModels.keys()) if (!globalMetaModels[key].dropTable()) ret = false; return ret; } /*! Returns the QDjangoMetaModel with the given \a name. */ QDjangoMetaModel QDjango::metaModel(const char *name) { if (globalMetaModels.contains(name)) return globalMetaModels.value(name); // otherwise, try to find a model anyway foreach (QByteArray modelName, globalMetaModels.keys()) { if (qstricmp(name, modelName.data()) == 0) return globalMetaModels.value(modelName); } return QDjangoMetaModel(); } QDjangoMetaModel QDjango::registerModel(const QMetaObject *meta) { const QByteArray name = meta->className(); if (!globalMetaModels.contains(name)) globalMetaModels.insert(name, QDjangoMetaModel(meta)); return globalMetaModels[name]; } QDjangoDatabase::DatabaseType QDjangoDatabase::databaseType(const QSqlDatabase &db) { Q_UNUSED(db); return globalDatabaseType; } <commit_msg>fix Microsoft SQL Server detection<commit_after>/* * Copyright (C) 2010-2014 Jeremy Lainé * Contact: https://github.com/jlaine/qdjango * * This file is part of the QDjango Library. * * 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. */ #include <QCoreApplication> #include <QDateTime> #include <QDebug> #include <QSqlDriver> #include <QSqlError> #include <QSqlQuery> #include <QStringList> #include <QThread> #include "QDjango.h" static const char *connectionPrefix = "_qdjango_"; QMap<QByteArray, QDjangoMetaModel> globalMetaModels = QMap<QByteArray, QDjangoMetaModel>(); static QDjangoDatabase *globalDatabase = 0; static QDjangoDatabase::DatabaseType globalDatabaseType = QDjangoDatabase::UnknownDB; static bool globalDebugEnabled = false; /// \cond QDjangoDatabase::QDjangoDatabase(QObject *parent) : QObject(parent), connectionId(0) { } void QDjangoDatabase::threadFinished() { QThread *thread = qobject_cast<QThread*>(sender()); if (!thread) return; // cleanup database connection for the thread QMutexLocker locker(&mutex); disconnect(thread, SIGNAL(finished()), this, SLOT(threadFinished())); const QString connectionName = copies.value(thread).connectionName(); copies.remove(thread); if (connectionName.startsWith(QLatin1String(connectionPrefix))) QSqlDatabase::removeDatabase(connectionName); } static void closeDatabase() { delete globalDatabase; } static QDjangoDatabase::DatabaseType getDatabaseType(QSqlDatabase &db) { const QString driverName = db.driverName(); if (driverName == QLatin1String("QMYSQL") || driverName == QLatin1String("QMYSQL3")) return QDjangoDatabase::MySqlServer; else if (driverName == QLatin1String("QSQLITE") || driverName == QLatin1String("QSQLITE2")) return QDjangoDatabase::SQLite; else if (driverName == QLatin1String("QPSQL")) return QDjangoDatabase::PostgreSQL; else if (driverName == QLatin1String("QODBC")) { QSqlQuery query(db); if (query.exec("SELECT sqlite_version()")) return QDjangoDatabase::SQLite; if (query.exec("SELECT @@version") && query.next() && query.value(0).toString().contains("Microsoft SQL Server")) return QDjangoDatabase::MSSqlServer; if (query.exec("SELECT version()") && query.next()) { if (query.value(0).toString().contains("PostgreSQL")) return QDjangoDatabase::PostgreSQL; else return QDjangoDatabase::MySqlServer; } } return QDjangoDatabase::UnknownDB; } static void initDatabase(QSqlDatabase db) { QDjangoDatabase::DatabaseType databaseType = QDjangoDatabase::databaseType(db); if (databaseType == QDjangoDatabase::SQLite) { // enable foreign key constraint handling QDjangoQuery query(db); query.prepare("PRAGMA foreign_keys=on"); query.exec(); } } QDjangoQuery::QDjangoQuery(QSqlDatabase db) : QSqlQuery(db) { } void QDjangoQuery::addBindValue(const QVariant &val, QSql::ParamType paramType) { // this hack is required so that we do not store a mix of local // and UTC times if (val.type() == QVariant::DateTime) QSqlQuery::addBindValue(val.toDateTime().toLocalTime(), paramType); else QSqlQuery::addBindValue(val, paramType); } bool QDjangoQuery::exec() { if (globalDebugEnabled) { qDebug() << "SQL query" << lastQuery(); QMapIterator<QString, QVariant> i(boundValues()); while (i.hasNext()) { i.next(); qDebug() << "SQL " << i.key().toLatin1().data() << "=" << i.value().toString().toLatin1().data(); } } if (!QSqlQuery::exec()) { if (globalDebugEnabled) qWarning() << "SQL error" << lastError(); return false; } return true; } bool QDjangoQuery::exec(const QString &query) { if (globalDebugEnabled) qDebug() << "SQL query" << query; if (!QSqlQuery::exec(query)) { if (globalDebugEnabled) qWarning() << "SQL error" << lastError(); return false; } return true; } /// \endcond /*! Returns the database used by QDjango. If you call this method from any thread but the application's main thread, a new connection to the database will be created. The connection will automatically be torn down once the thread finishes. \sa setDatabase() */ QSqlDatabase QDjango::database() { if (!globalDatabase) return QSqlDatabase(); // if we are in the main thread, return reference connection QThread *thread = QThread::currentThread(); if (thread == globalDatabase->thread()) return globalDatabase->reference; // if we have a connection for this thread, return it QMutexLocker locker(&globalDatabase->mutex); if (globalDatabase->copies.contains(thread)) return globalDatabase->copies[thread]; // create a new connection for this thread QObject::connect(thread, SIGNAL(finished()), globalDatabase, SLOT(threadFinished())); QSqlDatabase db = QSqlDatabase::cloneDatabase(globalDatabase->reference, QLatin1String(connectionPrefix) + QString::number(globalDatabase->connectionId++)); db.open(); initDatabase(db); globalDatabase->copies.insert(thread, db); return db; } /*! Sets the database used by QDjango. You must call this method from your application's main thread. \sa database() */ void QDjango::setDatabase(QSqlDatabase database) { globalDatabaseType = getDatabaseType(database); if (globalDatabaseType == QDjangoDatabase::UnknownDB) { qWarning() << "Unsupported database driver" << database.driverName(); } if (!globalDatabase) { globalDatabase = new QDjangoDatabase(); qAddPostRoutine(closeDatabase); } initDatabase(database); globalDatabase->reference = database; } /*! Returns whether debugging information should be printed. \sa setDebugEnabled() */ bool QDjango::isDebugEnabled() { return globalDebugEnabled; } /*! Sets whether debugging information should be printed. \sa isDebugEnabled() */ void QDjango::setDebugEnabled(bool enabled) { globalDebugEnabled = enabled; } /*! Creates the database tables for all registered models. */ bool QDjango::createTables() { bool ret = true; foreach (const QByteArray &key, globalMetaModels.keys()) if (!globalMetaModels[key].createTable()) ret = false; return ret; } /*! Drops the database tables for all registered models. */ bool QDjango::dropTables() { bool ret = true; foreach (const QByteArray &key, globalMetaModels.keys()) if (!globalMetaModels[key].dropTable()) ret = false; return ret; } /*! Returns the QDjangoMetaModel with the given \a name. */ QDjangoMetaModel QDjango::metaModel(const char *name) { if (globalMetaModels.contains(name)) return globalMetaModels.value(name); // otherwise, try to find a model anyway foreach (QByteArray modelName, globalMetaModels.keys()) { if (qstricmp(name, modelName.data()) == 0) return globalMetaModels.value(modelName); } return QDjangoMetaModel(); } QDjangoMetaModel QDjango::registerModel(const QMetaObject *meta) { const QByteArray name = meta->className(); if (!globalMetaModels.contains(name)) globalMetaModels.insert(name, QDjangoMetaModel(meta)); return globalMetaModels[name]; } QDjangoDatabase::DatabaseType QDjangoDatabase::databaseType(const QSqlDatabase &db) { Q_UNUSED(db); return globalDatabaseType; } <|endoftext|>
<commit_before>/* * Copyright 2017 deepstreamHub GmbH * * 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 <cstdint> #include <algorithm> #include <chrono> #include <stdexcept> #include <buffer.hpp> #include <client.hpp> #include <deepstream.hpp> #include <error_handler.hpp> #include <exception.hpp> #include <message.hpp> #include <message_builder.hpp> #include <scope_guard.hpp> #include <websockets.hpp> #include <websockets/poco.hpp> #include <use.hpp> #include <cassert> namespace deepstream { std::unique_ptr<Client> Client::make( const std::string& uri, std::unique_ptr<ErrorHandler> p_error_handler) { assert( p_error_handler ); std::unique_ptr<websockets::Client> p_websocket( new websockets::poco::Client(uri) ); p_websocket->set_receive_timeout( std::chrono::seconds(1) ); std::unique_ptr<Client> p( new Client( std::move(p_websocket), std::move(p_error_handler) ) ); Buffer buffer; parser::MessageList messages; client::State& state = p->state_; if( p->receive_(&buffer, &messages) != websockets::State::OPEN ) return p; assert( messages.size() == 1 ); assert( state == client::State::CHALLENGING ); { MessageBuilder chr(Topic::CONNECTION, Action::CHALLENGE_RESPONSE); chr.add_argument( Buffer(uri.cbegin(), uri.cend()) ); if( p->send_(chr) != websockets::State::OPEN ) return p; } if( p->receive_(&buffer, &messages) != websockets::State::OPEN ) return p; assert( messages.size() == 1 ); assert( state == client::State::AWAIT_AUTHENTICATION ); return p; } Client::Client( std::unique_ptr<websockets::Client> p_websocket, std::unique_ptr<ErrorHandler> p_error_handler ) : state_(client::State::AWAIT_CONNECTION), p_websocket_( std::move(p_websocket) ), p_error_handler_( std::move(p_error_handler) ) { assert( p_websocket_ ); assert( p_error_handler_ ); } client::State Client::login( const std::string& auth, Buffer* p_user_data) { if( state_ != client::State::AWAIT_AUTHENTICATION ) throw std::logic_error("Cannot login() in current state"); MessageBuilder areq(Topic::AUTH, Action::REQUEST); areq.add_argument(auth); if( send_(areq) != websockets::State::OPEN ) return state_; Buffer buffer; parser::MessageList messages; if( receive_(&buffer, &messages) != websockets::State::OPEN ) return state_; assert( messages.size() == 1 ); assert( state_ == client::State::CONNECTED ); const Message& aa_msg = messages.front(); assert( aa_msg.topic() == Topic::AUTH ); assert( aa_msg.action() == Action::REQUEST ); assert( aa_msg.is_ack() ); assert( aa_msg.num_arguments() >= 0 ); assert( aa_msg.num_arguments() <= 1 ); if( aa_msg.num_arguments() == 0 && p_user_data ) p_user_data->clear(); else if( aa_msg.num_arguments() == 1 && p_user_data ) *p_user_data = aa_msg[0]; return state_; } void Client::close() { state_ = client::State::DISCONNECTED; p_websocket_->close(); } websockets::State Client::receive_( Buffer* p_buffer, parser::MessageList* p_messages) { assert( p_buffer ); assert( p_messages ); auto receive_ret = p_websocket_->receive_frame(); websockets::State ws_state = receive_ret.first; std::unique_ptr<websockets::Frame> p_frame = std::move(receive_ret.second); if( ws_state == websockets::State::OPEN && !p_frame ) { p_buffer->clear(); p_messages->clear(); return ws_state; } if( ws_state == websockets::State::CLOSED && p_frame ) { p_buffer->clear(); p_messages->clear(); close(); return ws_state; } if( ws_state == websockets::State::CLOSED && !p_frame ) { p_buffer->clear(); p_messages->clear(); close(); p_error_handler_->sudden_disconnect( p_websocket_->uri() ); return ws_state; } if( ws_state == websockets::State::ERROR ) { assert( p_frame ); close(); p_error_handler_->invalid_close_frame_size(*p_frame); return ws_state; } assert( ws_state == websockets::State::OPEN ); assert( p_frame ); const Buffer& payload = p_frame->payload(); p_buffer->assign( payload.cbegin(), payload.cend() ); p_buffer->push_back(0); p_buffer->push_back(0); auto parser_ret = parser::execute( p_buffer->data(), p_buffer->size() ); const parser::ErrorList& errors = parser_ret.second; std::for_each( errors.cbegin(), errors.cend(), [this] (const parser::Error& e) { this->p_error_handler_->parser_error(e); } ); if( !errors.empty() ) { p_buffer->clear(); p_messages->clear(); close(); return websockets::State::ERROR; } *p_messages = std::move(parser_ret.first); for(auto it = p_messages->cbegin(); it != p_messages->cend(); ++it) { const Message& msg = *it; client::State old_state = state_; client::State new_state = client::transition(old_state, msg, Sender::SERVER); assert( new_state != client::State::DISCONNECTED ); if( new_state == client::State::ERROR ) { close(); p_error_handler_->invalid_state_transition(old_state, msg); return websockets::State::ERROR; } state_ = new_state; } return ws_state; } websockets::State Client::send_(const Message& message) { client::State new_state = client::transition(state_, message, Sender::CLIENT); assert( new_state != client::State::ERROR ); if( new_state == client::State::ERROR ) throw std::logic_error( "Invalid client state transition" ); state_ = new_state; try { websockets::State state = p_websocket_->send_frame(message.to_binary()); if( state != websockets::State::OPEN ) { close(); p_error_handler_->sudden_disconnect( p_websocket_->uri() ); return websockets::State::CLOSED; } return state; } catch(SystemError& e) { p_error_handler_->system_error( e.error() ); } catch(std::exception& e) { p_error_handler_->websocket_exception(e); } close(); return websockets::State::ERROR; } } <commit_msg>Client: handle log-in errors properly<commit_after>/* * Copyright 2017 deepstreamHub GmbH * * 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 <cstdint> #include <algorithm> #include <chrono> #include <stdexcept> #include <buffer.hpp> #include <client.hpp> #include <deepstream.hpp> #include <error_handler.hpp> #include <exception.hpp> #include <message.hpp> #include <message_builder.hpp> #include <scope_guard.hpp> #include <websockets.hpp> #include <websockets/poco.hpp> #include <use.hpp> #include <cassert> namespace deepstream { std::unique_ptr<Client> Client::make( const std::string& uri, std::unique_ptr<ErrorHandler> p_error_handler) { assert( p_error_handler ); std::unique_ptr<websockets::Client> p_websocket( new websockets::poco::Client(uri) ); p_websocket->set_receive_timeout( std::chrono::seconds(1) ); std::unique_ptr<Client> p( new Client( std::move(p_websocket), std::move(p_error_handler) ) ); Buffer buffer; parser::MessageList messages; client::State& state = p->state_; if( p->receive_(&buffer, &messages) != websockets::State::OPEN ) return p; assert( messages.size() == 1 ); assert( state == client::State::CHALLENGING ); { MessageBuilder chr(Topic::CONNECTION, Action::CHALLENGE_RESPONSE); chr.add_argument( Buffer(uri.cbegin(), uri.cend()) ); if( p->send_(chr) != websockets::State::OPEN ) return p; } if( p->receive_(&buffer, &messages) != websockets::State::OPEN ) return p; assert( messages.size() == 1 ); assert( state == client::State::AWAIT_AUTHENTICATION ); return p; } Client::Client( std::unique_ptr<websockets::Client> p_websocket, std::unique_ptr<ErrorHandler> p_error_handler ) : state_(client::State::AWAIT_CONNECTION), p_websocket_( std::move(p_websocket) ), p_error_handler_( std::move(p_error_handler) ) { assert( p_websocket_ ); assert( p_error_handler_ ); } client::State Client::login( const std::string& auth, Buffer* p_user_data) { if( state_ != client::State::AWAIT_AUTHENTICATION ) throw std::logic_error("Cannot login() in current state"); MessageBuilder areq(Topic::AUTH, Action::REQUEST); areq.add_argument(auth); if( send_(areq) != websockets::State::OPEN ) return state_; Buffer buffer; parser::MessageList messages; if( receive_(&buffer, &messages) != websockets::State::OPEN ) return state_; assert( messages.size() == 1 ); const Message& msg = messages.front(); if( msg.topic() == Topic::AUTH && msg.action() == Action::REQUEST && msg.is_ack() ) { assert( state_ == client::State::CONNECTED ); if( msg.num_arguments() == 0 && p_user_data ) p_user_data->clear(); else if( msg.num_arguments() == 1 && p_user_data ) *p_user_data = msg[0]; return state_; } if( msg.topic() == Topic::AUTH && msg.action() == Action::ERROR_INVALID_AUTH_DATA ) { assert( state_ == client::State::AWAIT_AUTHENTICATION ); return state_; } if( msg.topic() == Topic::AUTH && msg.action() == Action::ERROR_INVALID_AUTH_MSG ) { close(); return state_; } if( msg.topic() == Topic::AUTH && msg.action() == Action::ERROR_TOO_MANY_AUTH_ATTEMPTS ) { close(); return state_; } assert(0); close(); return client::State::ERROR; } void Client::close() { state_ = client::State::DISCONNECTED; p_websocket_->close(); } websockets::State Client::receive_( Buffer* p_buffer, parser::MessageList* p_messages) { assert( p_buffer ); assert( p_messages ); auto receive_ret = p_websocket_->receive_frame(); websockets::State ws_state = receive_ret.first; std::unique_ptr<websockets::Frame> p_frame = std::move(receive_ret.second); if( ws_state == websockets::State::OPEN && !p_frame ) { p_buffer->clear(); p_messages->clear(); return ws_state; } if( ws_state == websockets::State::CLOSED && p_frame ) { p_buffer->clear(); p_messages->clear(); close(); return ws_state; } if( ws_state == websockets::State::CLOSED && !p_frame ) { p_buffer->clear(); p_messages->clear(); close(); p_error_handler_->sudden_disconnect( p_websocket_->uri() ); return ws_state; } if( ws_state == websockets::State::ERROR ) { assert( p_frame ); close(); p_error_handler_->invalid_close_frame_size(*p_frame); return ws_state; } assert( ws_state == websockets::State::OPEN ); assert( p_frame ); const Buffer& payload = p_frame->payload(); p_buffer->assign( payload.cbegin(), payload.cend() ); p_buffer->push_back(0); p_buffer->push_back(0); auto parser_ret = parser::execute( p_buffer->data(), p_buffer->size() ); const parser::ErrorList& errors = parser_ret.second; std::for_each( errors.cbegin(), errors.cend(), [this] (const parser::Error& e) { this->p_error_handler_->parser_error(e); } ); if( !errors.empty() ) { p_buffer->clear(); p_messages->clear(); close(); return websockets::State::ERROR; } *p_messages = std::move(parser_ret.first); for(auto it = p_messages->cbegin(); it != p_messages->cend(); ++it) { const Message& msg = *it; client::State old_state = state_; client::State new_state = client::transition(old_state, msg, Sender::SERVER); if( new_state == client::State::ERROR ) { close(); p_error_handler_->invalid_state_transition(old_state, msg); return websockets::State::ERROR; } if( new_state == client::State::DISCONNECTED ) { close(); return websockets::State::CLOSED; } state_ = new_state; } return ws_state; } websockets::State Client::send_(const Message& message) { client::State new_state = client::transition(state_, message, Sender::CLIENT); assert( new_state != client::State::ERROR ); if( new_state == client::State::ERROR ) throw std::logic_error( "Invalid client state transition" ); state_ = new_state; try { websockets::State state = p_websocket_->send_frame(message.to_binary()); if( state != websockets::State::OPEN ) { close(); p_error_handler_->sudden_disconnect( p_websocket_->uri() ); return websockets::State::CLOSED; } return state; } catch(SystemError& e) { p_error_handler_->system_error( e.error() ); } catch(std::exception& e) { p_error_handler_->websocket_exception(e); } close(); return websockets::State::ERROR; } } <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the Qt Mobility Components. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "versittest.h" #include "vcardcomparator.h" #include <QDir> #include <QFile> #include <QStringList> #include <QBuffer> #include <QList> #include <QtTest/QtTest> #include <qcontactmanager.h> #include <qversitreader.h> #include <qversitwriter.h> #include <qversitdocument.h> #include <qversitcontactgenerator.h> #include <qversitcontactconverter.h> VersitTest::VersitTest() : QObject(), mSaveContacts(false), mScaledImageHeight(0), mScaledImageWidth(0) { } VersitTest::VersitTest(bool saveContacts,int scaledImageHeight,int scaledImageWidth) : QObject(), mSaveContacts(saveContacts), mScaledImageHeight(scaledImageHeight), mScaledImageWidth(scaledImageWidth) { QString homeDir = QDir::homePath(); if (!homeDir.endsWith(QString::fromAscii("/"))) homeDir += QString::fromAscii("/"); QDir dir(homeDir); QString testDir("testvcards/"); mInputDirPath = homeDir + testDir + QString::fromAscii("in"); mExcludeFieldsFileName = homeDir + testDir + QString::fromAscii("excludefields.txt"); mOutputDirPath = homeDir + testDir + QString::fromAscii("out"); mImageAndAudioClipPath = homeDir + testDir + QString::fromAscii("images_and_audio"); } void VersitTest::scale(const QString& imageFileName, QByteArray& imageData) { if (mScaledImageHeight > 0 && mScaledImageWidth > 0) { QImage image(imageFileName); image = image.scaled(mScaledImageHeight,mScaledImageWidth); QBuffer imageBuffer(&imageData); QByteArray fileExtension = imageFileName.section('.',-1).toUpper().toAscii(); image.save(&imageBuffer,fileExtension.constData()); } } void VersitTest::initTestCase() { QDir dir(mInputDirPath); QStringList type("*.vcf"); mFiles = dir.entryList(type); mExcludedFields = new QStringList; QFile excludeFieldsFile(mExcludeFieldsFileName); if (excludeFieldsFile.open(QIODevice::ReadOnly)) { while (!excludeFieldsFile.atEnd()) { QString field(excludeFieldsFile.readLine().trimmed()); mExcludedFields->append(field); } excludeFieldsFile.close(); } mContactManager = new QContactManager(QString::fromAscii("symbian")); if (!dir.exists(mImageAndAudioClipPath)) { dir.mkdir(mImageAndAudioClipPath); } } void VersitTest::cleanupTestCase() { delete mContactManager; delete mExcludedFields; mFiles.clear(); } void VersitTest::init() { mReader = new QVersitReader; mWriter = new QVersitWriter; } void VersitTest::cleanup() { delete mWriter; delete mReader; } void VersitTest::test() { // Run test against the data if its availble if ( QTest::currentDataTag() ) { QFETCH(QString, InFile); QFile in(InFile); QVERIFY(in.open(QIODevice::ReadOnly)); QDir dir; if (!dir.exists(mOutputDirPath)) dir.mkdir(mOutputDirPath); QFileInfo fileInfo = in.fileName(); QFile out(mOutputDirPath+ "/" + fileInfo.fileName()); out.remove(); QVERIFY(out.open(QIODevice::ReadWrite)); // Note that QBENCHMARK may execute the "executeTest" // function several times (see QBENCHMARK documentation). // This may cause the creation of multiple images or audio clips // per one vCard property like PHOTO or SOUND QBENCHMARK { executeTest(in,out); } in.close(); out.close(); } } void VersitTest::test_data() { QTest::addColumn<QString>("InFile"); QStringListIterator fileIterator(mFiles); while (fileIterator.hasNext()) { QString fileName = mInputDirPath + "/" + fileIterator.next(); QTest::newRow(fileName.toAscii().data()) << fileName; } } void VersitTest::executeTest(QFile& in, QIODevice& out) { mReader->setDevice(&in); out.reset(); mWriter->setDevice(&out); // Parse the input QVERIFY2(mReader->readSynchronously(), in.fileName().toAscii().constData()); // Convert to QContacts QList<QContact> contacts; QVersitContactGenerator generator; QList<QVersitDocument::VersitType> documentTypes; foreach (QVersitDocument document, mReader->result()) { generator.setImagePath(mImageAndAudioClipPath); generator.setAudioClipPath(mImageAndAudioClipPath); QContact contact = generator.generateContact(document); if (mSaveContacts) QVERIFY(mContactManager->saveContact(&contact)); contacts.append(contact); documentTypes.append(document.versitType()); } // Convert back to QVersitDocuments QList<QVersitDocument> documents; QVersitContactConverter converter; connect(&converter, SIGNAL(scale(const QString&,QByteArray&)), this, SLOT(scale(const QString&,QByteArray&))); foreach (QContact contact, contacts) { QVersitDocument document = converter.convertContact(contact); if (!documentTypes.isEmpty()) document.setVersitType(documentTypes.takeFirst()); documents.append(document); } // Encode and write to output foreach (QVersitDocument document, documents) { mWriter->setVersitDocument(document); QVERIFY2(mWriter->writeSynchronously(), in.fileName().toAscii().constData()); } // Compare the input and output in.seek(0); out.seek(0); VCardComparator comparator(in,out,*mExcludedFields); QCOMPARE(QString(),comparator.nonMatchingLines()); } <commit_msg>Versit: Test driver according to the QVersitReader and QVersitWriter changes<commit_after>/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the Qt Mobility Components. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "versittest.h" #include "vcardcomparator.h" #include <QDir> #include <QFile> #include <QStringList> #include <QBuffer> #include <QList> #include <QtTest/QtTest> #include <qcontactmanager.h> #include <qversitreader.h> #include <qversitwriter.h> #include <qversitdocument.h> #include <qversitcontactgenerator.h> #include <qversitcontactconverter.h> VersitTest::VersitTest() : QObject(), mSaveContacts(false), mScaledImageHeight(0), mScaledImageWidth(0) { } VersitTest::VersitTest(bool saveContacts,int scaledImageHeight,int scaledImageWidth) : QObject(), mSaveContacts(saveContacts), mScaledImageHeight(scaledImageHeight), mScaledImageWidth(scaledImageWidth) { QString homeDir = QDir::homePath(); if (!homeDir.endsWith(QString::fromAscii("/"))) homeDir += QString::fromAscii("/"); QDir dir(homeDir); QString testDir("testvcards/"); mInputDirPath = homeDir + testDir + QString::fromAscii("in"); mExcludeFieldsFileName = homeDir + testDir + QString::fromAscii("excludefields.txt"); mOutputDirPath = homeDir + testDir + QString::fromAscii("out"); mImageAndAudioClipPath = homeDir + testDir + QString::fromAscii("images_and_audio"); } void VersitTest::scale(const QString& imageFileName, QByteArray& imageData) { if (mScaledImageHeight > 0 && mScaledImageWidth > 0) { QImage image(imageFileName); image = image.scaled(mScaledImageHeight,mScaledImageWidth); QBuffer imageBuffer(&imageData); QByteArray fileExtension = imageFileName.section('.',-1).toUpper().toAscii(); image.save(&imageBuffer,fileExtension.constData()); } } void VersitTest::initTestCase() { QDir dir(mInputDirPath); QStringList type("*.vcf"); mFiles = dir.entryList(type); mExcludedFields = new QStringList; QFile excludeFieldsFile(mExcludeFieldsFileName); if (excludeFieldsFile.open(QIODevice::ReadOnly)) { while (!excludeFieldsFile.atEnd()) { QString field(excludeFieldsFile.readLine().trimmed()); mExcludedFields->append(field); } excludeFieldsFile.close(); } mContactManager = new QContactManager(QString::fromAscii("symbian")); if (!dir.exists(mImageAndAudioClipPath)) { dir.mkdir(mImageAndAudioClipPath); } } void VersitTest::cleanupTestCase() { delete mContactManager; delete mExcludedFields; mFiles.clear(); } void VersitTest::init() { mReader = new QVersitReader; mWriter = new QVersitWriter; } void VersitTest::cleanup() { delete mWriter; delete mReader; } void VersitTest::test() { // Run test against the data if its availble if ( QTest::currentDataTag() ) { QFETCH(QString, InFile); QFile in(InFile); QVERIFY(in.open(QIODevice::ReadOnly)); QDir dir; if (!dir.exists(mOutputDirPath)) dir.mkdir(mOutputDirPath); QFileInfo fileInfo = in.fileName(); QFile out(mOutputDirPath+ "/" + fileInfo.fileName()); out.remove(); QVERIFY(out.open(QIODevice::ReadWrite)); // Note that QBENCHMARK may execute the "executeTest" // function several times (see QBENCHMARK documentation). // This may cause the creation of multiple images or audio clips // per one vCard property like PHOTO or SOUND QBENCHMARK { executeTest(in,out); } in.close(); out.close(); } } void VersitTest::test_data() { QTest::addColumn<QString>("InFile"); QStringListIterator fileIterator(mFiles); while (fileIterator.hasNext()) { QString fileName = mInputDirPath + "/" + fileIterator.next(); QTest::newRow(fileName.toAscii().data()) << fileName; } } void VersitTest::executeTest(QFile& in, QIODevice& out) { in.seek(0); mReader->setDevice(&in); out.reset(); mWriter->setDevice(&out); // Parse the input QVERIFY2(mReader->readAll(),in.fileName().toAscii().constData()); // Convert to QContacts QList<QContact> contacts; QVersitContactGenerator generator; QList<QVersitDocument::VersitType> documentTypes; foreach (QVersitDocument document, mReader->result()) { generator.setImagePath(mImageAndAudioClipPath); generator.setAudioClipPath(mImageAndAudioClipPath); QContact contact = generator.generateContact(document); if (mSaveContacts) QVERIFY(mContactManager->saveContact(&contact)); contacts.append(contact); documentTypes.append(document.versitType()); } // Convert back to QVersitDocuments QList<QVersitDocument> documents; QVersitContactConverter converter; connect(&converter, SIGNAL(scale(const QString&,QByteArray&)), this, SLOT(scale(const QString&,QByteArray&))); foreach (QContact contact, contacts) { QVersitDocument document = converter.convertContact(contact); if (!documentTypes.isEmpty()) document.setVersitType(documentTypes.takeFirst()); documents.append(document); } // Encode and write to output foreach (QVersitDocument document, documents) { mWriter->setVersitDocument(document); QVERIFY2(mWriter->writeAll(),in.fileName().toAscii().constData()); } // Compare the input and output in.seek(0); out.seek(0); VCardComparator comparator(in,out,*mExcludedFields); QCOMPARE(QString(),comparator.nonMatchingLines()); } <|endoftext|>
<commit_before>// Copyright 2013 Duncan Smith #include "service/service.h" #include <iostream> #include <boost/log/trivial.hpp> #include <boost/log/core.hpp> #include <boost/log/expressions.hpp> #include <boost/log/sinks/text_file_backend.hpp> #include <boost/log/utility/setup/file.hpp> #include <boost/log/utility/setup/console.hpp> #include <boost/log/utility/setup/common_attributes.hpp> #include <boost/log/sources/severity_logger.hpp> #include <boost/log/sources/record_ostream.hpp> #include <service/args.h> // NOLINT namespace osoa { Service::Service() : args_(new Args()) {} Service::~Service() { BOOST_LOG_TRIVIAL(info) << "service stop"; } void Service::Initialize(int argc, const char *argv[]) { args().Initialize(argc, argv); using namespace boost::log; add_common_attributes(); add_console_log(); add_file_log ( keywords::file_name = "sample_%N.log", keywords::rotation_size = 10 * 1024 * 1024, keywords::time_based_rotation = sinks::file::rotation_at_time_point(0, 0, 0), keywords::format = "[%TimeStamp%]: %Message%" ); auto log_level = (args().verbose()) ? trivial::debug : trivial::info; core::get()->set_filter(trivial::severity >= log_level); BOOST_LOG_TRIVIAL(info) << "service start"; } } // namespace osoa <commit_msg>file severity logging<commit_after>// Copyright 2013 Duncan Smith #include "service/service.h" #include <iostream> #include <boost/log/trivial.hpp> #include <boost/log/core.hpp> #include <boost/log/expressions.hpp> #include <boost/log/sinks/text_file_backend.hpp> #include <boost/log/utility/setup/file.hpp> #include <boost/log/utility/setup/console.hpp> #include <boost/log/utility/setup/common_attributes.hpp> #include <boost/log/sources/global_logger_storage.hpp> #include <boost/log/sources/logger.hpp> #include <boost/log/sources/severity_logger.hpp> #include <boost/log/sources/severity_feature.hpp> #include <boost/log/sources/record_ostream.hpp> #include <boost/move/utility.hpp> #include <service/args.h> // NOLINT namespace src = boost::log::sources; namespace osoa { BOOST_LOG_INLINE_GLOBAL_LOGGER_DEFAULT(svc_logger, src::severity_logger_mt<boost::log::trivial::severity_level>) Service::Service() : args_(new Args()) {} Service::~Service() { BOOST_LOG_TRIVIAL(info) << "service stop"; } void Service::Initialize(int argc, const char *argv[]) { args().Initialize(argc, argv); using namespace boost::log; add_common_attributes(); add_console_log(); add_file_log ( keywords::file_name = "sample_%N.log", keywords::rotation_size = 10 * 1024 * 1024, keywords::time_based_rotation = sinks::file::rotation_at_time_point(0, 0, 0), keywords::format = "[%TimeStamp%]: %Message%" ); auto log_level = (args().verbose()) ? trivial::debug : trivial::info; core::get()->set_filter(trivial::severity >= log_level); auto& lg = svc_logger::get(); BOOST_LOG_SEV(lg, trivial::info) << "Started the service."; BOOST_LOG_SEV(lg, trivial::debug) << "really Started the service."; } } // namespace osoa <|endoftext|>
<commit_before>#include "stan/math/functions/inv_logit.hpp" #include <gtest/gtest.h> TEST(MathFunctions, inv_logit) { using stan::math::inv_logit; EXPECT_FLOAT_EQ(0.5, inv_logit(0.0)); EXPECT_FLOAT_EQ(1.0/(1.0 + exp(-5.0)), inv_logit(5.0)); } <commit_msg>added NaN test for inv_logit<commit_after>#include <stan/math/functions/inv_logit.hpp> #include <boost/math/special_functions/fpclassify.hpp> #include <gtest/gtest.h> TEST(MathFunctions, inv_logit) { using stan::math::inv_logit; EXPECT_FLOAT_EQ(0.5, inv_logit(0.0)); EXPECT_FLOAT_EQ(1.0/(1.0 + exp(-5.0)), inv_logit(5.0)); } TEST(MathFunctions, inv_logit_nan) { double nan = std::numeric_limits<double>::quiet_NaN(); EXPECT_PRED1(boost::math::isnan<double>, stan::math::inv_logit(nan)); } <|endoftext|>
<commit_before>#include "PassMyoA.h" #include "CompNeoHookean.h" #include "FEMesh.h" #include "EigenEllipticResult.h" #include "MechanicsModel.h" #include "EigenNRsolver.h" #include "LBFGSB.h" using namespace voom; int main(int argc, char** argv) { // Timing time_t start, end; time(&start); // Initialize Mesh FEMesh Cube("Cube6.node", "Cube6.ele"); FEMesh surfMesh("Cube6.node", "Cube6Surf.ele"); cout << endl; cout << "Number Of Nodes : " << Cube.getNumberOfNodes() << endl; cout << "Number Of Element : " << Cube.getNumberOfElements() << endl; cout << "Mesh Dimension : " << Cube.getDimension() << endl << endl; // Initialize Material uint NumMat = Cube.getNumberOfElements(); vector<MechanicsMaterial * > materials; materials.reserve(NumMat); vector<Vector3d > Fibers; Fibers.reserve(NumMat); for (int k = 0; k < NumMat; k++) { CompNeoHookean* Mat = new CompNeoHookean(k, 1.0, 1.0); materials.push_back(Mat); Vector3d N; N << 1.0/sqrt(3.0), 1.0/sqrt(3.0), 1.0/sqrt(3.0); Fibers.push_back(N); } // Load fibers into elements Cube.setFibers(Fibers); // Initialize Model int NodeDoF = 3; int PressureFlag = 1; Real Pressure = 1.0; int NodalForcesFlag = 1; vector<int > ForcesID; vector<Real > Forces; MechanicsModel myModel(&Cube, materials, NodeDoF, PressureFlag, &surfMesh, NodalForcesFlag); myModel.updatePressure(Pressure); myModel.updateNodalForces(&ForcesID, &Forces); // Initialize Result uint PbDoF = (Cube.getNumberOfNodes())*myModel.getDoFperNode(); EigenEllipticResult myResults(PbDoF, NumMat*2); // Run Consistency check Real perturbationFactor = 0.1; uint myRequest = 7; // Check both Forces and Stiffness Real myH = 1e-6; Real myTol = 1e-7; myModel.checkConsistency(myResults, perturbationFactor, myRequest, myH, myTol); myModel.checkDmat(myResults, perturbationFactor, myH, myTol); // Print initial configuration myModel.writeOutputVTK("CubeSmall_", 0); // Check on applied pressure myRequest = 2; myResults.setRequest(myRequest); myModel.compute(myResults); VectorXd Fstart = *(myResults._residual); Real pX = 0.0, pY = 0.0, pZ = 0.0; for (int i = 0; i < Fstart.size(); i += 3) { pX += Fstart(i); pY += Fstart(i+1); pZ += Fstart(i+2); } cout << endl << "Pressure = " << pX << " " << pY << " " << pZ << endl << endl; // EBC vector<int > DoFid(8,0); vector<Real > DoFvalues(8, 0.0); DoFid[0] = 0; DoFid[1] = 1; DoFid[2] = 2; DoFid[3] = 4; DoFid[4] = 5; DoFid[5] = 8; DoFid[6] = 9; DoFid[7] = 11; for(int i = 0; i < DoFid.size(); i++) { DoFvalues[i] = Cube.getX(floor(double(DoFid[i])/3.0) ,DoFid[i]%3); // cout << DoFid[i] << " " << DoFvalues[i] << endl; } // Lin tet cube - applied displacements // // for (uint i = 18; i < 27; i++) { // DoFid[i-5] = i*3 + 2; // Lower top in z direction by 0.1 // DoFvalues[i-5] = 1.95; // } // Solver Real NRtol = 1.0e-12; uint NRmaxIter = 100; EigenNRsolver mySolver(&myModel, DoFid, DoFvalues, CHOL, NRtol, NRmaxIter); mySolver.solve(DISP); myModel.writeOutputVTK("CubeSmall_", 1); myModel.writeField("CubeSmall_", 1); // int m = 5; // double factr = 1.0e+1; // double pgtol = 1.0e-5; // int iprint = 0; // int maxIterations = -1; // vector<int > nbd(PbDoF, 0); // vector<double > lowerBound(PbDoF, 0.0); // vector<double > upperBound(PbDoF, 0.0); // for(int i = 0; i < DoFid.size(); i++) { // nbd[DoFid[i]] = 2; // lowerBound[DoFid[i]] = DoFvalues[i]; // upperBound[DoFid[i]] = DoFvalues[i]; // } // cout << "PbDoF = " << PbDoF << endl; // for (int j = 0; j < PbDoF; j++) { // cout << nbd[j] << " " << lowerBound[j] << " " << upperBound[j] << endl; // } // LBFGSB mySolver(& myModel, & myResults, m, factr, pgtol, iprint, maxIterations); // mySolver.setBounds(nbd, lowerBound, upperBound); // mySolver.solve(); // // Print final configuration // myModel.writeOutputVTK("CubeQuad_", 1); // // Print _field // cout << endl; // myModel.printField(); // cout << endl; // Compute Residual myRequest = 2; myResults.setRequest(myRequest); myModel.compute(myResults); VectorXd F = *(myResults._residual); for (int i = 0; i < DoFid.size(); i ++) { ForcesID.push_back( DoFid[i] ); Forces.push_back( -F(DoFid[i]) ); } // Timing time (&end); cout << endl << "BVP solved in " << difftime(end,start) << " s" << endl; return 0; } <commit_msg>Strips and cubes<commit_after>#include "PassMyoA.h" #include "CompNeoHookean.h" #include "FEMesh.h" #include "EigenEllipticResult.h" #include "MechanicsModel.h" #include "EigenNRsolver.h" #include "LBFGSB.h" using namespace voom; int main(int argc, char** argv) { // Timing time_t start, end; time(&start); // Initialize Mesh // Assumptions to use this main as is: strip has a face at z=0; tetrahedral mesh // FEMesh Cube("Cube6.node", "Cube6.ele"); // FEMesh surfMesh("Cube6.node", "Cube6Surf.ele"); FEMesh Cube("Strip36.node", "Strip36.ele"); FEMesh surfMesh("Strip36.node", "Strip36Surf.ele"); // FEMesh Cube("Strip144.node", "Strip144.ele"); // FEMesh surfMesh("Strip144.node", "Strip144Surf.ele"); cout << endl; cout << "Number Of Nodes : " << Cube.getNumberOfNodes() << endl; cout << "Number Of Element : " << Cube.getNumberOfElements() << endl; cout << "Mesh Dimension : " << Cube.getDimension() << endl << endl; // Initialize Material uint NumMat = Cube.getNumberOfElements(); vector<MechanicsMaterial * > materials; materials.reserve(NumMat); vector<Vector3d > Fibers; Fibers.reserve(NumMat); for (int k = 0; k < NumMat; k++) { CompNeoHookean* Mat = new CompNeoHookean(k, 1.0, 1.0); materials.push_back(Mat); Vector3d N; N << 0.0, 0.0, 1.0; Fibers.push_back(N); } // Load fibers into elements Cube.setFibers(Fibers); // Initialize Model int NodeDoF = 3; int PressureFlag = 1; Real Pressure = 1.54; int NodalForcesFlag = 1; vector<int > ForcesID; vector<Real > Forces; MechanicsModel myModel(&Cube, materials, NodeDoF, PressureFlag, &surfMesh, NodalForcesFlag); myModel.updatePressure(Pressure); myModel.updateNodalForces(&ForcesID, &Forces); // Initialize Result uint myRequest; uint PbDoF = (Cube.getNumberOfNodes())*myModel.getDoFperNode(); EigenEllipticResult myResults(PbDoF, NumMat*2); // Run Consistency check /* Real perturbationFactor = 0.1; myRequest = 7; // Check both Forces and Stiffness Real myH = 1e-6; Real myTol = 1e-7; myModel.checkConsistency(myResults, perturbationFactor, myRequest, myH, myTol); myModel.checkDmat(myResults, perturbationFactor, myH, myTol); */ // Print initial configuration // myModel.writeOutputVTK("CubeSmall_", 0); myModel.writeOutputVTK("Strip36_", 0); // Check on applied pressure myRequest = 2; myResults.setRequest(myRequest); myModel.compute(myResults); VectorXd Fstart = *(myResults._residual); Real pX = 0.0, pY = 0.0, pZ = 0.0; for (int i = 0; i < Fstart.size(); i += 3) { pX += Fstart(i); pY += Fstart(i+1); pZ += Fstart(i+2); } cout << endl << "Pressure = " << pX << " " << pY << " " << pZ << endl << endl; // EBC vector<int > DoFid; vector<Real > DoFvalues; for(int i = 0; i < Cube.getNumberOfNodes(); i++) { // All nodes at x = 0 if ( Cube.getX(i, 0) < 1.0e-12 ) { DoFid.push_back(i*3); // All nodes at y =0 if ( Cube.getX(i, 1) < 1.0e-12 ) { DoFid.push_back(i*3 + 1); } // All nodes at x = z if ( Cube.getX(i, 2) < 1.0e-12 ) { DoFid.push_back(i*3 + 2); } } } for(int i = 0; i < DoFid.size(); i++) { DoFvalues.push_back( Cube.getX(floor(double(DoFid[i])/3.0) ,DoFid[i]%3) ); // cout << DoFid[i] << " " << DoFvalues[i] << endl; } // Lin tet cube - applied displacements // // for (uint i = 18; i < 27; i++) { // DoFid[i-5] = i*3 + 2; // Lower top in z direction by 0.1 // DoFvalues[i-5] = 1.95; // } // Solver Real NRtol = 1.0e-12; uint NRmaxIter = 100; EigenNRsolver mySolver(&myModel, DoFid, DoFvalues, CHOL, NRtol, NRmaxIter); mySolver.solve(DISP); // myModel.writeOutputVTK("CubeSmall_", 1); myModel.writeOutputVTK("Strip36_", 1); // int m = 5; // double factr = 1.0e+1; // double pgtol = 1.0e-5; // int iprint = 0; // int maxIterations = -1; // vector<int > nbd(PbDoF, 0); // vector<double > lowerBound(PbDoF, 0.0); // vector<double > upperBound(PbDoF, 0.0); // for(int i = 0; i < DoFid.size(); i++) { // nbd[DoFid[i]] = 2; // lowerBound[DoFid[i]] = DoFvalues[i]; // upperBound[DoFid[i]] = DoFvalues[i]; // } // cout << "PbDoF = " << PbDoF << endl; // for (int j = 0; j < PbDoF; j++) { // cout << nbd[j] << " " << lowerBound[j] << " " << upperBound[j] << endl; // } // LBFGSB mySolver(& myModel, & myResults, m, factr, pgtol, iprint, maxIterations); // mySolver.setBounds(nbd, lowerBound, upperBound); // mySolver.solve(); // // Print final configuration // myModel.writeOutputVTK("CubeQuad_", 1); // // Print _field // cout << endl; // myModel.printField(); // cout << endl; // Compute Residual myRequest = 2; myResults.setRequest(myRequest); myModel.compute(myResults); VectorXd F = *(myResults._residual); for (int i = 0; i < DoFid.size(); i ++) { ForcesID.push_back( DoFid[i] ); Forces.push_back( -F(DoFid[i]) ); } // Timing time (&end); cout << endl << "BVP solved in " << difftime(end,start) << " s" << endl; return 0; } <|endoftext|>
<commit_before>/************************************************************************* * Copyright (C) 1995-2020, 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 <ROOT/Browsable/RProvider.hxx> #include "TLeaf.h" #include "TBranch.h" #include "TTree.h" #include "TH1.h" #include "TDirectory.h" #include "TVirtualPad.h" #include <ROOT/RCanvas.hxx> #include <ROOT/RObjectDrawable.hxx> using namespace ROOT::Experimental; /** Provider for drawing of ROOT6 classes */ class RV6DrawProviderTTree : public Browsable::RProvider { public: RV6DrawProviderTTree() { RegisterDraw6(TLeaf::Class(), [](TVirtualPad *pad, std::unique_ptr<Browsable::RHolder> &obj, const std::string &opt) -> bool { // try take object without ownership auto tleaf = obj->get_object<TLeaf>(); if (!tleaf) return false; auto ttree = tleaf->GetBranch()->GetTree(); if (!ttree) return false; std::string expr = std::string(tleaf->GetName()) + ">>htemp_tree_draw"; ttree->Draw(expr.c_str(),"","goff"); if (!gDirectory) return false; auto htemp = dynamic_cast<TH1*>(gDirectory->FindObject("htemp_tree_draw")); if (!htemp) return false; htemp->SetDirectory(nullptr); htemp->SetName(tleaf->GetName()); pad->GetListOfPrimitives()->Clear(); pad->GetListOfPrimitives()->Add(htemp, opt.c_str()); return true; }); } } newRV6DrawProviderTTree; /** Provider for drawing of ROOT7 classes */ class RV7DrawProviderTTree : public Browsable::RProvider { public: RV7DrawProviderTTree() { RegisterDraw7(TLeaf::Class(), [](std::shared_ptr<RPadBase> &subpad, std::unique_ptr<Browsable::RHolder> &obj, const std::string &opt) -> bool { // try take object without ownership auto tleaf = obj->get_object<TLeaf>(); if (!tleaf) return false; auto ttree = tleaf->GetBranch()->GetTree(); if (!ttree) return false; std::string expr = std::string(tleaf->GetName()) + ">>htemp_tree_draw"; ttree->Draw(expr.c_str(),"","goff"); if (!gDirectory) return false; auto htemp = dynamic_cast<TH1*>(gDirectory->FindObject("htemp_tree_draw")); if (!htemp) return false; htemp->SetDirectory(nullptr); htemp->SetName(tleaf->GetName()); if (subpad->NumPrimitives() > 0) { subpad->Wipe(); subpad->GetCanvas()->Modified(); subpad->GetCanvas()->Update(true); } std::shared_ptr<TH1> shared; shared.reset(htemp); subpad->Draw<RObjectDrawable>(shared, opt); return true; }); } } newRV7DrawProviderTTree; <commit_msg>[rbrowsable] complete splitting of TLeaf draw6/7 providers<commit_after>/************************************************************************* * Copyright (C) 1995-2020, 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 "TLeafProvider.hxx" #include "TVirtualPad.h" /** Provider for drawing of ROOT6 classes */ class TLeafDraw6Provider : public TLeafProvider { public: TLeafDraw6Provider() { RegisterDraw6(TLeaf::Class(), [](TVirtualPad *pad, std::unique_ptr<Browsable::RHolder> &obj, const std::string &opt) -> bool { auto hist = TLeafProvider::DrawLeaf(obj); if (!hist) return false; pad->GetListOfPrimitives()->Clear(); pad->GetListOfPrimitives()->Add(hist, opt.c_str()); return true; }); } } newTLeafDraw6Provider; <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2009-2010 TECHNOGERMA Systems France and/or its subsidiary(-ies). ** Contact: Technogerma Systems France Information (contact@technogerma.fr) ** ** This file is part of the CAMP library. ** ** The MIT License (MIT) ** ** Copyright (C) 2009-2010 TECHNOGERMA Systems France and/or its subsidiary(-ies). ** ** 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. ** ****************************************************************************/ #ifndef CAMP_ARRAYMAPPER_HPP #define CAMP_ARRAYMAPPER_HPP #include <camp/config.hpp> #include <camp/detail/yesnotype.hpp> #include <boost/array.hpp> #include <list> #include <vector> namespace camp_ext { /** * \class ArrayMapper * * \brief Template providing a mapping between C++ arrays and CAMP ArrayProperty * * ArrayMapper<T> must define the following members in order to make T fully compliant with the system: * * \li \c ElementType: type of the elements stored in the array * \li \c dynamic(): tells if the array is dynamic (i.e. supports insert and remove) * \li \c size(): retrieve the size of the array * \li \c get(): get the value of an element * \li \c set(): set the value of an element * \li \c insert(): insert a new element * \li \c remove(): remove an element * * ValueMapper is specialized for every supported type, and can be specialized * for any of your own array types in order to extend the system. * * By default, ValueMapper supports the following types of array: * * \li T[] * \li boost::array * \li std::vector * \li std::list * * Here is an example of mapping for the std::vector class: * * \code * namespace camp_ext * { * template <typename T> * struct ArrayMapper<std::vector<T> > * { * typedef T ElementType; * * static bool dynamic() * { * return true; * } * * static std::size_t size(const std::vector<T>& arr) * { * return arr.size(); * } * * static const T& get(const std::vector<T>& arr, std::size_t index) * { * return arr[index]; * } * * static void set(std::vector<T>& arr, std::size_t index, const T& value) * { * arr[index] = value; * } * * static void insert(std::vector<T>& arr, std::size_t before, const T& value) * { * arr.insert(arr.begin() + before, value); * } * * static void remove(std::vector<T>& arr, std::size_t index) * { * arr.erase(arr.begin() + index); * } * }; * } * \endcode */ /* * Generic version -- doesn't define anything */ template <typename T> struct ArrayMapper { }; /* * Specialization of ArrayMapper for built-in static arrays */ template <typename T, std::size_t N> struct ArrayMapper<T[N]> { typedef T ElementType; static bool dynamic() { return false; } static std::size_t size(T (&)[N]) { return N; } static const T& get(T (& arr)[N], std::size_t index) { return arr[index]; } static void set(T (& arr)[N], std::size_t index, const T& value) { arr[index] = value; } static void insert(T (&)[N], std::size_t, const T&) { } static void remove(T (&)[N], std::size_t) { } }; /* * Specialization of ArrayMapper for boost::array */ template <typename T, std::size_t N> struct ArrayMapper<boost::array<T, N> > { typedef T ElementType; static bool dynamic() { return false; } static std::size_t size(const boost::array<T, N>&) { return N; } static const T& get(const boost::array<T, N>& arr, std::size_t index) { return arr[index]; } static void set(boost::array<T, N>& arr, std::size_t index, const T& value) { arr[index] = value; } static void insert(boost::array<T, N>&, std::size_t, const T&) { } static void remove(boost::array<T, N>&, std::size_t) { } }; /* * Specialization of ArrayMapper for std::vector */ template <typename T> struct ArrayMapper<std::vector<T> > { typedef T ElementType; static bool dynamic() { return true; } static std::size_t size(const std::vector<T>& arr) { return arr.size(); } static const T& get(const std::vector<T>& arr, std::size_t index) { return arr[index]; } static void set(std::vector<T>& arr, std::size_t index, const T& value) { arr[index] = value; } static void insert(std::vector<T>& arr, std::size_t before, const T& value) { arr.insert(arr.begin() + before, value); } static void remove(std::vector<T>& arr, std::size_t index) { arr.erase(arr.begin() + index); } }; /* * Specialization of ArrayMapper for std::list */ template <typename T> struct ArrayMapper<std::list<T> > { typedef T ElementType; static bool dynamic() { return true; } static std::size_t size(const std::list<T>& arr) { return arr.size(); } static const T& get(const std::list<T>& arr, std::size_t index) { typename std::list<T>::const_iterator it = arr.begin(); std::advance(it, index); return *it; } static void set(std::list<T>& arr, std::size_t index, const T& value) { typename std::list<T>::iterator it = arr.begin(); std::advance(it, index); *it = value; } static void insert(std::list<T>& arr, std::size_t before, const T& value) { typename std::list<T>::iterator it = arr.begin(); std::advance(it, before); arr.insert(it, value); } static void remove(std::list<T>& arr, std::size_t index) { typename std::list<T>::iterator it = arr.begin(); std::advance(it, index); arr.erase(it); } }; } // namespace camp_ext namespace camp { namespace detail { /** * \brief Helper structure to check at compile time if a type is an array * * This structure check if the specialization of ArrayMapper for the * template parameter T exists (i.e. the ElementType member is properly defined). */ template <typename T> struct IsArray { template <typename U> static TypeYes check(typename U::ElementType*); template <typename U> static TypeNo check(...); enum {value = sizeof(check<camp_ext::ArrayMapper<T> >(0)) == sizeof(TypeYes)}; }; } // namespace detail } // namespace camp #endif // CAMP_ARRAYMAPPER_HPP <commit_msg>boost/array unrequired.<commit_after>/**************************************************************************** ** ** Copyright (C) 2009-2010 TECHNOGERMA Systems France and/or its subsidiary(-ies). ** Contact: Technogerma Systems France Information (contact@technogerma.fr) ** ** This file is part of the CAMP library. ** ** The MIT License (MIT) ** ** Copyright (C) 2009-2010 TECHNOGERMA Systems France and/or its subsidiary(-ies). ** ** 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. ** ****************************************************************************/ #ifndef CAMP_ARRAYMAPPER_HPP #define CAMP_ARRAYMAPPER_HPP #include <camp/config.hpp> #include <camp/detail/yesnotype.hpp> #include <list> #include <vector> namespace camp_ext { /** * \class ArrayMapper * * \brief Template providing a mapping between C++ arrays and CAMP ArrayProperty * * ArrayMapper<T> must define the following members in order to make T fully compliant with the system: * * \li \c ElementType: type of the elements stored in the array * \li \c dynamic(): tells if the array is dynamic (i.e. supports insert and remove) * \li \c size(): retrieve the size of the array * \li \c get(): get the value of an element * \li \c set(): set the value of an element * \li \c insert(): insert a new element * \li \c remove(): remove an element * * ValueMapper is specialized for every supported type, and can be specialized * for any of your own array types in order to extend the system. * * By default, ValueMapper supports the following types of array: * * \li T[] * \li boost::array * \li std::vector * \li std::list * * Here is an example of mapping for the std::vector class: * * \code * namespace camp_ext * { * template <typename T> * struct ArrayMapper<std::vector<T> > * { * typedef T ElementType; * * static bool dynamic() * { * return true; * } * * static std::size_t size(const std::vector<T>& arr) * { * return arr.size(); * } * * static const T& get(const std::vector<T>& arr, std::size_t index) * { * return arr[index]; * } * * static void set(std::vector<T>& arr, std::size_t index, const T& value) * { * arr[index] = value; * } * * static void insert(std::vector<T>& arr, std::size_t before, const T& value) * { * arr.insert(arr.begin() + before, value); * } * * static void remove(std::vector<T>& arr, std::size_t index) * { * arr.erase(arr.begin() + index); * } * }; * } * \endcode */ /* * Generic version -- doesn't define anything */ template <typename T> struct ArrayMapper { }; /* * Specialization of ArrayMapper for built-in static arrays */ template <typename T, std::size_t N> struct ArrayMapper<T[N]> { typedef T ElementType; static bool dynamic() { return false; } static std::size_t size(T (&)[N]) { return N; } static const T& get(T (& arr)[N], std::size_t index) { return arr[index]; } static void set(T (& arr)[N], std::size_t index, const T& value) { arr[index] = value; } static void insert(T (&)[N], std::size_t, const T&) { } static void remove(T (&)[N], std::size_t) { } }; /* * Specialization of ArrayMapper for boost::array */ template <typename T, std::size_t N> struct ArrayMapper<boost::array<T, N> > { typedef T ElementType; static bool dynamic() { return false; } static std::size_t size(const boost::array<T, N>&) { return N; } static const T& get(const boost::array<T, N>& arr, std::size_t index) { return arr[index]; } static void set(boost::array<T, N>& arr, std::size_t index, const T& value) { arr[index] = value; } static void insert(boost::array<T, N>&, std::size_t, const T&) { } static void remove(boost::array<T, N>&, std::size_t) { } }; /* * Specialization of ArrayMapper for std::vector */ template <typename T> struct ArrayMapper<std::vector<T> > { typedef T ElementType; static bool dynamic() { return true; } static std::size_t size(const std::vector<T>& arr) { return arr.size(); } static const T& get(const std::vector<T>& arr, std::size_t index) { return arr[index]; } static void set(std::vector<T>& arr, std::size_t index, const T& value) { arr[index] = value; } static void insert(std::vector<T>& arr, std::size_t before, const T& value) { arr.insert(arr.begin() + before, value); } static void remove(std::vector<T>& arr, std::size_t index) { arr.erase(arr.begin() + index); } }; /* * Specialization of ArrayMapper for std::list */ template <typename T> struct ArrayMapper<std::list<T> > { typedef T ElementType; static bool dynamic() { return true; } static std::size_t size(const std::list<T>& arr) { return arr.size(); } static const T& get(const std::list<T>& arr, std::size_t index) { typename std::list<T>::const_iterator it = arr.begin(); std::advance(it, index); return *it; } static void set(std::list<T>& arr, std::size_t index, const T& value) { typename std::list<T>::iterator it = arr.begin(); std::advance(it, index); *it = value; } static void insert(std::list<T>& arr, std::size_t before, const T& value) { typename std::list<T>::iterator it = arr.begin(); std::advance(it, before); arr.insert(it, value); } static void remove(std::list<T>& arr, std::size_t index) { typename std::list<T>::iterator it = arr.begin(); std::advance(it, index); arr.erase(it); } }; } // namespace camp_ext namespace camp { namespace detail { /** * \brief Helper structure to check at compile time if a type is an array * * This structure check if the specialization of ArrayMapper for the * template parameter T exists (i.e. the ElementType member is properly defined). */ template <typename T> struct IsArray { template <typename U> static TypeYes check(typename U::ElementType*); template <typename U> static TypeNo check(...); enum {value = sizeof(check<camp_ext::ArrayMapper<T> >(0)) == sizeof(TypeYes)}; }; } // namespace detail } // namespace camp #endif // CAMP_ARRAYMAPPER_HPP <|endoftext|>
<commit_before>// Implements the DeployInst class #include "deploy_inst.h" namespace cycamore { DeployInst::DeployInst(cyclus::Context* ctx) : cyclus::Institution(ctx) {} DeployInst::~DeployInst() {} void DeployInst::Build(cyclus::Agent* parent) { cyclus::Institution::Build(parent); BuildSched::iterator it; for (int i = 0; i < prototypes.size(); i++) { std::string proto = prototypes[i]; std::stringstream ss; ss << proto; if (lifetimes.size() == prototypes.size()) { cyclus::Agent* a = context()->CreateAgent<Agent>(proto); a->lifetime(lifetimes[i]); ss << "_life_" << lifetimes[i]; proto = ss.str(); context()->AddPrototype(proto, a); } int t = build_times[i]; for (int j = 0; j < n_build[i]; j++) { context()->SchedBuild(this, proto, t); } } } void DeployInst::EnterNotify() { cyclus::Institution::EnterNotify(); int n = prototypes.size(); if (build_times.size() != n) { std::stringstream ss; ss << "prototype '" << prototype() << "' has " << build_times.size() << " build_times vals, expected " << n; throw cyclus::ValueError(ss.str()); } else if (n_build.size() != n) { std::stringstream ss; ss << "prototype '" << prototype() << "' has " << n_build.size() << " n_build vals, expected " << n; throw cyclus::ValueError(ss.str()); } else if (lifetimes.size() > 0 && lifetimes.size() != n) { std::stringstream ss; ss << "prototype '" << prototype() << "' has " << lifetimes.size() << " lifetimes vals, expected " << n; throw cyclus::ValueError(ss.str()); } } extern "C" cyclus::Agent* ConstructDeployInst(cyclus::Context* ctx) { return new DeployInst(ctx); } } // namespace cycamore <commit_msg>fix duplicate prototype entries in db<commit_after>// Implements the DeployInst class #include "deploy_inst.h" namespace cycamore { DeployInst::DeployInst(cyclus::Context* ctx) : cyclus::Institution(ctx) {} DeployInst::~DeployInst() {} void DeployInst::Build(cyclus::Agent* parent) { cyclus::Institution::Build(parent); BuildSched::iterator it; for (int i = 0; i < prototypes.size(); i++) { std::string proto = prototypes[i]; std::stringstream ss; ss << proto; if (lifetimes.size() == prototypes.size()) { cyclus::Agent* a = context()->CreateAgent<Agent>(proto); if (a->lifetime() != lifetimes[i]) { a->lifetime(lifetimes[i]); if (lifetimes[i] == -1) { ss << "_life_forever"; } else { ss << "_life_" << lifetimes[i]; } proto = ss.str(); context()->AddPrototype(proto, a); } } int t = build_times[i]; for (int j = 0; j < n_build[i]; j++) { context()->SchedBuild(this, proto, t); } } } void DeployInst::EnterNotify() { cyclus::Institution::EnterNotify(); int n = prototypes.size(); if (build_times.size() != n) { std::stringstream ss; ss << "prototype '" << prototype() << "' has " << build_times.size() << " build_times vals, expected " << n; throw cyclus::ValueError(ss.str()); } else if (n_build.size() != n) { std::stringstream ss; ss << "prototype '" << prototype() << "' has " << n_build.size() << " n_build vals, expected " << n; throw cyclus::ValueError(ss.str()); } else if (lifetimes.size() > 0 && lifetimes.size() != n) { std::stringstream ss; ss << "prototype '" << prototype() << "' has " << lifetimes.size() << " lifetimes vals, expected " << n; throw cyclus::ValueError(ss.str()); } } extern "C" cyclus::Agent* ConstructDeployInst(cyclus::Context* ctx) { return new DeployInst(ctx); } } // namespace cycamore <|endoftext|>
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/file_util.h" #include "chrome/browser/automation/url_request_mock_http_job.h" #include "chrome/common/chrome_switches.h" #include "chrome/test/automation/browser_proxy.h" #include "chrome/test/ui/ui_test.h" #include "chrome/views/dialog_delegate.h" #include "net/url_request/url_request_unittest.h" const std::string NOLISTENERS_HTML = "<html><head><title>nolisteners</title></head><body></body></html>"; const std::string UNLOAD_HTML = "<html><head><title>unload</title></head><body>" "<script>window.onunload=function(e){}</script></body></html>"; const std::string BEFORE_UNLOAD_HTML = "<html><head><title>beforeunload</title></head><body>" "<script>window.onbeforeunload=function(e){return 'foo'}</script>" "</body></html>"; const std::string TWO_SECOND_BEFORE_UNLOAD_HTML = "<html><head><title>twosecondbeforeunload</title></head><body>" "<script>window.onbeforeunload=function(e){" "var start = new Date().getTime();" "while(new Date().getTime() - start < 2000){}" "return 'foo';" "}</script></body></html>"; const std::string INFINITE_UNLOAD_HTML = "<html><head><title>infiniteunload</title></head><body>" "<script>window.onunload=function(e){while(true){}}</script>" "</body></html>"; const std::string INFINITE_BEFORE_UNLOAD_HTML = "<html><head><title>infinitebeforeunload</title></head><body>" "<script>window.onbeforeunload=function(e){while(true){}}</script>" "</body></html>"; const std::string INFINITE_UNLOAD_ALERT_HTML = "<html><head><title>infiniteunloadalert</title></head><body>" "<script>window.onunload=function(e){" "while(true){}" "alert('foo');" "}</script></body></html>"; const std::string INFINITE_BEFORE_UNLOAD_ALERT_HTML = "<html><head><title>infinitebeforeunloadalert</title></head><body>" "<script>window.onbeforeunload=function(e){" "while(true){}" "alert('foo');" "}</script></body></html>"; const std::string TWO_SECOND_UNLOAD_ALERT_HTML = "<html><head><title>twosecondunloadalert</title></head><body>" "<script>window.onunload=function(e){" "var start = new Date().getTime();" "while(new Date().getTime() - start < 2000){}" "alert('foo');" "}</script></body></html>"; const std::string TWO_SECOND_BEFORE_UNLOAD_ALERT_HTML = "<html><head><title>twosecondbeforeunloadalert</title></head><body>" "<script>window.onbeforeunload=function(e){" "var start = new Date().getTime();" "while(new Date().getTime() - start < 2000){}" "alert('foo');" "}</script></body></html>"; class UnloadTest : public UITest { public: void WaitForBrowserClosed() { const int kCheckDelayMs = 100; int max_wait_time = 5000; while (max_wait_time > 0) { max_wait_time -= kCheckDelayMs; Sleep(kCheckDelayMs); if (!IsBrowserRunning()) break; } } void CheckTitle(const std::wstring& expected_title) { const int kCheckDelayMs = 100; int max_wait_time = 5000; while (max_wait_time > 0) { max_wait_time -= kCheckDelayMs; Sleep(kCheckDelayMs); if (expected_title == GetActiveTabTitle()) break; } EXPECT_EQ(expected_title, GetActiveTabTitle()); } void NavigateToDataURL(const std::string& html_content, const std::wstring& expected_title) { NavigateToURL(GURL("data:text/html," + html_content)); CheckTitle(expected_title); } void NavigateToNolistenersFileTwice() { NavigateToURL( URLRequestMockHTTPJob::GetMockUrl(L"title2.html")); CheckTitle(L"Title Of Awesomeness"); NavigateToURL( URLRequestMockHTTPJob::GetMockUrl(L"title2.html")); CheckTitle(L"Title Of Awesomeness"); } // Navigates to a URL asynchronously, then again synchronously. The first // load is purposely async to test the case where the user loads another // page without waiting for the first load to complete. void NavigateToNolistenersFileTwiceAsync() { // TODO(ojan): We hit a DCHECK in RenderViewHost::OnMsgShouldCloseACK // if we don't sleep here. Sleep(400); NavigateToURLAsync( URLRequestMockHTTPJob::GetMockUrl(L"title2.html")); Sleep(400); NavigateToURL( URLRequestMockHTTPJob::GetMockUrl(L"title2.html")); CheckTitle(L"Title Of Awesomeness"); } void LoadUrlAndQuitBrowser(const std::string& html_content, const std::wstring& expected_title = L"") { scoped_ptr<BrowserProxy> browser(automation()->GetBrowserWindow(0)); NavigateToDataURL(html_content, expected_title); bool application_closed = false; EXPECT_TRUE(CloseBrowser(browser.get(), &application_closed)); } void ClickModalDialogButton(views::DialogDelegate::DialogButton button) { bool modal_dialog_showing = false; views::DialogDelegate::DialogButton available_buttons; EXPECT_TRUE(automation()->WaitForAppModalDialog(3000)); EXPECT_TRUE(automation()->GetShowingAppModalDialog(&modal_dialog_showing, &available_buttons)); ASSERT_TRUE(modal_dialog_showing); EXPECT_TRUE((button & available_buttons) != NULL); EXPECT_TRUE(automation()->ClickAppModalDialogButton(button)); } }; // Navigate to a page with an infinite unload handler. // Then two two async crosssite requests to ensure // we don't get confused and think we're closing the tab. TEST_F(UnloadTest, CrossSiteInfiniteUnloadAsync) { // Tests makes no sense in single-process mode since the renderer is hung. if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kSingleProcess)) return; NavigateToDataURL(INFINITE_UNLOAD_HTML, L"infiniteunload"); // Must navigate to a non-data URL to trigger cross-site codepath. NavigateToNolistenersFileTwiceAsync(); ASSERT_TRUE(IsBrowserRunning()); } // Navigate to a page with an infinite unload handler. // Then two two sync crosssite requests to ensure // we correctly nav to each one. TEST_F(UnloadTest, CrossSiteInfiniteUnloadSync) { // Tests makes no sense in single-process mode since the renderer is hung. if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kSingleProcess)) return; NavigateToDataURL(INFINITE_UNLOAD_HTML, L"infiniteunload"); // Must navigate to a non-data URL to trigger cross-site codepath. NavigateToNolistenersFileTwice(); ASSERT_TRUE(IsBrowserRunning()); } // Navigate to a page with an infinite beforeunload handler. // Then two two async crosssite requests to ensure // we don't get confused and think we're closing the tab. TEST_F(UnloadTest, CrossSiteInfiniteBeforeUnloadAsync) { // Tests makes no sense in single-process mode since the renderer is hung. if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kSingleProcess)) return; NavigateToDataURL(INFINITE_BEFORE_UNLOAD_HTML, L"infinitebeforeunload"); // Must navigate to a non-data URL to trigger cross-site codepath. NavigateToNolistenersFileTwiceAsync(); ASSERT_TRUE(IsBrowserRunning()); } // Navigate to a page with an infinite beforeunload handler. // Then two two sync crosssite requests to ensure // we correctly nav to each one. TEST_F(UnloadTest, CrossSiteInfiniteBeforeUnloadSync) { // Tests makes no sense in single-process mode since the renderer is hung. if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kSingleProcess)) return; NavigateToDataURL(INFINITE_BEFORE_UNLOAD_HTML, L"infinitebeforeunload"); // Must navigate to a non-data URL to trigger cross-site codepath. NavigateToNolistenersFileTwice(); ASSERT_TRUE(IsBrowserRunning()); } // Tests closing the browser on a page with no unload listeners registered. TEST_F(UnloadTest, BrowserCloseNoUnloadListeners) { LoadUrlAndQuitBrowser(NOLISTENERS_HTML, L"nolisteners"); } // Tests closing the browser on a page with an unload listener registered. TEST_F(UnloadTest, BrowserCloseUnload) { LoadUrlAndQuitBrowser(UNLOAD_HTML, L"unload"); } // Tests closing the browser with a beforeunload handler and clicking // OK in the beforeunload confirm dialog. TEST_F(UnloadTest, BrowserCloseBeforeUnloadOK) { scoped_ptr<BrowserProxy> browser(automation()->GetBrowserWindow(0)); NavigateToDataURL(BEFORE_UNLOAD_HTML, L"beforeunload"); CloseBrowserAsync(browser.get()); ClickModalDialogButton(views::DialogDelegate::DIALOGBUTTON_OK); WaitForBrowserClosed(); EXPECT_FALSE(IsBrowserRunning()); } // Tests closing the browser with a beforeunload handler and clicking // CANCEL in the beforeunload confirm dialog. TEST_F(UnloadTest, BrowserCloseBeforeUnloadCancel) { scoped_ptr<BrowserProxy> browser(automation()->GetBrowserWindow(0)); NavigateToDataURL(BEFORE_UNLOAD_HTML, L"beforeunload"); CloseBrowserAsync(browser.get()); ClickModalDialogButton(views::DialogDelegate::DIALOGBUTTON_CANCEL); WaitForBrowserClosed(); EXPECT_TRUE(IsBrowserRunning()); CloseBrowserAsync(browser.get()); ClickModalDialogButton(views::DialogDelegate::DIALOGBUTTON_OK); WaitForBrowserClosed(); EXPECT_FALSE(IsBrowserRunning()); } // Tests closing the browser with a beforeunload handler that takes // two seconds to run. TEST_F(UnloadTest, BrowserCloseTwoSecondBeforeUnload) { LoadUrlAndQuitBrowser(TWO_SECOND_BEFORE_UNLOAD_HTML, L"twosecondbeforeunload"); } // Tests closing the browser on a page with an unload listener registered where // the unload handler has an infinite loop. TEST_F(UnloadTest, BrowserCloseInfiniteUnload) { LoadUrlAndQuitBrowser(INFINITE_UNLOAD_HTML, L"infiniteunload"); } // Tests closing the browser with a beforeunload handler that hangs. TEST_F(UnloadTest, BrowserCloseInfiniteBeforeUnload) { LoadUrlAndQuitBrowser(INFINITE_BEFORE_UNLOAD_HTML, L"infinitebeforeunload"); } // Tests closing the browser on a page with an unload listener registered where // the unload handler has an infinite loop followed by an alert. TEST_F(UnloadTest, BrowserCloseInfiniteUnloadAlert) { LoadUrlAndQuitBrowser(INFINITE_UNLOAD_ALERT_HTML, L"infiniteunloadalert"); } // Tests closing the browser with a beforeunload handler that hangs then // pops up an alert. TEST_F(UnloadTest, BrowserCloseInfiniteBeforeUnloadAlert) { LoadUrlAndQuitBrowser(INFINITE_BEFORE_UNLOAD_ALERT_HTML, L"infinitebeforeunloadalert"); } // Tests closing the browser on a page with an unload listener registered where // the unload handler has an 2 second long loop followed by an alert. TEST_F(UnloadTest, BrowserCloseTwoSecondUnloadAlert) { LoadUrlAndQuitBrowser(TWO_SECOND_UNLOAD_ALERT_HTML, L"twosecondunloadalert"); } // Tests closing the browser with a beforeunload handler that takes // two seconds to run then pops up an alert. TEST_F(UnloadTest, BrowserCloseTwoSecondBeforeUnloadAlert) { LoadUrlAndQuitBrowser(TWO_SECOND_BEFORE_UNLOAD_ALERT_HTML, L"twosecondbeforeunloadalert"); } // TODO(ojan): Add tests for unload/beforeunload that have multiple tabs // and multiple windows. <commit_msg>Don't run unload tests that hang the renderer in single-process mode, since now the browser thread waits for the renderer thread on shutdown.<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/file_util.h" #include "chrome/browser/automation/url_request_mock_http_job.h" #include "chrome/common/chrome_switches.h" #include "chrome/test/automation/browser_proxy.h" #include "chrome/test/ui/ui_test.h" #include "chrome/views/dialog_delegate.h" #include "net/url_request/url_request_unittest.h" const std::string NOLISTENERS_HTML = "<html><head><title>nolisteners</title></head><body></body></html>"; const std::string UNLOAD_HTML = "<html><head><title>unload</title></head><body>" "<script>window.onunload=function(e){}</script></body></html>"; const std::string BEFORE_UNLOAD_HTML = "<html><head><title>beforeunload</title></head><body>" "<script>window.onbeforeunload=function(e){return 'foo'}</script>" "</body></html>"; const std::string TWO_SECOND_BEFORE_UNLOAD_HTML = "<html><head><title>twosecondbeforeunload</title></head><body>" "<script>window.onbeforeunload=function(e){" "var start = new Date().getTime();" "while(new Date().getTime() - start < 2000){}" "return 'foo';" "}</script></body></html>"; const std::string INFINITE_UNLOAD_HTML = "<html><head><title>infiniteunload</title></head><body>" "<script>window.onunload=function(e){while(true){}}</script>" "</body></html>"; const std::string INFINITE_BEFORE_UNLOAD_HTML = "<html><head><title>infinitebeforeunload</title></head><body>" "<script>window.onbeforeunload=function(e){while(true){}}</script>" "</body></html>"; const std::string INFINITE_UNLOAD_ALERT_HTML = "<html><head><title>infiniteunloadalert</title></head><body>" "<script>window.onunload=function(e){" "while(true){}" "alert('foo');" "}</script></body></html>"; const std::string INFINITE_BEFORE_UNLOAD_ALERT_HTML = "<html><head><title>infinitebeforeunloadalert</title></head><body>" "<script>window.onbeforeunload=function(e){" "while(true){}" "alert('foo');" "}</script></body></html>"; const std::string TWO_SECOND_UNLOAD_ALERT_HTML = "<html><head><title>twosecondunloadalert</title></head><body>" "<script>window.onunload=function(e){" "var start = new Date().getTime();" "while(new Date().getTime() - start < 2000){}" "alert('foo');" "}</script></body></html>"; const std::string TWO_SECOND_BEFORE_UNLOAD_ALERT_HTML = "<html><head><title>twosecondbeforeunloadalert</title></head><body>" "<script>window.onbeforeunload=function(e){" "var start = new Date().getTime();" "while(new Date().getTime() - start < 2000){}" "alert('foo');" "}</script></body></html>"; class UnloadTest : public UITest { public: void WaitForBrowserClosed() { const int kCheckDelayMs = 100; int max_wait_time = 5000; while (max_wait_time > 0) { max_wait_time -= kCheckDelayMs; Sleep(kCheckDelayMs); if (!IsBrowserRunning()) break; } } void CheckTitle(const std::wstring& expected_title) { const int kCheckDelayMs = 100; int max_wait_time = 5000; while (max_wait_time > 0) { max_wait_time -= kCheckDelayMs; Sleep(kCheckDelayMs); if (expected_title == GetActiveTabTitle()) break; } EXPECT_EQ(expected_title, GetActiveTabTitle()); } void NavigateToDataURL(const std::string& html_content, const std::wstring& expected_title) { NavigateToURL(GURL("data:text/html," + html_content)); CheckTitle(expected_title); } void NavigateToNolistenersFileTwice() { NavigateToURL( URLRequestMockHTTPJob::GetMockUrl(L"title2.html")); CheckTitle(L"Title Of Awesomeness"); NavigateToURL( URLRequestMockHTTPJob::GetMockUrl(L"title2.html")); CheckTitle(L"Title Of Awesomeness"); } // Navigates to a URL asynchronously, then again synchronously. The first // load is purposely async to test the case where the user loads another // page without waiting for the first load to complete. void NavigateToNolistenersFileTwiceAsync() { // TODO(ojan): We hit a DCHECK in RenderViewHost::OnMsgShouldCloseACK // if we don't sleep here. Sleep(400); NavigateToURLAsync( URLRequestMockHTTPJob::GetMockUrl(L"title2.html")); Sleep(400); NavigateToURL( URLRequestMockHTTPJob::GetMockUrl(L"title2.html")); CheckTitle(L"Title Of Awesomeness"); } void LoadUrlAndQuitBrowser(const std::string& html_content, const std::wstring& expected_title = L"") { scoped_ptr<BrowserProxy> browser(automation()->GetBrowserWindow(0)); NavigateToDataURL(html_content, expected_title); bool application_closed = false; EXPECT_TRUE(CloseBrowser(browser.get(), &application_closed)); } void ClickModalDialogButton(views::DialogDelegate::DialogButton button) { bool modal_dialog_showing = false; views::DialogDelegate::DialogButton available_buttons; EXPECT_TRUE(automation()->WaitForAppModalDialog(3000)); EXPECT_TRUE(automation()->GetShowingAppModalDialog(&modal_dialog_showing, &available_buttons)); ASSERT_TRUE(modal_dialog_showing); EXPECT_TRUE((button & available_buttons) != NULL); EXPECT_TRUE(automation()->ClickAppModalDialogButton(button)); } }; // Navigate to a page with an infinite unload handler. // Then two two async crosssite requests to ensure // we don't get confused and think we're closing the tab. TEST_F(UnloadTest, CrossSiteInfiniteUnloadAsync) { // Tests makes no sense in single-process mode since the renderer is hung. if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kSingleProcess)) return; NavigateToDataURL(INFINITE_UNLOAD_HTML, L"infiniteunload"); // Must navigate to a non-data URL to trigger cross-site codepath. NavigateToNolistenersFileTwiceAsync(); ASSERT_TRUE(IsBrowserRunning()); } // Navigate to a page with an infinite unload handler. // Then two two sync crosssite requests to ensure // we correctly nav to each one. TEST_F(UnloadTest, CrossSiteInfiniteUnloadSync) { // Tests makes no sense in single-process mode since the renderer is hung. if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kSingleProcess)) return; NavigateToDataURL(INFINITE_UNLOAD_HTML, L"infiniteunload"); // Must navigate to a non-data URL to trigger cross-site codepath. NavigateToNolistenersFileTwice(); ASSERT_TRUE(IsBrowserRunning()); } // Navigate to a page with an infinite beforeunload handler. // Then two two async crosssite requests to ensure // we don't get confused and think we're closing the tab. TEST_F(UnloadTest, CrossSiteInfiniteBeforeUnloadAsync) { // Tests makes no sense in single-process mode since the renderer is hung. if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kSingleProcess)) return; NavigateToDataURL(INFINITE_BEFORE_UNLOAD_HTML, L"infinitebeforeunload"); // Must navigate to a non-data URL to trigger cross-site codepath. NavigateToNolistenersFileTwiceAsync(); ASSERT_TRUE(IsBrowserRunning()); } // Navigate to a page with an infinite beforeunload handler. // Then two two sync crosssite requests to ensure // we correctly nav to each one. TEST_F(UnloadTest, CrossSiteInfiniteBeforeUnloadSync) { // Tests makes no sense in single-process mode since the renderer is hung. if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kSingleProcess)) return; NavigateToDataURL(INFINITE_BEFORE_UNLOAD_HTML, L"infinitebeforeunload"); // Must navigate to a non-data URL to trigger cross-site codepath. NavigateToNolistenersFileTwice(); ASSERT_TRUE(IsBrowserRunning()); } // Tests closing the browser on a page with no unload listeners registered. TEST_F(UnloadTest, BrowserCloseNoUnloadListeners) { LoadUrlAndQuitBrowser(NOLISTENERS_HTML, L"nolisteners"); } // Tests closing the browser on a page with an unload listener registered. TEST_F(UnloadTest, BrowserCloseUnload) { LoadUrlAndQuitBrowser(UNLOAD_HTML, L"unload"); } // Tests closing the browser with a beforeunload handler and clicking // OK in the beforeunload confirm dialog. TEST_F(UnloadTest, BrowserCloseBeforeUnloadOK) { scoped_ptr<BrowserProxy> browser(automation()->GetBrowserWindow(0)); NavigateToDataURL(BEFORE_UNLOAD_HTML, L"beforeunload"); CloseBrowserAsync(browser.get()); ClickModalDialogButton(views::DialogDelegate::DIALOGBUTTON_OK); WaitForBrowserClosed(); EXPECT_FALSE(IsBrowserRunning()); } // Tests closing the browser with a beforeunload handler and clicking // CANCEL in the beforeunload confirm dialog. TEST_F(UnloadTest, BrowserCloseBeforeUnloadCancel) { scoped_ptr<BrowserProxy> browser(automation()->GetBrowserWindow(0)); NavigateToDataURL(BEFORE_UNLOAD_HTML, L"beforeunload"); CloseBrowserAsync(browser.get()); ClickModalDialogButton(views::DialogDelegate::DIALOGBUTTON_CANCEL); WaitForBrowserClosed(); EXPECT_TRUE(IsBrowserRunning()); CloseBrowserAsync(browser.get()); ClickModalDialogButton(views::DialogDelegate::DIALOGBUTTON_OK); WaitForBrowserClosed(); EXPECT_FALSE(IsBrowserRunning()); } // Tests closing the browser with a beforeunload handler that takes // two seconds to run. TEST_F(UnloadTest, BrowserCloseTwoSecondBeforeUnload) { LoadUrlAndQuitBrowser(TWO_SECOND_BEFORE_UNLOAD_HTML, L"twosecondbeforeunload"); } // Tests closing the browser on a page with an unload listener registered where // the unload handler has an infinite loop. TEST_F(UnloadTest, BrowserCloseInfiniteUnload) { // Tests makes no sense in single-process mode since the renderer is hung. if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kSingleProcess)) return; LoadUrlAndQuitBrowser(INFINITE_UNLOAD_HTML, L"infiniteunload"); } // Tests closing the browser with a beforeunload handler that hangs. TEST_F(UnloadTest, BrowserCloseInfiniteBeforeUnload) { // Tests makes no sense in single-process mode since the renderer is hung. if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kSingleProcess)) return; LoadUrlAndQuitBrowser(INFINITE_BEFORE_UNLOAD_HTML, L"infinitebeforeunload"); } // Tests closing the browser on a page with an unload listener registered where // the unload handler has an infinite loop followed by an alert. TEST_F(UnloadTest, BrowserCloseInfiniteUnloadAlert) { // Tests makes no sense in single-process mode since the renderer is hung. if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kSingleProcess)) return; LoadUrlAndQuitBrowser(INFINITE_UNLOAD_ALERT_HTML, L"infiniteunloadalert"); } // Tests closing the browser with a beforeunload handler that hangs then // pops up an alert. TEST_F(UnloadTest, BrowserCloseInfiniteBeforeUnloadAlert) { // Tests makes no sense in single-process mode since the renderer is hung. if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kSingleProcess)) return; LoadUrlAndQuitBrowser(INFINITE_BEFORE_UNLOAD_ALERT_HTML, L"infinitebeforeunloadalert"); } // Tests closing the browser on a page with an unload listener registered where // the unload handler has an 2 second long loop followed by an alert. TEST_F(UnloadTest, BrowserCloseTwoSecondUnloadAlert) { LoadUrlAndQuitBrowser(TWO_SECOND_UNLOAD_ALERT_HTML, L"twosecondunloadalert"); } // Tests closing the browser with a beforeunload handler that takes // two seconds to run then pops up an alert. TEST_F(UnloadTest, BrowserCloseTwoSecondBeforeUnloadAlert) { LoadUrlAndQuitBrowser(TWO_SECOND_BEFORE_UNLOAD_ALERT_HTML, L"twosecondbeforeunloadalert"); } // TODO(ojan): Add tests for unload/beforeunload that have multiple tabs // and multiple windows. <|endoftext|>
<commit_before>// // Copyright 2012 Francisco Jerez // // 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 "core/compiler.hpp" #include <clang/Frontend/CompilerInstance.h> #include <clang/Frontend/TextDiagnosticBuffer.h> #include <clang/Frontend/TextDiagnosticPrinter.h> #include <clang/CodeGen/CodeGenAction.h> #include <clang/Basic/TargetInfo.h> #include <llvm/Bitcode/BitstreamWriter.h> #include <llvm/Bitcode/ReaderWriter.h> #include <llvm/Linker.h> #if HAVE_LLVM < 0x0303 #include <llvm/DerivedTypes.h> #include <llvm/LLVMContext.h> #include <llvm/Module.h> #else #include <llvm/IR/DerivedTypes.h> #include <llvm/IR/LLVMContext.h> #include <llvm/IR/Module.h> #include <llvm/Support/SourceMgr.h> #include <llvm/IRReader/IRReader.h> #endif #include <llvm/PassManager.h> #include <llvm/Support/TargetSelect.h> #include <llvm/Support/MemoryBuffer.h> #if HAVE_LLVM < 0x0303 #include <llvm/Support/PathV1.h> #endif #include <llvm/Transforms/IPO.h> #include <llvm/Transforms/IPO/PassManagerBuilder.h> #if HAVE_LLVM < 0x0302 #include <llvm/Target/TargetData.h> #elif HAVE_LLVM < 0x0303 #include <llvm/DataLayout.h> #else #include <llvm/IR/DataLayout.h> #endif #include "pipe/p_state.h" #include "util/u_memory.h" #include <iostream> #include <iomanip> #include <fstream> #include <cstdio> #include <sstream> using namespace clover; namespace { #if 0 void build_binary(const std::string &source, const std::string &target, const std::string &name) { clang::CompilerInstance c; clang::EmitObjAction act(&llvm::getGlobalContext()); std::string log; llvm::raw_string_ostream s_log(log); LLVMInitializeTGSITarget(); LLVMInitializeTGSITargetInfo(); LLVMInitializeTGSITargetMC(); LLVMInitializeTGSIAsmPrinter(); c.getFrontendOpts().Inputs.push_back( std::make_pair(clang::IK_OpenCL, name)); c.getHeaderSearchOpts().UseBuiltinIncludes = false; c.getHeaderSearchOpts().UseStandardIncludes = false; c.getLangOpts().NoBuiltin = true; c.getTargetOpts().Triple = target; c.getInvocation().setLangDefaults(clang::IK_OpenCL); c.createDiagnostics(0, NULL, new clang::TextDiagnosticPrinter( s_log, c.getDiagnosticOpts())); c.getPreprocessorOpts().addRemappedFile( name, llvm::MemoryBuffer::getMemBuffer(source)); if (!c.ExecuteAction(act)) throw build_error(log); } module load_binary(const char *name) { std::ifstream fs((name)); std::vector<unsigned char> str((std::istreambuf_iterator<char>(fs)), (std::istreambuf_iterator<char>())); compat::istream cs(str); return module::deserialize(cs); } #endif llvm::Module * compile(const std::string &source, const std::string &name, const std::string &triple, const std::string &processor, const std::string &opts, clang::LangAS::Map& address_spaces) { clang::CompilerInstance c; clang::CompilerInvocation invocation; clang::EmitLLVMOnlyAction act(&llvm::getGlobalContext()); std::string log; llvm::raw_string_ostream s_log(log); // Parse the compiler options: std::vector<std::string> opts_array; std::istringstream ss(opts); while (!ss.eof()) { std::string opt; getline(ss, opt, ' '); opts_array.push_back(opt); } opts_array.push_back(name); std::vector<const char *> opts_carray; for (unsigned i = 0; i < opts_array.size(); i++) { opts_carray.push_back(opts_array.at(i).c_str()); } llvm::IntrusiveRefCntPtr<clang::DiagnosticIDs> DiagID; llvm::IntrusiveRefCntPtr<clang::DiagnosticOptions> DiagOpts; clang::TextDiagnosticBuffer *DiagsBuffer; DiagID = new clang::DiagnosticIDs(); DiagOpts = new clang::DiagnosticOptions(); DiagsBuffer = new clang::TextDiagnosticBuffer(); clang::DiagnosticsEngine Diags(DiagID, &*DiagOpts, DiagsBuffer); bool Success; Success = clang::CompilerInvocation::CreateFromArgs(c.getInvocation(), opts_carray.data(), opts_carray.data() + opts_carray.size(), Diags); if (!Success) { throw invalid_option_error(); } c.getFrontendOpts().ProgramAction = clang::frontend::EmitLLVMOnly; c.getHeaderSearchOpts().UseBuiltinIncludes = true; c.getHeaderSearchOpts().UseStandardSystemIncludes = true; c.getHeaderSearchOpts().ResourceDir = CLANG_RESOURCE_DIR; // Add libclc generic search path c.getHeaderSearchOpts().AddPath(LIBCLC_INCLUDEDIR, clang::frontend::Angled, false, false #if HAVE_LLVM < 0x0303 , false #endif ); // Add libclc include c.getPreprocessorOpts().Includes.push_back("clc/clc.h"); // clc.h requires that this macro be defined: c.getPreprocessorOpts().addMacroDef("cl_clang_storage_class_specifiers"); c.getPreprocessorOpts().addMacroDef("cl_khr_fp64"); c.getLangOpts().NoBuiltin = true; c.getTargetOpts().Triple = triple; c.getTargetOpts().CPU = processor; #if HAVE_LLVM <= 0x0301 c.getInvocation().setLangDefaults(clang::IK_OpenCL); #else c.getInvocation().setLangDefaults(c.getLangOpts(), clang::IK_OpenCL, clang::LangStandard::lang_opencl11); #endif c.createDiagnostics( #if HAVE_LLVM < 0x0303 0, NULL, #endif new clang::TextDiagnosticPrinter( s_log, #if HAVE_LLVM <= 0x0301 c.getDiagnosticOpts())); #else &c.getDiagnosticOpts())); #endif c.getPreprocessorOpts().addRemappedFile(name, llvm::MemoryBuffer::getMemBuffer(source)); // Compile the code if (!c.ExecuteAction(act)) throw build_error(log); // Get address spaces map to be able to find kernel argument address space memcpy(address_spaces, c.getTarget().getAddressSpaceMap(), sizeof(address_spaces)); return act.takeModule(); } void find_kernels(llvm::Module *mod, std::vector<llvm::Function *> &kernels) { const llvm::NamedMDNode *kernel_node = mod->getNamedMetadata("opencl.kernels"); // This means there are no kernels in the program. The spec does not // require that we return an error here, but there will be an error if // the user tries to pass this program to a clCreateKernel() call. if (!kernel_node) { return; } for (unsigned i = 0; i < kernel_node->getNumOperands(); ++i) { kernels.push_back(llvm::dyn_cast<llvm::Function>( kernel_node->getOperand(i)->getOperand(0))); } } void link(llvm::Module *mod, const std::string &triple, const std::string &processor, const std::vector<llvm::Function *> &kernels) { llvm::PassManager PM; llvm::PassManagerBuilder Builder; std::string libclc_path = LIBCLC_LIBEXECDIR + processor + "-" + triple + ".bc"; // Link the kernel with libclc #if HAVE_LLVM < 0x0303 bool isNative; llvm::Linker linker("clover", mod); linker.LinkInFile(llvm::sys::Path(libclc_path), isNative); mod = linker.releaseModule(); #else std::string err_str; llvm::SMDiagnostic err; llvm::Module *libclc_mod = llvm::ParseIRFile(libclc_path, err, mod->getContext()); if (llvm::Linker::LinkModules(mod, libclc_mod, llvm::Linker::DestroySource, &err_str)) { throw build_error(err_str); } #endif // Add a function internalizer pass. // // By default, the function internalizer pass will look for a function // called "main" and then mark all other functions as internal. Marking // functions as internal enables the optimizer to perform optimizations // like function inlining and global dead-code elimination. // // When there is no "main" function in a module, the internalize pass will // treat the module like a library, and it won't internalize any functions. // Since there is no "main" function in our kernels, we need to tell // the internalizer pass that this module is not a library by passing a // list of kernel functions to the internalizer. The internalizer will // treat the functions in the list as "main" functions and internalize // all of the other functions. std::vector<const char*> export_list; for (std::vector<llvm::Function *>::const_iterator I = kernels.begin(), E = kernels.end(); I != E; ++I) { llvm::Function *kernel = *I; export_list.push_back(kernel->getName().data()); } #if HAVE_LLVM < 0x0304 PM.add(llvm::createInternalizePass(export_list)); #else std::vector<const char*> dso_list; PM.add(llvm::createInternalizePass(export_list, dso_list)); #endif // Run link time optimizations Builder.OptLevel = 2; Builder.populateLTOPassManager(PM, false, true); PM.run(*mod); } module build_module_llvm(llvm::Module *mod, const std::vector<llvm::Function *> &kernels, clang::LangAS::Map& address_spaces) { module m; struct pipe_llvm_program_header header; llvm::SmallVector<char, 1024> llvm_bitcode; llvm::raw_svector_ostream bitcode_ostream(llvm_bitcode); llvm::BitstreamWriter writer(llvm_bitcode); llvm::WriteBitcodeToFile(mod, bitcode_ostream); bitcode_ostream.flush(); for (unsigned i = 0; i < kernels.size(); ++i) { llvm::Function *kernel_func; std::string kernel_name; compat::vector<module::argument> args; kernel_func = kernels[i]; kernel_name = kernel_func->getName(); for (llvm::Function::arg_iterator I = kernel_func->arg_begin(), E = kernel_func->arg_end(); I != E; ++I) { llvm::Argument &arg = *I; #if HAVE_LLVM < 0x0302 llvm::TargetData TD(kernel_func->getParent()); #else llvm::DataLayout TD(kernel_func->getParent()->getDataLayout()); #endif llvm::Type *arg_type = arg.getType(); unsigned arg_size = TD.getTypeStoreSize(arg_type); llvm::Type *target_type = arg_type->isIntegerTy() ? TD.getSmallestLegalIntType(mod->getContext(), arg_size * 8) : arg_type; unsigned target_size = TD.getTypeStoreSize(target_type); unsigned target_align = TD.getABITypeAlignment(target_type); if (llvm::isa<llvm::PointerType>(arg_type) && arg.hasByValAttr()) { arg_type = llvm::dyn_cast<llvm::PointerType>(arg_type)->getElementType(); } if (arg_type->isPointerTy()) { unsigned address_space = llvm::cast<llvm::PointerType>(arg_type)->getAddressSpace(); if (address_space == address_spaces[clang::LangAS::opencl_local - clang::LangAS::Offset]) { args.push_back(module::argument(module::argument::local, arg_size, target_size, target_align, module::argument::zero_ext)); } else { // XXX: Correctly handle constant address space. There is no // way for r600g to pass a handle for constant buffers back // to clover like it can for global buffers, so // creating constant arguements will break r600g. For now, // continue treating constant buffers as global buffers // until we can come up with a way to create handles for // constant buffers. args.push_back(module::argument(module::argument::global, arg_size, target_size, target_align, module::argument::zero_ext)); } } else { llvm::AttributeSet attrs = kernel_func->getAttributes(); enum module::argument::ext_type ext_type = (attrs.hasAttribute(arg.getArgNo() + 1, llvm::Attribute::SExt) ? module::argument::sign_ext : module::argument::zero_ext); args.push_back( module::argument(module::argument::scalar, arg_size, target_size, target_align, ext_type)); } } m.syms.push_back(module::symbol(kernel_name, 0, i, args )); } header.num_bytes = llvm_bitcode.size(); std::string data; data.insert(0, (char*)(&header), sizeof(header)); data.insert(data.end(), llvm_bitcode.begin(), llvm_bitcode.end()); m.secs.push_back(module::section(0, module::section::text, header.num_bytes, data)); return m; } } // End anonymous namespace module clover::compile_program_llvm(const compat::string &source, enum pipe_shader_ir ir, const compat::string &target, const compat::string &opts) { std::vector<llvm::Function *> kernels; size_t processor_str_len = std::string(target.begin()).find_first_of("-"); std::string processor(target.begin(), 0, processor_str_len); std::string triple(target.begin(), processor_str_len + 1, target.size() - processor_str_len - 1); clang::LangAS::Map address_spaces; // The input file name must have the .cl extension in order for the // CompilerInvocation class to recognize it as an OpenCL source file. llvm::Module *mod = compile(source, "input.cl", triple, processor, opts, address_spaces); find_kernels(mod, kernels); link(mod, triple, processor, kernels); // Build the clover::module switch (ir) { case PIPE_SHADER_IR_TGSI: //XXX: Handle TGSI assert(0); return module(); default: return build_module_llvm(mod, kernels, address_spaces); } } <commit_msg>clover: Link libclc before running any optimizations<commit_after>// // Copyright 2012 Francisco Jerez // // 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 "core/compiler.hpp" #include <clang/Frontend/CompilerInstance.h> #include <clang/Frontend/TextDiagnosticBuffer.h> #include <clang/Frontend/TextDiagnosticPrinter.h> #include <clang/CodeGen/CodeGenAction.h> #include <clang/Basic/TargetInfo.h> #include <llvm/Bitcode/BitstreamWriter.h> #include <llvm/Bitcode/ReaderWriter.h> #include <llvm/Linker.h> #if HAVE_LLVM < 0x0303 #include <llvm/DerivedTypes.h> #include <llvm/LLVMContext.h> #include <llvm/Module.h> #else #include <llvm/IR/DerivedTypes.h> #include <llvm/IR/LLVMContext.h> #include <llvm/IR/Module.h> #include <llvm/Support/SourceMgr.h> #include <llvm/IRReader/IRReader.h> #endif #include <llvm/PassManager.h> #include <llvm/Support/TargetSelect.h> #include <llvm/Support/MemoryBuffer.h> #if HAVE_LLVM < 0x0303 #include <llvm/Support/PathV1.h> #endif #include <llvm/Transforms/IPO.h> #include <llvm/Transforms/IPO/PassManagerBuilder.h> #if HAVE_LLVM < 0x0302 #include <llvm/Target/TargetData.h> #elif HAVE_LLVM < 0x0303 #include <llvm/DataLayout.h> #else #include <llvm/IR/DataLayout.h> #endif #include "pipe/p_state.h" #include "util/u_memory.h" #include <iostream> #include <iomanip> #include <fstream> #include <cstdio> #include <sstream> using namespace clover; namespace { #if 0 void build_binary(const std::string &source, const std::string &target, const std::string &name) { clang::CompilerInstance c; clang::EmitObjAction act(&llvm::getGlobalContext()); std::string log; llvm::raw_string_ostream s_log(log); LLVMInitializeTGSITarget(); LLVMInitializeTGSITargetInfo(); LLVMInitializeTGSITargetMC(); LLVMInitializeTGSIAsmPrinter(); c.getFrontendOpts().Inputs.push_back( std::make_pair(clang::IK_OpenCL, name)); c.getHeaderSearchOpts().UseBuiltinIncludes = false; c.getHeaderSearchOpts().UseStandardIncludes = false; c.getLangOpts().NoBuiltin = true; c.getTargetOpts().Triple = target; c.getInvocation().setLangDefaults(clang::IK_OpenCL); c.createDiagnostics(0, NULL, new clang::TextDiagnosticPrinter( s_log, c.getDiagnosticOpts())); c.getPreprocessorOpts().addRemappedFile( name, llvm::MemoryBuffer::getMemBuffer(source)); if (!c.ExecuteAction(act)) throw build_error(log); } module load_binary(const char *name) { std::ifstream fs((name)); std::vector<unsigned char> str((std::istreambuf_iterator<char>(fs)), (std::istreambuf_iterator<char>())); compat::istream cs(str); return module::deserialize(cs); } #endif llvm::Module * compile(const std::string &source, const std::string &name, const std::string &triple, const std::string &processor, const std::string &opts, clang::LangAS::Map& address_spaces) { clang::CompilerInstance c; clang::CompilerInvocation invocation; clang::EmitLLVMOnlyAction act(&llvm::getGlobalContext()); std::string log; llvm::raw_string_ostream s_log(log); std::string libclc_path = LIBCLC_LIBEXECDIR + processor + "-" + triple + ".bc"; // Parse the compiler options: std::vector<std::string> opts_array; std::istringstream ss(opts); while (!ss.eof()) { std::string opt; getline(ss, opt, ' '); opts_array.push_back(opt); } opts_array.push_back(name); std::vector<const char *> opts_carray; for (unsigned i = 0; i < opts_array.size(); i++) { opts_carray.push_back(opts_array.at(i).c_str()); } llvm::IntrusiveRefCntPtr<clang::DiagnosticIDs> DiagID; llvm::IntrusiveRefCntPtr<clang::DiagnosticOptions> DiagOpts; clang::TextDiagnosticBuffer *DiagsBuffer; DiagID = new clang::DiagnosticIDs(); DiagOpts = new clang::DiagnosticOptions(); DiagsBuffer = new clang::TextDiagnosticBuffer(); clang::DiagnosticsEngine Diags(DiagID, &*DiagOpts, DiagsBuffer); bool Success; Success = clang::CompilerInvocation::CreateFromArgs(c.getInvocation(), opts_carray.data(), opts_carray.data() + opts_carray.size(), Diags); if (!Success) { throw invalid_option_error(); } c.getFrontendOpts().ProgramAction = clang::frontend::EmitLLVMOnly; c.getHeaderSearchOpts().UseBuiltinIncludes = true; c.getHeaderSearchOpts().UseStandardSystemIncludes = true; c.getHeaderSearchOpts().ResourceDir = CLANG_RESOURCE_DIR; // Add libclc generic search path c.getHeaderSearchOpts().AddPath(LIBCLC_INCLUDEDIR, clang::frontend::Angled, false, false #if HAVE_LLVM < 0x0303 , false #endif ); // Add libclc include c.getPreprocessorOpts().Includes.push_back("clc/clc.h"); // clc.h requires that this macro be defined: c.getPreprocessorOpts().addMacroDef("cl_clang_storage_class_specifiers"); c.getPreprocessorOpts().addMacroDef("cl_khr_fp64"); c.getLangOpts().NoBuiltin = true; c.getTargetOpts().Triple = triple; c.getTargetOpts().CPU = processor; #if HAVE_LLVM <= 0x0301 c.getInvocation().setLangDefaults(clang::IK_OpenCL); #else c.getInvocation().setLangDefaults(c.getLangOpts(), clang::IK_OpenCL, clang::LangStandard::lang_opencl11); #endif c.createDiagnostics( #if HAVE_LLVM < 0x0303 0, NULL, #endif new clang::TextDiagnosticPrinter( s_log, #if HAVE_LLVM <= 0x0301 c.getDiagnosticOpts())); #else &c.getDiagnosticOpts())); #endif c.getPreprocessorOpts().addRemappedFile(name, llvm::MemoryBuffer::getMemBuffer(source)); // Setting this attribute tells clang to link this file before // performing any optimizations. This is required so that // we can replace calls to the OpenCL C barrier() builtin // with calls to target intrinsics that have the noduplicate // attribute. This attribute will prevent Clang from creating // illegal uses of barrier() (e.g. Moving barrier() inside a conditional // that is no executed by all threads) during its optimizaton passes. c.getCodeGenOpts().LinkBitcodeFile = libclc_path; // Compile the code if (!c.ExecuteAction(act)) throw build_error(log); // Get address spaces map to be able to find kernel argument address space memcpy(address_spaces, c.getTarget().getAddressSpaceMap(), sizeof(address_spaces)); return act.takeModule(); } void find_kernels(llvm::Module *mod, std::vector<llvm::Function *> &kernels) { const llvm::NamedMDNode *kernel_node = mod->getNamedMetadata("opencl.kernels"); // This means there are no kernels in the program. The spec does not // require that we return an error here, but there will be an error if // the user tries to pass this program to a clCreateKernel() call. if (!kernel_node) { return; } for (unsigned i = 0; i < kernel_node->getNumOperands(); ++i) { kernels.push_back(llvm::dyn_cast<llvm::Function>( kernel_node->getOperand(i)->getOperand(0))); } } void internalize_functions(llvm::Module *mod, const std::vector<llvm::Function *> &kernels) { llvm::PassManager PM; // Add a function internalizer pass. // // By default, the function internalizer pass will look for a function // called "main" and then mark all other functions as internal. Marking // functions as internal enables the optimizer to perform optimizations // like function inlining and global dead-code elimination. // // When there is no "main" function in a module, the internalize pass will // treat the module like a library, and it won't internalize any functions. // Since there is no "main" function in our kernels, we need to tell // the internalizer pass that this module is not a library by passing a // list of kernel functions to the internalizer. The internalizer will // treat the functions in the list as "main" functions and internalize // all of the other functions. std::vector<const char*> export_list; for (std::vector<llvm::Function *>::const_iterator I = kernels.begin(), E = kernels.end(); I != E; ++I) { llvm::Function *kernel = *I; export_list.push_back(kernel->getName().data()); } #if HAVE_LLVM < 0x0304 PM.add(llvm::createInternalizePass(export_list)); #else std::vector<const char*> dso_list; PM.add(llvm::createInternalizePass(export_list, dso_list)); #endif PM.run(*mod); } module build_module_llvm(llvm::Module *mod, const std::vector<llvm::Function *> &kernels, clang::LangAS::Map& address_spaces) { module m; struct pipe_llvm_program_header header; llvm::SmallVector<char, 1024> llvm_bitcode; llvm::raw_svector_ostream bitcode_ostream(llvm_bitcode); llvm::BitstreamWriter writer(llvm_bitcode); llvm::WriteBitcodeToFile(mod, bitcode_ostream); bitcode_ostream.flush(); for (unsigned i = 0; i < kernels.size(); ++i) { llvm::Function *kernel_func; std::string kernel_name; compat::vector<module::argument> args; kernel_func = kernels[i]; kernel_name = kernel_func->getName(); for (llvm::Function::arg_iterator I = kernel_func->arg_begin(), E = kernel_func->arg_end(); I != E; ++I) { llvm::Argument &arg = *I; #if HAVE_LLVM < 0x0302 llvm::TargetData TD(kernel_func->getParent()); #else llvm::DataLayout TD(kernel_func->getParent()->getDataLayout()); #endif llvm::Type *arg_type = arg.getType(); unsigned arg_size = TD.getTypeStoreSize(arg_type); llvm::Type *target_type = arg_type->isIntegerTy() ? TD.getSmallestLegalIntType(mod->getContext(), arg_size * 8) : arg_type; unsigned target_size = TD.getTypeStoreSize(target_type); unsigned target_align = TD.getABITypeAlignment(target_type); if (llvm::isa<llvm::PointerType>(arg_type) && arg.hasByValAttr()) { arg_type = llvm::dyn_cast<llvm::PointerType>(arg_type)->getElementType(); } if (arg_type->isPointerTy()) { unsigned address_space = llvm::cast<llvm::PointerType>(arg_type)->getAddressSpace(); if (address_space == address_spaces[clang::LangAS::opencl_local - clang::LangAS::Offset]) { args.push_back(module::argument(module::argument::local, arg_size, target_size, target_align, module::argument::zero_ext)); } else { // XXX: Correctly handle constant address space. There is no // way for r600g to pass a handle for constant buffers back // to clover like it can for global buffers, so // creating constant arguements will break r600g. For now, // continue treating constant buffers as global buffers // until we can come up with a way to create handles for // constant buffers. args.push_back(module::argument(module::argument::global, arg_size, target_size, target_align, module::argument::zero_ext)); } } else { llvm::AttributeSet attrs = kernel_func->getAttributes(); enum module::argument::ext_type ext_type = (attrs.hasAttribute(arg.getArgNo() + 1, llvm::Attribute::SExt) ? module::argument::sign_ext : module::argument::zero_ext); args.push_back( module::argument(module::argument::scalar, arg_size, target_size, target_align, ext_type)); } } m.syms.push_back(module::symbol(kernel_name, 0, i, args )); } header.num_bytes = llvm_bitcode.size(); std::string data; data.insert(0, (char*)(&header), sizeof(header)); data.insert(data.end(), llvm_bitcode.begin(), llvm_bitcode.end()); m.secs.push_back(module::section(0, module::section::text, header.num_bytes, data)); return m; } } // End anonymous namespace module clover::compile_program_llvm(const compat::string &source, enum pipe_shader_ir ir, const compat::string &target, const compat::string &opts) { std::vector<llvm::Function *> kernels; size_t processor_str_len = std::string(target.begin()).find_first_of("-"); std::string processor(target.begin(), 0, processor_str_len); std::string triple(target.begin(), processor_str_len + 1, target.size() - processor_str_len - 1); clang::LangAS::Map address_spaces; // The input file name must have the .cl extension in order for the // CompilerInvocation class to recognize it as an OpenCL source file. llvm::Module *mod = compile(source, "input.cl", triple, processor, opts, address_spaces); find_kernels(mod, kernels); internalize_functions(mod, kernels); // Build the clover::module switch (ir) { case PIPE_SHADER_IR_TGSI: //XXX: Handle TGSI assert(0); return module(); default: return build_module_llvm(mod, kernels, address_spaces); } } <|endoftext|>
<commit_before><commit_msg>AutoFill Renderer crash in form_manager.cc FindChildTextInner()<commit_after><|endoftext|>
<commit_before>#ifndef DVDT_INFER_H #define DVDT_INFER_H #include <vector> #include "clblast.h" namespace clblast{ template <typename T> const std::vector<std::string> GetConf(const Layout layout, const Transpose a_transpose, const Transpose b_transpose, const size_t m, const size_t n, const size_t k, const T alpha, const size_t a_offset, const size_t a_ld, const size_t b_offset, const size_t b_ld, const T beta, const size_t c_offset, const size_t c_ld, int * flag){ std::vector<std::string> routines_vett = {"Copy","Pad","Transpose", "Padtranspose","KernelSelection"}; routines_vett.push_back("XgemmDirect"); routines_vett.push_back("Xgemm"); *flag=-1; return routines_vett; } template const std::vector<std::string> GetConf<float>(const Layout layout, const Transpose a_transpose, const Transpose b_transpose, const size_t m, const size_t n, const size_t k, const float alpha, const size_t a_offset, const size_t a_ld, const size_t b_offset, const size_t b_ld, const float beta, const size_t c_offset, const size_t c_ld, int * flag); template const std::vector<std::string> GetConf<double>(const Layout layout, const Transpose a_transpose, const Transpose b_transpose, const size_t m, const size_t n, const size_t k, const double alpha, const size_t a_offset, const size_t a_ld, const size_t b_offset, const size_t b_ld, const double beta, const size_t c_offset, const size_t c_ld, int * flag); template const std::vector<std::string> GetConf<float2>(const Layout layout, const Transpose a_transpose, const Transpose b_transpose, const size_t m, const size_t n, const size_t k, const float2 alpha, const size_t a_offset, const size_t a_ld, const size_t b_offset, const size_t b_ld, const float2 beta, const size_t c_offset, const size_t c_ld, int * flag); template const std::vector<std::string> GetConf<double2>(const Layout layout, const Transpose a_transpose, const Transpose b_transpose, const size_t m, const size_t n, const size_t k, const double2 alpha, const size_t a_offset, const size_t a_ld, const size_t b_offset, const size_t b_ld, const double2 beta, const size_t c_offset, const size_t c_l, int * flag); template const std::vector<std::string> GetConf<half>(const Layout layout, const Transpose a_transpose, const Transpose b_transpose, const size_t m, const size_t n, const size_t k, const half alpha, const size_t a_offset, const size_t a_ld, const size_t b_offset, const size_t b_ld, const half beta, const size_t c_offset, const size_t c_ld, int * flag); template <typename T> StatusCode PUBLIC_API testConf(const Layout layout, const Transpose a_transpose, const Transpose b_transpose, const size_t m, const size_t n, const size_t k, const half alpha, const size_t a_offset, const size_t a_ld, const size_t b_offset, const size_t b_ld, const half beta, const size_t c_offset, const size_t c_ld, const int len, const std::vector<std::string> v){ auto platform = Platform(size_t{0}); auto device = Device(platform, size_t{0}); auto context = Context(device); auto queue = Queue(context, device); for(auto i = 0; i < len ; i++) { std::vector<std::string> routines_vett = {"Copy","Pad","Transpose", "Padtranspose","KernelSelection"}; routines_vett.push_back(v[i]); try { auto queue_plain = queue(); auto event = cl_event{}; auto queue_cpp = Queue(*queue); int flag = -1; const std::vector<std::string> routines_vett = GetConf<T>(layout, a_transpose, b_transpose, m, n,k, alpha, a_offset, a_ld, b_offset, b_ld, beta, c_offset, c_ld, &flag); auto routine = Xgemm<T>(queue_cpp, event, routines_vett); routine.DoGemm(layout, a_transpose, b_transpose, m, n, k, alpha, Buffer<T>(a_buffer), a_offset, a_ld, Buffer<T>(b_buffer), b_offset, b_ld, beta, Buffer<T>(c_buffer), c_offset, c_ld); return StatusCode::kSuccess; } catch (...) { return DispatchException(); } } } template StatusCode PUBLIC_API testConf<float>(const Layout layout, const Transpose a_transpose, const Transpose b_transpose, const size_t m, const size_t n, const size_t k, const float alpha, const size_t a_offset, const size_t a_ld, const size_t b_offset, const size_t b_ld, const float beta, const size_t c_offset, const size_t c_ld, const int len, const std::vector<std::string> v); template StatusCode PUBLIC_API testConf<double>(const Layout layout, const Transpose a_transpose, const Transpose b_transpose, const size_t m, const size_t n, const size_t k, const double alpha, const size_t a_offset, const size_t a_ld, const size_t b_offset, const size_t b_ld, const double beta, const size_t c_offset, const size_t c_ld, const int len, const std::vector<std::string> v); template StatusCode PUBLIC_API testConf<float2>(const Layout layout, const Transpose a_transpose, const Transpose b_transpose, const size_t m, const size_t n, const size_t k, const float2 alpha, const size_t a_offset, const size_t a_ld, const size_t b_offset, const size_t b_ld, const float2 beta, const size_t c_offset, const size_t c_ld, const int len, const std::vector<std::string> v); template StatusCode PUBLIC_API testConf<double2>(const Layout layout, const Transpose a_transpose, const Transpose b_transpose, const size_t m, const size_t n, const size_t k, const double2 alpha, const size_t a_offset, const size_t a_ld, const size_t b_offset, const size_t b_ld, const double2 beta, const size_t c_offset, const size_t c_ld, const int len, const std::vector<std::string> v); template StatusCode PUBLIC_API testConf<half>(const Layout layout, const Transpose a_transpose, const Transpose b_transpose, const size_t m, const size_t n, const size_t k, const half alpha, const size_t a_offset, const size_t a_ld, const size_t b_offset, const size_t b_ld, const half beta, const size_t c_offset, const size_t c_ld, const int len, const std::vector<std::string> v); } #endif <commit_msg>Bug fixing<commit_after>#ifndef DVDT_INFER_H #define DVDT_INFER_H #include <vector> #include "clblast.h" namespace clblast{ template <typename T> const std::vector<std::string> GetConf(const Layout layout, const Transpose a_transpose, const Transpose b_transpose, const size_t m, const size_t n, const size_t k, const T alpha, const size_t a_offset, const size_t a_ld, const size_t b_offset, const size_t b_ld, const T beta, const size_t c_offset, const size_t c_ld, int * flag){ std::vector<std::string> routines_vett = {"Copy","Pad","Transpose", "Padtranspose","KernelSelection"}; routines_vett.push_back("XgemmDirect"); routines_vett.push_back("Xgemm"); *flag=-1; return routines_vett; } template const std::vector<std::string> GetConf<float>(const Layout layout, const Transpose a_transpose, const Transpose b_transpose, const size_t m, const size_t n, const size_t k, const float alpha, const size_t a_offset, const size_t a_ld, const size_t b_offset, const size_t b_ld, const float beta, const size_t c_offset, const size_t c_ld, int * flag); template const std::vector<std::string> GetConf<double>(const Layout layout, const Transpose a_transpose, const Transpose b_transpose, const size_t m, const size_t n, const size_t k, const double alpha, const size_t a_offset, const size_t a_ld, const size_t b_offset, const size_t b_ld, const double beta, const size_t c_offset, const size_t c_ld, int * flag); template const std::vector<std::string> GetConf<float2>(const Layout layout, const Transpose a_transpose, const Transpose b_transpose, const size_t m, const size_t n, const size_t k, const float2 alpha, const size_t a_offset, const size_t a_ld, const size_t b_offset, const size_t b_ld, const float2 beta, const size_t c_offset, const size_t c_ld, int * flag); template const std::vector<std::string> GetConf<double2>(const Layout layout, const Transpose a_transpose, const Transpose b_transpose, const size_t m, const size_t n, const size_t k, const double2 alpha, const size_t a_offset, const size_t a_ld, const size_t b_offset, const size_t b_ld, const double2 beta, const size_t c_offset, const size_t c_l, int * flag); template const std::vector<std::string> GetConf<half>(const Layout layout, const Transpose a_transpose, const Transpose b_transpose, const size_t m, const size_t n, const size_t k, const half alpha, const size_t a_offset, const size_t a_ld, const size_t b_offset, const size_t b_ld, const half beta, const size_t c_offset, const size_t c_ld, int * flag); template <typename T> StatusCode PUBLIC_API testConf(const Layout layout, const Transpose a_transpose, const Transpose b_transpose, const size_t m, const size_t n, const size_t k, const half alpha, const size_t a_offset, const size_t a_ld, const size_t b_offset, const size_t b_ld, const half beta, const size_t c_offset, const size_t c_ld, const int len, const std::vector<std::string> v){ auto platform = Platform(size_t{0}); auto device = Device(platform, size_t{0}); auto context = Context(device); auto queue = Queue(context, device); for(auto i = 0; i < len ; i++) { std::vector<std::string> routines_vett = {"Copy","Pad","Transpose", "Padtranspose","KernelSelection"}; routines_vett.push_back(v[i]); try { auto queue_plain = queue(); auto event = cl_event{}; auto queue_cpp = Queue(queue); int flag = -1; const std::vector<std::string> routines_vett = GetConf<T>(layout, a_transpose, b_transpose, m, n,k, alpha, a_offset, a_ld, b_offset, b_ld, beta, c_offset, c_ld, &flag); auto routine = Xgemm<T>(queue_cpp, event, routines_vett); routine.DoGemm(layout, a_transpose, b_transpose, m, n, k, alpha, Buffer<T>(a_buffer), a_offset, a_ld, Buffer<T>(b_buffer), b_offset, b_ld, beta, Buffer<T>(c_buffer), c_offset, c_ld); return StatusCode::kSuccess; } catch (...) { return DispatchException(); } } } template StatusCode PUBLIC_API testConf<float>(const Layout layout, const Transpose a_transpose, const Transpose b_transpose, const size_t m, const size_t n, const size_t k, const float alpha, const size_t a_offset, const size_t a_ld, const size_t b_offset, const size_t b_ld, const float beta, const size_t c_offset, const size_t c_ld, const int len, const std::vector<std::string> v); template StatusCode PUBLIC_API testConf<double>(const Layout layout, const Transpose a_transpose, const Transpose b_transpose, const size_t m, const size_t n, const size_t k, const double alpha, const size_t a_offset, const size_t a_ld, const size_t b_offset, const size_t b_ld, const double beta, const size_t c_offset, const size_t c_ld, const int len, const std::vector<std::string> v); template StatusCode PUBLIC_API testConf<float2>(const Layout layout, const Transpose a_transpose, const Transpose b_transpose, const size_t m, const size_t n, const size_t k, const float2 alpha, const size_t a_offset, const size_t a_ld, const size_t b_offset, const size_t b_ld, const float2 beta, const size_t c_offset, const size_t c_ld, const int len, const std::vector<std::string> v); template StatusCode PUBLIC_API testConf<double2>(const Layout layout, const Transpose a_transpose, const Transpose b_transpose, const size_t m, const size_t n, const size_t k, const double2 alpha, const size_t a_offset, const size_t a_ld, const size_t b_offset, const size_t b_ld, const double2 beta, const size_t c_offset, const size_t c_ld, const int len, const std::vector<std::string> v); template StatusCode PUBLIC_API testConf<half>(const Layout layout, const Transpose a_transpose, const Transpose b_transpose, const size_t m, const size_t n, const size_t k, const half alpha, const size_t a_offset, const size_t a_ld, const size_t b_offset, const size_t b_ld, const half beta, const size_t c_offset, const size_t c_ld, const int len, const std::vector<std::string> v); } #endif <|endoftext|>
<commit_before>/* * Copyright (c) 2008-2016 the MRtrix3 contributors * * 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/ * * MRtrix 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. * * For more details, see www.mrtrix.org * */ #include "math/math.h" #include "dwi/shells.h" namespace MR { namespace DWI { using namespace App; using namespace Eigen; const OptionGroup ShellOption = OptionGroup ("DW Shell selection options") + Option ("shell", "specify one or more diffusion-weighted gradient shells to use during " "processing, as a comma-separated list of the desired approximate b-values. " "Note that some commands are incompatible with multiple shells, and " "will throw an error if more than one b-value are provided.") + Argument ("list").type_sequence_float(); Shell::Shell (const MatrixXd& grad, const std::vector<size_t>& indices) : volumes (indices), mean (0.0), stdev (0.0), min (std::numeric_limits<default_type>::max()), max (0.0) { assert (volumes.size()); for (std::vector<size_t>::const_iterator i = volumes.begin(); i != volumes.end(); i++) { const default_type b = grad (*i, 3); mean += b; min = std::min (min, b); max = std::max (min, b); } mean /= default_type(volumes.size()); for (std::vector<size_t>::const_iterator i = volumes.begin(); i != volumes.end(); i++) stdev += Math::pow2 (grad (*i, 3) - mean); stdev = std::sqrt (stdev / (volumes.size() - 1)); } Shells& Shells::select_shells (const bool keep_bzero, const bool force_single_shell) { // Easiest way to restrict processing to particular shells is to simply erase // the unwanted shells; makes it command independent BitSet to_retain (shells.size(), false); if (keep_bzero && smallest().is_bzero()) to_retain[0] = true; auto opt = App::get_options ("shell"); if (opt.size()) { std::vector<default_type> desired_bvalues = opt[0][0]; if (desired_bvalues.size() > 1 && !(desired_bvalues.front() == 0) && force_single_shell) throw Exception ("Command not compatible with multiple non-zero b-shells"); for (std::vector<default_type>::const_iterator b = desired_bvalues.begin(); b != desired_bvalues.end(); ++b) { if (*b < 0) throw Exception ("Cannot select shells corresponding to negative b-values"); // Automatically select a b=0 shell if the requested b-value is zero if (*b <= bzero_threshold()) { if (smallest().is_bzero()) { to_retain[0] = true; DEBUG ("User requested b-value " + str(*b) + "; got b=0 shell : " + str(smallest().get_mean()) + " +- " + str(smallest().get_stdev()) + " with " + str(smallest().count()) + " volumes"); } else { throw Exception ("User selected b=0 shell, but no such data exists"); } } else { // First, see if the b-value lies within the range of one of the shells // If this doesn't occur, need to make a decision based on the shell distributions // Few ways this could be done: // * Compute number of standard deviations away from each shell mean, see if there's a clear winner // - Won't work if any of the standard deviations are zero // * Assume each is a Poisson distribution, see if there's a clear winner // Prompt warning if decision is slightly askew, exception if ambiguous bool shell_selected = false; for (size_t s = 0; s != shells.size(); ++s) { if ((*b >= shells[s].get_min()) && (*b <= shells[s].get_max())) { to_retain[s] = true; shell_selected = true; DEBUG ("User requested b-value " + str(*b) + "; got shell " + str(s) + ": " + str(shells[s].get_mean()) + " +- " + str(shells[s].get_stdev()) + " with " + str(shells[s].count()) + " volumes"); } } if (!shell_selected) { // First, check to see if all non-zero shells have a non-zero standard deviation bool zero_stdev = false; for (std::vector<Shell>::const_iterator s = shells.begin(); s != shells.end(); ++s) { if (!s->is_bzero() && !s->get_stdev()) { zero_stdev = true; break; } } size_t best_shell = 0; default_type best_num_stdevs = std::numeric_limits<default_type>::max(); bool ambiguous = false; for (size_t s = 0; s != shells.size(); ++s) { const default_type num_stdev = std::abs ((*b - shells[s].get_mean()) / (zero_stdev ? std::sqrt (shells[s].get_mean()) : shells[s].get_stdev())); const bool within_range = (num_stdev < (zero_stdev ? 1.0 : 5.0)); if (within_range) { if (!shell_selected) { best_shell = s; best_num_stdevs = num_stdev; } else { // More than one shell plausible; decide whether or not the decision is unambiguous if (num_stdev < 0.1 * best_num_stdevs) { best_shell = s; best_num_stdevs = num_stdev; } else if (num_stdev < 10.0 * best_num_stdevs) { ambiguous = true; } // No need to do anything if the existing selection is significantly better than this shell } } } if (ambiguous) { std::string bvalues; for (size_t s = 0; s != shells.size(); ++s) { if (bvalues.size()) bvalues += ", "; bvalues += str(shells[s].get_mean()) + " +- " + str(shells[s].get_stdev()); } throw Exception ("Unable to robustly select desired shell b=" + str(*b) + " (detected shells are: " + bvalues + ")"); } WARN ("User requested shell b=" + str(*b) + "; have selected shell " + str(shells[best_shell].get_mean()) + " +- " + str(shells[best_shell].get_stdev())); to_retain[best_shell] = true; } } // End checking to see if requested shell is b=0 } // End looping over list of requested b-value shells } else { if (force_single_shell && !is_single_shell()) WARN ("Multiple non-zero b-value shells detected; automatically selecting b=" + str(largest().get_mean()) + " with " + str(largest().count()) + " volumes"); to_retain[shells.size()-1] = true; } if (to_retain.full()) { DEBUG ("No DW shells to be removed"); return *this; } // Erase the unwanted shells std::vector<Shell> new_shells; for (size_t s = 0; s != shells.size(); ++s) { if (to_retain[s]) new_shells.push_back (shells[s]); } shells.swap (new_shells); return *this; } Shells& Shells::reject_small_shells (const size_t min_volumes) { for (std::vector<Shell>::iterator s = shells.begin(); s != shells.end();) { if (!s->is_bzero() && s->count() < min_volumes) s = shells.erase (s); else ++s; } return *this; } Shells::Shells (const MatrixXd& grad) { BValueList bvals = grad.col (3); std::vector<size_t> clusters (bvals.size(), 0); const size_t num_shells = clusterBvalues (bvals, clusters); if ((num_shells < 1) || (num_shells > std::sqrt (default_type(grad.rows())))) throw Exception ("Gradient encoding matrix does not represent a HARDI sequence"); for (size_t shellIdx = 0; shellIdx <= num_shells; shellIdx++) { std::vector<size_t> volumes; for (size_t volumeIdx = 0; volumeIdx != clusters.size(); ++volumeIdx) { if (clusters[volumeIdx] == shellIdx) volumes.push_back (volumeIdx); } if (shellIdx) { shells.push_back (Shell (grad, volumes)); } else if (volumes.size()) { std::string unassigned; for (size_t i = 0; i != volumes.size(); ++i) { if (unassigned.size()) unassigned += ", "; unassigned += str(volumes[i]) + " (" + str(bvals[volumes[i]]) + ")"; } WARN ("The following image volumes were not successfully assigned to a b-value shell:"); WARN (unassigned); } } std::sort (shells.begin(), shells.end()); if (smallest().is_bzero()) { INFO ("Diffusion gradient encoding data clustered into " + str(num_shells - 1) + " non-zero shells and " + str(smallest().count()) + " b=0 volumes"); } else { INFO ("Diffusion gradient encoding data clustered into " + str(num_shells) + " shells (no b=0 volumes)"); } DEBUG ("Shells: b = { " + str ([&]{ std::string m; for (auto& s : shells) m += str(s.get_mean()) + "(" + str(s.count()) + ") "; return m; }()) + "}"); } size_t Shells::clusterBvalues (const BValueList& bvals, std::vector<size_t>& clusters) const { BitSet visited (bvals.size(), false); size_t clusterIdx = 0; for (ssize_t ii = 0; ii != bvals.size(); ii++) { if (!visited[ii]) { visited[ii] = true; const default_type b = bvals[ii]; std::vector<size_t> neighborIdx; regionQuery (bvals, b, neighborIdx); if (b > bzero_threshold() && neighborIdx.size() < DWI_SHELLS_MIN_LINKAGE) { clusters[ii] = 0; } else { clusters[ii] = ++clusterIdx; for (size_t i = 0; i < neighborIdx.size(); i++) { if (!visited[neighborIdx[i]]) { visited[neighborIdx[i]] = true; std::vector<size_t> neighborIdx2; regionQuery (bvals, bvals[neighborIdx[i]], neighborIdx2); if (neighborIdx2.size() >= DWI_SHELLS_MIN_LINKAGE) for (size_t j = 0; j != neighborIdx2.size(); j++) neighborIdx.push_back (neighborIdx2[j]); } if (clusters[neighborIdx[i]] == 0) clusters[neighborIdx[i]] = clusterIdx; } } } } return clusterIdx; } void Shells::regionQuery (const BValueList& bvals, const default_type b, std::vector<size_t>& idx) const { for (ssize_t i = 0; i < bvals.size(); i++) { if (std::abs (b - bvals[i]) < DWI_SHELLS_EPSILON) idx.push_back (i); } } } } <commit_msg>DWI::Shells: Tweak shell selection heuristic<commit_after>/* * Copyright (c) 2008-2016 the MRtrix3 contributors * * 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/ * * MRtrix 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. * * For more details, see www.mrtrix.org * */ #include "debug.h" #include "math/math.h" #include "dwi/shells.h" namespace MR { namespace DWI { using namespace App; using namespace Eigen; const OptionGroup ShellOption = OptionGroup ("DW Shell selection options") + Option ("shell", "specify one or more diffusion-weighted gradient shells to use during " "processing, as a comma-separated list of the desired approximate b-values. " "Note that some commands are incompatible with multiple shells, and " "will throw an error if more than one b-value are provided.") + Argument ("list").type_sequence_float(); Shell::Shell (const MatrixXd& grad, const std::vector<size_t>& indices) : volumes (indices), mean (0.0), stdev (0.0), min (std::numeric_limits<default_type>::max()), max (0.0) { assert (volumes.size()); for (std::vector<size_t>::const_iterator i = volumes.begin(); i != volumes.end(); i++) { const default_type b = grad (*i, 3); mean += b; min = std::min (min, b); max = std::max (min, b); } mean /= default_type(volumes.size()); for (std::vector<size_t>::const_iterator i = volumes.begin(); i != volumes.end(); i++) stdev += Math::pow2 (grad (*i, 3) - mean); stdev = std::sqrt (stdev / (volumes.size() - 1)); } Shells& Shells::select_shells (const bool keep_bzero, const bool force_single_shell) { // Easiest way to restrict processing to particular shells is to simply erase // the unwanted shells; makes it command independent BitSet to_retain (shells.size(), false); if (keep_bzero && smallest().is_bzero()) to_retain[0] = true; auto opt = App::get_options ("shell"); if (opt.size()) { std::vector<default_type> desired_bvalues = opt[0][0]; if (desired_bvalues.size() > 1 && !(desired_bvalues.front() == 0) && force_single_shell) throw Exception ("Command not compatible with multiple non-zero b-shells"); for (std::vector<default_type>::const_iterator b = desired_bvalues.begin(); b != desired_bvalues.end(); ++b) { if (*b < 0) throw Exception ("Cannot select shells corresponding to negative b-values"); // Automatically select a b=0 shell if the requested b-value is zero if (*b <= bzero_threshold()) { if (smallest().is_bzero()) { to_retain[0] = true; DEBUG ("User requested b-value " + str(*b) + "; got b=0 shell : " + str(smallest().get_mean()) + " +- " + str(smallest().get_stdev()) + " with " + str(smallest().count()) + " volumes"); } else { throw Exception ("User selected b=0 shell, but no such data exists"); } } else { // First, see if the b-value lies within the range of one of the shells // If this doesn't occur, need to make a decision based on the shell distributions // Few ways this could be done: // * Compute number of standard deviations away from each shell mean, see if there's a clear winner // - Won't work if any of the standard deviations are zero // * Assume each is a Poisson distribution, see if there's a clear winner // Prompt warning if decision is slightly askew, exception if ambiguous bool shell_selected = false; for (size_t s = 0; s != shells.size(); ++s) { if ((*b >= shells[s].get_min()) && (*b <= shells[s].get_max())) { to_retain[s] = true; shell_selected = true; DEBUG ("User requested b-value " + str(*b) + "; got shell " + str(s) + ": " + str(shells[s].get_mean()) + " +- " + str(shells[s].get_stdev()) + " with " + str(shells[s].count()) + " volumes"); } } if (!shell_selected) { // Check to see if we can unambiguously select a shell based on b-value integer rounding size_t best_shell = 0; bool ambiguous = false; for (size_t s = 0; s != shells.size(); ++s) { if (std::abs (*b - shells[s].get_mean()) <= 1.0) { if (shell_selected) { ambiguous = true; } else { best_shell = s; shell_selected = true; } } } if (shell_selected && !ambiguous) { to_retain[best_shell] = true; DEBUG ("User requested b-value " + str(*b) + "; got shell " + str(best_shell) + ": " + str(shells[best_shell].get_mean()) + " +- " + str(shells[best_shell].get_stdev()) + " with " + str(shells[best_shell].count()) + " volumes"); } else { // First, check to see if all non-zero shells have (effectively) non-zero standard deviation // (If one non-zero shell has negligible standard deviation, assume a Poisson distribution for all shells) bool zero_stdev = false; for (std::vector<Shell>::const_iterator s = shells.begin(); s != shells.end(); ++s) { if (!s->is_bzero() && s->get_stdev() < 1.0) { zero_stdev = true; break; } } size_t best_shell = 0; default_type best_num_stdevs = std::numeric_limits<default_type>::max(); bool ambiguous = false; for (size_t s = 0; s != shells.size(); ++s) { const default_type stdev = (shells[s].is_bzero() ? 0.5 * bzero_threshold() : (zero_stdev ? std::sqrt (shells[s].get_mean()) : shells[s].get_stdev())); const default_type num_stdev = std::abs ((*b - shells[s].get_mean()) / stdev); if (num_stdev < best_num_stdevs) { ambiguous = (num_stdev >= 0.1 * best_num_stdevs); best_shell = s; best_num_stdevs = num_stdev; } else { ambiguous = (num_stdev < 10.0 * best_num_stdevs); } } if (ambiguous) { std::string bvalues; for (size_t s = 0; s != shells.size(); ++s) { if (bvalues.size()) bvalues += ", "; bvalues += str(shells[s].get_mean()) + " +- " + str(shells[s].get_stdev()); } throw Exception ("Unable to robustly select desired shell b=" + str(*b) + " (detected shells are: " + bvalues + ")"); } else { WARN ("User requested shell b=" + str(*b) + "; have selected shell " + str(shells[best_shell].get_mean()) + " +- " + str(shells[best_shell].get_stdev())); to_retain[best_shell] = true; } } // End checking if the requested b-value is within 1.0 of a shell mean } // End checking if the shell can be selected because of lying within the numerical range of a shell } // End checking to see if requested shell is b=0 } // End looping over list of requested b-value shells } else { if (force_single_shell && !is_single_shell()) WARN ("Multiple non-zero b-value shells detected; automatically selecting b=" + str(largest().get_mean()) + " with " + str(largest().count()) + " volumes"); to_retain[shells.size()-1] = true; } if (to_retain.full()) { DEBUG ("No DW shells to be removed"); return *this; } // Erase the unwanted shells std::vector<Shell> new_shells; for (size_t s = 0; s != shells.size(); ++s) { if (to_retain[s]) new_shells.push_back (shells[s]); } shells.swap (new_shells); return *this; } Shells& Shells::reject_small_shells (const size_t min_volumes) { for (std::vector<Shell>::iterator s = shells.begin(); s != shells.end();) { if (!s->is_bzero() && s->count() < min_volumes) s = shells.erase (s); else ++s; } return *this; } Shells::Shells (const MatrixXd& grad) { BValueList bvals = grad.col (3); std::vector<size_t> clusters (bvals.size(), 0); const size_t num_shells = clusterBvalues (bvals, clusters); if ((num_shells < 1) || (num_shells > std::sqrt (default_type(grad.rows())))) throw Exception ("Gradient encoding matrix does not represent a HARDI sequence"); for (size_t shellIdx = 0; shellIdx <= num_shells; shellIdx++) { std::vector<size_t> volumes; for (size_t volumeIdx = 0; volumeIdx != clusters.size(); ++volumeIdx) { if (clusters[volumeIdx] == shellIdx) volumes.push_back (volumeIdx); } if (shellIdx) { shells.push_back (Shell (grad, volumes)); } else if (volumes.size()) { std::string unassigned; for (size_t i = 0; i != volumes.size(); ++i) { if (unassigned.size()) unassigned += ", "; unassigned += str(volumes[i]) + " (" + str(bvals[volumes[i]]) + ")"; } WARN ("The following image volumes were not successfully assigned to a b-value shell:"); WARN (unassigned); } } std::sort (shells.begin(), shells.end()); if (smallest().is_bzero()) { INFO ("Diffusion gradient encoding data clustered into " + str(num_shells - 1) + " non-zero shells and " + str(smallest().count()) + " b=0 volumes"); } else { INFO ("Diffusion gradient encoding data clustered into " + str(num_shells) + " shells (no b=0 volumes)"); } DEBUG ("Shells: b = { " + str ([&]{ std::string m; for (auto& s : shells) m += str(s.get_mean()) + "(" + str(s.count()) + ") "; return m; }()) + "}"); } size_t Shells::clusterBvalues (const BValueList& bvals, std::vector<size_t>& clusters) const { BitSet visited (bvals.size(), false); size_t clusterIdx = 0; for (ssize_t ii = 0; ii != bvals.size(); ii++) { if (!visited[ii]) { visited[ii] = true; const default_type b = bvals[ii]; std::vector<size_t> neighborIdx; regionQuery (bvals, b, neighborIdx); if (b > bzero_threshold() && neighborIdx.size() < DWI_SHELLS_MIN_LINKAGE) { clusters[ii] = 0; } else { clusters[ii] = ++clusterIdx; for (size_t i = 0; i < neighborIdx.size(); i++) { if (!visited[neighborIdx[i]]) { visited[neighborIdx[i]] = true; std::vector<size_t> neighborIdx2; regionQuery (bvals, bvals[neighborIdx[i]], neighborIdx2); if (neighborIdx2.size() >= DWI_SHELLS_MIN_LINKAGE) for (size_t j = 0; j != neighborIdx2.size(); j++) neighborIdx.push_back (neighborIdx2[j]); } if (clusters[neighborIdx[i]] == 0) clusters[neighborIdx[i]] = clusterIdx; } } } } return clusterIdx; } void Shells::regionQuery (const BValueList& bvals, const default_type b, std::vector<size_t>& idx) const { for (ssize_t i = 0; i < bvals.size(); i++) { if (std::abs (b - bvals[i]) < DWI_SHELLS_EPSILON) idx.push_back (i); } } } } <|endoftext|>
<commit_before>#ifndef KISSFFT_CLASS_HH #include <complex> #include <valarray> #include <cmath> namespace kissfft_utils { template <typename T_scalar> struct traits { typedef T_scalar scalar_type; typedef std::complex<scalar_type> cpx_type; void fill_twiddles( std::complex<T_scalar> * dst ,uint64_t nfft,bool inverse) { T_scalar phinc = (inverse?2:-2)* acos( (T_scalar) -1) / nfft; for (uint64_t i=0;i<nfft;++i) dst[i] = exp( std::complex<T_scalar>(0,i*phinc) ); } void prepare( std::valarray< std::complex<T_scalar> > & dst, uint64_t nfft,bool inverse, std::valarray<uint64_t> & stageRadix, std::valarray<uint64_t> & stageRemainder ) { _twiddles.resize(nfft); fill_twiddles( &_twiddles[0],nfft,inverse); dst = _twiddles; //factorize //start factoring out 4's, then 2's, then 3,5,7,9,... uint64_t n= nfft; uint64_t p=4; uint64_t i = 0; do { while (n % p) { switch (p) { case 4: p = 2; break; case 2: p = 3; break; default: p += 2; break; } if (p*p>n) p=n;// no more factors } n /= p; stageRadix[i] = p; stageRemainder[i++] = n; }while(n>1); } std::valarray<cpx_type> _twiddles; const cpx_type twiddle(uint64_t i) { return _twiddles[i]; } }; } template <typename T_Scalar, typename T_traits=kissfft_utils::traits<T_Scalar> > class kissfft { public: typedef T_traits traits_type; typedef typename traits_type::scalar_type scalar_type; typedef typename traits_type::cpx_type cpx_type; kissfft(uint64_t nfft,bool inverse,const traits_type & traits=traits_type() ) :_nfft(nfft),_inverse(inverse),_traits(traits) { uint64_t s = 2; double sqrt_nfft = std::sqrt(nfft); uint64_t i = 0; for (i = 2; i<sqrt_nfft; ++i) { if (nfft % i ==0) { s = s + 2; } } if (i == sqrt_nfft) { s = s + 1; } _stageRadix = std::valarray<uint64_t>(s); _stageRemainder = std::valarray<uint64_t>(s); _traits.prepare(_twiddles, _nfft,_inverse ,_stageRadix, _stageRemainder); } void transform(const cpx_type * src , cpx_type * dst) { kf_work(0, dst, src, 1,1); } private: void kf_work( uint64_t stage,cpx_type * Fout, const cpx_type * f, size_t fstride,size_t in_stride) { uint64_t p = _stageRadix[stage]; uint64_t m = _stageRemainder[stage]; cpx_type * Fout_beg = Fout; cpx_type * Fout_end = Fout + p*m; if (m==1) { do{ *Fout = *f; f += fstride*in_stride; }while(++Fout != Fout_end ); }else{ do{ // recursive call: // DFT of size m*p performed by doing // p instances of smaller DFTs of size m, // each one takes a decimated version of the input kf_work(stage+1, Fout , f, fstride*p,in_stride); f += fstride*in_stride; }while( (Fout += m) != Fout_end ); } Fout=Fout_beg; // recombine the p smaller DFTs switch (p) { case 2: kf_bfly2(Fout,fstride,m); break; case 3: kf_bfly3(Fout,fstride,m); break; case 4: kf_bfly4(Fout,fstride,m); break; case 5: kf_bfly5(Fout,fstride,m); break; default: kf_bfly_generic(Fout,fstride,m,p); break; } } // these were #define macros in the original kiss_fft void C_ADD( cpx_type & c,const cpx_type & a,const cpx_type & b) { c=a+b;} void C_MUL( cpx_type & c,const cpx_type & a,const cpx_type & b) { c=a*b;} void C_SUB( cpx_type & c,const cpx_type & a,const cpx_type & b) { c=a-b;} void C_ADDTO( cpx_type & c,const cpx_type & a) { c+=a;} scalar_type S_MUL( const scalar_type & a,const scalar_type & b) { return a*b;} scalar_type HALF_OF( const scalar_type & a) { return a*.5;} void C_MULBYSCALAR(cpx_type & c,const scalar_type & a) {c*=a;} void kf_bfly2( cpx_type * Fout, const size_t fstride, uint64_t m) { for (uint64_t k=0;k<m;++k) { cpx_type t = Fout[m+k] * _traits.twiddle(k*fstride); Fout[m+k] = Fout[k] - t; Fout[k] += t; } } void kf_bfly4( cpx_type * Fout, const size_t fstride, const size_t m) { cpx_type scratch[7]; uint64_t negative_if_inverse = _inverse * -2 +1; for (size_t k=0;k<m;++k) { scratch[0] = Fout[k+m] * _traits.twiddle(k*fstride); scratch[1] = Fout[k+2*m] * _traits.twiddle(k*fstride*2); scratch[2] = Fout[k+3*m] * _traits.twiddle(k*fstride*3); scratch[5] = Fout[k] - scratch[1]; Fout[k] += scratch[1]; scratch[3] = scratch[0] + scratch[2]; scratch[4] = scratch[0] - scratch[2]; scratch[4] = cpx_type( scratch[4].imag()*negative_if_inverse , -scratch[4].real()* negative_if_inverse ); Fout[k+2*m] = Fout[k] - scratch[3]; Fout[k] += scratch[3]; Fout[k+m] = scratch[5] + scratch[4]; Fout[k+3*m] = scratch[5] - scratch[4]; } } void kf_bfly3( cpx_type * Fout, const size_t fstride, const size_t m) { size_t k=m; const size_t m2 = 2*m; cpx_type *tw1,*tw2; cpx_type scratch[5]; cpx_type epi3; epi3 = _twiddles[fstride*m]; tw1=tw2=&_twiddles[0]; do{ scratch[1] = Fout[m] * *tw1; scratch[2] = Fout[m2] * *tw2; scratch[3] = scratch[1] + scratch[2]; scratch[0] = scratch[1] - scratch[2]; tw1 += fstride; tw2 += fstride*2; Fout[m] = cpx_type( Fout->real() - (scratch[3].real()*0.5 ) , Fout->imag() - (scratch[3].imag()*0.5 ) ); C_MULBYSCALAR( scratch[0] , epi3.imag() ); *Fout +=scratch[3]; Fout[m2] = cpx_type( Fout[m].real() + scratch[0].imag() , Fout[m].imag() - scratch[0].real() ); Fout[m] += cpx_type( -scratch[0].imag(),scratch[0].real() ); ++Fout; }while(--k); } void kf_bfly5( cpx_type * Fout, const size_t fstride, const size_t m) { cpx_type *Fout0,*Fout1,*Fout2,*Fout3,*Fout4; size_t u; cpx_type scratch[13]; cpx_type * twiddles = &_twiddles[0]; cpx_type *tw; cpx_type ya,yb; ya = twiddles[fstride*m]; yb = twiddles[fstride*2*m]; Fout0=Fout; Fout1=Fout0+m; Fout2=Fout0+2*m; Fout3=Fout0+3*m; Fout4=Fout0+4*m; tw=twiddles; for ( u=0; u<m; ++u ) { scratch[0] = *Fout0; C_MUL(scratch[1] ,*Fout1, tw[u*fstride]); C_MUL(scratch[2] ,*Fout2, tw[2*u*fstride]); C_MUL(scratch[3] ,*Fout3, tw[3*u*fstride]); C_MUL(scratch[4] ,*Fout4, tw[4*u*fstride]); C_ADD( scratch[7],scratch[1],scratch[4]); C_SUB( scratch[10],scratch[1],scratch[4]); C_ADD( scratch[8],scratch[2],scratch[3]); C_SUB( scratch[9],scratch[2],scratch[3]); C_ADDTO( *Fout0, scratch[7]); C_ADDTO( *Fout0, scratch[8]); scratch[5] = scratch[0] + cpx_type( S_MUL(scratch[7].real(),ya.real() ) + S_MUL(scratch[8].real() ,yb.real() ), S_MUL(scratch[7].imag(),ya.real()) + S_MUL(scratch[8].imag(),yb.real()) ); scratch[6] = cpx_type( S_MUL(scratch[10].imag(),ya.imag()) + S_MUL(scratch[9].imag(),yb.imag()), -S_MUL(scratch[10].real(),ya.imag()) - S_MUL(scratch[9].real(),yb.imag()) ); C_SUB(*Fout1,scratch[5],scratch[6]); C_ADD(*Fout4,scratch[5],scratch[6]); scratch[11] = scratch[0] + cpx_type( S_MUL(scratch[7].real(),yb.real()) + S_MUL(scratch[8].real(),ya.real()), S_MUL(scratch[7].imag(),yb.real()) + S_MUL(scratch[8].imag(),ya.real()) ); scratch[12] = cpx_type( -S_MUL(scratch[10].imag(),yb.imag()) + S_MUL(scratch[9].imag(),ya.imag()), S_MUL(scratch[10].real(),yb.imag()) - S_MUL(scratch[9].real(),ya.imag()) ); C_ADD(*Fout2,scratch[11],scratch[12]); C_SUB(*Fout3,scratch[11],scratch[12]); ++Fout0;++Fout1;++Fout2;++Fout3;++Fout4; } } /* perform the butterfly for one stage of a mixed radix FFT */ void kf_bfly_generic( cpx_type * Fout, const size_t fstride, uint64_t m, uint64_t p ) { uint64_t u,k,q1,q; cpx_type * twiddles = &_twiddles[0]; cpx_type t; uint64_t Norig = _nfft; cpx_type scratchbuf[p]; for ( u=0; u<m; ++u ) { k=u; for ( q1=0 ; q1<p ; ++q1 ) { scratchbuf[q1] = Fout[ k ]; k += m; } k=u; for ( q1=0 ; q1<p ; ++q1 ) { uint64_t twidx=0; Fout[ k ] = scratchbuf[0]; for (q=1;q<p;++q ) { twidx += fstride * k; if (twidx>=Norig) twidx-=Norig; t = scratchbuf[q] * twiddles[twidx]; Fout[ k ] + t; } k += m; } } } uint64_t _nfft; bool _inverse; std::valarray<cpx_type> _twiddles; std::valarray<uint64_t> _stageRadix; std::valarray<uint64_t> _stageRemainder; traits_type _traits; }; #endif <commit_msg>use operator new to alocate memory<commit_after>#ifndef KISSFFT_CLASS_HH #include <complex> #include <valarray> #include <cmath> namespace kissfft_utils { template <typename T_scalar> struct traits { typedef T_scalar scalar_type; typedef std::complex<scalar_type> cpx_type; void fill_twiddles( std::complex<T_scalar> * dst ,uint64_t nfft,bool inverse) { T_scalar phinc = (inverse?2:-2)* acos( (T_scalar) -1) / nfft; for (uint64_t i=0;i<nfft;++i) dst[i] = exp( std::complex<T_scalar>(0,i*phinc) ); } void prepare( std::valarray< std::complex<T_scalar> > & dst, uint64_t nfft,bool inverse, std::valarray<uint64_t> & stageRadix, std::valarray<uint64_t> & stageRemainder ) { _twiddles.resize(nfft); fill_twiddles( &_twiddles[0],nfft,inverse); dst = _twiddles; //factorize //start factoring out 4's, then 2's, then 3,5,7,9,... uint64_t n= nfft; uint64_t p=4; uint64_t i = 0; do { while (n % p) { switch (p) { case 4: p = 2; break; case 2: p = 3; break; default: p += 2; break; } if (p*p>n) p=n;// no more factors } n /= p; stageRadix[i] = p; stageRemainder[i++] = n; }while(n>1); } std::valarray<cpx_type> _twiddles; const cpx_type twiddle(uint64_t i) { return _twiddles[i]; } }; } template <typename T_Scalar, typename T_traits=kissfft_utils::traits<T_Scalar> > class kissfft { public: typedef T_traits traits_type; typedef typename traits_type::scalar_type scalar_type; typedef typename traits_type::cpx_type cpx_type; kissfft(uint64_t nfft,bool inverse,const traits_type & traits=traits_type() ) :_nfft(nfft),_inverse(inverse),_traits(traits) { uint64_t s = 2; double sqrt_nfft = std::sqrt(nfft); uint64_t i = 0; for (i = 2; i<sqrt_nfft; ++i) { if (nfft % i ==0) { s = s + 2; } } if (i == sqrt_nfft) { s = s + 1; } _stageRadix = std::valarray<uint64_t>(s); _stageRemainder = std::valarray<uint64_t>(s); _traits.prepare(_twiddles, _nfft,_inverse ,_stageRadix, _stageRemainder); } void transform(const cpx_type * src , cpx_type * dst) { kf_work(0, dst, src, 1,1); } private: void kf_work( uint64_t stage,cpx_type * Fout, const cpx_type * f, size_t fstride,size_t in_stride) { uint64_t p = _stageRadix[stage]; uint64_t m = _stageRemainder[stage]; cpx_type * Fout_beg = Fout; cpx_type * Fout_end = Fout + p*m; if (m==1) { do{ *Fout = *f; f += fstride*in_stride; }while(++Fout != Fout_end ); }else{ do{ // recursive call: // DFT of size m*p performed by doing // p instances of smaller DFTs of size m, // each one takes a decimated version of the input kf_work(stage+1, Fout , f, fstride*p,in_stride); f += fstride*in_stride; }while( (Fout += m) != Fout_end ); } Fout=Fout_beg; // recombine the p smaller DFTs switch (p) { case 2: kf_bfly2(Fout,fstride,m); break; case 3: kf_bfly3(Fout,fstride,m); break; case 4: kf_bfly4(Fout,fstride,m); break; case 5: kf_bfly5(Fout,fstride,m); break; default: kf_bfly_generic(Fout,fstride,m,p); break; } } // these were #define macros in the original kiss_fft void C_ADD( cpx_type & c,const cpx_type & a,const cpx_type & b) { c=a+b;} void C_MUL( cpx_type & c,const cpx_type & a,const cpx_type & b) { c=a*b;} void C_SUB( cpx_type & c,const cpx_type & a,const cpx_type & b) { c=a-b;} void C_ADDTO( cpx_type & c,const cpx_type & a) { c+=a;} scalar_type S_MUL( const scalar_type & a,const scalar_type & b) { return a*b;} scalar_type HALF_OF( const scalar_type & a) { return a*.5;} void C_MULBYSCALAR(cpx_type & c,const scalar_type & a) {c*=a;} void kf_bfly2( cpx_type * Fout, const size_t fstride, uint64_t m) { for (uint64_t k=0;k<m;++k) { cpx_type t = Fout[m+k] * _traits.twiddle(k*fstride); Fout[m+k] = Fout[k] - t; Fout[k] += t; } } void kf_bfly4( cpx_type * Fout, const size_t fstride, const size_t m) { cpx_type scratch[7]; uint64_t negative_if_inverse = _inverse * -2 +1; for (size_t k=0;k<m;++k) { scratch[0] = Fout[k+m] * _traits.twiddle(k*fstride); scratch[1] = Fout[k+2*m] * _traits.twiddle(k*fstride*2); scratch[2] = Fout[k+3*m] * _traits.twiddle(k*fstride*3); scratch[5] = Fout[k] - scratch[1]; Fout[k] += scratch[1]; scratch[3] = scratch[0] + scratch[2]; scratch[4] = scratch[0] - scratch[2]; scratch[4] = cpx_type( scratch[4].imag()*negative_if_inverse , -scratch[4].real()* negative_if_inverse ); Fout[k+2*m] = Fout[k] - scratch[3]; Fout[k] += scratch[3]; Fout[k+m] = scratch[5] + scratch[4]; Fout[k+3*m] = scratch[5] - scratch[4]; } } void kf_bfly3( cpx_type * Fout, const size_t fstride, const size_t m) { size_t k=m; const size_t m2 = 2*m; cpx_type *tw1,*tw2; cpx_type scratch[5]; cpx_type epi3; epi3 = _twiddles[fstride*m]; tw1=tw2=&_twiddles[0]; do{ scratch[1] = Fout[m] * *tw1; scratch[2] = Fout[m2] * *tw2; scratch[3] = scratch[1] + scratch[2]; scratch[0] = scratch[1] - scratch[2]; tw1 += fstride; tw2 += fstride*2; Fout[m] = cpx_type( Fout->real() - (scratch[3].real()*0.5 ) , Fout->imag() - (scratch[3].imag()*0.5 ) ); C_MULBYSCALAR( scratch[0] , epi3.imag() ); *Fout +=scratch[3]; Fout[m2] = cpx_type( Fout[m].real() + scratch[0].imag() , Fout[m].imag() - scratch[0].real() ); Fout[m] += cpx_type( -scratch[0].imag(),scratch[0].real() ); ++Fout; }while(--k); } void kf_bfly5( cpx_type * Fout, const size_t fstride, const size_t m) { cpx_type *Fout0,*Fout1,*Fout2,*Fout3,*Fout4; size_t u; cpx_type scratch[13]; cpx_type * twiddles = &_twiddles[0]; cpx_type *tw; cpx_type ya,yb; ya = twiddles[fstride*m]; yb = twiddles[fstride*2*m]; Fout0=Fout; Fout1=Fout0+m; Fout2=Fout0+2*m; Fout3=Fout0+3*m; Fout4=Fout0+4*m; tw=twiddles; for ( u=0; u<m; ++u ) { scratch[0] = *Fout0; C_MUL(scratch[1] ,*Fout1, tw[u*fstride]); C_MUL(scratch[2] ,*Fout2, tw[2*u*fstride]); C_MUL(scratch[3] ,*Fout3, tw[3*u*fstride]); C_MUL(scratch[4] ,*Fout4, tw[4*u*fstride]); C_ADD( scratch[7],scratch[1],scratch[4]); C_SUB( scratch[10],scratch[1],scratch[4]); C_ADD( scratch[8],scratch[2],scratch[3]); C_SUB( scratch[9],scratch[2],scratch[3]); C_ADDTO( *Fout0, scratch[7]); C_ADDTO( *Fout0, scratch[8]); scratch[5] = scratch[0] + cpx_type( S_MUL(scratch[7].real(),ya.real() ) + S_MUL(scratch[8].real() ,yb.real() ), S_MUL(scratch[7].imag(),ya.real()) + S_MUL(scratch[8].imag(),yb.real()) ); scratch[6] = cpx_type( S_MUL(scratch[10].imag(),ya.imag()) + S_MUL(scratch[9].imag(),yb.imag()), -S_MUL(scratch[10].real(),ya.imag()) - S_MUL(scratch[9].real(),yb.imag()) ); C_SUB(*Fout1,scratch[5],scratch[6]); C_ADD(*Fout4,scratch[5],scratch[6]); scratch[11] = scratch[0] + cpx_type( S_MUL(scratch[7].real(),yb.real()) + S_MUL(scratch[8].real(),ya.real()), S_MUL(scratch[7].imag(),yb.real()) + S_MUL(scratch[8].imag(),ya.real()) ); scratch[12] = cpx_type( -S_MUL(scratch[10].imag(),yb.imag()) + S_MUL(scratch[9].imag(),ya.imag()), S_MUL(scratch[10].real(),yb.imag()) - S_MUL(scratch[9].real(),ya.imag()) ); C_ADD(*Fout2,scratch[11],scratch[12]); C_SUB(*Fout3,scratch[11],scratch[12]); ++Fout0;++Fout1;++Fout2;++Fout3;++Fout4; } } /* perform the butterfly for one stage of a mixed radix FFT */ void kf_bfly_generic( cpx_type * Fout, const size_t fstride, uint64_t m, uint64_t p ) { uint64_t u,k,q1,q; cpx_type * twiddles = &_twiddles[0]; cpx_type t; uint64_t Norig = _nfft; cpx_type scratchbuf = new cpx_type[p]; for ( u=0; u<m; ++u ) { k=u; for ( q1=0 ; q1<p ; ++q1 ) { scratchbuf[q1] = Fout[ k ]; k += m; } k=u; for ( q1=0 ; q1<p ; ++q1 ) { uint64_t twidx=0; Fout[ k ] = scratchbuf[0]; for (q=1;q<p;++q ) { twidx += fstride * k; if (twidx>=Norig) twidx-=Norig; t = scratchbuf[q] * twiddles[twidx]; Fout[ k ] + t; } k += m; } } delete[] scratchbuf; } uint64_t _nfft; bool _inverse; std::valarray<cpx_type> _twiddles; std::valarray<uint64_t> _stageRadix; std::valarray<uint64_t> _stageRemainder; traits_type _traits; }; #endif <|endoftext|>
<commit_before>/* * Copyright (c) 2012 Sacha Refshauge * */ // Qt 4.7+ / 5.0+ implementation of the framework. // Currently supports: Symbian, Blackberry, Meego, Linux, Windows #include <QApplication> #include <QUrl> #include <QDir> #include <QDesktopWidget> #include <QDesktopServices> #include <QLocale> #include <QThread> #ifdef __SYMBIAN32__ #include <e32std.h> #include <QSystemScreenSaver> #include <QFeedbackHapticsEffect> #include "SymbianMediaKeys.h" #endif #ifdef QT_HAS_SDL #include "SDL/SDLJoystick.h" #endif #include "QtMain.h" InputState* input_state; std::string System_GetProperty(SystemProperty prop) { switch (prop) { case SYSPROP_NAME: #ifdef __SYMBIAN32__ return "Qt:Symbian"; #elif defined(BLACKBERRY) return "Qt:Blackberry"; #elif defined(MEEGO_EDITION_HARMATTAN) return "Qt:Meego"; #elif defined(Q_OS_LINUX) return "Qt:Linux"; #elif defined(_WIN32) return "Qt:Windows"; #else return "Qt"; #endif case SYSPROP_LANGREGION: return QLocale::system().name().toStdString(); default: return ""; } } void Vibrate(int length_ms) { if (length_ms == -1 || length_ms == -3) length_ms = 50; else if (length_ms == -2) length_ms = 25; // Symbian only for now #if defined(__SYMBIAN32__) QFeedbackHapticsEffect effect; effect.setIntensity(0.8); effect.setDuration(length_ms); effect.start(); #endif } void LaunchBrowser(const char *url) { QDesktopServices::openUrl(QUrl(url)); } float CalculateDPIScale() { // Sane default rather than check DPI #ifdef __SYMBIAN32__ return 1.4f; #elif defined(ARM) return 1.2f; #else return 1.0f; #endif } #ifndef QT_HAS_SDL Q_DECL_EXPORT #endif int main(int argc, char *argv[]) { #ifdef Q_OS_LINUX QApplication::setAttribute(Qt::AA_X11InitThreads, true); #endif QApplication a(argc, argv); QSize res = QApplication::desktop()->screenGeometry().size(); if (res.width() < res.height()) res.transpose(); pixel_xres = res.width(); pixel_yres = res.height(); g_dpi_scale = CalculateDPIScale(); dp_xres = (int)(pixel_xres * g_dpi_scale); dp_yres = (int)(pixel_yres * g_dpi_scale); net::Init(); #ifdef __SYMBIAN32__ const char *savegame_dir = "E:/PPSSPP/"; const char *assets_dir = "E:/PPSSPP/"; #elif defined(BLACKBERRY) const char *savegame_dir = "/accounts/1000/shared/misc/"; const char *assets_dir = "app/native/assets/"; #elif defined(MEEGO_EDITION_HARMATTAN) const char *savegame_dir = "/home/user/MyDocs/PPSSPP/"; QDir myDocs("/home/user/MyDocs/"); if (!myDocs.exists("PPSSPP")) myDocs.mkdir("PPSSPP"); const char *assets_dir = "/opt/PPSSPP/"; #else const char *savegame_dir = "./"; const char *assets_dir = "./"; #endif NativeInit(argc, (const char **)argv, savegame_dir, assets_dir, "BADCOFFEE"); #if defined(ARM) MainUI w; w.resize(pixel_xres, pixel_yres); w.showFullScreen(); #endif #ifdef __SYMBIAN32__ // Set RunFast hardware mode for VFPv2. User::SetFloatingPointMode(EFpModeRunFast); // Disable screensaver QSystemScreenSaver *ssObject = new QSystemScreenSaver(&w); ssObject->setScreenSaverInhibit(); SymbianMediaKeys* mediakeys = new SymbianMediaKeys(); #endif QThread* thread = new QThread; MainAudio *audio = new MainAudio(); audio->moveToThread(thread); QObject::connect(thread, SIGNAL(started()), audio, SLOT(run())); QObject::connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater())); thread->start(); #ifdef QT_HAS_SDL SDLJoystick joy(true); joy.startEventLoop(); #endif int ret = a.exec(); delete audio; thread->quit(); NativeShutdown(); net::Shutdown(); return ret; } <commit_msg>Symbian buildfix<commit_after>/* * Copyright (c) 2012 Sacha Refshauge * */ // Qt 4.7+ / 5.0+ implementation of the framework. // Currently supports: Symbian, Blackberry, Meego, Linux, Windows #include <QApplication> #include <QUrl> #include <QDir> #include <QDesktopWidget> #include <QDesktopServices> #include <QLocale> #include <QThread> #ifdef __SYMBIAN32__ #include <e32std.h> #include <QSystemScreenSaver> #include <QFeedbackHapticsEffect> #include "SymbianMediaKeys.h" #endif #ifdef QT_HAS_SDL #include "SDL/SDLJoystick.h" #endif #include "QtMain.h" InputState* input_state; std::string System_GetProperty(SystemProperty prop) { switch (prop) { case SYSPROP_NAME: #ifdef __SYMBIAN32__ return "Qt:Symbian"; #elif defined(BLACKBERRY) return "Qt:Blackberry"; #elif defined(MEEGO_EDITION_HARMATTAN) return "Qt:Meego"; #elif defined(Q_OS_LINUX) return "Qt:Linux"; #elif defined(_WIN32) return "Qt:Windows"; #else return "Qt"; #endif case SYSPROP_LANGREGION: return QLocale::system().name().toStdString(); default: return ""; } } void System_SendMessage(const char *command, const char *parameter) { // Log? } void Vibrate(int length_ms) { if (length_ms == -1 || length_ms == -3) length_ms = 50; else if (length_ms == -2) length_ms = 25; // Symbian only for now #if defined(__SYMBIAN32__) QFeedbackHapticsEffect effect; effect.setIntensity(0.8); effect.setDuration(length_ms); effect.start(); #endif } void LaunchBrowser(const char *url) { QDesktopServices::openUrl(QUrl(url)); } float CalculateDPIScale() { // Sane default rather than check DPI #ifdef __SYMBIAN32__ return 1.4f; #elif defined(ARM) return 1.2f; #else return 1.0f; #endif } #ifndef QT_HAS_SDL Q_DECL_EXPORT #endif int main(int argc, char *argv[]) { #ifdef Q_OS_LINUX QApplication::setAttribute(Qt::AA_X11InitThreads, true); #endif QApplication a(argc, argv); QSize res = QApplication::desktop()->screenGeometry().size(); if (res.width() < res.height()) res.transpose(); pixel_xres = res.width(); pixel_yres = res.height(); g_dpi_scale = CalculateDPIScale(); dp_xres = (int)(pixel_xres * g_dpi_scale); dp_yres = (int)(pixel_yres * g_dpi_scale); net::Init(); #ifdef __SYMBIAN32__ const char *savegame_dir = "E:/PPSSPP/"; const char *assets_dir = "E:/PPSSPP/"; #elif defined(BLACKBERRY) const char *savegame_dir = "/accounts/1000/shared/misc/"; const char *assets_dir = "app/native/assets/"; #elif defined(MEEGO_EDITION_HARMATTAN) const char *savegame_dir = "/home/user/MyDocs/PPSSPP/"; QDir myDocs("/home/user/MyDocs/"); if (!myDocs.exists("PPSSPP")) myDocs.mkdir("PPSSPP"); const char *assets_dir = "/opt/PPSSPP/"; #else const char *savegame_dir = "./"; const char *assets_dir = "./"; #endif NativeInit(argc, (const char **)argv, savegame_dir, assets_dir, "BADCOFFEE"); #if defined(ARM) MainUI w; w.resize(pixel_xres, pixel_yres); w.showFullScreen(); #endif #ifdef __SYMBIAN32__ // Set RunFast hardware mode for VFPv2. User::SetFloatingPointMode(EFpModeRunFast); // Disable screensaver QSystemScreenSaver *ssObject = new QSystemScreenSaver(&w); ssObject->setScreenSaverInhibit(); SymbianMediaKeys* mediakeys = new SymbianMediaKeys(); #endif QThread* thread = new QThread; MainAudio *audio = new MainAudio(); audio->moveToThread(thread); QObject::connect(thread, SIGNAL(started()), audio, SLOT(run())); QObject::connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater())); thread->start(); #ifdef QT_HAS_SDL SDLJoystick joy(true); joy.startEventLoop(); #endif int ret = a.exec(); delete audio; thread->quit(); NativeShutdown(); net::Shutdown(); return ret; } <|endoftext|>
<commit_before>#define DEBUG 1 /** * File : E2.cpp * Author : Kazune Takahashi * Created : 3/10/2019, 2:26:12 PM * Powered by Visual Studio Code */ #include <iostream> #include <iomanip> // << fixed << setprecision(xxx) #include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ; #include <vector> #include <string> // to_string(nnn) // substr(m, n) // stoi(nnn) #include <complex> #include <tuple> #include <queue> #include <stack> #include <map> // if (M.find(key) != M.end()) { } #include <set> #include <functional> #include <random> // auto rd = bind(uniform_int_distribution<int>(0, 9), mt19937(10101010)); #include <chrono> // std::chrono::system_clock::time_point start_time, end_time; // start = std::chrono::system_clock::now(); // double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count(); #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> using namespace std; typedef long long ll; // const int dx[4] = {1, 0, -1, 0}; // const int dy[4] = {0, 1, 0, -1}; // const int C = 1e6+10; // const ll M = 1000000007; class UnionFind { public: vector<long long> par; UnionFind(int n) : par(n, -1) {} void init(int n) { par.assign(n, -1); } int root(int x) { if (par[x] < 0) { return x; } return par[x] = root(par[x]); } bool is_same(int x, int y) { return root(x) == root(y); } bool merge(int x, int y) { x = root(x); y = root(y); if (x == y) { return false; } if (par[x] > par[y]) { swap(x, y); } par[x] += par[y]; par[y] = x; return true; } long long size(int x) { return -par[root(x)]; } }; int N, M; ll X[100010]; int A[100010]; int B[100010]; ll Y[100010]; typedef tuple<ll, int, int, bool> edge; vector<edge> V; vector<int> W[100010]; typedef tuple<ll, int> task; vector<task> T; void dfs(ll cost, int v) { if (W[v].empty()) { return; } for (auto i : W[v]) { edge x = V[i]; ll score = get<0>(x); int a = get<1>(x); int b = get<2>(x); int dst = ((a == v) ? b : a); if (get<3>(x)) { continue; } if (cost >= score) { get<3>(x) = true; if (!W[dst].empty()) { dfs(cost, dst); } } } W[v].clear(); } int main() { cin >> N >> M; for (auto i = 0; i < N; i++) { cin >> X[i]; } for (auto i = 0; i < M; i++) { cin >> A[i] >> B[i] >> Y[i]; A[i]--; B[i]--; V.push_back(edge(Y[i], A[i], B[i], false)); } sort(V.begin(), V.end()); for (auto i = 0; i < M; i++) { edge x = V[i]; int a = get<1>(x); int b = get<2>(x); W[a].push_back(i); W[b].push_back(i); } UnionFind UF(N); for (auto i = 0; i < N; i++) { UF.par[i] = -X[i]; } for (auto i = 0; i < M; i++) { edge x = V[i]; ll cost = get<0>(x); int a = get<1>(x); int b = get<2>(x); ll score = 0; if (UF.is_same(a, b)) { score = UF.size(a); } else { score = UF.size(a) + UF.size(b); UF.merge(a, b); } if (score >= cost) { T.push_back(task(cost, a)); } } #if DEBUG == 1 cerr << "Here" << endl; #endif reverse(T.begin(), T.end()); for (auto x : T) { dfs(get<0>(x), get<1>(x)); } int ans = 0; for (auto i = 0; i < M; i++) { if (!get<3>(V[i])) { ans++; } } cout << ans << endl; }<commit_msg>tried E2.cpp to 'E'<commit_after>#define DEBUG 1 /** * File : E2.cpp * Author : Kazune Takahashi * Created : 3/10/2019, 2:26:12 PM * Powered by Visual Studio Code */ #include <iostream> #include <iomanip> // << fixed << setprecision(xxx) #include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ; #include <vector> #include <string> // to_string(nnn) // substr(m, n) // stoi(nnn) #include <complex> #include <tuple> #include <queue> #include <stack> #include <map> // if (M.find(key) != M.end()) { } #include <set> #include <functional> #include <random> // auto rd = bind(uniform_int_distribution<int>(0, 9), mt19937(10101010)); #include <chrono> // std::chrono::system_clock::time_point start_time, end_time; // start = std::chrono::system_clock::now(); // double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count(); #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> using namespace std; typedef long long ll; // const int dx[4] = {1, 0, -1, 0}; // const int dy[4] = {0, 1, 0, -1}; // const int C = 1e6+10; // const ll M = 1000000007; class UnionFind { public: vector<long long> par; UnionFind(int n) : par(n, -1) {} void init(int n) { par.assign(n, -1); } int root(int x) { if (par[x] < 0) { return x; } return par[x] = root(par[x]); } bool is_same(int x, int y) { return root(x) == root(y); } bool merge(int x, int y) { x = root(x); y = root(y); if (x == y) { return false; } if (par[x] > par[y]) { swap(x, y); } par[x] += par[y]; par[y] = x; return true; } long long size(int x) { return -par[root(x)]; } }; int N, M; ll X[100010]; int A[100010]; int B[100010]; ll Y[100010]; typedef tuple<ll, int, int, bool> edge; vector<edge> V; vector<int> W[100010]; typedef tuple<ll, int> task; vector<task> T; void dfs(ll cost, int v) { if (W[v].empty()) { return; } for (auto i : W[v]) { edge x = V[i]; ll score = get<0>(x); int a = get<1>(x); int b = get<2>(x); int dst = ((a == v) ? b : a); if (get<3>(x)) { continue; } if (cost >= score) { get<3>(x) = true; if (!W[dst].empty()) { dfs(cost, dst); } } } W[v].clear(); } int main() { cin >> N >> M; for (auto i = 0; i < N; i++) { cin >> X[i]; } for (auto i = 0; i < M; i++) { cin >> A[i] >> B[i] >> Y[i]; A[i]--; B[i]--; V.push_back(edge(Y[i], A[i], B[i], false)); } sort(V.begin(), V.end()); for (auto i = 0; i < M; i++) { edge x = V[i]; int a = get<1>(x); int b = get<2>(x); W[a].push_back(i); W[b].push_back(i); } UnionFind UF(N); for (auto i = 0; i < N; i++) { UF.par[i] = -X[i]; } for (auto i = 0; i < M; i++) { edge x = V[i]; ll cost = get<0>(x); int a = get<1>(x); int b = get<2>(x); ll score = 0; if (UF.is_same(a, b)) { score = UF.size(a); } else { score = UF.size(a) + UF.size(b); UF.merge(a, b); } if (score >= cost) { T.push_back(task(cost, a)); } } reverse(T.begin(), T.end()); for (auto x : T) { dfs(get<0>(x), get<1>(x)); } #if DEBUG == 1 cerr << "Here" << endl; #endif int ans = 0; for (auto i = 0; i < M; i++) { if (!get<3>(V[i])) { ans++; } } cout << ans << endl; }<|endoftext|>
<commit_before>/* * Copyright (c) 2005, Peter Sommerlad and IFS Institute for Software at HSR Rapperswil, Switzerland * All rights reserved. * * This library/application is free software; you can redistribute and/or modify it under the terms of * the license that is included with this library/application in the file license.txt. */ //--- interface include -------------------------------------------------------- #include "LFListenerPool.h" //--- standard modules used ---------------------------------------------------- #include "StringStream.h" #include "Timers.h" #include "SysLog.h" #include "RequestProcessor.h" #include "RequestListener.h" #include "WPMStatHandler.h" #include "Dbg.h" #if defined(ONLY_STD_IOSTREAM) using namespace std; #endif //--- c-library modules used --------------------------------------------------- LFListenerPool::LFListenerPool(RequestReactor *reactor) : LeaderFollowerPool(reactor) { StartTrace(LFListenerPool.Ctor); } LFListenerPool::~LFListenerPool() { StartTrace(LFListenerPool.Dtor); Terminate(); } bool LFListenerPool::InitReactor(ROAnything args) { StartTrace(LFListenerPool.InitReactor); if (fReactor && ((RequestReactor *)fReactor)->ValidInit()) { return LeaderFollowerPool::InitReactor(args); } return false; } bool LFListenerPool::Init(int maxParallelRequests, ROAnything args, bool useThreadLocalStorage) { StartTrace(LFListenerPool.Init); Anything leaderFollowerConfig; for (long i = 0; i < args.GetSize(); ++i) { const char *acceptorName = args[i].AsCharPtr("AcceptorFactory"); Trace("AcceptorFactory: " << acceptorName); AcceptorFactory *acf = AcceptorFactory::FindAcceptorFactory(acceptorName); if (!acf) { String msg("AcceptorFactory: "); msg << acceptorName << " not found!"; Trace(msg); SYSERROR(msg); return false; } Acceptor *acceptor = acf->MakeAcceptor(0); if (!acceptor) { const char *logMsg = "no acceptor created"; SYSERROR(logMsg); Trace(logMsg); return false; } acceptor->SetThreadLocal(useThreadLocalStorage); leaderFollowerConfig[acceptorName] = (IFAObject *)acceptor; } return LeaderFollowerPool::Init(maxParallelRequests, leaderFollowerConfig); } void LFListenerPool::BlockRequests() { StartTrace(LFListenerPool.BlockRequests); MutexEntry me(fLFMutex); fOldLeader = fCurrentLeader; fCurrentLeader = cBlockPromotion; } //:support reinitialization of server by unblocking request handling after the fact void LFListenerPool::UnblockRequests() { StartTrace(LFListenerPool.UnblockRequests); MutexEntry me(fLFMutex); fCurrentLeader = fOldLeader; fFollowersCondition.Signal(); } bool LFListenerPool::AwaitEmpty(long sec) { return ((RequestReactor *)fReactor)->AwaitEmpty(sec); } RequestReactor::RequestReactor(RequestProcessor *rp, WPMStatHandler *stat) : Reactor() , fProcessor(rp) , fStatHandler(stat) { StartTrace(RequestReactor.Ctor); Assert(ValidInit()); } bool RequestReactor::ValidInit() { StartTrace(RequestReactor.ValidInit); return (fProcessor && fStatHandler); } RequestReactor::~RequestReactor() { StartTrace(RequestReactor.Dtor); // must be done before dll's get unloaded delete fProcessor; if (fStatHandler) { Anything statistic; fStatHandler->Statistic(statistic); String strbuf; StringStream stream(strbuf); statistic.PrintOn(stream) << "\n"; stream.flush(); SysLog::WriteToStderr(strbuf); delete fStatHandler; } } void RequestReactor::Statistic(Anything &item) { StartTrace(RequestReactor.Statistic); if (fStatHandler) { fStatHandler->Statistic(item); } } void RequestReactor::RegisterHandle(Acceptor *acceptor) { StartTrace(RequestReactor.RegisterHandle); if ( acceptor ) { Reactor::RegisterHandle(acceptor); } } class StatEntry { public: StatEntry(WPMStatHandler *stat); ~StatEntry(); protected: WPMStatHandler *fStat; }; void RequestReactor::DoProcessEvent(Socket *sock) { StartTrace(RequestReactor.DoProcessEvent); if ( fProcessor && sock ) { bool keepConnection; do { StatEntry se(fStatHandler); // **the** one and only context for this request Context ctx(sock); { // set the request timer to time // the duration of this request RequestTimer(Cycle, "Nr: " << fStatHandler->GetTotalRequests(), ctx); fProcessor->ProcessRequest(ctx); } // log all time related items RequestTimeLogger(ctx); if (!sock->HadTimeout()) { // short timeout, is some request still waiting... keepConnection = fProcessor->KeepConnectionAlive(ctx); } else { keepConnection = false; Trace("Close connection"); } } while (keepConnection); } } bool RequestReactor::AwaitEmpty(long sec) { StartTrace1(RequestReactor.AwaitEmpty, "sec:[" << sec << "]"); if ( fStatHandler ) { // check for active requests running // but wait at most sec seconds long tstart = time(0); long tnow = tstart; int msgCount = 0; long parallelRequests = 0; while (((parallelRequests = fStatHandler->GetCurrentParallelRequests()) > 0) && // check for active requests (tstart + sec > tnow)) { // check for timeout Thread::Wait(1); // wait for 1 second tnow = time(0); // calculate new time ++msgCount; // message interval count if ((msgCount % 5) == 0) { // tell us the story. OStringStream os; os << "MaxSecToWait: " << setw(4) << sec << " SecsWaited: " << setw(4) << msgCount << " Pending requests: " << setw(6) << parallelRequests << endl; SysLog::WriteToStderr(os.str()); } } Trace("CurrentParallelRequests:[" << parallelRequests << "]"); return (parallelRequests <= 0); } Trace("StatHandler not set!!"); return false; } StatEntry::StatEntry(WPMStatHandler *stat) : fStat(stat) { if (fStat) { fStat->HandleStatEvt(WPMStatHandler::eEnter); } } StatEntry::~StatEntry() { if (fStat) { fStat->HandleStatEvt(WPMStatHandler::eLeave); } } <commit_msg>added trace of pool config<commit_after>/* * Copyright (c) 2005, Peter Sommerlad and IFS Institute for Software at HSR Rapperswil, Switzerland * All rights reserved. * * This library/application is free software; you can redistribute and/or modify it under the terms of * the license that is included with this library/application in the file license.txt. */ //--- interface include -------------------------------------------------------- #include "LFListenerPool.h" //--- standard modules used ---------------------------------------------------- #include "StringStream.h" #include "Timers.h" #include "SysLog.h" #include "RequestProcessor.h" #include "RequestListener.h" #include "WPMStatHandler.h" #include "Dbg.h" #if defined(ONLY_STD_IOSTREAM) using namespace std; #endif //--- c-library modules used --------------------------------------------------- LFListenerPool::LFListenerPool(RequestReactor *reactor) : LeaderFollowerPool(reactor) { StartTrace(LFListenerPool.Ctor); } LFListenerPool::~LFListenerPool() { StartTrace(LFListenerPool.Dtor); Terminate(); } bool LFListenerPool::InitReactor(ROAnything args) { StartTrace(LFListenerPool.InitReactor); if (fReactor && ((RequestReactor *)fReactor)->ValidInit()) { return LeaderFollowerPool::InitReactor(args); } return false; } bool LFListenerPool::Init(int maxParallelRequests, ROAnything args, bool useThreadLocalStorage) { StartTrace(LFListenerPool.Init); Anything leaderFollowerConfig; TraceAny(args, "LFListenerPool config"); for (long i = 0; i < args.GetSize(); ++i) { const char *acceptorName = args[i].AsCharPtr("AcceptorFactory"); Trace("AcceptorFactory: " << acceptorName); AcceptorFactory *acf = AcceptorFactory::FindAcceptorFactory(acceptorName); if (!acf) { String msg("AcceptorFactory: "); msg << acceptorName << " not found!"; Trace(msg); SYSERROR(msg); return false; } Acceptor *acceptor = acf->MakeAcceptor(0); if (!acceptor) { const char *logMsg = "no acceptor created"; SYSERROR(logMsg); Trace(logMsg); return false; } acceptor->SetThreadLocal(useThreadLocalStorage); leaderFollowerConfig[acceptorName] = (IFAObject *)acceptor; } return LeaderFollowerPool::Init(maxParallelRequests, leaderFollowerConfig); } void LFListenerPool::BlockRequests() { StartTrace(LFListenerPool.BlockRequests); MutexEntry me(fLFMutex); fOldLeader = fCurrentLeader; fCurrentLeader = cBlockPromotion; } //:support reinitialization of server by unblocking request handling after the fact void LFListenerPool::UnblockRequests() { StartTrace(LFListenerPool.UnblockRequests); MutexEntry me(fLFMutex); fCurrentLeader = fOldLeader; fFollowersCondition.Signal(); } bool LFListenerPool::AwaitEmpty(long sec) { return ((RequestReactor *)fReactor)->AwaitEmpty(sec); } RequestReactor::RequestReactor(RequestProcessor *rp, WPMStatHandler *stat) : Reactor() , fProcessor(rp) , fStatHandler(stat) { StartTrace(RequestReactor.Ctor); Assert(ValidInit()); } bool RequestReactor::ValidInit() { StartTrace(RequestReactor.ValidInit); return (fProcessor && fStatHandler); } RequestReactor::~RequestReactor() { StartTrace(RequestReactor.Dtor); // must be done before dll's get unloaded delete fProcessor; if (fStatHandler) { Anything statistic; fStatHandler->Statistic(statistic); String strbuf; StringStream stream(strbuf); statistic.PrintOn(stream) << "\n"; stream.flush(); SysLog::WriteToStderr(strbuf); delete fStatHandler; } } void RequestReactor::Statistic(Anything &item) { StartTrace(RequestReactor.Statistic); if (fStatHandler) { fStatHandler->Statistic(item); } } void RequestReactor::RegisterHandle(Acceptor *acceptor) { StartTrace(RequestReactor.RegisterHandle); if ( acceptor ) { Reactor::RegisterHandle(acceptor); } } class StatEntry { public: StatEntry(WPMStatHandler *stat); ~StatEntry(); protected: WPMStatHandler *fStat; }; void RequestReactor::DoProcessEvent(Socket *sock) { StartTrace(RequestReactor.DoProcessEvent); if ( fProcessor && sock ) { bool keepConnection; do { StatEntry se(fStatHandler); // **the** one and only context for this request Context ctx(sock); { // set the request timer to time // the duration of this request RequestTimer(Cycle, "Nr: " << fStatHandler->GetTotalRequests(), ctx); fProcessor->ProcessRequest(ctx); } // log all time related items RequestTimeLogger(ctx); if (!sock->HadTimeout()) { // short timeout, is some request still waiting... keepConnection = fProcessor->KeepConnectionAlive(ctx); } else { keepConnection = false; Trace("Close connection"); } } while (keepConnection); } } bool RequestReactor::AwaitEmpty(long sec) { StartTrace1(RequestReactor.AwaitEmpty, "sec:[" << sec << "]"); if ( fStatHandler ) { // check for active requests running // but wait at most sec seconds long tstart = time(0); long tnow = tstart; int msgCount = 0; long parallelRequests = 0; while (((parallelRequests = fStatHandler->GetCurrentParallelRequests()) > 0) && // check for active requests (tstart + sec > tnow)) { // check for timeout Thread::Wait(1); // wait for 1 second tnow = time(0); // calculate new time ++msgCount; // message interval count if ((msgCount % 5) == 0) { // tell us the story. OStringStream os; os << "MaxSecToWait: " << setw(4) << sec << " SecsWaited: " << setw(4) << msgCount << " Pending requests: " << setw(6) << parallelRequests << endl; SysLog::WriteToStderr(os.str()); } } Trace("CurrentParallelRequests:[" << parallelRequests << "]"); return (parallelRequests <= 0); } Trace("StatHandler not set!!"); return false; } StatEntry::StatEntry(WPMStatHandler *stat) : fStat(stat) { if (fStat) { fStat->HandleStatEvt(WPMStatHandler::eEnter); } } StatEntry::~StatEntry() { if (fStat) { fStat->HandleStatEvt(WPMStatHandler::eLeave); } } <|endoftext|>
<commit_before>#include "origin_drm.h" #include <QLineEdit> #include <QCheckBox> OriginDRM::OriginDRM() : DRMType("<b>Origin</b>"){} /** Check if Origin exists or not and set various class variables accordingly. */ void OriginDRM::checkOriginExists() { QDir originRoot; QDir originFolder; #if defined(_WIN32) || defined(_WIN64) originRoot = QDir(qgetenv("APPDATA").append("/Origin")); #else originRoot = QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation).append("/Origin/"); #endif if (originRoot.exists()) { pt::ptree originTree; read_xml(originRoot.filePath("local.xml").toLocal8Bit().constData(), originTree); for (auto &xmlIter : originTree.get_child("Settings")) { if (xmlIter.second.get<std::string>("<xmlattr>.key") == "DownloadInPlaceDir") { originFolder = QString::fromStdString(xmlIter.second.get<std::string>("<xmlattr>.value")); break; } } if (originFolder == QDir(".")) { originFolder = QDir("C:\\Program Files (x86)\\Origin Games\\"); } } if (originFolder.filePath("").trimmed() != "" && originFolder.exists() && originFolder != QDir(".")) { this->setRootDir(originFolder); this->setIsInstalled(); statusLabel->setPixmap(QPixmap(":/SystemMenu/Icons/Tick.svg")); descLabel = new QLabel("Origin found in " + originFolder.filePath("")); } else { statusLabel->setPixmap(QPixmap(":SystemMenu/Icons/Cross.svg")); descLabel = new QLabel("Origin not found. Verify installation and try again."); } } /** Using rootDir, which is initialized earlier in the wizard, utilize `recursiveFindFiles()` to find every executable within * each respective directory. Some directories will contain more than one executable, so it's up to the user to select the correct one. */ void OriginDRM::findGames() { rootDir.setFilter(QDir::Dirs | QDir::NoDotAndDotDot | QDir::NoSymLinks); QStringList folderList = rootDir.entryList(); int count = 0; for (auto i : folderList) { if (i != "DownloadCache") { pt::ptree& node = originTree.add("games.game", ""); QDir dir(rootDir.absoluteFilePath(i)); dir.setNameFilters(QStringList("*.exe")); dir.setFilter(QDir::Files | QDir::NoDotAndDotDot | QDir::NoSymLinks); QStringList test = recursiveFindFiles(dir); node.put("name", dir.dirName().toLocal8Bit().constData()); for (auto exe : test) { node.add("exes.exe", exe.toLocal8Bit().constData()); } count++; } } originTree.add("games.count", count); } /** Getter for the originTree */ pt::ptree OriginDRM::getGames() { return originTree; } /** Create the wizard tab for Origin * \param parent Parent of the widget * */ QWidget* OriginDRM::createPane(QWidget* parent) { viewport = new QWidget(parent); scrollArea = new QScrollArea(parent); int row = 0; for (pt::ptree::value_type& games : originTree.get_child("games")) { boost::optional<std::string> exeTest = games.second.get_optional<std::string>("exes"); if (exeTest) { QButtonGroup* group = new QButtonGroup(); QLineEdit* name = new QLineEdit(QString::fromStdString(games.second.get<std::string>("name"))); name->setFixedWidth(350); QCheckBox* checkBox = new QCheckBox(); layout->addWidget(name, row, 0, Qt::AlignVCenter | Qt::AlignLeft); row++; for (auto& exe : games.second.get_child("exes")) { checkBox = new QCheckBox("Executable: " + QString::fromStdString(exe.second.data())); group->addButton(checkBox); layout->addWidget(checkBox, row, 0, Qt::AlignVCenter | Qt::AlignLeft); row++; } buttonGroupVector.push_back(group); } } viewport->setLayout(layout); scrollArea->setWidget(viewport); return scrollArea; } /** Getter for buttonGroupVector */ QList<QButtonGroup*> OriginDRM::getButtonGroupVector() { return buttonGroupVector; } <commit_msg>Missed one<commit_after>#include "origin_drm.h" #include <QLineEdit> #include <QCheckBox> #include <QStandardPaths> OriginDRM::OriginDRM() : DRMType("<b>Origin</b>"){} /** Check if Origin exists or not and set various class variables accordingly. */ void OriginDRM::checkOriginExists() { QDir originRoot; QDir originFolder; #if defined(_WIN32) || defined(_WIN64) originRoot = QDir(qgetenv("APPDATA").append("/Origin")); #else originRoot = QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation).append("/Origin/"); #endif if (originRoot.exists()) { pt::ptree originTree; read_xml(originRoot.filePath("local.xml").toLocal8Bit().constData(), originTree); for (auto &xmlIter : originTree.get_child("Settings")) { if (xmlIter.second.get<std::string>("<xmlattr>.key") == "DownloadInPlaceDir") { originFolder = QString::fromStdString(xmlIter.second.get<std::string>("<xmlattr>.value")); break; } } if (originFolder == QDir(".")) { originFolder = QDir("C:\\Program Files (x86)\\Origin Games\\"); } } if (originFolder.filePath("").trimmed() != "" && originFolder.exists() && originFolder != QDir(".")) { this->setRootDir(originFolder); this->setIsInstalled(); statusLabel->setPixmap(QPixmap(":/SystemMenu/Icons/Tick.svg")); descLabel = new QLabel("Origin found in " + originFolder.filePath("")); } else { statusLabel->setPixmap(QPixmap(":SystemMenu/Icons/Cross.svg")); descLabel = new QLabel("Origin not found. Verify installation and try again."); } } /** Using rootDir, which is initialized earlier in the wizard, utilize `recursiveFindFiles()` to find every executable within * each respective directory. Some directories will contain more than one executable, so it's up to the user to select the correct one. */ void OriginDRM::findGames() { rootDir.setFilter(QDir::Dirs | QDir::NoDotAndDotDot | QDir::NoSymLinks); QStringList folderList = rootDir.entryList(); int count = 0; for (auto i : folderList) { if (i != "DownloadCache") { pt::ptree& node = originTree.add("games.game", ""); QDir dir(rootDir.absoluteFilePath(i)); dir.setNameFilters(QStringList("*.exe")); dir.setFilter(QDir::Files | QDir::NoDotAndDotDot | QDir::NoSymLinks); QStringList test = recursiveFindFiles(dir); node.put("name", dir.dirName().toLocal8Bit().constData()); for (auto exe : test) { node.add("exes.exe", exe.toLocal8Bit().constData()); } count++; } } originTree.add("games.count", count); } /** Getter for the originTree */ pt::ptree OriginDRM::getGames() { return originTree; } /** Create the wizard tab for Origin * \param parent Parent of the widget * */ QWidget* OriginDRM::createPane(QWidget* parent) { viewport = new QWidget(parent); scrollArea = new QScrollArea(parent); int row = 0; for (pt::ptree::value_type& games : originTree.get_child("games")) { boost::optional<std::string> exeTest = games.second.get_optional<std::string>("exes"); if (exeTest) { QButtonGroup* group = new QButtonGroup(); QLineEdit* name = new QLineEdit(QString::fromStdString(games.second.get<std::string>("name"))); name->setFixedWidth(350); QCheckBox* checkBox = new QCheckBox(); layout->addWidget(name, row, 0, Qt::AlignVCenter | Qt::AlignLeft); row++; for (auto& exe : games.second.get_child("exes")) { checkBox = new QCheckBox("Executable: " + QString::fromStdString(exe.second.data())); group->addButton(checkBox); layout->addWidget(checkBox, row, 0, Qt::AlignVCenter | Qt::AlignLeft); row++; } buttonGroupVector.push_back(group); } } viewport->setLayout(layout); scrollArea->setWidget(viewport); return scrollArea; } /** Getter for buttonGroupVector */ QList<QButtonGroup*> OriginDRM::getButtonGroupVector() { return buttonGroupVector; } <|endoftext|>
<commit_before>#define DEBUG 1 /** * File : E.cpp * Author : Kazune Takahashi * Created : 2/17/2019, 2:03:40 PM * Powered by Visual Studio Code */ #include <iostream> #include <iomanip> // << fixed << setprecision(xxx) #include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ; #include <vector> #include <string> // to_string(nnn) // substr(m, n) // stoi(nnn) #include <complex> #include <tuple> #include <queue> #include <stack> #include <map> // if (M.find(key) != M.end()) { } #include <set> #include <functional> #include <random> // auto rd = bind(uniform_int_distribution<int>(0, 9), mt19937(10101010)); #include <chrono> // std::chrono::system_clock::time_point start_time, end_time; // start = std::chrono::system_clock::now(); // double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count(); #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> using namespace std; typedef long long ll; // const int dx[4] = {1, 0, -1, 0}; // const int dy[4] = {0, 1, 0, -1}; // const int C = 1e6+10; const ll MOD = 1000000007; ll N, K; ll power(int x) { if (x < 0) { return 0; } if (x == 0) { return 1; } if (x % 2 == 0) { ll y = power(x / 2); return (y * y) % MOD; } else { return (power(x - 1) * 2) % MOD; } } ll DP[5010][5010]; ll DP2[5010][5010]; void init() { for (auto i = 0; i < N; i++) { DP[0][i] = power(i - (K - 1)); } DP2[0][0] = DP[0][0]; for (auto i = 1; i < N; i++) { DP2[0][i] = DP2[0][i - 1] + DP[0][i]; DP2[0][i] %= MOD; } } void flush() { #if DEBUG == 1 for (auto i = 0; i < N; i++) { for (auto j = 0; j < N; j++) { cerr << "DP[" << i << "][" << j << "] = " << DP[i][j] << endl; } } #endif ll ans = 0; for (auto i = 0; i < N; i++) { ans += DP[i][N - 1]; ans %= MOD; } cout << ans << endl; } int main() { cin >> N >> K; init(); for (auto i = 1; i < N; i++) { for (auto j = 0; j < N; j++) { DP[i][j] = 0; if (j > 0) { DP[i][j] += (DP2[i - 1][j - 1] * power(j - i - (K - 1))) % MOD; } DP[i][j] += (DP[i - 1][j] * power(j - i - (K - 2))) % MOD; } DP2[i][0] = DP[i][0]; for (auto j = 1; j < N; j++) { DP2[i][j] = DP2[i][j - 1] + DP[i][j]; DP2[i][j] %= MOD; } } flush(); }<commit_msg>tried E.cpp to 'E'<commit_after>#define DEBUG 1 /** * File : E.cpp * Author : Kazune Takahashi * Created : 2/17/2019, 2:03:40 PM * Powered by Visual Studio Code */ #include <iostream> #include <iomanip> // << fixed << setprecision(xxx) #include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ; #include <vector> #include <string> // to_string(nnn) // substr(m, n) // stoi(nnn) #include <complex> #include <tuple> #include <queue> #include <stack> #include <map> // if (M.find(key) != M.end()) { } #include <set> #include <functional> #include <random> // auto rd = bind(uniform_int_distribution<int>(0, 9), mt19937(10101010)); #include <chrono> // std::chrono::system_clock::time_point start_time, end_time; // start = std::chrono::system_clock::now(); // double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count(); #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> using namespace std; typedef long long ll; // const int dx[4] = {1, 0, -1, 0}; // const int dy[4] = {0, 1, 0, -1}; // const int C = 1e6+10; const ll MOD = 1000000007; ll N, K; ll memo[100010]; ll power(int x) { if (x < 0) { return 0; } assert(x < 100010); return memo[x]; } ll DP[5010][5010]; ll DP2[5010][5010]; void init() { memo[0] = 1; for (auto i = 1; i < 100010; i++) { memo[i] = memo[i - 1] * 2; memo[i] %= MOD; } for (auto i = 0; i < N; i++) { DP[0][i] = power(i - (K - 1)); } DP2[0][0] = DP[0][0]; for (auto i = 1; i < N; i++) { DP2[0][i] = DP2[0][i - 1] + DP[0][i]; DP2[0][i] %= MOD; } } void flush() { #if DEBUG == 1 for (auto i = 0; i < N; i++) { for (auto j = 0; j < N; j++) { cerr << "DP[" << i << "][" << j << "] = " << DP[i][j] << endl; } } #endif ll ans = 0; for (auto i = 0; i < N; i++) { ans += DP[i][N - 1]; ans %= MOD; } cout << ans << endl; } int main() { cin >> N >> K; init(); for (auto i = 1; i < N; i++) { for (auto j = 0; j < N; j++) { DP[i][j] = 0; if (j > 0) { DP[i][j] += (DP2[i - 1][j - 1] * power(j - i - (K - 1))) % MOD; } DP[i][j] += (DP[i - 1][j] * power(j - i - (K - 2))) % MOD; } DP2[i][0] = DP[i][0]; for (auto j = 1; j < N; j++) { DP2[i][j] = DP2[i][j - 1] + DP[i][j]; DP2[i][j] %= MOD; } } flush(); }<|endoftext|>
<commit_before>#define DEBUG 1 /** * File : F2.cpp * Author : Kazune Takahashi * Created : 2019-6-2 00:47:04 * Powered by Visual Studio Code */ #include <iostream> #include <iomanip> #include <algorithm> #include <vector> #include <string> #include <complex> #include <tuple> #include <queue> #include <stack> #include <map> #include <set> #include <functional> #include <random> #include <chrono> #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> using namespace std; typedef long long ll; bool dp_L[2010][2010]; bool dp_R[2010][2010]; bool W[2010][2010]; int main() { int N; cin >> N; for (auto i = 1; i < N; i++) { string S; cin >> S; for (auto j = 0; j < i; j++) { if (S[j] == '1') { W[i][j] = false; W[j][i] = true; } else { W[i][j] = true; W[j][i] = false; } } } for (auto i = 0; i < N; i++) { dp_L[i][i] = true; dp_R[i][i] = true; } for (auto n = 1; n < N; n++) { for (auto a = 0; a + n < N; a++) { int b = a + n; dp_L[a][b] = false; for (auto c = a + 1; c < b; c++) { if (dp_L[a][c] && dp_L[c][b]) { dp_L[a][b] = true; break; } } if (!dp_L[a][b] && W[a][b]) { if (a + 1 == b) { dp_L[a][b] = true; } else { for (auto c = a + 1; c < b; c++) { if (dp_L[a][c] && dp_R[c][b]) { dp_L[a][b] = true; break; } } } } dp_R[a][b] = false; for (auto c = a + 1; c < b; c++) { if (dp_R[a][c] && dp_R[c][b]) { dp_R[a][b] = true; break; } } if (!dp_R[a][b] && W[b][a]) { if (a + 1 == b) { dp_R[a][b] = true; } else { for (auto c = a + 1; c < b; c++) { if (dp_L[a][c] && dp_R[c][b]) { dp_R[a][b] = true; break; } } } } #if DEBUG == 1 cerr << "dp_L[" << a << "][" << b << "] = " << dp_L[a][b] << endl; cerr << "dp_R[" << a << "][" << b << "] = " << dp_R[a][b] << endl; #endif } } int ans = 0; for (auto i = 0; i < N; i++) { if (dp_L[0][i] && dp_R[i][N - 1]) { ans++; } } cout << ans << endl; }<commit_msg>tried F2.cpp to 'F'<commit_after>#define DEBUG 1 /** * File : F2.cpp * Author : Kazune Takahashi * Created : 2019-6-2 00:47:04 * Powered by Visual Studio Code */ #include <iostream> #include <iomanip> #include <algorithm> #include <vector> #include <string> #include <complex> #include <tuple> #include <queue> #include <stack> #include <map> #include <set> #include <functional> #include <random> #include <chrono> #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> using namespace std; typedef long long ll; bool dp_L[2010][2010]; bool dp_R[2010][2010]; bool W[2010][2010]; int main() { int N; cin >> N; for (auto i = 1; i < N; i++) { string S; cin >> S; for (auto j = 0; j < i; j++) { if (S[j] == '1') { W[i][j] = false; W[j][i] = true; } else { W[i][j] = true; W[j][i] = false; } } } for (auto i = 0; i < N; i++) { dp_L[i][i] = true; dp_R[i][i] = true; } for (auto n = 1; n < N; n++) { for (auto a = 0; a + n < N; a++) { int b = a + n; dp_L[a][b] = false; for (auto c = a + 1; c < b; c++) { if (dp_L[a][c] && dp_L[c][b]) { dp_L[a][b] = true; break; } } if (!dp_L[a][b] && W[a][b]) { if (a + 1 == b) { dp_L[a][b] = true; } else { for (auto c = a + 1; c < b; c++) { if (dp_L[a][c] && dp_R[c][b]) { dp_L[a][b] = true; break; } } } } dp_R[a][b] = false; for (auto c = a + 1; c < b; c++) { if (dp_R[a][c] && dp_R[c][b]) { dp_R[a][b] = true; break; } } if (!dp_R[a][b] && W[b][a]) { if (a + 1 == b) { dp_R[a][b] = true; } else { for (auto c = a + 1; c < b; c++) { if (dp_L[a][c] && dp_R[c][b]) { dp_R[a][b] = true; break; } } } } if (dp_R[a][b] && W[a][b]) { dp_L[a][b] = true; } if (dp_L[a][b] && W[b][a]) { dp_R[a][b] = true; } #if DEBUG == 1 cerr << "dp_L[" << a << "][" << b << "] = " << dp_L[a][b] << endl; cerr << "dp_R[" << a << "][" << b << "] = " << dp_R[a][b] << endl; #endif } } int ans = 0; for (auto i = 0; i < N; i++) { if (dp_L[0][i] && dp_R[i][N - 1]) { ans++; } } cout << ans << endl; }<|endoftext|>
<commit_before>// 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 <glog/logging.h> #include <sys/types.h> #include <sys/wait.h> #include <process/delay.hpp> #include <process/future.hpp> #include <process/id.hpp> #include <process/once.hpp> #include <process/owned.hpp> #include <process/reap.hpp> #include <stout/check.hpp> #include <stout/foreach.hpp> #include <stout/multihashmap.hpp> #include <stout/none.hpp> #include <stout/os.hpp> #include <stout/result.hpp> #include <stout/try.hpp> namespace process { // TODO(bmahler): This can be optimized to use a thread per pid, where // each thread makes a blocking call to waitpid. This eliminates the // unfortunate poll delay. // // Simple bounded linear model for computing the poll interval. // Values were chosen such that at (50 pids, 100 ms) the CPU usage is // less than approx. 0.5% of a single core, and at (500 pids, 1000 ms) // less than approx. 1.0% of single core. Tested on Linux 3.10 with // Intel Xeon E5620 and OSX 10.9 with Intel i7 4980HQ. // // 1000ms _____ // / // (interval) / // / // 100ms -----/ // 50 500 // // (# pids) // const size_t LOW_PID_COUNT = 50; Duration MIN_REAP_INTERVAL() { return Milliseconds(100); } const size_t HIGH_PID_COUNT = 500; Duration MAX_REAP_INTERVAL() { return Seconds(1); } class ReaperProcess : public Process<ReaperProcess> { public: ReaperProcess() : ProcessBase(ID::generate("reaper")) {} Future<Option<int> > reap(pid_t pid) { // Check to see if this pid exists. if (os::exists(pid)) { Owned<Promise<Option<int> > > promise(new Promise<Option<int> >()); promises.put(pid, promise); return promise->future(); } else { return None(); } } protected: virtual void initialize() { wait(); } void wait() { // There are two cases to consider for each pid when it terminates: // 1) The process is our child. In this case, we will reap the process and // notify with the exit status. // 2) The process was not our child. In this case, it will be reaped by // someone else (its parent or init, if reparented) so we cannot know // the exit status and we must notify with None(). // // NOTE: A child can only be reaped by us, the parent. If a child exits // between waitpid and the (!exists) conditional it will still exist as a // zombie; it will be reaped by us on the next loop. foreach (pid_t pid, promises.keys()) { int status; if (waitpid(pid, &status, WNOHANG) > 0) { // We have reaped a child. notify(pid, status); } else if (!os::exists(pid)) { // The process no longer exists and has been reaped by someone else. notify(pid, None()); } } delay(interval(), self(), &ReaperProcess::wait); // Reap forever! } void notify(pid_t pid, Result<int> status) { foreach (const Owned<Promise<Option<int> > >& promise, promises.get(pid)) { if (status.isError()) { promise->fail(status.error()); } else if (status.isNone()) { promise->set(Option<int>::none()); } else { promise->set(Option<int>(status.get())); } } promises.remove(pid); } private: const Duration interval() { size_t count = promises.size(); if (count <= LOW_PID_COUNT) { return MIN_REAP_INTERVAL(); } else if (count >= HIGH_PID_COUNT) { return MAX_REAP_INTERVAL(); } // Linear interpolation between min and max reap intervals. double fraction = ((double) (count - LOW_PID_COUNT) / (HIGH_PID_COUNT - LOW_PID_COUNT)); return (MIN_REAP_INTERVAL() + (MAX_REAP_INTERVAL() - MIN_REAP_INTERVAL()) * fraction); } multihashmap<pid_t, Owned<Promise<Option<int> > > > promises; }; // Global reaper object. static ReaperProcess* reaper = NULL; Future<Option<int> > reap(pid_t pid) { static Once* initialized = new Once(); if (!initialized->once()) { reaper = new ReaperProcess(); spawn(reaper); initialized->done(); } CHECK_NOTNULL(reaper); return dispatch(reaper, &ReaperProcess::reap, pid); } } // namespace process { <commit_msg>Stout: [2/2] Transitioned reap.cpp to `os::waitpid`.<commit_after>// 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 <glog/logging.h> #include <sys/types.h> #ifndef __WINDOWS__ #include <sys/wait.h> #endif #include <process/delay.hpp> #include <process/future.hpp> #include <process/id.hpp> #include <process/once.hpp> #include <process/owned.hpp> #include <process/reap.hpp> #include <stout/check.hpp> #include <stout/foreach.hpp> #include <stout/multihashmap.hpp> #include <stout/none.hpp> #include <stout/os.hpp> #include <stout/result.hpp> #include <stout/try.hpp> namespace process { // TODO(bmahler): This can be optimized to use a thread per pid, where // each thread makes a blocking call to waitpid. This eliminates the // unfortunate poll delay. // // Simple bounded linear model for computing the poll interval. // Values were chosen such that at (50 pids, 100 ms) the CPU usage is // less than approx. 0.5% of a single core, and at (500 pids, 1000 ms) // less than approx. 1.0% of single core. Tested on Linux 3.10 with // Intel Xeon E5620 and OSX 10.9 with Intel i7 4980HQ. // // 1000ms _____ // / // (interval) / // / // 100ms -----/ // 50 500 // // (# pids) // const size_t LOW_PID_COUNT = 50; Duration MIN_REAP_INTERVAL() { return Milliseconds(100); } const size_t HIGH_PID_COUNT = 500; Duration MAX_REAP_INTERVAL() { return Seconds(1); } class ReaperProcess : public Process<ReaperProcess> { public: ReaperProcess() : ProcessBase(ID::generate("reaper")) {} Future<Option<int> > reap(pid_t pid) { // Check to see if this pid exists. if (os::exists(pid)) { Owned<Promise<Option<int> > > promise(new Promise<Option<int> >()); promises.put(pid, promise); return promise->future(); } else { return None(); } } protected: virtual void initialize() { wait(); } void wait() { // There are two cases to consider for each pid when it terminates: // 1) The process is our child. In this case, we will reap the process and // notify with the exit status. // 2) The process was not our child. In this case, it will be reaped by // someone else (its parent or init, if reparented) so we cannot know // the exit status and we must notify with None(). // // NOTE: A child can only be reaped by us, the parent. If a child exits // between waitpid and the (!exists) conditional it will still exist as a // zombie; it will be reaped by us on the next loop. foreach (pid_t pid, promises.keys()) { int status; Result<pid_t> child_pid = os::waitpid(pid, &status, WNOHANG); if (child_pid.isSome()) { // We have reaped a child. notify(pid, status); } else if (!os::exists(pid)) { // The process no longer exists and has been reaped by someone else. notify(pid, None()); } } delay(interval(), self(), &ReaperProcess::wait); // Reap forever! } void notify(pid_t pid, Result<int> status) { foreach (const Owned<Promise<Option<int> > >& promise, promises.get(pid)) { if (status.isError()) { promise->fail(status.error()); } else if (status.isNone()) { promise->set(Option<int>::none()); } else { promise->set(Option<int>(status.get())); } } promises.remove(pid); } private: const Duration interval() { size_t count = promises.size(); if (count <= LOW_PID_COUNT) { return MIN_REAP_INTERVAL(); } else if (count >= HIGH_PID_COUNT) { return MAX_REAP_INTERVAL(); } // Linear interpolation between min and max reap intervals. double fraction = ((double) (count - LOW_PID_COUNT) / (HIGH_PID_COUNT - LOW_PID_COUNT)); return (MIN_REAP_INTERVAL() + (MAX_REAP_INTERVAL() - MIN_REAP_INTERVAL()) * fraction); } multihashmap<pid_t, Owned<Promise<Option<int> > > > promises; }; // Global reaper object. static ReaperProcess* reaper = NULL; Future<Option<int> > reap(pid_t pid) { static Once* initialized = new Once(); if (!initialized->once()) { reaper = new ReaperProcess(); spawn(reaper); initialized->done(); } CHECK_NOTNULL(reaper); return dispatch(reaper, &ReaperProcess::reap, pid); } } // namespace process { <|endoftext|>
<commit_before>#include "destroy_system.h" #include "game/transcendental/cosmos.h" #include "game/transcendental/entity_id.h" #include "game/components/sub_entities_component.h" #include "game/messages/queue_destruction.h" #include "game/messages/will_soon_be_deleted.h" #include "game/transcendental/entity_handle.h" #include "game/transcendental/step.h" #include "augs/ensure.h" void destroy_system::queue_children_of_queued_entities(fixed_step& step) { auto& cosmos = step.cosm; auto& delta = step.get_delta(); auto& queued = step.messages.get_queue<messages::queue_destruction>(); auto& deletions = step.messages.get_queue<messages::will_soon_be_deleted>(); for (auto it : queued) { auto deletion_adder = [&deletions](entity_id descendant) { deletions.push_back(descendant); }; deletions.push_back(it.subject); cosmos[it.subject].for_each_sub_entity_recursive(deletion_adder); } queued.clear(); } void destroy_system::perform_deletions(fixed_step& step) { auto& cosmos = step.cosm; auto& delta = step.get_delta(); auto& deletions = step.messages.get_queue<messages::will_soon_be_deleted>(); // destroy in reverse order; children first for (auto& it = deletions.rbegin(); it != deletions.rend(); ++it) { // ensure(cosmos[(*it).subject].alive()); cosmos.delete_entity((*it).subject); } deletions.clear(); } <commit_msg>consts for justice<commit_after>#include "destroy_system.h" #include "game/transcendental/cosmos.h" #include "game/transcendental/entity_id.h" #include "game/components/sub_entities_component.h" #include "game/messages/queue_destruction.h" #include "game/messages/will_soon_be_deleted.h" #include "game/transcendental/entity_handle.h" #include "game/transcendental/step.h" #include "augs/ensure.h" void destroy_system::queue_children_of_queued_entities(fixed_step& step) { auto& cosmos = step.cosm; auto& queued = step.messages.get_queue<messages::queue_destruction>(); auto& deletions = step.messages.get_queue<messages::will_soon_be_deleted>(); for (const auto& it : queued) { auto deletion_adder = [&deletions](entity_id descendant) { deletions.push_back(descendant); }; deletions.push_back(it.subject); cosmos[it.subject].for_each_sub_entity_recursive(deletion_adder); } queued.clear(); } void destroy_system::perform_deletions(fixed_step& step) { auto& cosmos = step.cosm; auto& deletions = step.messages.get_queue<messages::will_soon_be_deleted>(); // destroy in reverse order; children first for (auto& it = deletions.rbegin(); it != deletions.rend(); ++it) { // ensure(cosmos[(*it).subject].alive()); cosmos.delete_entity((*it).subject); } deletions.clear(); } <|endoftext|>
<commit_before>/** * This file is part of the CernVM File System. */ #include "json_document.h" #include <cassert> #include <cstdlib> #include <cstring> #include "logging.h" using namespace std; // NOLINT JsonDocument *JsonDocument::Create(const string &text) { UniquePtr<JsonDocument> json(new JsonDocument()); bool retval = json->Parse(text); if (!retval) return NULL; return json.Release(); } string JsonDocument::EscapeString(const string &input) { string escaped; escaped.reserve(input.length()); for (unsigned i = 0, s = input.length(); i < s; ++i) { if (input[i] == '\\') { escaped.push_back('\\'); escaped.push_back('\\'); } else if (input[i] == '"') { escaped.push_back('\\'); escaped.push_back('"'); } else { escaped.push_back(input[i]); } } return escaped; } JsonDocument::JsonDocument() : allocator_(kDefaultBlockSize), root_(NULL), raw_text_(NULL) { } JsonDocument::~JsonDocument() { if (raw_text_) free(raw_text_); } /** * Parses a JSON string in text. * * @return true if parsing was successful */ bool JsonDocument::Parse(const string &text) { assert(root_ == NULL); // The used JSON library 'vjson' is a destructive parser and therefore // alters the content of the provided buffer. The buffer must persist as // name and string values from JSON nodes just point into it. raw_text_ = strdup(text.c_str()); char *error_pos = 0; char *error_desc = 0; int error_line = 0; JSON *root = json_parse(raw_text_, &error_pos, &error_desc, &error_line, &allocator_); // check if the json string was parsed successfully if (!root) { LogCvmfs(kLogUtility, kLogDebug, "Failed to parse Riak configuration json string. " "Error at line %d: %s (%s)", error_line, error_desc, error_pos); return false; } root_ = root; return true; } string JsonDocument::PrintArray(JSON *first_child, PrintOptions print_options) { string result = "["; if (print_options.with_whitespace) { result += "\n"; print_options.num_indent += 2; } JSON *value = first_child; if (value != NULL) { result += PrintValue(value, print_options); value = value->next_sibling; } while (value != NULL) { result += print_options.with_whitespace ? ",\n" : ","; result += PrintValue(value, print_options); value = value->next_sibling; } if (print_options.with_whitespace) { result += "\n"; for (unsigned i = 2; i < print_options.num_indent; ++i) result.push_back(' '); } return result + "]"; } /** * JSON string in a canonical format: * - No whitespaces * - Variable names and strings in quotes * * Can be used as a canonical representation to sign or encrypt a JSON text. */ string JsonDocument::PrintCanonical() { if (!root_) return ""; PrintOptions print_options; return PrintObject(root_->first_child, print_options); } string JsonDocument::PrintObject(JSON *first_child, PrintOptions print_options) { string result = "{"; if (print_options.with_whitespace) { result += "\n"; print_options.num_indent += 2; } JSON *value = first_child; if (value != NULL) { result += PrintValue(value, print_options); value = value->next_sibling; } while (value != NULL) { result += print_options.with_whitespace ? ",\n" : ","; result += PrintValue(value, print_options); value = value->next_sibling; } if (print_options.with_whitespace) { result += "\n"; for (unsigned i = 2; i < print_options.num_indent; ++i) result.push_back(' '); } return result + "}"; } /** * JSON string for humans. */ string JsonDocument::PrintPretty() { if (!root_) return ""; PrintOptions print_options; print_options.with_whitespace = true; return PrintObject(root_->first_child, print_options); } std::string JsonDocument::PrintValue(JSON *value, PrintOptions print_options) { assert(value); string result; for (unsigned i = 0; i < print_options.num_indent; ++i) result.push_back(' '); if (value->name) { result += "\"" + EscapeString(value->name) + "\":"; if (print_options.with_whitespace) result += " "; } switch (value->type) { case JSON_NULL: result += "null"; break; case JSON_OBJECT: result += PrintObject(value->first_child, print_options); break; case JSON_ARRAY: result += PrintArray(value->first_child, print_options); break; case JSON_STRING: result += "\"" + EscapeString(value->string_value) + "\""; break; case JSON_INT: result += StringifyInt(value->int_value); break; case JSON_FLOAT: result += StringifyDouble(value->float_value); break; case JSON_BOOL: result += value->int_value ? "true" : "false"; break; default: abort(); } return result; } <commit_msg>remove riak reference from debug string<commit_after>/** * This file is part of the CernVM File System. */ #include "json_document.h" #include <cassert> #include <cstdlib> #include <cstring> #include "logging.h" using namespace std; // NOLINT JsonDocument *JsonDocument::Create(const string &text) { UniquePtr<JsonDocument> json(new JsonDocument()); bool retval = json->Parse(text); if (!retval) return NULL; return json.Release(); } string JsonDocument::EscapeString(const string &input) { string escaped; escaped.reserve(input.length()); for (unsigned i = 0, s = input.length(); i < s; ++i) { if (input[i] == '\\') { escaped.push_back('\\'); escaped.push_back('\\'); } else if (input[i] == '"') { escaped.push_back('\\'); escaped.push_back('"'); } else { escaped.push_back(input[i]); } } return escaped; } JsonDocument::JsonDocument() : allocator_(kDefaultBlockSize), root_(NULL), raw_text_(NULL) { } JsonDocument::~JsonDocument() { if (raw_text_) free(raw_text_); } /** * Parses a JSON string in text. * * @return true if parsing was successful */ bool JsonDocument::Parse(const string &text) { assert(root_ == NULL); // The used JSON library 'vjson' is a destructive parser and therefore // alters the content of the provided buffer. The buffer must persist as // name and string values from JSON nodes just point into it. raw_text_ = strdup(text.c_str()); char *error_pos = 0; char *error_desc = 0; int error_line = 0; JSON *root = json_parse(raw_text_, &error_pos, &error_desc, &error_line, &allocator_); // check if the json string was parsed successfully if (!root) { LogCvmfs(kLogUtility, kLogDebug, "Failed to parse json string. Error at line %d: %s (%s)", error_line, error_desc, error_pos); return false; } root_ = root; return true; } string JsonDocument::PrintArray(JSON *first_child, PrintOptions print_options) { string result = "["; if (print_options.with_whitespace) { result += "\n"; print_options.num_indent += 2; } JSON *value = first_child; if (value != NULL) { result += PrintValue(value, print_options); value = value->next_sibling; } while (value != NULL) { result += print_options.with_whitespace ? ",\n" : ","; result += PrintValue(value, print_options); value = value->next_sibling; } if (print_options.with_whitespace) { result += "\n"; for (unsigned i = 2; i < print_options.num_indent; ++i) result.push_back(' '); } return result + "]"; } /** * JSON string in a canonical format: * - No whitespaces * - Variable names and strings in quotes * * Can be used as a canonical representation to sign or encrypt a JSON text. */ string JsonDocument::PrintCanonical() { if (!root_) return ""; PrintOptions print_options; return PrintObject(root_->first_child, print_options); } string JsonDocument::PrintObject(JSON *first_child, PrintOptions print_options) { string result = "{"; if (print_options.with_whitespace) { result += "\n"; print_options.num_indent += 2; } JSON *value = first_child; if (value != NULL) { result += PrintValue(value, print_options); value = value->next_sibling; } while (value != NULL) { result += print_options.with_whitespace ? ",\n" : ","; result += PrintValue(value, print_options); value = value->next_sibling; } if (print_options.with_whitespace) { result += "\n"; for (unsigned i = 2; i < print_options.num_indent; ++i) result.push_back(' '); } return result + "}"; } /** * JSON string for humans. */ string JsonDocument::PrintPretty() { if (!root_) return ""; PrintOptions print_options; print_options.with_whitespace = true; return PrintObject(root_->first_child, print_options); } std::string JsonDocument::PrintValue(JSON *value, PrintOptions print_options) { assert(value); string result; for (unsigned i = 0; i < print_options.num_indent; ++i) result.push_back(' '); if (value->name) { result += "\"" + EscapeString(value->name) + "\":"; if (print_options.with_whitespace) result += " "; } switch (value->type) { case JSON_NULL: result += "null"; break; case JSON_OBJECT: result += PrintObject(value->first_child, print_options); break; case JSON_ARRAY: result += PrintArray(value->first_child, print_options); break; case JSON_STRING: result += "\"" + EscapeString(value->string_value) + "\""; break; case JSON_INT: result += StringifyInt(value->int_value); break; case JSON_FLOAT: result += StringifyDouble(value->float_value); break; case JSON_BOOL: result += value->int_value ? "true" : "false"; break; default: abort(); } return result; } <|endoftext|>
<commit_before>/** * This file is part of the CernVM File System. * * This command processes a repository's catalog structure to detect and remove * outdated and/or unneeded data objects. */ #include "cvmfs_config.h" #include "swissknife_gc.h" #include <string> #include "garbage_collection/garbage_collector.h" #include "garbage_collection/hash_filter.h" #include "manifest.h" #include "upload_facility.h" namespace swissknife { typedef HttpObjectFetcher<> ObjectFetcher; typedef CatalogTraversal<ObjectFetcher> ReadonlyCatalogTraversal; typedef GarbageCollector<ReadonlyCatalogTraversal, SimpleHashFilter> GC; typedef GC::Configuration GcConfig; ParameterList CommandGc::GetParams() { ParameterList r; r.push_back(Parameter::Mandatory('r', "repository url")); r.push_back(Parameter::Mandatory('u', "spooler definition string")); r.push_back(Parameter::Mandatory('n', "fully qualified repository name")); r.push_back(Parameter::Optional('h', "conserve <h> revisions")); r.push_back(Parameter::Optional('z', "conserve revisions younger than <z>")); r.push_back(Parameter::Optional('k', "repository master key(s)")); r.push_back(Parameter::Optional('t', "temporary directory")); r.push_back(Parameter::Optional('L', "path to deletion log file")); r.push_back(Parameter::Switch('d', "dry run")); r.push_back(Parameter::Switch('l', "list objects to be removed")); return r; } int CommandGc::Main(const ArgumentList &args) { const std::string &repo_url = *args.find('r')->second; const std::string &spooler = *args.find('u')->second; const std::string &repo_name = *args.find('n')->second; const int64_t revisions = (args.count('h') > 0) ? String2Int64(*args.find('h')->second) : GcConfig::kFullHistory; const time_t timestamp = (args.count('z') > 0) ? static_cast<time_t>(String2Int64(*args.find('z')->second)) : GcConfig::kNoTimestamp; const std::string &repo_keys = (args.count('k') > 0) ? *args.find('k')->second : ""; const bool dry_run = (args.count('d') > 0); const bool list_condemned_objects = (args.count('l') > 0); const std::string temp_directory = (args.count('t') > 0) ? *args.find('t')->second : "/tmp"; const std::string deletion_log_path = (args.count('L') > 0) ? *args.find('L')->second : ""; if (revisions < 0) { LogCvmfs(kLogCvmfs, kLogStderr, "at least one revision needs to be preserved"); return 1; } if (timestamp == GcConfig::kNoTimestamp && revisions == GcConfig::kFullHistory) { LogCvmfs(kLogCvmfs, kLogStderr, "neither a timestamp nor history threshold given"); return 1; } const bool follow_redirects = false; if (!this->InitDownloadManager(follow_redirects) || !this->InitVerifyingSignatureManager(repo_keys)) { LogCvmfs(kLogCatalog, kLogStderr, "failed to init repo connection"); return 1; } ObjectFetcher object_fetcher(repo_name, repo_url, temp_directory, download_manager(), signature_manager()); UniquePtr<manifest::Manifest> manifest; ObjectFetcher::Failures retval = object_fetcher.FetchManifest(&manifest); if (retval != ObjectFetcher::kFailOk) { LogCvmfs(kLogCvmfs, kLogStderr, "failed to load repository manifest " "(%d - %s)", retval, Code2Ascii(retval)); return 1; } if (!manifest->garbage_collectable()) { LogCvmfs(kLogCvmfs, kLogStderr, "repository does not allow garbage collection"); return 1; } UniquePtr<manifest::Reflog> reflog; reflog = GetOrCreateReflog(&object_fetcher, repo_name); if (!reflog.IsValid()) { LogCvmfs(kLogCvmfs, kLogStderr, "failed to load or create Reflog"); return 1; } const upload::SpoolerDefinition spooler_definition(spooler, shash::kAny); UniquePtr<upload::AbstractUploader> uploader( upload::AbstractUploader::Construct(spooler_definition)); if (!uploader.IsValid()) { LogCvmfs(kLogCvmfs, kLogStderr, "failed to initialize spooler for '%s'", spooler.c_str()); return 1; } FILE *deletion_log_file = NULL; if (!deletion_log_path.empty()) { deletion_log_file = fopen(deletion_log_path.c_str(), "a+"); if (NULL == deletion_log_file) { LogCvmfs(kLogCvmfs, kLogStderr, "failed to open deletion log file " "(errno: %d)", errno); return 1; } } GcConfig config; config.uploader = uploader.weak_ref(); config.keep_history_depth = revisions; config.keep_history_timestamp = timestamp; config.dry_run = dry_run; config.verbose = list_condemned_objects; config.object_fetcher = &object_fetcher; config.reflog = reflog.weak_ref(); config.deleted_objects_logfile = deletion_log_file; if (deletion_log_file != NULL) { const int bytes_written = fprintf(deletion_log_file, "# Garbage Collection started at %s\n", StringifyTime(time(NULL), true).c_str()); if (bytes_written < 0) { LogCvmfs(kLogCvmfs, kLogStderr, "failed to write to deletion log '%s' " "(errno: %d)", deletion_log_path.c_str(), errno); return 1; } } GC collector(config); const bool success = collector.Collect(); if (deletion_log_file != NULL) { const int bytes_written = fprintf(deletion_log_file, "# Garbage Collection finished at %s\n\n", StringifyTime(time(NULL), true).c_str()); assert(bytes_written >= 0); fclose(deletion_log_file); } return success ? 0 : 1; } } // namespace swissknife <commit_msg>FIX: crash in `swissknife gc`<commit_after>/** * This file is part of the CernVM File System. * * This command processes a repository's catalog structure to detect and remove * outdated and/or unneeded data objects. */ #include "cvmfs_config.h" #include "swissknife_gc.h" #include <string> #include "garbage_collection/garbage_collector.h" #include "garbage_collection/hash_filter.h" #include "manifest.h" #include "upload_facility.h" namespace swissknife { typedef HttpObjectFetcher<> ObjectFetcher; typedef CatalogTraversal<ObjectFetcher> ReadonlyCatalogTraversal; typedef GarbageCollector<ReadonlyCatalogTraversal, SimpleHashFilter> GC; typedef GC::Configuration GcConfig; ParameterList CommandGc::GetParams() { ParameterList r; r.push_back(Parameter::Mandatory('r', "repository url")); r.push_back(Parameter::Mandatory('u', "spooler definition string")); r.push_back(Parameter::Mandatory('n', "fully qualified repository name")); r.push_back(Parameter::Optional('h', "conserve <h> revisions")); r.push_back(Parameter::Optional('z', "conserve revisions younger than <z>")); r.push_back(Parameter::Optional('k', "repository master key(s)")); r.push_back(Parameter::Optional('t', "temporary directory")); r.push_back(Parameter::Optional('L', "path to deletion log file")); r.push_back(Parameter::Switch('d', "dry run")); r.push_back(Parameter::Switch('l', "list objects to be removed")); return r; } int CommandGc::Main(const ArgumentList &args) { const std::string &repo_url = *args.find('r')->second; const std::string &spooler = *args.find('u')->second; const std::string &repo_name = *args.find('n')->second; const int64_t revisions = (args.count('h') > 0) ? String2Int64(*args.find('h')->second) : GcConfig::kFullHistory; const time_t timestamp = (args.count('z') > 0) ? static_cast<time_t>(String2Int64(*args.find('z')->second)) : GcConfig::kNoTimestamp; const std::string &repo_keys = (args.count('k') > 0) ? *args.find('k')->second : ""; const bool dry_run = (args.count('d') > 0); const bool list_condemned_objects = (args.count('l') > 0); const std::string temp_directory = (args.count('t') > 0) ? *args.find('t')->second : "/tmp"; const std::string deletion_log_path = (args.count('L') > 0) ? *args.find('L')->second : ""; if (revisions < 0) { LogCvmfs(kLogCvmfs, kLogStderr, "at least one revision needs to be preserved"); return 1; } if (timestamp == GcConfig::kNoTimestamp && revisions == GcConfig::kFullHistory) { LogCvmfs(kLogCvmfs, kLogStderr, "neither a timestamp nor history threshold given"); return 1; } const bool follow_redirects = false; if (!this->InitDownloadManager(follow_redirects) || !this->InitVerifyingSignatureManager(repo_keys)) { LogCvmfs(kLogCatalog, kLogStderr, "failed to init repo connection"); return 1; } ObjectFetcher object_fetcher(repo_name, repo_url, temp_directory, download_manager(), signature_manager()); UniquePtr<manifest::Manifest> manifest; ObjectFetcher::Failures retval = object_fetcher.FetchManifest(&manifest); if (retval != ObjectFetcher::kFailOk) { LogCvmfs(kLogCvmfs, kLogStderr, "failed to load repository manifest " "(%d - %s)", retval, Code2Ascii(retval)); return 1; } if (!manifest->garbage_collectable()) { LogCvmfs(kLogCvmfs, kLogStderr, "repository does not allow garbage collection"); return 1; } UniquePtr<manifest::Reflog> reflog; reflog = GetOrCreateReflog(&object_fetcher, repo_name); if (!reflog.IsValid()) { LogCvmfs(kLogCvmfs, kLogStderr, "failed to load or create Reflog"); return 1; } const upload::SpoolerDefinition spooler_definition(spooler, shash::kAny); UniquePtr<upload::AbstractUploader> uploader( upload::AbstractUploader::Construct(spooler_definition)); if (!uploader.IsValid()) { LogCvmfs(kLogCvmfs, kLogStderr, "failed to initialize spooler for '%s'", spooler.c_str()); return 1; } FILE *deletion_log_file = NULL; if (!deletion_log_path.empty()) { deletion_log_file = fopen(deletion_log_path.c_str(), "a+"); if (NULL == deletion_log_file) { LogCvmfs(kLogCvmfs, kLogStderr, "failed to open deletion log file " "(errno: %d)", errno); uploader->TearDown(); return 1; } } GcConfig config; config.uploader = uploader.weak_ref(); config.keep_history_depth = revisions; config.keep_history_timestamp = timestamp; config.dry_run = dry_run; config.verbose = list_condemned_objects; config.object_fetcher = &object_fetcher; config.reflog = reflog.weak_ref(); config.deleted_objects_logfile = deletion_log_file; if (deletion_log_file != NULL) { const int bytes_written = fprintf(deletion_log_file, "# Garbage Collection started at %s\n", StringifyTime(time(NULL), true).c_str()); if (bytes_written < 0) { LogCvmfs(kLogCvmfs, kLogStderr, "failed to write to deletion log '%s' " "(errno: %d)", deletion_log_path.c_str(), errno); uploader->TearDown(); return 1; } } GC collector(config); const bool success = collector.Collect(); uploader->TearDown(); if (deletion_log_file != NULL) { const int bytes_written = fprintf(deletion_log_file, "# Garbage Collection finished at %s\n\n", StringifyTime(time(NULL), true).c_str()); assert(bytes_written >= 0); fclose(deletion_log_file); } return success ? 0 : 1; } } // namespace swissknife <|endoftext|>
<commit_before>#include <iostream> #include <string> #include <vector> #ifndef INSTRUMENT_COPIES #define INSTRUMENT_COPIES 1 #endif #if INSTRUMENT_COPIES inline std::size_t& allocations () { static std::size_t allocations_ = 0; return allocations_; } inline void reset_allocations () { allocations() = 0; } void * operator new (std::size_t size) { ++allocations(); return malloc(size); } void * operator new[] (std::size_t size) { ++allocations(); return malloc(size); } #endif struct hi_printable { void print () const { std::cout << "Hello, world!\n"; } }; struct bye_printable { void print () const { std::cout << "Bye, now!\n"; } }; struct large_printable : std::vector<std::string> { large_printable () : std::vector<std::string> (1000, std::string(1000, ' ')) {} large_printable (const large_printable & rhs) : std::vector<std::string> (rhs) {} large_printable & operator= (const large_printable & rhs) { static_cast<std::vector<std::string> &>(*this) = rhs; return *this; } large_printable (large_printable && rhs) = default; large_printable & operator= (large_printable && rhs) = default; void print () const { std::cout << "I'm expensive to copy.\n"; } }; <commit_msg>std::vector<std::string> -> std::vector<double> in large printable type.<commit_after>#include <iostream> #include <vector> #ifndef INSTRUMENT_COPIES #define INSTRUMENT_COPIES 1 #endif #if INSTRUMENT_COPIES inline std::size_t& allocations () { static std::size_t allocations_ = 0; return allocations_; } inline void reset_allocations () { allocations() = 0; } void * operator new (std::size_t size) { ++allocations(); return malloc(size); } void * operator new[] (std::size_t size) { ++allocations(); return malloc(size); } #endif struct hi_printable { void print () const { std::cout << "Hello, world!\n"; } }; struct bye_printable { void print () const { std::cout << "Bye, now!\n"; } }; struct large_printable : std::vector<double> { large_printable () : std::vector<double> (1024 * 1024) {} large_printable (const large_printable & rhs) : std::vector<double> (rhs) {} large_printable & operator= (const large_printable & rhs) { static_cast<std::vector<double> &>(*this) = rhs; return *this; } large_printable (large_printable && rhs) = default; large_printable & operator= (large_printable && rhs) = default; void print () const { std::cout << "I'm expensive to copy.\n"; } }; <|endoftext|>
<commit_before>/* * GameState.cpp * OpenLieroX * * Created by Albert Zeyer on 15.02.12. * code under LGPL * */ #include "GameState.h" #include "Game.h" #include "Settings.h" #include "CWorm.h" #include "CBytestream.h" #include "ClassInfo.h" #include "ProfileSystem.h" ScriptVar_t ObjectState::getValue(AttribRef a) const { Attribs::const_iterator it = attribs.find(a); if(it == attribs.end()) return a.getAttrDesc()->defaultValue; return it->second.value; } GameStateUpdates::operator bool() const { if(!objs.empty()) return true; if(!objCreations.empty()) return true; if(!objDeletions.empty()) return true; return false; } void GameStateUpdates::writeToBs(CBytestream* bs) const { bs->writeInt16((uint16_t)objCreations.size()); foreach(o, objCreations) { o->writeToBs(bs); } bs->writeInt16((uint16_t)objDeletions.size()); foreach(o, objDeletions) { o->writeToBs(bs); } bs->writeInt((uint32_t)objs.size(), 4); foreach(a, objs) { const ObjAttrRef& attr = *a; ScriptVar_t curValue = a->get(); attr.writeToBs(bs); bs->writeVar(curValue); } } static BaseObject* getObjFromRef(ObjRef r) { switch(r.classId) { case LuaID<Game>::value: return &game; case LuaID<CWorm>::value: return game.wormById(r.objId); default: break; } return NULL; } static bool attrBelongsToClass(const ClassInfo* classInfo, const AttrDesc* attrDesc) { return classInfo->isTypeOf(attrDesc->objTypeId); } void GameStateUpdates::handleFromBs(CBytestream* bs) { uint16_t creationsNum = bs->readInt16(); for(uint16_t i = 0; i < creationsNum; ++i) { ObjRef r; r.readFromBs(bs); //BaseObject* o = getClassInfo(r.classId)->createInstance(); //o->thisRef.classId = r.classId; //o->thisRef.objId = r.objId; // we only handle/support CWorm objects for now... if(game.isServer()) { errors << "GameStateUpdates::handleFromBs: got obj creation as server: " << r.description() << endl; bs->SkipAll(); return; } if(r.classId != LuaID<CWorm>::value) { errors << "GameStateUpdates::handleFromBs: obj-creation: invalid class: " << r.description() << endl; bs->SkipAll(); return; } if(game.wormById(r.objId, false) != NULL) { errors << "GameStateUpdates::handleFromBs: worm-creation: worm " << r.objId << " already exists" << endl; bs->SkipAll(); return; } game.createNewWorm(r.objId, false, NULL, Version()); } uint16_t deletionsNum = bs->readInt16(); for(uint16_t i = 0; i < deletionsNum; ++i) { ObjRef r; r.readFromBs(bs); // we only handle/support CWorm objects for now... if(game.isServer()) { errors << "GameStateUpdates::handleFromBs: got obj deletion as server: " << r.description() << endl; bs->SkipAll(); return; } if(r.classId != LuaID<CWorm>::value) { errors << "GameStateUpdates::handleFromBs: obj-deletion: invalid class: " << r.description() << endl; bs->SkipAll(); return; } CWorm* w = game.wormById(r.objId, false); if(!w) { errors << "GameStateUpdates::handleFromBs: obj-deletion: worm " << r.objId << " does not exist" << endl; bs->SkipAll(); return; } game.removeWorm(w); } uint32_t attrUpdatesNum = bs->readInt(4); for(uint32_t i = 0; i < attrUpdatesNum; ++i) { ObjAttrRef r; r.readFromBs(bs); const AttrDesc* attrDesc = r.attr.getAttrDesc(); if(attrDesc == NULL) { errors << "GameStateUpdates::handleFromBs: AttrDesc for update not found" << endl; bs->SkipAll(); return; } const ClassInfo* classInfo = getClassInfo(r.obj.classId); if(classInfo == NULL) { errors << "GameStateUpdates::handleFromBs: class " << r.obj.classId << " for obj-update unknown" << endl; bs->SkipAll(); return; } if(!attrBelongsToClass(classInfo, attrDesc)) { errors << "GameStateUpdates::handleFromBs: attr " << attrDesc->description() << " does not belong to class " << r.obj.classId << " for obj-update" << endl; bs->SkipAll(); return; } ScriptVar_t v; bs->readVar(v); // for now, this is somewhat specific to the only types we support if(r.obj.classId == LuaID<Settings>::value) { if(game.isServer()) { errors << "GameStateUpdates::handleFromBs: got settings update as server" << endl; bs->SkipAll(); return; } if(!Settings::getAttrDescs().belongsToUs(attrDesc)) { errors << "GameStateUpdates::handleFromBs: settings update AttrDesc " << attrDesc->description() << " is not a setting attr" << endl; bs->SkipAll(); return; } FeatureIndex fIndex = Settings::getAttrDescs().getIndex(attrDesc); cClient->getGameLobby().overwrite[fIndex] = v; } else { BaseObject* o = getObjFromRef(r.obj); if(o == NULL) { errors << "GameStateUpdates::handleFromBs: object for attr update not found" << endl; bs->SkipAll(); return; } if(o->thisRef != r.obj) { errors << "GameStateUpdates::handleFromBs: object-ref for attr update invalid" << endl; bs->SkipAll(); return; } ScriptVarPtr_t p = attrDesc->getValueScriptPtr(o); p.fromScriptVar(v); } //notes << "game state update: <" << r.obj.description() << "> " << attrDesc->attrName << " to " << v.toString() << endl; } } void GameStateUpdates::pushObjAttrUpdate(ObjAttrRef a) { objs.insert(a); } void GameStateUpdates::pushObjCreation(ObjRef o) { objDeletions.erase(o); objCreations.insert(o); } void GameStateUpdates::pushObjDeletion(ObjRef o) { Objs::iterator itStart = objs.lower_bound(ObjAttrRef::LowerLimit(o)); Objs::iterator itEnd = objs.upper_bound(ObjAttrRef::UpperLimit(o)); objs.erase(itStart, itEnd); objCreations.erase(o); objDeletions.insert(o); } void GameStateUpdates::reset() { objs.clear(); objCreations.clear(); objDeletions.clear(); } static bool ownObject(ObjRef o) { // This is very custom right now and need to be made somewhat more general. if(o.classId == LuaID<CWorm>::value) { CWorm* w = game.wormById(o.objId, false); if(!w) return false; return w->getLocal(); } if(game.isServer()) return true; return false; } void GameStateUpdates::diffFromStateToCurrent(const GameState& s) { reset(); foreach(o, game.gameStateUpdates->objCreations) { if(game.isClient()) continue; // none-at-all right now... worm-creation is handled independently atm if(!ownObject(*o)) continue; if(!s.haveObject(*o)) pushObjCreation(*o); } foreach(u, game.gameStateUpdates->objs) { if(!ownObject(u->obj)) continue; const AttrDesc* attrDesc = u->attr.getAttrDesc(); if(attrDesc->serverside) { if(game.isClient()) continue; } else { // non serverside attr if(game.isClient() && !ownObject(u->obj)) continue; } ScriptVar_t curValue = u->get(); ScriptVar_t stateValue = attrDesc->defaultValue; if(s.haveObject(u->obj)) stateValue = s.getValue(*u); //notes << "update " << u->description() << ": " << curValue.toString() << " -> " << stateValue.toString() << endl; if(curValue != stateValue) pushObjAttrUpdate(*u); } foreach(o, game.gameStateUpdates->objDeletions) { if(game.isClient()) continue; // see obj-creations if(!ownObject(*o)) continue; if(s.haveObject(*o)) pushObjDeletion(*o); } } static ObjectState& GameState_registerObj(GameState& s, BaseObject* obj) { return s.objs[obj->thisRef] = ObjectState(obj); } GameState::GameState() { // register singletons which are always there GameState_registerObj(*this, &game); GameState_registerObj(*this, &gameSettings); } GameState GameState::Current() { GameState s; s.updateToCurrent(); return s; } void GameState::reset() { *this = GameState(); } void GameState::updateToCurrent() { reset(); foreach(o, game.gameStateUpdates->objCreations) { objs[*o] = ObjectState(*o); } foreach(u, game.gameStateUpdates->objs) { ObjAttrRef r = *u; Objs::iterator it = objs.find(r.obj); assert(it != objs.end()); ObjectState& s = it->second; assert(s.obj == it->first); s.attribs[u->attr].value = r.get(); } } void GameState::addObject(ObjRef o) { assert(!haveObject(o)); objs[o] = ObjectState(o); } bool GameState::haveObject(ObjRef o) const { Objs::const_iterator it = objs.find(o); return it != objs.end(); } ScriptVar_t GameState::getValue(ObjAttrRef a) const { Objs::const_iterator it = objs.find(a.obj); assert(it != objs.end()); assert(it->second.obj == a.obj); return it->second.getValue(a.attr); } <commit_msg>GameStateUpdates: small fix, better dbg msgs<commit_after>/* * GameState.cpp * OpenLieroX * * Created by Albert Zeyer on 15.02.12. * code under LGPL * */ #include "GameState.h" #include "Game.h" #include "Settings.h" #include "CWorm.h" #include "CBytestream.h" #include "ClassInfo.h" #include "ProfileSystem.h" ScriptVar_t ObjectState::getValue(AttribRef a) const { Attribs::const_iterator it = attribs.find(a); if(it == attribs.end()) return a.getAttrDesc()->defaultValue; return it->second.value; } GameStateUpdates::operator bool() const { if(!objs.empty()) return true; if(!objCreations.empty()) return true; if(!objDeletions.empty()) return true; return false; } void GameStateUpdates::writeToBs(CBytestream* bs) const { bs->writeInt16((uint16_t)objCreations.size()); foreach(o, objCreations) { o->writeToBs(bs); } bs->writeInt16((uint16_t)objDeletions.size()); foreach(o, objDeletions) { o->writeToBs(bs); } bs->writeInt((uint32_t)objs.size(), 4); foreach(a, objs) { const ObjAttrRef& attr = *a; ScriptVar_t curValue = a->get(); attr.writeToBs(bs); bs->writeVar(curValue); } } static BaseObject* getObjFromRef(ObjRef r) { switch(r.classId) { case LuaID<Game>::value: return &game; case LuaID<CWorm>::value: return game.wormById(r.objId, false); default: break; } return NULL; } static bool attrBelongsToClass(const ClassInfo* classInfo, const AttrDesc* attrDesc) { return classInfo->isTypeOf(attrDesc->objTypeId); } void GameStateUpdates::handleFromBs(CBytestream* bs) { uint16_t creationsNum = bs->readInt16(); for(uint16_t i = 0; i < creationsNum; ++i) { ObjRef r; r.readFromBs(bs); //BaseObject* o = getClassInfo(r.classId)->createInstance(); //o->thisRef.classId = r.classId; //o->thisRef.objId = r.objId; // we only handle/support CWorm objects for now... if(game.isServer()) { errors << "GameStateUpdates::handleFromBs: got obj creation as server: " << r.description() << endl; bs->SkipAll(); return; } if(r.classId != LuaID<CWorm>::value) { errors << "GameStateUpdates::handleFromBs: obj-creation: invalid class: " << r.description() << endl; bs->SkipAll(); return; } if(game.wormById(r.objId, false) != NULL) { errors << "GameStateUpdates::handleFromBs: worm-creation: worm " << r.objId << " already exists" << endl; bs->SkipAll(); return; } game.createNewWorm(r.objId, false, NULL, Version()); } uint16_t deletionsNum = bs->readInt16(); for(uint16_t i = 0; i < deletionsNum; ++i) { ObjRef r; r.readFromBs(bs); // we only handle/support CWorm objects for now... if(game.isServer()) { errors << "GameStateUpdates::handleFromBs: got obj deletion as server: " << r.description() << endl; bs->SkipAll(); return; } if(r.classId != LuaID<CWorm>::value) { errors << "GameStateUpdates::handleFromBs: obj-deletion: invalid class: " << r.description() << endl; bs->SkipAll(); return; } CWorm* w = game.wormById(r.objId, false); if(!w) { errors << "GameStateUpdates::handleFromBs: obj-deletion: worm " << r.objId << " does not exist" << endl; bs->SkipAll(); return; } game.removeWorm(w); } uint32_t attrUpdatesNum = bs->readInt(4); for(uint32_t i = 0; i < attrUpdatesNum; ++i) { ObjAttrRef r; r.readFromBs(bs); const AttrDesc* attrDesc = r.attr.getAttrDesc(); if(attrDesc == NULL) { errors << "GameStateUpdates::handleFromBs: AttrDesc for update not found" << endl; bs->SkipAll(); return; } const ClassInfo* classInfo = getClassInfo(r.obj.classId); if(classInfo == NULL) { errors << "GameStateUpdates::handleFromBs: class " << r.obj.classId << " for obj-update unknown" << endl; bs->SkipAll(); return; } if(!attrBelongsToClass(classInfo, attrDesc)) { errors << "GameStateUpdates::handleFromBs: attr " << attrDesc->description() << " does not belong to class " << r.obj.classId << " for obj-update" << endl; bs->SkipAll(); return; } ScriptVar_t v; bs->readVar(v); // for now, this is somewhat specific to the only types we support if(r.obj.classId == LuaID<Settings>::value) { if(game.isServer()) { errors << "GameStateUpdates::handleFromBs: got settings update as server" << endl; bs->SkipAll(); return; } if(!Settings::getAttrDescs().belongsToUs(attrDesc)) { errors << "GameStateUpdates::handleFromBs: settings update AttrDesc " << attrDesc->description() << " is not a setting attr" << endl; bs->SkipAll(); return; } FeatureIndex fIndex = Settings::getAttrDescs().getIndex(attrDesc); cClient->getGameLobby().overwrite[fIndex] = v; } else { BaseObject* o = getObjFromRef(r.obj); if(o == NULL) { errors << "GameStateUpdates::handleFromBs: object for attr update not found: " << r.description() << endl; bs->SkipAll(); return; } if(o->thisRef != r.obj) { errors << "GameStateUpdates::handleFromBs: object-ref for attr update invalid: " << r.description() << endl; bs->SkipAll(); return; } ScriptVarPtr_t p = attrDesc->getValueScriptPtr(o); p.fromScriptVar(v); } //notes << "game state update: <" << r.obj.description() << "> " << attrDesc->attrName << " to " << v.toString() << endl; } } void GameStateUpdates::pushObjAttrUpdate(ObjAttrRef a) { objs.insert(a); } void GameStateUpdates::pushObjCreation(ObjRef o) { objDeletions.erase(o); objCreations.insert(o); } void GameStateUpdates::pushObjDeletion(ObjRef o) { Objs::iterator itStart = objs.lower_bound(ObjAttrRef::LowerLimit(o)); Objs::iterator itEnd = objs.upper_bound(ObjAttrRef::UpperLimit(o)); objs.erase(itStart, itEnd); objCreations.erase(o); objDeletions.insert(o); } void GameStateUpdates::reset() { objs.clear(); objCreations.clear(); objDeletions.clear(); } static bool ownObject(ObjRef o) { // This is very custom right now and need to be made somewhat more general. if(o.classId == LuaID<CWorm>::value) { CWorm* w = game.wormById(o.objId, false); if(!w) return false; return w->getLocal(); } if(game.isServer()) return true; return false; } void GameStateUpdates::diffFromStateToCurrent(const GameState& s) { reset(); foreach(o, game.gameStateUpdates->objCreations) { if(game.isClient()) continue; // none-at-all right now... worm-creation is handled independently atm if(!ownObject(*o)) continue; if(!s.haveObject(*o)) pushObjCreation(*o); } foreach(u, game.gameStateUpdates->objs) { if(!ownObject(u->obj)) continue; const AttrDesc* attrDesc = u->attr.getAttrDesc(); if(attrDesc->serverside) { if(game.isClient()) continue; } else { // non serverside attr if(game.isClient() && !ownObject(u->obj)) continue; } ScriptVar_t curValue = u->get(); ScriptVar_t stateValue = attrDesc->defaultValue; if(s.haveObject(u->obj)) stateValue = s.getValue(*u); //notes << "update " << u->description() << ": " << curValue.toString() << " -> " << stateValue.toString() << endl; if(curValue != stateValue) pushObjAttrUpdate(*u); } foreach(o, game.gameStateUpdates->objDeletions) { if(game.isClient()) continue; // see obj-creations if(!ownObject(*o)) continue; if(s.haveObject(*o)) pushObjDeletion(*o); } } static ObjectState& GameState_registerObj(GameState& s, BaseObject* obj) { return s.objs[obj->thisRef] = ObjectState(obj); } GameState::GameState() { // register singletons which are always there GameState_registerObj(*this, &game); GameState_registerObj(*this, &gameSettings); } GameState GameState::Current() { GameState s; s.updateToCurrent(); return s; } void GameState::reset() { *this = GameState(); } void GameState::updateToCurrent() { reset(); foreach(o, game.gameStateUpdates->objCreations) { objs[*o] = ObjectState(*o); } foreach(u, game.gameStateUpdates->objs) { ObjAttrRef r = *u; Objs::iterator it = objs.find(r.obj); assert(it != objs.end()); ObjectState& s = it->second; assert(s.obj == it->first); s.attribs[u->attr].value = r.get(); } } void GameState::addObject(ObjRef o) { assert(!haveObject(o)); objs[o] = ObjectState(o); } bool GameState::haveObject(ObjRef o) const { Objs::const_iterator it = objs.find(o); return it != objs.end(); } ScriptVar_t GameState::getValue(ObjAttrRef a) const { Objs::const_iterator it = objs.find(a.obj); assert(it != objs.end()); assert(it->second.obj == a.obj); return it->second.getValue(a.attr); } <|endoftext|>
<commit_before> #include <cstdarg> #include <cstdlib> #include <cstring> #include <cerrno> #include "z80.h" namespace { using z80::fast_u8; using z80::fast_u16; using z80::least_u8; #if defined(__GNUC__) || defined(__clang__) # define LIKE_PRINTF(format, args) \ __attribute__((__format__(__printf__, format, args))) #else # define LIKE_PRINTF(format, args) /* nothing */ #endif const char program_name[] = "benchmark"; [[noreturn]] LIKE_PRINTF(1, 0) void verror(const char *format, va_list args) { std::fprintf(stderr, "%s: ", program_name); std::vfprintf(stderr, format, args); std::fprintf(stderr, "\n"); exit(EXIT_FAILURE); } [[noreturn]] LIKE_PRINTF(1, 2) void error(const char *format, ...) { va_list args; va_start(args, format); verror(format, args); va_end(args); } static constexpr fast_u16 quit_addr = 0x0000; static constexpr fast_u16 bdos_addr = 0x0005; static constexpr fast_u16 entry_addr = 0x0100; // Handles CP/M BDOS calls to write text messages. template<typename B> class default_watcher : public B { public: typedef B base; void write_char(fast_u8 c) { std::putchar(static_cast<char>(c)); } void handle_c_write() { write_char(base::get_e()); } void handle_c_writestr() { fast_u16 addr = base::get_de(); for(;;) { fast_u8 c = self().on_read(addr); if(c == '$') break; write_char(c); addr = (addr + 1) % z80::address_space_size; } } void handle_bdos_call() { switch(base::get_c()) { case c_write: handle_c_write(); break; case c_writestr: handle_c_writestr(); break; } } void on_step() { if(base::get_pc() == bdos_addr) handle_bdos_call(); base::on_step(); } void on_report() {} protected: using base::self; private: static constexpr fast_u8 c_write = 0x02; static constexpr fast_u8 c_writestr = 0x09; }; // Lets the emulator to perform at full speed. template<typename B> class empty_watcher : public B { public: typedef B base; void on_report() {} protected: using base::self; }; // Tracks use of CPU state. template<typename B> class state_watcher : public B { public: typedef B base; fast_u16 on_get_pc() { ++pc_reads; return base::on_get_pc(); } void on_set_pc(fast_u16 nn) { ++pc_writes; base::on_set_pc(nn); } fast_u16 on_get_sp() { ++sp_reads; return base::on_get_sp(); } void on_set_sp(fast_u16 nn) { ++sp_writes; base::on_set_sp(nn); } fast_u16 on_get_wz() { ++wz_reads; return base::on_get_wz(); } void on_set_wz(fast_u16 nn) { ++wz_writes; base::on_set_wz(nn); } fast_u16 on_get_bc() { ++bc_reads; return base::on_get_bc(); } void on_set_bc(fast_u16 nn) { ++bc_writes; base::on_set_bc(nn); } fast_u8 on_get_b() { ++b_reads; return base::on_get_b(); } void on_set_b(fast_u8 n) { ++b_writes; base::on_set_b(n); } fast_u8 on_get_c() { ++c_reads; return base::on_get_c(); } void on_set_c(fast_u8 n) { ++c_writes; base::on_set_c(n); } fast_u16 on_get_de() { ++de_reads; return base::on_get_de(); } void on_set_de(fast_u16 nn) { ++de_writes; base::on_set_de(nn); } fast_u8 on_get_d() { ++d_reads; return base::on_get_d(); } void on_set_d(fast_u8 n) { ++d_writes; base::on_set_d(n); } fast_u8 on_get_e() { ++e_reads; return base::on_get_e(); } void on_set_e(fast_u8 n) { ++e_writes; base::on_set_e(n); } fast_u16 on_get_hl() { ++hl_reads; return base::on_get_hl(); } void on_set_hl(fast_u16 nn) { ++hl_writes; base::on_set_hl(nn); } fast_u8 on_get_h() { ++h_reads; return base::on_get_h(); } void on_set_h(fast_u8 n) { ++h_writes; base::on_set_h(n); } fast_u8 on_get_l() { ++l_reads; return base::on_get_l(); } void on_set_l(fast_u8 n) { ++l_writes; base::on_set_l(n); } fast_u16 on_get_af() { ++af_reads; return base::on_get_af(); } void on_set_af(fast_u16 nn) { ++af_writes; base::on_set_af(nn); } fast_u8 on_get_a() { ++a_reads; return base::on_get_a(); } void on_set_a(fast_u8 n) { ++a_writes; base::on_set_a(n); } fast_u8 on_get_f() { ++f_reads; return base::on_get_f(); } void on_set_f(fast_u8 n) { ++f_writes; base::on_set_f(n); } bool on_is_int_disabled() { ++is_int_disabled_reads; return base::on_is_int_disabled(); } void on_set_is_int_disabled(bool f) { ++is_int_disabled_writes; base::on_set_is_int_disabled(f); } bool on_is_halted() { ++is_halted_reads; return base::on_is_halted(); } void on_set_is_halted(bool f) { ++is_halted_writes; base::on_set_is_halted(f); } void on_report() { std::printf("pc reads: %10.0f\n" "pc writes: %10.0f\n" "sp reads: %10.0f\n" "sp writes: %10.0f\n" "wz reads: %10.0f\n" "wz writes: %10.0f\n" "bc reads: %10.0f\n" "bc writes: %10.0f\n" "b reads: %10.0f\n" "b writes: %10.0f\n" "c reads: %10.0f\n" "c writes: %10.0f\n" "de reads: %10.0f\n" "de writes: %10.0f\n" "d reads: %10.0f\n" "d writes: %10.0f\n" "e reads: %10.0f\n" "e writes: %10.0f\n" "hl reads: %10.0f\n" "hl writes: %10.0f\n" "h reads: %10.0f\n" "h writes: %10.0f\n" "l reads: %10.0f\n" "l writes: %10.0f\n" "af reads: %10.0f\n" "af writes: %10.0f\n" "a reads: %10.0f\n" "a writes: %10.0f\n" "f reads: %10.0f\n" "f writes: %10.0f\n" "is_int_disabled reads: %10.0f\n" "is_int_disabled writes: %10.0f\n" "is_halted reads: %10.0f\n" "is_halted writes: %10.0f\n", static_cast<double>(pc_reads), static_cast<double>(pc_writes), static_cast<double>(sp_reads), static_cast<double>(sp_writes), static_cast<double>(wz_reads), static_cast<double>(wz_writes), static_cast<double>(bc_reads), static_cast<double>(bc_writes), static_cast<double>(b_reads), static_cast<double>(b_writes), static_cast<double>(c_reads), static_cast<double>(c_writes), static_cast<double>(de_reads), static_cast<double>(de_writes), static_cast<double>(d_reads), static_cast<double>(d_writes), static_cast<double>(e_reads), static_cast<double>(e_writes), static_cast<double>(hl_reads), static_cast<double>(hl_writes), static_cast<double>(h_reads), static_cast<double>(h_writes), static_cast<double>(l_reads), static_cast<double>(l_writes), static_cast<double>(af_reads), static_cast<double>(af_writes), static_cast<double>(a_reads), static_cast<double>(a_writes), static_cast<double>(f_reads), static_cast<double>(f_writes), static_cast<double>(is_int_disabled_reads), static_cast<double>(is_int_disabled_writes), static_cast<double>(is_halted_reads), static_cast<double>(is_halted_writes)); } protected: using base::self; double pc_reads = 0; double pc_writes = 0; double sp_reads = 0; double sp_writes = 0; double wz_reads = 0; double wz_writes = 0; double bc_reads = 0; double bc_writes = 0; double b_reads = 0; double b_writes = 0; double c_reads = 0; double c_writes = 0; double de_reads = 0; double de_writes = 0; double d_reads = 0; double d_writes = 0; double e_reads = 0; double e_writes = 0; double hl_reads = 0; double hl_writes = 0; double h_reads = 0; double h_writes = 0; double l_reads = 0; double l_writes = 0; double af_reads = 0; double af_writes = 0; double a_reads = 0; double a_writes = 0; double f_reads = 0; double f_writes = 0; double is_int_disabled_reads = 0; double is_int_disabled_writes = 0; double is_halted_reads = 0; double is_halted_writes = 0; }; #define WATCHER default_watcher template<typename B> class emulator : public WATCHER<B> { public: typedef WATCHER<B> base; emulator() {} fast_u8 on_read(fast_u16 addr) { assert(addr < z80::address_space_size); return memory[addr]; } void on_write(fast_u16 addr, fast_u8 n) { assert(addr < z80::address_space_size); memory[addr] = static_cast<least_u8>(n); } void run(const char *program) { FILE *f = std::fopen(program, "rb"); if(!f) { error("Cannot open file '%s': %s", program, std::strerror(errno)); } std::size_t count = std::fread( memory + entry_addr, /* size= */ 1, z80::address_space_size - entry_addr, f); if(ferror(f)) { error("Cannot read file '%s': %s", program, std::strerror(errno)); } if(count == 0) error("Program file '%s' is empty", program); if(!feof(f)) error("Program file '%s' is too large", program); if(std::fclose(f) != 0) { error("Cannot close file '%s': %s", program, std::strerror(errno)); } base::set_pc(entry_addr); memory[bdos_addr] = 0xc9; // ret for(;;) { fast_u16 pc = base::get_pc(); if(pc == quit_addr) break; self().on_step(); } self().on_report(); } protected: using base::self; private: least_u8 memory[z80::address_space_size] = {}; }; class i8080_emulator : public emulator<z80::i8080_cpu<i8080_emulator>> {}; class z80_emulator : public emulator<z80::z80_cpu<z80_emulator>> {}; [[noreturn]] static void usage() { error("benchmark {i8080|z80} <program.com>"); } } // anonymous namespace int main(int argc, char *argv[]) { if(argc != 3) usage(); const char *program = argv[2]; const char *cpu = argv[1]; if(std::strcmp(cpu, "i8080") == 0) { i8080_emulator e; e.run(program); } else if(std::strcmp(cpu, "z80") == 0) { z80_emulator e; e.run(program); } else { error("Unknown CPU '%s'", cpu); } } <commit_msg>Do not track the interrupts-enabled flip-flop in the benchmark.<commit_after> #include <cstdarg> #include <cstdlib> #include <cstring> #include <cerrno> #include "z80.h" namespace { using z80::fast_u8; using z80::fast_u16; using z80::least_u8; using z80::unused; #if defined(__GNUC__) || defined(__clang__) # define LIKE_PRINTF(format, args) \ __attribute__((__format__(__printf__, format, args))) #else # define LIKE_PRINTF(format, args) /* nothing */ #endif const char program_name[] = "benchmark"; [[noreturn]] LIKE_PRINTF(1, 0) void verror(const char *format, va_list args) { std::fprintf(stderr, "%s: ", program_name); std::vfprintf(stderr, format, args); std::fprintf(stderr, "\n"); exit(EXIT_FAILURE); } [[noreturn]] LIKE_PRINTF(1, 2) void error(const char *format, ...) { va_list args; va_start(args, format); verror(format, args); va_end(args); } static constexpr fast_u16 quit_addr = 0x0000; static constexpr fast_u16 bdos_addr = 0x0005; static constexpr fast_u16 entry_addr = 0x0100; // Handles CP/M BDOS calls to write text messages. template<typename B> class default_watcher : public B { public: typedef B base; void write_char(fast_u8 c) { std::putchar(static_cast<char>(c)); } void handle_c_write() { write_char(base::get_e()); } void handle_c_writestr() { fast_u16 addr = base::get_de(); for(;;) { fast_u8 c = self().on_read(addr); if(c == '$') break; write_char(c); addr = (addr + 1) % z80::address_space_size; } } void handle_bdos_call() { switch(base::get_c()) { case c_write: handle_c_write(); break; case c_writestr: handle_c_writestr(); break; } } void on_step() { if(base::get_pc() == bdos_addr) handle_bdos_call(); base::on_step(); } void on_report() {} protected: using base::self; private: static constexpr fast_u8 c_write = 0x02; static constexpr fast_u8 c_writestr = 0x09; }; // Lets the emulator to perform at full speed. template<typename B> class empty_watcher : public B { public: typedef B base; // The benchmark emulator provides no support for interrupts, // so no need to track the flag. // TODO: Remove that flag from the emulator's state at all. void on_set_is_int_disabled(bool f) { unused(f); } void on_report() {} protected: using base::self; }; // Tracks use of CPU state. template<typename B> class state_watcher : public B { public: typedef B base; fast_u16 on_get_pc() { ++pc_reads; return base::on_get_pc(); } void on_set_pc(fast_u16 nn) { ++pc_writes; base::on_set_pc(nn); } fast_u16 on_get_sp() { ++sp_reads; return base::on_get_sp(); } void on_set_sp(fast_u16 nn) { ++sp_writes; base::on_set_sp(nn); } fast_u16 on_get_wz() { ++wz_reads; return base::on_get_wz(); } void on_set_wz(fast_u16 nn) { ++wz_writes; base::on_set_wz(nn); } fast_u16 on_get_bc() { ++bc_reads; return base::on_get_bc(); } void on_set_bc(fast_u16 nn) { ++bc_writes; base::on_set_bc(nn); } fast_u8 on_get_b() { ++b_reads; return base::on_get_b(); } void on_set_b(fast_u8 n) { ++b_writes; base::on_set_b(n); } fast_u8 on_get_c() { ++c_reads; return base::on_get_c(); } void on_set_c(fast_u8 n) { ++c_writes; base::on_set_c(n); } fast_u16 on_get_de() { ++de_reads; return base::on_get_de(); } void on_set_de(fast_u16 nn) { ++de_writes; base::on_set_de(nn); } fast_u8 on_get_d() { ++d_reads; return base::on_get_d(); } void on_set_d(fast_u8 n) { ++d_writes; base::on_set_d(n); } fast_u8 on_get_e() { ++e_reads; return base::on_get_e(); } void on_set_e(fast_u8 n) { ++e_writes; base::on_set_e(n); } fast_u16 on_get_hl() { ++hl_reads; return base::on_get_hl(); } void on_set_hl(fast_u16 nn) { ++hl_writes; base::on_set_hl(nn); } fast_u8 on_get_h() { ++h_reads; return base::on_get_h(); } void on_set_h(fast_u8 n) { ++h_writes; base::on_set_h(n); } fast_u8 on_get_l() { ++l_reads; return base::on_get_l(); } void on_set_l(fast_u8 n) { ++l_writes; base::on_set_l(n); } fast_u16 on_get_af() { ++af_reads; return base::on_get_af(); } void on_set_af(fast_u16 nn) { ++af_writes; base::on_set_af(nn); } fast_u8 on_get_a() { ++a_reads; return base::on_get_a(); } void on_set_a(fast_u8 n) { ++a_writes; base::on_set_a(n); } fast_u8 on_get_f() { ++f_reads; return base::on_get_f(); } void on_set_f(fast_u8 n) { ++f_writes; base::on_set_f(n); } bool on_is_int_disabled() { ++is_int_disabled_reads; return base::on_is_int_disabled(); } void on_set_is_int_disabled(bool f) { ++is_int_disabled_writes; base::on_set_is_int_disabled(f); } bool on_is_halted() { ++is_halted_reads; return base::on_is_halted(); } void on_set_is_halted(bool f) { ++is_halted_writes; base::on_set_is_halted(f); } void on_report() { std::printf("pc reads: %10.0f\n" "pc writes: %10.0f\n" "sp reads: %10.0f\n" "sp writes: %10.0f\n" "wz reads: %10.0f\n" "wz writes: %10.0f\n" "bc reads: %10.0f\n" "bc writes: %10.0f\n" "b reads: %10.0f\n" "b writes: %10.0f\n" "c reads: %10.0f\n" "c writes: %10.0f\n" "de reads: %10.0f\n" "de writes: %10.0f\n" "d reads: %10.0f\n" "d writes: %10.0f\n" "e reads: %10.0f\n" "e writes: %10.0f\n" "hl reads: %10.0f\n" "hl writes: %10.0f\n" "h reads: %10.0f\n" "h writes: %10.0f\n" "l reads: %10.0f\n" "l writes: %10.0f\n" "af reads: %10.0f\n" "af writes: %10.0f\n" "a reads: %10.0f\n" "a writes: %10.0f\n" "f reads: %10.0f\n" "f writes: %10.0f\n" "is_int_disabled reads: %10.0f\n" "is_int_disabled writes: %10.0f\n" "is_halted reads: %10.0f\n" "is_halted writes: %10.0f\n", static_cast<double>(pc_reads), static_cast<double>(pc_writes), static_cast<double>(sp_reads), static_cast<double>(sp_writes), static_cast<double>(wz_reads), static_cast<double>(wz_writes), static_cast<double>(bc_reads), static_cast<double>(bc_writes), static_cast<double>(b_reads), static_cast<double>(b_writes), static_cast<double>(c_reads), static_cast<double>(c_writes), static_cast<double>(de_reads), static_cast<double>(de_writes), static_cast<double>(d_reads), static_cast<double>(d_writes), static_cast<double>(e_reads), static_cast<double>(e_writes), static_cast<double>(hl_reads), static_cast<double>(hl_writes), static_cast<double>(h_reads), static_cast<double>(h_writes), static_cast<double>(l_reads), static_cast<double>(l_writes), static_cast<double>(af_reads), static_cast<double>(af_writes), static_cast<double>(a_reads), static_cast<double>(a_writes), static_cast<double>(f_reads), static_cast<double>(f_writes), static_cast<double>(is_int_disabled_reads), static_cast<double>(is_int_disabled_writes), static_cast<double>(is_halted_reads), static_cast<double>(is_halted_writes)); } protected: using base::self; double pc_reads = 0; double pc_writes = 0; double sp_reads = 0; double sp_writes = 0; double wz_reads = 0; double wz_writes = 0; double bc_reads = 0; double bc_writes = 0; double b_reads = 0; double b_writes = 0; double c_reads = 0; double c_writes = 0; double de_reads = 0; double de_writes = 0; double d_reads = 0; double d_writes = 0; double e_reads = 0; double e_writes = 0; double hl_reads = 0; double hl_writes = 0; double h_reads = 0; double h_writes = 0; double l_reads = 0; double l_writes = 0; double af_reads = 0; double af_writes = 0; double a_reads = 0; double a_writes = 0; double f_reads = 0; double f_writes = 0; double is_int_disabled_reads = 0; double is_int_disabled_writes = 0; double is_halted_reads = 0; double is_halted_writes = 0; }; #define WATCHER default_watcher template<typename B> class emulator : public WATCHER<B> { public: typedef WATCHER<B> base; emulator() {} fast_u8 on_read(fast_u16 addr) { assert(addr < z80::address_space_size); return memory[addr]; } void on_write(fast_u16 addr, fast_u8 n) { assert(addr < z80::address_space_size); memory[addr] = static_cast<least_u8>(n); } void run(const char *program) { FILE *f = std::fopen(program, "rb"); if(!f) { error("Cannot open file '%s': %s", program, std::strerror(errno)); } std::size_t count = std::fread( memory + entry_addr, /* size= */ 1, z80::address_space_size - entry_addr, f); if(ferror(f)) { error("Cannot read file '%s': %s", program, std::strerror(errno)); } if(count == 0) error("Program file '%s' is empty", program); if(!feof(f)) error("Program file '%s' is too large", program); if(std::fclose(f) != 0) { error("Cannot close file '%s': %s", program, std::strerror(errno)); } base::set_pc(entry_addr); memory[bdos_addr] = 0xc9; // ret for(;;) { fast_u16 pc = base::get_pc(); if(pc == quit_addr) break; self().on_step(); } self().on_report(); } protected: using base::self; private: least_u8 memory[z80::address_space_size] = {}; }; class i8080_emulator : public emulator<z80::i8080_cpu<i8080_emulator>> {}; class z80_emulator : public emulator<z80::z80_cpu<z80_emulator>> {}; [[noreturn]] static void usage() { error("benchmark {i8080|z80} <program.com>"); } } // anonymous namespace int main(int argc, char *argv[]) { if(argc != 3) usage(); const char *program = argv[2]; const char *cpu = argv[1]; if(std::strcmp(cpu, "i8080") == 0) { i8080_emulator e; e.run(program); } else if(std::strcmp(cpu, "z80") == 0) { z80_emulator e; e.run(program); } else { error("Unknown CPU '%s'", cpu); } } <|endoftext|>
<commit_before>#ifndef __FILESYSTEM_HPP_INCLUDED__ #define __FILESYSTEM_HPP_INCLUDED__ #include <string> #include <vector> namespace dafs { const int BLOCK_SIZE_IN_BYTES = 1048576; struct Block { int id; int revision; std::string owner; char contents[BLOCK_SIZE_IN_BYTES]; Block(int id_, int revision_, std::string owner_, std::string contents_) : id(id_), revision(revision_), owner(owner_) { contents_.copy(contents, contents_.length()); } }; class File { public: File(); void Read(); void Write(std::string string, int offset); private: unsigned int read_pointer; unsigned int write_pointer; }; class SuperBlock { private: std::vector<File> files; std::vector<Block> blocks; }; } #endif <commit_msg>Add metafile class<commit_after>#ifndef __FILESYSTEM_HPP_INCLUDED__ #define __FILESYSTEM_HPP_INCLUDED__ #include <string> #include <vector> namespace dafs { const int BLOCK_SIZE_IN_BYTES = 1048576; struct Block { int id; int revision; std::string owner; char contents[BLOCK_SIZE_IN_BYTES]; Block(int id_, int revision_, std::string owner_, std::string contents_) : id(id_), revision(revision_), owner(owner_) { contents_.copy(contents, contents_.length()); } }; class MetaFile { }; class File { public: File(); void Read(); void Write(std::string string, int offset); private: unsigned int read_pointer; unsigned int write_pointer; MetaFile previous; MetaFile current; MetaFile next; }; class SuperBlock { private: std::vector<File> files; std::vector<Block> blocks; }; } #endif <|endoftext|>
<commit_before>/*********************************************************************************************************************** * Copyright (C) 2016 Andrew Zonenberg and contributors * * * * This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General * * Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) * * any later version. * * * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for * * more details. * * * * You should have received a copy of the GNU Lesser General Public License along with this program; if not, you may * * find one here: * * https://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt * * or you may search the http://www.gnu.org website for the version 2.1 license, or you may write to the Free Software * * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA * **********************************************************************************************************************/ //Windows appears to define an ERROR macro in its headers. //Conflicts with ERROR enum defined in log.h. #if defined(_WIN32) #undef ERROR #endif #include <log.h> #include <gpdevboard.h> #include <unistd.h> using namespace std; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // USB command helpers bool SendInterruptTransfer(hdevice hdev, const uint8_t* buf, size_t size) { if(hid_write(hdev, buf, size) < 0) { LogError("hid_write failed (%ls)\n", hid_error(hdev)); return false; } return true; } bool ReceiveInterruptTransfer(hdevice hdev, uint8_t* buf, size_t size) { if(hid_read_timeout(hdev, buf, size, 250) < 0) { LogError("hid_read_timeout failed (%ls)\n", hid_error(hdev)); return false; } return true; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Enumeration / setup helpers //Set up USB stuff bool USBSetup() { if(0 != hid_init()) { LogError("hid_init failed\n"); return false; } return true; } void USBCleanup(hdevice hdev) { hid_close(hdev); hid_exit(); } /** @brief Gets the device handle @param idVendor USB VID @param idProduct USB PID @param nboard Number of the board to open. Note that this index is counted for all VID matches regardless of PID! This is important so we can match both bootloader and operating dev boards. */ hdevice OpenDevice(uint16_t idVendor, uint16_t idProduct, int nboard) { //initial sanity check if(nboard < 0) { LogError("invalid device index (should be >0)\n"); return NULL; } int dev_index = 0; struct hid_device_info *devs, *cur_dev; devs = hid_enumerate(idVendor, idProduct); cur_dev = devs; while (cur_dev) { LogDebug("Found Silego device at %s\n", cur_dev->path); if (dev_index == nboard) break; cur_dev = cur_dev->next; dev_index++; } hid_free_enumeration(devs); hdevice hdev; if (!cur_dev) return NULL; LogVerbose("Using device at %s\n", cur_dev->path); hdev = hid_open_path(cur_dev->path); if (!hdev) { LogError("hid_open_path failed\n"); return NULL; } return hdev; } //Gets a string descriptor as a STL string bool GetStringDescriptor(hdevice hdev, uint8_t index, string &desc) { char strbuf[128]; wchar_t wstrbuf[sizeof(strbuf)]; if(hid_get_indexed_string(hdev, index, wstrbuf, sizeof(strbuf)) < 0) { LogFatal("hid_get_indexed_string failed\n"); return false; } wcstombs(strbuf, wstrbuf, sizeof(strbuf)); desc = strbuf; return true; } <commit_msg>Fix GetStringDescriptor for the hidapi hidraw backend<commit_after>/*********************************************************************************************************************** * Copyright (C) 2016 Andrew Zonenberg and contributors * * * * This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General * * Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) * * any later version. * * * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for * * more details. * * * * You should have received a copy of the GNU Lesser General Public License along with this program; if not, you may * * find one here: * * https://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt * * or you may search the http://www.gnu.org website for the version 2.1 license, or you may write to the Free Software * * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA * **********************************************************************************************************************/ //Windows appears to define an ERROR macro in its headers. //Conflicts with ERROR enum defined in log.h. #if defined(_WIN32) #undef ERROR #endif #include <log.h> #include <gpdevboard.h> #include <unistd.h> using namespace std; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // USB command helpers bool SendInterruptTransfer(hdevice hdev, const uint8_t* buf, size_t size) { if(hid_write(hdev, buf, size) < 0) { LogError("hid_write failed (%ls)\n", hid_error(hdev)); return false; } return true; } bool ReceiveInterruptTransfer(hdevice hdev, uint8_t* buf, size_t size) { if(hid_read_timeout(hdev, buf, size, 250) < 0) { LogError("hid_read_timeout failed (%ls)\n", hid_error(hdev)); return false; } return true; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Enumeration / setup helpers //Set up USB stuff bool USBSetup() { if(0 != hid_init()) { LogError("hid_init failed\n"); return false; } return true; } void USBCleanup(hdevice hdev) { hid_close(hdev); hid_exit(); } /** @brief Gets the device handle @param idVendor USB VID @param idProduct USB PID @param nboard Number of the board to open. Note that this index is counted for all VID matches regardless of PID! This is important so we can match both bootloader and operating dev boards. */ hdevice OpenDevice(uint16_t idVendor, uint16_t idProduct, int nboard) { //initial sanity check if(nboard < 0) { LogError("invalid device index (should be >0)\n"); return NULL; } int dev_index = 0; struct hid_device_info *devs, *cur_dev; devs = hid_enumerate(idVendor, idProduct); cur_dev = devs; while (cur_dev) { LogDebug("Found Silego device at %s\n", cur_dev->path); if (dev_index == nboard) break; cur_dev = cur_dev->next; dev_index++; } hid_free_enumeration(devs); hdevice hdev; if (!cur_dev) return NULL; LogVerbose("Using device at %s\n", cur_dev->path); hdev = hid_open_path(cur_dev->path); if (!hdev) { LogError("hid_open_path failed\n"); return NULL; } return hdev; } //Gets a string descriptor as a STL string bool GetStringDescriptor(hdevice hdev, uint8_t index, string &desc) { char strbuf[128]; wchar_t wstrbuf[sizeof(strbuf)]; switch (index) { case 1: if (hid_get_product_string(hdev, wstrbuf, sizeof(strbuf)) < 0) { LogFatal("hid_get_product_string failed\n"); return false; } break; case 2: if (hid_get_manufacturer_string(hdev, wstrbuf, sizeof(strbuf)) < 0) { LogFatal("hid_get_manufacturer_string failed\n"); return false; } break; default: LogFatal("Invalid index %d\n", index); return false; } wcstombs(strbuf, wstrbuf, sizeof(strbuf)); desc = strbuf; return true; } <|endoftext|>
<commit_before>/* Copyright (c) 2003, Arvid Norberg, Daniel Wallin 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 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 TORRENT_ALERT_HPP_INCLUDED #define TORRENT_ALERT_HPP_INCLUDED #include <memory> #include <queue> #include <string> #ifdef _MSC_VER #pragma warning(push, 1) #endif #include <boost/function/function1.hpp> #include <boost/preprocessor/repetition/enum_params_with_a_default.hpp> #include <boost/preprocessor/repetition/enum.hpp> #include <boost/preprocessor/repetition/enum_params.hpp> #include <boost/preprocessor/repetition/enum_shifted_params.hpp> #ifdef _MSC_VER #pragma warning(pop) #endif #include "libtorrent/ptime.hpp" #include "libtorrent/config.hpp" #include "libtorrent/assert.hpp" #include "libtorrent/thread.hpp" #include "libtorrent/io_service_fwd.hpp" #ifndef TORRENT_MAX_ALERT_TYPES #define TORRENT_MAX_ALERT_TYPES 15 #endif namespace libtorrent { class TORRENT_EXPORT alert { public: #ifndef TORRENT_NO_DEPRECATE // only here for backwards compatibility enum severity_t { debug, info, warning, critical, fatal, none }; #endif enum category_t { error_notification = 0x1, peer_notification = 0x2, port_mapping_notification = 0x4, storage_notification = 0x8, tracker_notification = 0x10, debug_notification = 0x20, status_notification = 0x40, progress_notification = 0x80, ip_block_notification = 0x100, performance_warning = 0x200, dht_notification = 0x400, stats_notification = 0x800, all_categories = 0xffffffff }; alert(); virtual ~alert(); // a timestamp is automatically created in the constructor ptime timestamp() const; virtual int type() const = 0; virtual char const* what() const = 0; virtual std::string message() const = 0; virtual int category() const = 0; #ifndef TORRENT_NO_DEPRECATE TORRENT_DEPRECATED_PREFIX severity_t severity() const TORRENT_DEPRECATED { return warning; } #endif virtual std::auto_ptr<alert> clone() const = 0; private: ptime m_timestamp; }; class TORRENT_EXPORT alert_manager { public: enum { queue_size_limit_default = 1000 }; alert_manager(io_service& ios); ~alert_manager(); void post_alert(const alert& alert_); bool pending() const; std::auto_ptr<alert> get(); template <class T> bool should_post() const { mutex::scoped_lock lock(m_mutex); if (m_alerts.size() >= m_queue_size_limit) return false; return (m_alert_mask & T::static_category) != 0; } alert const* wait_for_alert(time_duration max_wait); void set_alert_mask(int m) { mutex::scoped_lock lock(m_mutex); m_alert_mask = m; } size_t alert_queue_size_limit() const { return m_queue_size_limit; } size_t set_alert_queue_size_limit(size_t queue_size_limit_); void set_dispatch_function(boost::function<void(alert const&)> const&); private: std::queue<alert*> m_alerts; mutable mutex m_mutex; condition m_condition; int m_alert_mask; size_t m_queue_size_limit; boost::function<void(alert const&)> m_dispatch; io_service& m_ios; }; struct TORRENT_EXPORT unhandled_alert : std::exception { unhandled_alert() {} }; #ifndef BOOST_NO_TYPEID namespace detail { struct void_; template<class Handler , BOOST_PP_ENUM_PARAMS(TORRENT_MAX_ALERT_TYPES, class T)> void handle_alert_dispatch( const std::auto_ptr<alert>& alert_, const Handler& handler , const std::type_info& typeid_ , BOOST_PP_ENUM_BINARY_PARAMS(TORRENT_MAX_ALERT_TYPES, T, *p)) { if (typeid_ == typeid(T0)) handler(*static_cast<T0*>(alert_.get())); else handle_alert_dispatch(alert_, handler, typeid_ , BOOST_PP_ENUM_SHIFTED_PARAMS( TORRENT_MAX_ALERT_TYPES, p), (void_*)0); } template<class Handler> void handle_alert_dispatch( const std::auto_ptr<alert>& alert_ , const Handler& handler , const std::type_info& typeid_ , BOOST_PP_ENUM_PARAMS(TORRENT_MAX_ALERT_TYPES, void_* BOOST_PP_INTERCEPT)) { throw unhandled_alert(); } } // namespace detail template<BOOST_PP_ENUM_PARAMS_WITH_A_DEFAULT( TORRENT_MAX_ALERT_TYPES, class T, detail::void_)> struct TORRENT_EXPORT handle_alert { template<class Handler> handle_alert(const std::auto_ptr<alert>& alert_ , const Handler& handler) { #define ALERT_POINTER_TYPE(z, n, text) (BOOST_PP_CAT(T, n)*)0 detail::handle_alert_dispatch(alert_, handler, typeid(*alert_) , BOOST_PP_ENUM(TORRENT_MAX_ALERT_TYPES, ALERT_POINTER_TYPE, _)); #undef ALERT_POINTER_TYPE } }; #endif // BOOST_NO_TYPEID template <class T> T* alert_cast(alert* a) { if (a->type() == T::alert_type) return static_cast<T*>(a); return 0; } template <class T> T const* alert_cast(alert const* a) { if (a->type() == T::alert_type) return static_cast<T const*>(a); return 0; } } // namespace libtorrent #endif // TORRENT_ALERT_HPP_INCLUDED <commit_msg>fixed unused variables warnings<commit_after>/* Copyright (c) 2003, Arvid Norberg, Daniel Wallin 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 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 TORRENT_ALERT_HPP_INCLUDED #define TORRENT_ALERT_HPP_INCLUDED #include <memory> #include <queue> #include <string> #ifdef _MSC_VER #pragma warning(push, 1) #endif #include <boost/function/function1.hpp> #include <boost/preprocessor/repetition/enum_params_with_a_default.hpp> #include <boost/preprocessor/repetition/enum.hpp> #include <boost/preprocessor/repetition/enum_params.hpp> #include <boost/preprocessor/repetition/enum_shifted_params.hpp> #include <boost/preprocessor/repetition/enum_shifted_binary_params.hpp> #ifdef _MSC_VER #pragma warning(pop) #endif #include "libtorrent/ptime.hpp" #include "libtorrent/config.hpp" #include "libtorrent/assert.hpp" #include "libtorrent/thread.hpp" #include "libtorrent/io_service_fwd.hpp" #ifndef TORRENT_MAX_ALERT_TYPES #define TORRENT_MAX_ALERT_TYPES 15 #endif namespace libtorrent { class TORRENT_EXPORT alert { public: #ifndef TORRENT_NO_DEPRECATE // only here for backwards compatibility enum severity_t { debug, info, warning, critical, fatal, none }; #endif enum category_t { error_notification = 0x1, peer_notification = 0x2, port_mapping_notification = 0x4, storage_notification = 0x8, tracker_notification = 0x10, debug_notification = 0x20, status_notification = 0x40, progress_notification = 0x80, ip_block_notification = 0x100, performance_warning = 0x200, dht_notification = 0x400, stats_notification = 0x800, all_categories = 0xffffffff }; alert(); virtual ~alert(); // a timestamp is automatically created in the constructor ptime timestamp() const; virtual int type() const = 0; virtual char const* what() const = 0; virtual std::string message() const = 0; virtual int category() const = 0; #ifndef TORRENT_NO_DEPRECATE TORRENT_DEPRECATED_PREFIX severity_t severity() const TORRENT_DEPRECATED { return warning; } #endif virtual std::auto_ptr<alert> clone() const = 0; private: ptime m_timestamp; }; class TORRENT_EXPORT alert_manager { public: enum { queue_size_limit_default = 1000 }; alert_manager(io_service& ios); ~alert_manager(); void post_alert(const alert& alert_); bool pending() const; std::auto_ptr<alert> get(); template <class T> bool should_post() const { mutex::scoped_lock lock(m_mutex); if (m_alerts.size() >= m_queue_size_limit) return false; return (m_alert_mask & T::static_category) != 0; } alert const* wait_for_alert(time_duration max_wait); void set_alert_mask(int m) { mutex::scoped_lock lock(m_mutex); m_alert_mask = m; } size_t alert_queue_size_limit() const { return m_queue_size_limit; } size_t set_alert_queue_size_limit(size_t queue_size_limit_); void set_dispatch_function(boost::function<void(alert const&)> const&); private: std::queue<alert*> m_alerts; mutable mutex m_mutex; condition m_condition; int m_alert_mask; size_t m_queue_size_limit; boost::function<void(alert const&)> m_dispatch; io_service& m_ios; }; struct TORRENT_EXPORT unhandled_alert : std::exception { unhandled_alert() {} }; #ifndef BOOST_NO_TYPEID namespace detail { struct void_; template<class Handler , BOOST_PP_ENUM_PARAMS(TORRENT_MAX_ALERT_TYPES, class T)> void handle_alert_dispatch( const std::auto_ptr<alert>& alert_, const Handler& handler , const std::type_info& typeid_ , T0*, BOOST_PP_ENUM_SHIFTED_BINARY_PARAMS(TORRENT_MAX_ALERT_TYPES, T, *p)) { if (typeid_ == typeid(T0)) handler(*static_cast<T0*>(alert_.get())); else handle_alert_dispatch(alert_, handler, typeid_ , BOOST_PP_ENUM_SHIFTED_PARAMS( TORRENT_MAX_ALERT_TYPES, p), (void_*)0); } template<class Handler> void handle_alert_dispatch( const std::auto_ptr<alert>& , const Handler& , const std::type_info& , BOOST_PP_ENUM_PARAMS(TORRENT_MAX_ALERT_TYPES, void_* BOOST_PP_INTERCEPT)) { throw unhandled_alert(); } } // namespace detail template<BOOST_PP_ENUM_PARAMS_WITH_A_DEFAULT( TORRENT_MAX_ALERT_TYPES, class T, detail::void_)> struct TORRENT_EXPORT handle_alert { template<class Handler> handle_alert(const std::auto_ptr<alert>& alert_ , const Handler& handler) { #define ALERT_POINTER_TYPE(z, n, text) (BOOST_PP_CAT(T, n)*)0 detail::handle_alert_dispatch(alert_, handler, typeid(*alert_) , BOOST_PP_ENUM(TORRENT_MAX_ALERT_TYPES, ALERT_POINTER_TYPE, _)); #undef ALERT_POINTER_TYPE } }; #endif // BOOST_NO_TYPEID template <class T> T* alert_cast(alert* a) { if (a->type() == T::alert_type) return static_cast<T*>(a); return 0; } template <class T> T const* alert_cast(alert const* a) { if (a->type() == T::alert_type) return static_cast<T const*>(a); return 0; } } // namespace libtorrent #endif // TORRENT_ALERT_HPP_INCLUDED <|endoftext|>
<commit_before>#include <fstream> #include <iostream> #include <sstream> #define SEQAN_PROFILE #ifndef RELEASE //#define SEQAN_DEBUG //#define SEQAN_TEST #endif #include <string> #include <seqan/basic.h> #include <seqan/sequence.h> #include <seqan/file.h> #include <seqan/map.h> #include <seqan/refinement.h> #include <seqan/store.h> #include <seqan/misc/misc_cmdparser.h> #include "base.h" #include "read_gff.h" #include "create_gff.h" #include "overlap_module.h" using namespace seqan; using namespace std; /////////////////////////////////////////////////////////////////////////////// ////// main /////////////////////////////////////////////////////////////////////////////// int main( int argc, const char *argv[] ) { CharString nameSAM; CharString nameGFF; CharString outputPath; unsigned nTuple; unsigned offsetInterval; unsigned thresholdGaps; unsigned thresholdCount; double thresholdRPKM = 0.0; bool maxTuple = 0; bool exact_nTuple = 0; bool unknownO = 0; CommandLineParser parser; ////////////////////////////////////////////////////////////////////////////// // Define options addTitleLine(parser, "**********************************************************************"); addTitleLine(parser, "*** INSEGT ***"); addTitleLine(parser, "*** INtersecting SEcond Generation sequencing daTa with annotation ***"); addTitleLine(parser, "**********************************************************************"); addSection(parser, "Main Options:"); addOption(parser, addArgumentText(CommandLineOption("s", "sam", "SAM-file with aligned reads", (int)OptionType::String), "<Filename>")); addOption(parser, addArgumentText(CommandLineOption("g", "gff", "GFF_file with annotations", (int)OptionType::String), "<Filename>")); addOption(parser, addArgumentText(CommandLineOption("p", "outputPath", "path for output-files", (int)OptionType::String, ""), "<String>")); addOption(parser, addArgumentText(CommandLineOption("n", "nTuple", "nTuple", (int)OptionType::Int, 2), "<Int>")); addOption(parser, addArgumentText(CommandLineOption("o", "offsetInterval", "offset to short alignment-intervals for search", (int)OptionType::Int, 5), "<Int>")); addOption(parser, addArgumentText(CommandLineOption("t", "thresholdGaps", "threshold for allowed gaps in alignment (not introns)", (int)OptionType::Int, 5), "<Int>")); addOption(parser, addArgumentText(CommandLineOption("c", "thresholdCount", "threshold for min. count of tuple for output", (int)OptionType::Int, 1), "<Int>")); addOption(parser, addArgumentText(CommandLineOption("r", "thresholdRPKM", "threshold for min. RPKM of tuple for output", (int)OptionType::Double, 0.0), "<Double>")); addOption(parser, CommandLineOption("m", "maxTuple", "create only maxTuple", (int)OptionType::Boolean)); addOption(parser, CommandLineOption("e", "exact_nTuple", "create only Tuple of exact length n", (int)OptionType::Boolean)); addOption(parser, CommandLineOption("u", "unknown_orientation", "orientation of reads is unknown", (int)OptionType::Boolean)); if (argc == 1) { shortHelp(parser, cerr); // print short help and exit return 0; } if (!parse(parser, argc, argv, ::std::cerr)) return 1; getOptionValueLong(parser, "sam", nameSAM); getOptionValueLong(parser, "gff", nameGFF); getOptionValueLong(parser, "outputPath", outputPath); getOptionValueLong(parser, "nTuple", nTuple); getOptionValueLong(parser, "offsetInterval", offsetInterval); getOptionValueLong(parser, "thresholdGaps", thresholdGaps); getOptionValueLong(parser, "thresholdCount", thresholdCount); getOptionValueLong(parser, "thresholdRPKM", thresholdRPKM); if (isSetLong(parser, "maxTuple")) maxTuple = 1; if (isSetLong(parser, "exact_nTuple")) exact_nTuple = 1; if (isSetLong(parser, "unknown_orientation")) unknownO = 1; if (maxTuple) { nTuple = 0; // sign for maxTuple exact_nTuple = 0; // not both possible: maxTuple is prefered over exact_nTuple and n } ngsOverlapper(nameSAM, nameGFF, outputPath, nTuple, exact_nTuple, thresholdGaps, offsetInterval, thresholdCount, thresholdRPKM, unknownO); return 0; } <commit_msg><commit_after>#include <fstream> #include <iostream> #include <sstream> #define SEQAN_PROFILE #ifndef RELEASE //#define SEQAN_DEBUG //#define SEQAN_TEST #endif #include <string> #include <seqan/basic.h> #include <seqan/sequence.h> #include <seqan/file.h> #include <seqan/map.h> #include <seqan/refinement.h> #include <seqan/store.h> #include <seqan/misc/misc_cmdparser.h> #include "base.h" #include "read_gff.h" #include "create_gff.h" #include "fusion.h" #include "overlap_module.h" using namespace seqan; using namespace std; /////////////////////////////////////////////////////////////////////////////// ////// main /////////////////////////////////////////////////////////////////////////////// int main( int argc, const char *argv[] ) { CharString nameSAM; CharString nameGFF; CharString outputPath; unsigned nTuple; unsigned offsetInterval; unsigned thresholdGaps; unsigned thresholdCount; double thresholdRPKM = 0.0; bool maxTuple = 0; bool exact_nTuple = 0; bool unknownO = 0; bool fusion = 0; CommandLineParser parser; ////////////////////////////////////////////////////////////////////////////// // Define options addTitleLine(parser, "**********************************************************************"); addTitleLine(parser, "*** INSEGT ***"); addTitleLine(parser, "*** INtersecting SEcond Generation sequencing daTa with annotation ***"); addTitleLine(parser, "**********************************************************************"); addSection(parser, "Main Options:"); addOption(parser, addArgumentText(CommandLineOption("s", "sam", "SAM-file with aligned reads", (int)OptionType::String), "<Filename>")); addOption(parser, addArgumentText(CommandLineOption("g", "gff", "GFF_file with annotations", (int)OptionType::String), "<Filename>")); addOption(parser, addArgumentText(CommandLineOption("p", "outputPath", "path for output-files", (int)OptionType::String, ""), "<String>")); addOption(parser, addArgumentText(CommandLineOption("n", "nTuple", "nTuple", (int)OptionType::Int, 2), "<Int>")); addOption(parser, addArgumentText(CommandLineOption("o", "offsetInterval", "offset to short alignment-intervals for search", (int)OptionType::Int, 5), "<Int>")); addOption(parser, addArgumentText(CommandLineOption("t", "thresholdGaps", "threshold for allowed gaps in alignment (not introns)", (int)OptionType::Int, 5), "<Int>")); addOption(parser, addArgumentText(CommandLineOption("c", "thresholdCount", "threshold for min. count of tuple for output", (int)OptionType::Int, 1), "<Int>")); addOption(parser, addArgumentText(CommandLineOption("r", "thresholdRPKM", "threshold for min. RPKM of tuple for output", (int)OptionType::Double, 0.0), "<Double>")); addOption(parser, CommandLineOption("m", "maxTuple", "create only maxTuple", (int)OptionType::Boolean)); addOption(parser, CommandLineOption("e", "exact_nTuple", "create only Tuple of exact length n", (int)OptionType::Boolean)); addOption(parser, CommandLineOption("u", "unknown_orientation", "orientation of reads is unknown", (int)OptionType::Boolean)); addOption(parser, CommandLineOption("f", "fusion_genes", "check for fusion genes and create separate output for matepair tuple", (int)OptionType::Boolean)); if (argc == 1) { shortHelp(parser, cerr); // print short help and exit return 0; } if (!parse(parser, argc, argv, ::std::cerr)) return 1; getOptionValueLong(parser, "sam", nameSAM); getOptionValueLong(parser, "gff", nameGFF); getOptionValueLong(parser, "outputPath", outputPath); getOptionValueLong(parser, "nTuple", nTuple); getOptionValueLong(parser, "offsetInterval", offsetInterval); getOptionValueLong(parser, "thresholdGaps", thresholdGaps); getOptionValueLong(parser, "thresholdCount", thresholdCount); getOptionValueLong(parser, "thresholdRPKM", thresholdRPKM); if (isSetLong(parser, "maxTuple")) maxTuple = 1; if (isSetLong(parser, "exact_nTuple")) exact_nTuple = 1; if (isSetLong(parser, "unknown_orientation")) unknownO = 1; if (isSetLong(parser, "fusion_genes")) fusion = 1; if (maxTuple) { nTuple = 0; // sign for maxTuple exact_nTuple = 0; // not both possible: maxTuple is prefered over exact_nTuple and n } ngsOverlapper(nameSAM, nameGFF, outputPath, nTuple, exact_nTuple, thresholdGaps, offsetInterval, thresholdCount, thresholdRPKM, unknownO, fusion); return 0; } <|endoftext|>
<commit_before>#ifndef GRAPHICSDEVICE_HPP_INCLUDED #define GRAPHICSDEVICE_HPP_INCLUDED #include "blendmode.hpp" #include "buffer.hpp" #include "cullface.hpp" #include "graphicsresource.hpp" #include "renderbuffer.hpp" #include "shadertype.hpp" #include "textureparam.hpp" #include "vertexarray.hpp" #include <string> #include <vector> #define RESOURCE_HANDLE(resource_name) struct resource_name { unsigned int name; }; namespace gst { class Color; class Image; class Resolution; class ShadowedData; class Viewport; RESOURCE_HANDLE(BufferHandle) RESOURCE_HANDLE(FramebufferHandle) RESOURCE_HANDLE(ProgramHandle) RESOURCE_HANDLE(RenderbufferHandle) RESOURCE_HANDLE(ShaderHandle) RESOURCE_HANDLE(TextureHandle) RESOURCE_HANDLE(VertexArrayHandle) // The responsibility of this class is to interact with a graphics card. class GraphicsDevice { public: virtual ~GraphicsDevice() = default; // Clear buffers to present values. virtual void clear(bool color, bool depth) = 0; // Set clear values for color buffers. virtual void set_clear_color(Color const & clear_color) = 0; // Set blend mode enabled/disabled with appropiate blend function. virtual void set_blend_mode(BlendMode blend_mode) = 0; // Set faces that can be culled. virtual void set_cull_face(CullFace cull_face) = 0; // Set depth mask enabled/disabled. virtual void set_depth_mask(bool depth_mask) = 0; // Set depth test enabled/disabled. virtual void set_depth_test(bool depth_test) = 0; // Set viewport. virtual void set_viewport(Viewport const & viewport) = 0; // Return new shader object. virtual ShaderHandle create_shader(ShaderType type) = 0; // Destroy shader object. virtual void destroy_shader(ShaderHandle shader) = 0; // Compile shader from specified source. virtual void compile_shader(ShaderHandle shader, std::string const & source) = 0; // Return status from last compile operation. virtual bool get_compile_status(ShaderHandle shader) = 0; // Return error message from last compile operation. virtual std::string get_compile_error(ShaderHandle shader) = 0; // Return new program object. virtual ProgramHandle create_program() = 0; // Destroy program object. virtual void destroy_program(ProgramHandle program) = 0; // Attach specified shader object to specified program object. virtual void attach_shader(ProgramHandle program, ShaderHandle shader) = 0; // Attach specified shader object to specified program object. virtual void detach_shader(ProgramHandle program, ShaderHandle shader) = 0; // Link program object. virtual void link_program(ProgramHandle program) = 0; // Return status from last link operation. virtual bool get_link_status(ProgramHandle program) = 0; // Return error message from last compile operation. virtual std::string get_link_error(ProgramHandle program) = 0; // Bind vertex attribute index with a named attribute variable. virtual void bind_attribute_location(ProgramHandle program, int index, std::string const & name) = 0; // Return uniform location from specified name. virtual int get_uniform_location(ProgramHandle program, std::string const & name) = 0; // Modify value of int uniform. virtual void uniform_int(int location, int value) = 0; // Modify value of float uniform. virtual void uniform_float(int location, float value) = 0; // Modify value of vec2 uniform. virtual void uniform_vec2(int location, glm::vec2 const & value) = 0; // Modify value of vec3 uniform. virtual void uniform_vec3(int location, glm::vec3 const & value) = 0; // Modify value of vec4 uniform. virtual void uniform_vec4(int location, glm::vec4 const & value) = 0; // Modify value of int array uniform. virtual void uniform_int_array(int location, std::vector<int> const & value) = 0; // Modify value of float array uniform. virtual void uniform_float_array(int location, std::vector<float> const & value) = 0; // Modify value of matrix uniform. virtual void uniform_matrix3(int location, int count, bool transpose, std::vector<float> const & value) = 0; // Modify value of matrix uniform. virtual void uniform_matrix4(int location, int count, bool transpose, std::vector<float> const & value) = 0; // Install specified program object as part of current rendering state. virtual void use_program(ProgramHandle program) = 0; // Return new buffer object. virtual ResourceName create_buffer() = 0; // Destroy buffer object. virtual void destroy_buffer(ResourceName name) = 0; // Bind buffer object. virtual void bind_buffer(ResourceName name, BufferTarget target) = 0; // Buffer data to current bound buffer object. virtual void buffer_data(BufferTarget target, ShadowedData const & data, DataUsage usage) = 0; // Return new vertex array object. virtual ResourceName create_vertex_array() = 0; // Destroy vertex array object. virtual void destroy_vertex_array(ResourceName name) = 0; // Bind vertex array object. virtual void bind_vertex_array(ResourceName name) = 0; // Render primitives from stored array data. virtual void draw_arrays(DrawMode mode, int first, int count) = 0; // Render primitives from stored array data. virtual void draw_elements(DrawMode mode, int count) = 0; // Enable and define generic vertex attribute. virtual void enable_vertex_attribute(VertexAttribute const & attribute) = 0; // Return new renderbuffer object. virtual ResourceName create_renderbuffer() = 0; // Destroy renderbuffer object. virtual void destroy_renderbuffer(ResourceName name) = 0; // Bind renderbuffer object. virtual void bind_renderbuffer(ResourceName name) = 0; // Establish data storage of specified format and dimensions for renderbuffer objects image. virtual void renderbuffer_storage(Resolution size, RenderbufferFormat format) = 0; // Create new texture object. virtual ResourceName create_texture() = 0; // Destroy texture object. virtual void destroy_texture(ResourceName name) = 0; // Bind texture object. virtual void bind_texture(ResourceName name, TextureTarget target, int unit) = 0; // Specify 2D texture image. virtual void texture_image_2d(TextureTarget target, Image const & image, TextureParam const & param) = 0; // Set texture parameters. virtual void texture_parameters(TextureTarget target, TextureParam const & param) = 0; // Create new framebuffer object. virtual ResourceName create_framebuffer() = 0; // Destroy framebuffer object. virtual void destroy_framebuffer(ResourceName name) = 0; // Bind framebuffer object. virtual void bind_framebuffer(ResourceName name) = 0; // Attach a level of a texture object to the currently bound // framebuffer object. virtual void framebuffer_texture_2d(ResourceName name) = 0; // Attach a renderbuffer object to the currently bound framebuffer // object. virtual void framebuffer_renderbuffer(ResourceName name) = 0; // Return array of status messages for currently bound framebuffer object. virtual std::vector<std::string> check_framebuffer_status() const = 0; // Return array of error messages (if any). virtual std::vector<std::string> get_errors() const = 0; }; } #endif <commit_msg>remove unused resource handles<commit_after>#ifndef GRAPHICSDEVICE_HPP_INCLUDED #define GRAPHICSDEVICE_HPP_INCLUDED #include "blendmode.hpp" #include "buffer.hpp" #include "cullface.hpp" #include "graphicsresource.hpp" #include "renderbuffer.hpp" #include "shadertype.hpp" #include "textureparam.hpp" #include "vertexarray.hpp" #include <string> #include <vector> #define RESOURCE_HANDLE(resource_name) struct resource_name { unsigned int name; }; namespace gst { class Color; class Image; class Resolution; class ShadowedData; class Viewport; RESOURCE_HANDLE(ProgramHandle) RESOURCE_HANDLE(ShaderHandle) // The responsibility of this class is to interact with a graphics card. class GraphicsDevice { public: virtual ~GraphicsDevice() = default; // Clear buffers to present values. virtual void clear(bool color, bool depth) = 0; // Set clear values for color buffers. virtual void set_clear_color(Color const & clear_color) = 0; // Set blend mode enabled/disabled with appropiate blend function. virtual void set_blend_mode(BlendMode blend_mode) = 0; // Set faces that can be culled. virtual void set_cull_face(CullFace cull_face) = 0; // Set depth mask enabled/disabled. virtual void set_depth_mask(bool depth_mask) = 0; // Set depth test enabled/disabled. virtual void set_depth_test(bool depth_test) = 0; // Set viewport. virtual void set_viewport(Viewport const & viewport) = 0; // Return new shader object. virtual ShaderHandle create_shader(ShaderType type) = 0; // Destroy shader object. virtual void destroy_shader(ShaderHandle shader) = 0; // Compile shader from specified source. virtual void compile_shader(ShaderHandle shader, std::string const & source) = 0; // Return status from last compile operation. virtual bool get_compile_status(ShaderHandle shader) = 0; // Return error message from last compile operation. virtual std::string get_compile_error(ShaderHandle shader) = 0; // Return new program object. virtual ProgramHandle create_program() = 0; // Destroy program object. virtual void destroy_program(ProgramHandle program) = 0; // Attach specified shader object to specified program object. virtual void attach_shader(ProgramHandle program, ShaderHandle shader) = 0; // Attach specified shader object to specified program object. virtual void detach_shader(ProgramHandle program, ShaderHandle shader) = 0; // Link program object. virtual void link_program(ProgramHandle program) = 0; // Return status from last link operation. virtual bool get_link_status(ProgramHandle program) = 0; // Return error message from last compile operation. virtual std::string get_link_error(ProgramHandle program) = 0; // Bind vertex attribute index with a named attribute variable. virtual void bind_attribute_location(ProgramHandle program, int index, std::string const & name) = 0; // Return uniform location from specified name. virtual int get_uniform_location(ProgramHandle program, std::string const & name) = 0; // Modify value of int uniform. virtual void uniform_int(int location, int value) = 0; // Modify value of float uniform. virtual void uniform_float(int location, float value) = 0; // Modify value of vec2 uniform. virtual void uniform_vec2(int location, glm::vec2 const & value) = 0; // Modify value of vec3 uniform. virtual void uniform_vec3(int location, glm::vec3 const & value) = 0; // Modify value of vec4 uniform. virtual void uniform_vec4(int location, glm::vec4 const & value) = 0; // Modify value of int array uniform. virtual void uniform_int_array(int location, std::vector<int> const & value) = 0; // Modify value of float array uniform. virtual void uniform_float_array(int location, std::vector<float> const & value) = 0; // Modify value of matrix uniform. virtual void uniform_matrix3(int location, int count, bool transpose, std::vector<float> const & value) = 0; // Modify value of matrix uniform. virtual void uniform_matrix4(int location, int count, bool transpose, std::vector<float> const & value) = 0; // Install specified program object as part of current rendering state. virtual void use_program(ProgramHandle program) = 0; // Return new buffer object. virtual ResourceName create_buffer() = 0; // Destroy buffer object. virtual void destroy_buffer(ResourceName name) = 0; // Bind buffer object. virtual void bind_buffer(ResourceName name, BufferTarget target) = 0; // Buffer data to current bound buffer object. virtual void buffer_data(BufferTarget target, ShadowedData const & data, DataUsage usage) = 0; // Return new vertex array object. virtual ResourceName create_vertex_array() = 0; // Destroy vertex array object. virtual void destroy_vertex_array(ResourceName name) = 0; // Bind vertex array object. virtual void bind_vertex_array(ResourceName name) = 0; // Render primitives from stored array data. virtual void draw_arrays(DrawMode mode, int first, int count) = 0; // Render primitives from stored array data. virtual void draw_elements(DrawMode mode, int count) = 0; // Enable and define generic vertex attribute. virtual void enable_vertex_attribute(VertexAttribute const & attribute) = 0; // Return new renderbuffer object. virtual ResourceName create_renderbuffer() = 0; // Destroy renderbuffer object. virtual void destroy_renderbuffer(ResourceName name) = 0; // Bind renderbuffer object. virtual void bind_renderbuffer(ResourceName name) = 0; // Establish data storage of specified format and dimensions for renderbuffer objects image. virtual void renderbuffer_storage(Resolution size, RenderbufferFormat format) = 0; // Create new texture object. virtual ResourceName create_texture() = 0; // Destroy texture object. virtual void destroy_texture(ResourceName name) = 0; // Bind texture object. virtual void bind_texture(ResourceName name, TextureTarget target, int unit) = 0; // Specify 2D texture image. virtual void texture_image_2d(TextureTarget target, Image const & image, TextureParam const & param) = 0; // Set texture parameters. virtual void texture_parameters(TextureTarget target, TextureParam const & param) = 0; // Create new framebuffer object. virtual ResourceName create_framebuffer() = 0; // Destroy framebuffer object. virtual void destroy_framebuffer(ResourceName name) = 0; // Bind framebuffer object. virtual void bind_framebuffer(ResourceName name) = 0; // Attach a level of a texture object to the currently bound // framebuffer object. virtual void framebuffer_texture_2d(ResourceName name) = 0; // Attach a renderbuffer object to the currently bound framebuffer // object. virtual void framebuffer_renderbuffer(ResourceName name) = 0; // Return array of status messages for currently bound framebuffer object. virtual std::vector<std::string> check_framebuffer_status() const = 0; // Return array of error messages (if any). virtual std::vector<std::string> get_errors() const = 0; }; } #endif <|endoftext|>
<commit_before>// // Copyright (c) 2015-2017, Deutsches Forschungszentrum für Künstliche Intelligenz GmbH. // Copyright (c) 2015-2017, University of Bremen // 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. // #pragma once #include "AccessIterator.hpp" #include <boost/container/flat_set.hpp> #include <boost/serialization/split_member.hpp> #include <boost/version.hpp> #include <boost_serialization/DynamicSizeSerialization.hpp> namespace maps { namespace grid { struct MLSConfig; template <class _Tp> struct myCmp : public std::binary_function<_Tp, _Tp, bool> { bool operator()(const _Tp& __x, const _Tp& __y) const { return *__x < *__y; } }; template <class S> class LevelList : public boost::container::flat_set<S> { typedef boost::container::flat_set<S> Base; public: LevelList() { }; #if BOOST_VERSION < 105500 // Custom copy constructor to work around boost bug: // https://svn.boost.org/trac/boost/ticket/9166 // Note: This is fixed in version 1.55 LevelList(const LevelList& other) { if(other.size() > 0) *this = other; } #endif template<class S2> LevelList(const LevelList<S2>& other) : Base(other.begin(), other.end()) { } protected: /** Grants access to boost serialization */ friend class boost::serialization::access; /** Serializes the members of this class*/ BOOST_SERIALIZATION_SPLIT_MEMBER() template<class Archive> void load(Archive &ar, const unsigned int version) { uint64_t count; loadSizeValue(ar, count); Base::clear(); Base::reserve(count); for(size_t i=0; i<count; ++i) { S obj; ar >> obj; Base::insert(Base::end(), std::move(obj)); } } template<class Archive> void save(Archive& ar, const unsigned int version) const { uint64_t size = (uint64_t)Base::size(); saveSizeValue(ar, size); for(typename Base::const_iterator it = Base::begin(); it!= Base::end(); ++it) { ar << *it; } } }; template <class S> class LevelList<S *> : public boost::container::flat_set<S *, myCmp<S *>> { typedef boost::container::flat_set<S *, myCmp<S *> > Base; public: LevelList() { }; #if BOOST_VERSION < 105500 // Custom copy constructor to work around boost bug: // https://svn.boost.org/trac/boost/ticket/9166 // Note: This is fixed in version 1.55 LevelList(const LevelList& other) { if(other.size() > 0) *this = other; } #endif /** Serializes the members of this class*/ BOOST_SERIALIZATION_SPLIT_MEMBER() template<class Archive> void load(Archive &ar, const unsigned int version) { uint64_t count; loadSizeValue(ar, count); Base::clear(); Base::reserve(count); for(size_t i=0; i<count; ++i) { S *obj; ar >> obj; Base::insert(Base::end(), obj); } } template<class Archive> void save(Archive& ar, const unsigned int version) const { uint64_t size = (uint64_t)Base::size(); saveSizeValue(ar, size); for(typename Base::const_iterator it = Base::begin(); it!= Base::end(); ++it) { ar << *it; } } template<class S2> LevelList(const LevelList<S2>& other) : boost::container::flat_set<S *, myCmp<S *>>(other.begin(), other.end()) { } }; template <class T> class LevelListAccess { public: virtual ConstAccessIterator<T> begin() = 0; virtual ConstAccessIterator<T> end() = 0; LevelListAccess() { } virtual ~LevelListAccess() {} }; template <class S, class SBase = S> class DerivableLevelList : public DerivableLevelList<SBase, SBase>, public LevelList<S> { protected: virtual ConstAccessIterator<SBase> getBegin() { return ConstAccessIteratorImpl<S, SBase, LevelList<S> >(LevelList<S>::begin()); }; virtual ConstAccessIterator<SBase> getEnd() { return ConstAccessIteratorImpl<S, SBase, LevelList<S> >(LevelList<S>::end()); }; virtual size_t getSize() const { return LevelList<S>::size(); }; public: using LevelList<S>::begin; using LevelList<S>::end; using LevelList<S>::find; using LevelList<S>::size; DerivableLevelList() { }; virtual ~DerivableLevelList() { }; }; template <class S> class DerivableLevelList<S, S> { protected: virtual ConstAccessIterator<S> getBegin() = 0; virtual ConstAccessIterator<S> getEnd() = 0; virtual size_t getSize() const = 0; public: typedef ConstAccessIterator<S> iterator; DerivableLevelList() { }; virtual ~DerivableLevelList() { } iterator begin() { return getBegin(); }; iterator end() { return getEnd(); }; size_t size() const { return getSize(); }; }; template <class T, class TBase> class LevelListAccessImpl : public LevelListAccess<TBase> { LevelList<T> *list; public: virtual ConstAccessIterator<TBase> begin() { return ConstAccessIteratorImpl<T, TBase, LevelList<T> >(list->begin()); }; virtual ConstAccessIterator<TBase> end() { return ConstAccessIteratorImpl<T, TBase, LevelList<T> >(list->end()); }; LevelListAccessImpl(LevelList<T> *list) : list(list) { }; virtual ~LevelListAccessImpl() {} }; }} // namespace maps <commit_msg>Use serialization from boost_serialization/BoostTypes<commit_after>// // Copyright (c) 2015-2017, Deutsches Forschungszentrum für Künstliche Intelligenz GmbH. // Copyright (c) 2015-2017, University of Bremen // 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. // #pragma once #include "AccessIterator.hpp" #include <boost/container/flat_set.hpp> #include <boost/version.hpp> #include <boost_serialization/BoostTypes.hpp> namespace maps { namespace grid { struct MLSConfig; template <class _Tp> struct myCmp : public std::binary_function<_Tp, _Tp, bool> { bool operator()(const _Tp& __x, const _Tp& __y) const { return *__x < *__y; } }; template <class S> class LevelList : public boost::container::flat_set<S> { typedef boost::container::flat_set<S> Base; public: LevelList() { }; #if BOOST_VERSION < 105500 // Custom copy constructor to work around boost bug: // https://svn.boost.org/trac/boost/ticket/9166 // Note: This is fixed in version 1.55 LevelList(const LevelList& other) { if(other.size() > 0) *this = other; } #endif template<class S2> LevelList(const LevelList<S2>& other) : Base(other.begin(), other.end()) { } protected: /** Grants access to boost serialization */ friend class boost::serialization::access; template <typename Archive> void serialize(Archive &ar, const unsigned int version) { boost::serialization::serialize(ar, static_cast<Base&>(*this), version); } }; template <class S> class LevelList<S *> : public boost::container::flat_set<S *, myCmp<S *>> { typedef boost::container::flat_set<S *, myCmp<S *> > Base; public: LevelList() { }; #if BOOST_VERSION < 105500 // Custom copy constructor to work around boost bug: // https://svn.boost.org/trac/boost/ticket/9166 // Note: This is fixed in version 1.55 LevelList(const LevelList& other) { if(other.size() > 0) *this = other; } #endif /** Serializes the members of this class*/ BOOST_SERIALIZATION_SPLIT_MEMBER() template<class Archive> void load(Archive &ar, const unsigned int version) { uint64_t count; loadSizeValue(ar, count); Base::clear(); Base::reserve(count); for(size_t i=0; i<count; ++i) { S *obj; ar >> obj; Base::insert(Base::end(), obj); } } template<class Archive> void save(Archive& ar, const unsigned int version) const { uint64_t size = (uint64_t)Base::size(); saveSizeValue(ar, size); for(typename Base::const_iterator it = Base::begin(); it!= Base::end(); ++it) { ar << *it; } } template<class S2> LevelList(const LevelList<S2>& other) : boost::container::flat_set<S *, myCmp<S *>>(other.begin(), other.end()) { } }; template <class T> class LevelListAccess { public: virtual ConstAccessIterator<T> begin() = 0; virtual ConstAccessIterator<T> end() = 0; LevelListAccess() { } virtual ~LevelListAccess() {} }; template <class S, class SBase = S> class DerivableLevelList : public DerivableLevelList<SBase, SBase>, public LevelList<S> { protected: virtual ConstAccessIterator<SBase> getBegin() { return ConstAccessIteratorImpl<S, SBase, LevelList<S> >(LevelList<S>::begin()); }; virtual ConstAccessIterator<SBase> getEnd() { return ConstAccessIteratorImpl<S, SBase, LevelList<S> >(LevelList<S>::end()); }; virtual size_t getSize() const { return LevelList<S>::size(); }; public: using LevelList<S>::begin; using LevelList<S>::end; using LevelList<S>::find; using LevelList<S>::size; DerivableLevelList() { }; virtual ~DerivableLevelList() { }; }; template <class S> class DerivableLevelList<S, S> { protected: virtual ConstAccessIterator<S> getBegin() = 0; virtual ConstAccessIterator<S> getEnd() = 0; virtual size_t getSize() const = 0; public: typedef ConstAccessIterator<S> iterator; DerivableLevelList() { }; virtual ~DerivableLevelList() { } iterator begin() { return getBegin(); }; iterator end() { return getEnd(); }; size_t size() const { return getSize(); }; }; template <class T, class TBase> class LevelListAccessImpl : public LevelListAccess<TBase> { LevelList<T> *list; public: virtual ConstAccessIterator<TBase> begin() { return ConstAccessIteratorImpl<T, TBase, LevelList<T> >(list->begin()); }; virtual ConstAccessIterator<TBase> end() { return ConstAccessIteratorImpl<T, TBase, LevelList<T> >(list->end()); }; LevelListAccessImpl(LevelList<T> *list) : list(list) { }; virtual ~LevelListAccessImpl() {} }; }} // namespace maps <|endoftext|>
<commit_before>// Copyright 2015-2017 Open Source Robotics Foundation, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "rcutils/logging_macros.h" #include "rcutils/strdup.h" #include "rmw/convert_rcutils_ret_to_rmw_ret.h" #include "rmw/error_handling.h" #include "rmw/sanity_checks.h" #include "rmw_connext_shared_cpp/ndds_include.hpp" #include "rmw_connext_shared_cpp/node_names.hpp" #include "rmw_connext_shared_cpp/types.hpp" rmw_ret_t get_node_names( const char * implementation_identifier, const rmw_node_t * node, rcutils_string_array_t * node_names) { if (!node) { RMW_SET_ERROR_MSG("node handle is null"); return RMW_RET_ERROR; } if (node->implementation_identifier != implementation_identifier) { RMW_SET_ERROR_MSG("node handle is not from this rmw implementation"); return RMW_RET_ERROR; } if (rmw_check_zero_rmw_string_array(node_names) != RMW_RET_OK) { return RMW_RET_ERROR; } DDSDomainParticipant * participant = static_cast<ConnextNodeInfo *>(node->data)->participant; DDS_InstanceHandleSeq handles; if (participant->get_discovered_participants(handles) != DDS_RETCODE_OK) { RMW_SET_ERROR_MSG("unable to fetch discovered participants."); return RMW_RET_ERROR; } auto length = handles.length() + 1; // add yourself rcutils_allocator_t allocator = rcutils_get_default_allocator(); rcutils_ret_t rcutils_ret = rcutils_string_array_init(node_names, length, &allocator); if (rcutils_ret != RCUTILS_RET_OK) { RMW_SET_ERROR_MSG(rcutils_get_error_string_safe()) return rmw_convert_rcutils_ret_to_rmw_ret(rcutils_ret); } DDS_DomainParticipantQos participant_qos; DDS_ReturnCode_t status = participant->get_qos(participant_qos); if (status != DDS_RETCODE_OK) { RMW_SET_ERROR_MSG("failed to get default participant qos"); return RMW_RET_ERROR; } node_names->data[0] = rcutils_strdup(participant_qos.participant_name.name, allocator); if (!node_names->data[0]) { RMW_SET_ERROR_MSG("could not allocate memory for node name") return RMW_RET_BAD_ALLOC; } for (auto i = 1; i < length; ++i) { DDS::ParticipantBuiltinTopicData pbtd; auto dds_ret = participant->get_discovered_participant_data(pbtd, handles[i - 1]); const char * name = pbtd.participant_name.name; if (!name || dds_ret != DDS_RETCODE_OK) { name = "(no name)"; } node_names->data[i] = rcutils_strdup(name, allocator); if (!node_names->data[i]) { RMW_SET_ERROR_MSG("could not allocate memory for node name") rcutils_ret = rcutils_string_array_fini(node_names); if (rcutils_ret != RCUTILS_RET_OK) { RCUTILS_LOG_ERROR_NAMED( "rmw_connext_cpp", "failed to cleanup during error handling: %s", rcutils_get_error_string_safe()) } return RMW_RET_BAD_ALLOC; } } return RMW_RET_OK; } <commit_msg>get participant name from user data first<commit_after>// Copyright 2015-2017 Open Source Robotics Foundation, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <string> #include <vector> #include "rcutils/logging_macros.h" #include "rcutils/strdup.h" #include "rmw/convert_rcutils_ret_to_rmw_ret.h" #include "rmw/error_handling.h" #include "rmw/impl/cpp/key_value.hpp" #include "rmw/sanity_checks.h" #include "rmw_connext_shared_cpp/ndds_include.hpp" #include "rmw_connext_shared_cpp/node_names.hpp" #include "rmw_connext_shared_cpp/types.hpp" rmw_ret_t get_node_names( const char * implementation_identifier, const rmw_node_t * node, rcutils_string_array_t * node_names) { if (!node) { RMW_SET_ERROR_MSG("node handle is null"); return RMW_RET_ERROR; } if (node->implementation_identifier != implementation_identifier) { RMW_SET_ERROR_MSG("node handle is not from this rmw implementation"); return RMW_RET_ERROR; } if (rmw_check_zero_rmw_string_array(node_names) != RMW_RET_OK) { return RMW_RET_ERROR; } DDSDomainParticipant * participant = static_cast<ConnextNodeInfo *>(node->data)->participant; DDS_InstanceHandleSeq handles; if (participant->get_discovered_participants(handles) != DDS_RETCODE_OK) { RMW_SET_ERROR_MSG("unable to fetch discovered participants."); return RMW_RET_ERROR; } auto length = handles.length() + 1; // add yourself rcutils_allocator_t allocator = rcutils_get_default_allocator(); rcutils_ret_t rcutils_ret = rcutils_string_array_init(node_names, length, &allocator); if (rcutils_ret != RCUTILS_RET_OK) { RMW_SET_ERROR_MSG(rcutils_get_error_string_safe()) return rmw_convert_rcutils_ret_to_rmw_ret(rcutils_ret); } DDS_DomainParticipantQos participant_qos; DDS_ReturnCode_t status = participant->get_qos(participant_qos); if (status != DDS_RETCODE_OK) { RMW_SET_ERROR_MSG("failed to get default participant qos"); return RMW_RET_ERROR; } node_names->data[0] = rcutils_strdup(participant_qos.participant_name.name, allocator); if (!node_names->data[0]) { RMW_SET_ERROR_MSG("could not allocate memory for node name") return RMW_RET_BAD_ALLOC; } for (auto i = 1; i < length; ++i) { DDS::ParticipantBuiltinTopicData pbtd; auto dds_ret = participant->get_discovered_participant_data(pbtd, handles[i - 1]); std::string name; if (DDS_RETCODE_OK == dds_ret) { auto data = static_cast<unsigned char *>(pbtd.user_data.value.get_contiguous_buffer()); std::vector<uint8_t> kv(data, data + pbtd.user_data.value.length()); auto map = rmw::impl::cpp::parse_key_value(kv); auto found = map.find("name"); if (found != map.end()) { name = std::string(found->second.begin(), found->second.end()); } if (name.empty()) { // use participant name if no name was found in the user data if (pbtd.participant_name.name) { name = pbtd.participant_name.name; } } } if (name.empty()) { // ignore discovered participants without a name node_names->data[i] = nullptr; continue; } node_names->data[i] = rcutils_strdup(name.c_str(), allocator); if (!node_names->data[i]) { RMW_SET_ERROR_MSG("could not allocate memory for node name") rcutils_ret = rcutils_string_array_fini(node_names); if (rcutils_ret != RCUTILS_RET_OK) { RCUTILS_LOG_ERROR_NAMED( "rmw_connext_cpp", "failed to cleanup during error handling: %s", rcutils_get_error_string_safe()) } return RMW_RET_BAD_ALLOC; } } return RMW_RET_OK; } <|endoftext|>
<commit_before>/* * Copyright (C) 2010, 2011, Gostai S.A.S. * * This software is provided "as is" without warranty of any kind, * either expressed or implied, including but not limited to the * implied warranties of fitness for a particular purpose. * * See the LICENSE file for more information. */ #ifndef URBI_OBJECT_EVENT_HH # define URBI_OBJECT_EVENT_HH # include <boost/signal.hpp> # include <boost/unordered_set.hpp> # include <libport/attributes.hh> # include <object/profile.hh> # include <urbi/object/cxx-object.hh> # include <urbi/object/lobby.hh> # include <runner/state.hh> namespace urbi { namespace object { class URBI_SDK_API Event: public CxxObject { friend class EventHandler; public: typedef Event self_type; Event(); Event(rEvent model); Event(rEvent model, rList payload); virtual ~Event(); URBI_CXX_OBJECT(Event, CxxObject); public: typedef boost::signal0<void> signal_type; signal_type& destructed_get(); signal_type& subscribed_get(); signal_type& unsubscribed_get(); ATTRIBUTE_R(signal_type, destructed); ATTRIBUTE_R(signal_type, subscribed); ATTRIBUTE_R(signal_type, unsubscribed); public: typedef boost::function1<void, const objects_type&> callback_type; class Subscription { public: void stop(); Subscription(); private: friend class Event; Subscription(rEvent event, callback_type* cb); rEvent event_; callback_type* cb_; }; public: /// C++ callback registration. Subscription onEvent(const callback_type& cb); /// Urbi callback registration. void onEvent(rExecutable guard, rExecutable enter, rExecutable leave = 0, bool sync = false); typedef void (Event::*on_event_type) (rExecutable guard, rExecutable enter, rExecutable leave, bool sync); /// Synchronous emission. void syncEmit(const objects_type& args); /// Asynchronous emission. void emit(const objects_type& args); void emit(); /// Asynchronous trigger. rEventHandler trigger(const objects_type& args); /// Synchronous trigger. rEventHandler syncTrigger(const objects_type& args); void waituntil(rObject pattern); bool hasSubscribers() const; private: void emit_backend(const objects_type& pl, bool detach); sched::rJob spawn_actions_job(rLobby lobby, rExecutable e, rProfile profile, const objects_type& args); rEventHandler trigger_backend(const objects_type& pl, bool detach); /** Callbacks listening on this event. * * /!\ Keep me private, if an Actions survives its owner Event, it will * SEGV. */ struct Actions: public libport::RefCounted { Actions(rExecutable g, rExecutable e, rExecutable l, bool s) : guard(g), enter(e), leave(l), frozen(0), sync(s) {} ~Actions(); bool operator==(const Actions& other) { return (guard == other.guard && enter == other.enter && leave == other.leave); } rExecutable guard, enter, leave; rProfile profile; /// Number of frozen tag this Actions is marked with. unsigned int frozen; /// Whether this onEvent is synchronous bool sync; std::vector<boost::signals::connection> connections; runner::State::tag_stack_type tag_stack; /// Create job with this lobby when executing actions if set. rLobby lobby; }; typedef libport::intrusive_ptr<Actions> rActions; void waituntil_release(rObject payload); void waituntil_remove(rTag what); rEvent source(); /** The following three functions are callbacks installed on tags. * The Actions argument is stored in the boost::bind. * Since the callbacks are removed in ~Actions(), it is safe not to * take shared pointers here. */ void unregister(Actions*); void freeze(Actions*); void unfreeze(Actions*); typedef std::vector<rActions> listeners_type; listeners_type listeners_; struct Waiter { Waiter(rTag ct, runner::Job* r, rObject& p) : controlTag(ct), runner(r), pattern(p) {} rTag controlTag; runner::Job* runner; rObject pattern; }; /// Job waiting for this event. std::vector<Waiter> waiters_; public: /// Active instances of this event (handler => payload). typedef boost::unordered_set<rEventHandler> actives_type; ATTRIBUTE_R(actives_type, active); private: /// C++ callbacks typedef std::vector<callback_type*> callbacks_type; // Using an unordered set is slightly slower with few elements, // which is the most common case (isn't it?). So although it // entails linear-time search, std::vector is preferable. // // typedef boost::unordered_set<callback_type*> callbacks_type; callbacks_type callbacks_; }; } } #endif <commit_msg>Fix windows compilation: export Event::Subscription in the API.<commit_after>/* * Copyright (C) 2010, 2011, Gostai S.A.S. * * This software is provided "as is" without warranty of any kind, * either expressed or implied, including but not limited to the * implied warranties of fitness for a particular purpose. * * See the LICENSE file for more information. */ #ifndef URBI_OBJECT_EVENT_HH # define URBI_OBJECT_EVENT_HH # include <boost/signal.hpp> # include <boost/unordered_set.hpp> # include <libport/attributes.hh> # include <object/profile.hh> # include <urbi/object/cxx-object.hh> # include <urbi/object/lobby.hh> # include <runner/state.hh> namespace urbi { namespace object { class URBI_SDK_API Event: public CxxObject { friend class EventHandler; public: typedef Event self_type; Event(); Event(rEvent model); Event(rEvent model, rList payload); virtual ~Event(); URBI_CXX_OBJECT(Event, CxxObject); public: typedef boost::signal0<void> signal_type; signal_type& destructed_get(); signal_type& subscribed_get(); signal_type& unsubscribed_get(); ATTRIBUTE_R(signal_type, destructed); ATTRIBUTE_R(signal_type, subscribed); ATTRIBUTE_R(signal_type, unsubscribed); public: typedef boost::function1<void, const objects_type&> callback_type; class URBI_SDK_API Subscription { public: void stop(); Subscription(); private: friend class Event; Subscription(rEvent event, callback_type* cb); rEvent event_; callback_type* cb_; }; public: /// C++ callback registration. Subscription onEvent(const callback_type& cb); /// Urbi callback registration. void onEvent(rExecutable guard, rExecutable enter, rExecutable leave = 0, bool sync = false); typedef void (Event::*on_event_type) (rExecutable guard, rExecutable enter, rExecutable leave, bool sync); /// Synchronous emission. void syncEmit(const objects_type& args); /// Asynchronous emission. void emit(const objects_type& args); void emit(); /// Asynchronous trigger. rEventHandler trigger(const objects_type& args); /// Synchronous trigger. rEventHandler syncTrigger(const objects_type& args); void waituntil(rObject pattern); bool hasSubscribers() const; private: void emit_backend(const objects_type& pl, bool detach); sched::rJob spawn_actions_job(rLobby lobby, rExecutable e, rProfile profile, const objects_type& args); rEventHandler trigger_backend(const objects_type& pl, bool detach); /** Callbacks listening on this event. * * /!\ Keep me private, if an Actions survives its owner Event, it will * SEGV. */ struct Actions: public libport::RefCounted { Actions(rExecutable g, rExecutable e, rExecutable l, bool s) : guard(g), enter(e), leave(l), frozen(0), sync(s) {} ~Actions(); bool operator==(const Actions& other) { return (guard == other.guard && enter == other.enter && leave == other.leave); } rExecutable guard, enter, leave; rProfile profile; /// Number of frozen tag this Actions is marked with. unsigned int frozen; /// Whether this onEvent is synchronous bool sync; std::vector<boost::signals::connection> connections; runner::State::tag_stack_type tag_stack; /// Create job with this lobby when executing actions if set. rLobby lobby; }; typedef libport::intrusive_ptr<Actions> rActions; void waituntil_release(rObject payload); void waituntil_remove(rTag what); rEvent source(); /** The following three functions are callbacks installed on tags. * The Actions argument is stored in the boost::bind. * Since the callbacks are removed in ~Actions(), it is safe not to * take shared pointers here. */ void unregister(Actions*); void freeze(Actions*); void unfreeze(Actions*); typedef std::vector<rActions> listeners_type; listeners_type listeners_; struct Waiter { Waiter(rTag ct, runner::Job* r, rObject& p) : controlTag(ct), runner(r), pattern(p) {} rTag controlTag; runner::Job* runner; rObject pattern; }; /// Job waiting for this event. std::vector<Waiter> waiters_; public: /// Active instances of this event (handler => payload). typedef boost::unordered_set<rEventHandler> actives_type; ATTRIBUTE_R(actives_type, active); private: /// C++ callbacks typedef std::vector<callback_type*> callbacks_type; // Using an unordered set is slightly slower with few elements, // which is the most common case (isn't it?). So although it // entails linear-time search, std::vector is preferable. // // typedef boost::unordered_set<callback_type*> callbacks_type; callbacks_type callbacks_; }; } } #endif <|endoftext|>
<commit_before>/* This file is part of Ingen. * Copyright (C) 2007 Dave Robillard <http://drobilla.net> * * Ingen 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. * * Ingen 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 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., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include <cassert> #include <raul/Atom.hpp> #include "interface/EngineInterface.hpp" #include "client/NodeModel.hpp" #include "client/PatchModel.hpp" #include "client/PluginUI.hpp" #include "App.hpp" #include "GladeFactory.hpp" #include "NodeControlWindow.hpp" #include "NodeModule.hpp" #include "PatchCanvas.hpp" #include "PatchWindow.hpp" #include "Port.hpp" #include "RenameWindow.hpp" #include "SubpatchModule.hpp" #include "WindowFactory.hpp" #include "Configuration.hpp" using namespace std; namespace Ingen { namespace GUI { NodeModule::NodeModule(boost::shared_ptr<PatchCanvas> canvas, SharedPtr<NodeModel> node) : FlowCanvas::Module(canvas, node->path().name()) , _node(node) , _gui_widget(NULL) , _gui_window(NULL) { assert(_node); node->signal_new_port.connect(sigc::bind(sigc::mem_fun(this, &NodeModule::add_port), true)); node->signal_removed_port.connect(sigc::mem_fun(this, &NodeModule::remove_port)); node->signal_variable.connect(sigc::mem_fun(this, &NodeModule::set_variable)); node->signal_property.connect(sigc::mem_fun(this, &NodeModule::set_property)); node->signal_renamed.connect(sigc::mem_fun(this, &NodeModule::rename)); } NodeModule::~NodeModule() { NodeControlWindow* win = App::instance().window_factory()->control_window(_node); if (win) { // Should remove from window factory via signal delete win; } } void NodeModule::create_menu() { Glib::RefPtr<Gnome::Glade::Xml> xml = GladeFactory::new_glade_reference(); xml->get_widget_derived("object_menu", _menu); _menu->init(_node); _menu->signal_embed_gui.connect(sigc::mem_fun(this, &NodeModule::embed_gui)); _menu->signal_popup_gui.connect(sigc::hide_return(sigc::mem_fun(this, &NodeModule::popup_gui))); set_menu(_menu); } boost::shared_ptr<NodeModule> NodeModule::create(boost::shared_ptr<PatchCanvas> canvas, SharedPtr<NodeModel> node, bool human) { boost::shared_ptr<NodeModule> ret; SharedPtr<PatchModel> patch = PtrCast<PatchModel>(node); if (patch) ret = boost::shared_ptr<NodeModule>(new SubpatchModule(canvas, patch)); else ret = boost::shared_ptr<NodeModule>(new NodeModule(canvas, node)); for (GraphObject::Variables::const_iterator m = node->variables().begin(); m != node->variables().end(); ++m) ret->set_variable(m->first, m->second); for (NodeModel::Ports::const_iterator p = node->ports().begin(); p != node->ports().end(); ++p) { ret->add_port(*p, false); } if (human) ret->show_human_names(human); ret->resize(); ret->set_stacked_border(node->polyphonic()); return ret; } void NodeModule::show_human_names(bool b) { Glib::Mutex::Lock lock(App::instance().world()->rdf_world->mutex()); if (b && node()->plugin()) set_name(((PluginModel*)node()->plugin())->human_name()); else b = false; if (!b) set_name(node()->symbol()); uint32_t index = 0; for (PortVector::const_iterator i = ports().begin(); i != ports().end(); ++i) { if (b) { string hn = ((PluginModel*)node()->plugin())->port_human_name(index); if (hn != "") (*i)->set_name(hn); } else { (*i)->set_name(node()->port(index)->symbol()); } ++index; } resize(); } void NodeModule::value_changed(uint32_t index, const Atom& value) { float control = 0.0f; switch (value.type()) { case Atom::FLOAT: control = value.get_float(); if (_plugin_ui) { SLV2UIInstance inst = _plugin_ui->instance(); const LV2UI_Descriptor* ui_descriptor = slv2_ui_instance_get_descriptor(inst); LV2UI_Handle ui_handle = slv2_ui_instance_get_handle(inst); if (ui_descriptor->port_event) ui_descriptor->port_event(ui_handle, index, 4, 0, &control); } break; case Atom::STRING: cout << "Port value type is a string? (\"" << value.get_string() << "\")" << endl; break; default: break; } } void NodeModule::embed_gui(bool embed) { if (embed) { if (_gui_window) { cerr << "LV2 GUI already popped up, cannot embed" << endl; return; } if (!_plugin_ui) { const PluginModel* const pm = dynamic_cast<const PluginModel*>(_node->plugin()); assert(pm); _plugin_ui = pm->ui(App::instance().world(), _node); } if (_plugin_ui) { GtkWidget* c_widget = (GtkWidget*)slv2_ui_instance_get_widget(_plugin_ui->instance()); _gui_widget = Glib::wrap(c_widget); assert(_gui_widget); Gtk::Container* container = new Gtk::EventBox(); container->set_name("ingen_embedded_node_gui_container"); container->add(*_gui_widget); FlowCanvas::Module::embed(container); } else { cerr << "ERROR: Failed to create LV2 UI" << endl; } if (_gui_widget) { _gui_widget->show_all(); for (NodeModel::Ports::const_iterator p = _node->ports().begin(); p != _node->ports().end(); ++p) if ((*p)->type().is_control() && (*p)->is_output()) App::instance().engine()->set_property((*p)->path(), "ingen:broadcast", true); } } else { // un-embed FlowCanvas::Module::embed(NULL); _plugin_ui.reset(); for (NodeModel::Ports::const_iterator p = _node->ports().begin(); p != _node->ports().end(); ++p) if ((*p)->type().is_control() && (*p)->is_output()) App::instance().engine()->set_property((*p)->path(), "ingen:broadcast", false); } if (embed && _embed_item) { initialise_gui_values(); set_base_color(0x212222FF); } else { set_default_base_color(); } resize(); } void NodeModule::rename() { set_name(_node->path().name()); resize(); } void NodeModule::add_port(SharedPtr<PortModel> port, bool resize_to_fit) { uint32_t index = _ports.size(); // FIXME: kludge, engine needs to tell us this string name = port->path().name(); if (App::instance().configuration()->name_style() == Configuration::HUMAN && node()->plugin()) name = ((PluginModel*)node()->plugin())->port_human_name(index); Module::add_port(boost::shared_ptr<Port>( new Port(PtrCast<NodeModule>(shared_from_this()), port, name))); port->signal_value_changed.connect(sigc::bind<0>( sigc::mem_fun(this, &NodeModule::value_changed), index)); if (resize_to_fit) resize(); } void NodeModule::remove_port(SharedPtr<PortModel> port) { SharedPtr<FlowCanvas::Port> p = Module::remove_port(port->path().name()); p.reset(); } bool NodeModule::popup_gui() { #ifdef HAVE_SLV2 if (_node->plugin() && _node->plugin()->type() == PluginModel::LV2) { if (_plugin_ui) { cerr << "LV2 GUI already embedded, cannot pop up" << endl; return false; } const PluginModel* const plugin = dynamic_cast<const PluginModel*>(_node->plugin()); assert(plugin); _plugin_ui = plugin->ui(App::instance().world(), _node); if (_plugin_ui) { GtkWidget* c_widget = (GtkWidget*)slv2_ui_instance_get_widget(_plugin_ui->instance()); _gui_widget = Glib::wrap(c_widget); _gui_window = new Gtk::Window(); _gui_window->add(*_gui_widget); _gui_widget->show_all(); initialise_gui_values(); _gui_window->signal_unmap().connect( sigc::mem_fun(this, &NodeModule::on_gui_window_close)); _gui_window->present(); return true; } else { cerr << "No LV2 GUI" << endl; } } #endif return false; } void NodeModule::on_gui_window_close() { delete _gui_window; _gui_window = NULL; _plugin_ui.reset(); _gui_widget = NULL; } void NodeModule::initialise_gui_values() { uint32_t index=0; for (NodeModel::Ports::const_iterator p = _node->ports().begin(); p != _node->ports().end(); ++p) { if ((*p)->type().is_control()) value_changed(index, (*p)->value()); ++index; } } void NodeModule::show_control_window() { App::instance().window_factory()->present_controls(_node); } void NodeModule::on_double_click(GdkEventButton* ev) { if ( ! popup_gui() ) show_control_window(); } void NodeModule::store_location() { const float x = static_cast<float>(property_x()); const float y = static_cast<float>(property_y()); const Atom& existing_x = _node->get_variable("ingenuity:canvas-x"); const Atom& existing_y = _node->get_variable("ingenuity:canvas-y"); if (existing_x.type() != Atom::FLOAT || existing_y.type() != Atom::FLOAT || existing_x.get_float() != x || existing_y.get_float() != y) { App::instance().engine()->set_variable(_node->path(), "ingenuity:canvas-x", Atom(x)); App::instance().engine()->set_variable(_node->path(), "ingenuity:canvas-y", Atom(y)); } } void NodeModule::set_variable(const string& key, const Atom& value) { if (key == "ingenuity:canvas-x" && value.type() == Atom::FLOAT) move_to(value.get_float(), property_y()); else if (key == "ingenuity:canvas-y" && value.type() == Atom::FLOAT) move_to(property_x(), value.get_float()); } void NodeModule::set_property(const string& key, const Atom& value) { if (key == "ingen:polyphonic" && value.type() == Atom::BOOL) { set_stacked_border(value.get_bool()); } else if (key == "ingen:selected" && value.type() == Atom::BOOL) { if (value.get_bool() != selected()) { if (value.get_bool()) _canvas.lock()->select_item(shared_from_this()); else _canvas.lock()->unselect_item(shared_from_this()); } } } void NodeModule::set_selected(bool b) { if (b != selected()) { Module::set_selected(b); if (App::instance().signal()) App::instance().engine()->set_property(_node->path(), "ingen:selected", b); } } } // namespace GUI } // namespace Ingen <commit_msg>Fix last fix. :)<commit_after>/* This file is part of Ingen. * Copyright (C) 2007 Dave Robillard <http://drobilla.net> * * Ingen 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. * * Ingen 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 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., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include <cassert> #include <raul/Atom.hpp> #include "interface/EngineInterface.hpp" #include "client/NodeModel.hpp" #include "client/PatchModel.hpp" #include "client/PluginUI.hpp" #include "App.hpp" #include "GladeFactory.hpp" #include "NodeControlWindow.hpp" #include "NodeModule.hpp" #include "PatchCanvas.hpp" #include "PatchWindow.hpp" #include "Port.hpp" #include "RenameWindow.hpp" #include "SubpatchModule.hpp" #include "WindowFactory.hpp" #include "Configuration.hpp" using namespace std; namespace Ingen { namespace GUI { NodeModule::NodeModule(boost::shared_ptr<PatchCanvas> canvas, SharedPtr<NodeModel> node) : FlowCanvas::Module(canvas, node->path().name()) , _node(node) , _gui_widget(NULL) , _gui_window(NULL) { assert(_node); node->signal_new_port.connect(sigc::bind(sigc::mem_fun(this, &NodeModule::add_port), true)); node->signal_removed_port.connect(sigc::mem_fun(this, &NodeModule::remove_port)); node->signal_variable.connect(sigc::mem_fun(this, &NodeModule::set_variable)); node->signal_property.connect(sigc::mem_fun(this, &NodeModule::set_property)); node->signal_renamed.connect(sigc::mem_fun(this, &NodeModule::rename)); } NodeModule::~NodeModule() { NodeControlWindow* win = App::instance().window_factory()->control_window(_node); if (win) { // Should remove from window factory via signal delete win; } } void NodeModule::create_menu() { Glib::RefPtr<Gnome::Glade::Xml> xml = GladeFactory::new_glade_reference(); xml->get_widget_derived("object_menu", _menu); _menu->init(_node); _menu->signal_embed_gui.connect(sigc::mem_fun(this, &NodeModule::embed_gui)); _menu->signal_popup_gui.connect(sigc::hide_return(sigc::mem_fun(this, &NodeModule::popup_gui))); set_menu(_menu); } boost::shared_ptr<NodeModule> NodeModule::create(boost::shared_ptr<PatchCanvas> canvas, SharedPtr<NodeModel> node, bool human) { boost::shared_ptr<NodeModule> ret; SharedPtr<PatchModel> patch = PtrCast<PatchModel>(node); if (patch) ret = boost::shared_ptr<NodeModule>(new SubpatchModule(canvas, patch)); else ret = boost::shared_ptr<NodeModule>(new NodeModule(canvas, node)); for (GraphObject::Variables::const_iterator m = node->variables().begin(); m != node->variables().end(); ++m) ret->set_variable(m->first, m->second); for (NodeModel::Ports::const_iterator p = node->ports().begin(); p != node->ports().end(); ++p) { ret->add_port(*p, false); } if (human) ret->show_human_names(human); ret->resize(); ret->set_stacked_border(node->polyphonic()); return ret; } void NodeModule::show_human_names(bool b) { if (b && node()->plugin()) { Glib::Mutex::Lock lock(App::instance().world()->rdf_world->mutex()); set_name(((PluginModel*)node()->plugin())->human_name()); } else { b = false; } if (!b) set_name(node()->symbol()); uint32_t index = 0; for (PortVector::const_iterator i = ports().begin(); i != ports().end(); ++i) { if (b) { string hn = ((PluginModel*)node()->plugin())->port_human_name(index); if (hn != "") (*i)->set_name(hn); } else { (*i)->set_name(node()->port(index)->symbol()); } ++index; } resize(); } void NodeModule::value_changed(uint32_t index, const Atom& value) { float control = 0.0f; switch (value.type()) { case Atom::FLOAT: control = value.get_float(); if (_plugin_ui) { SLV2UIInstance inst = _plugin_ui->instance(); const LV2UI_Descriptor* ui_descriptor = slv2_ui_instance_get_descriptor(inst); LV2UI_Handle ui_handle = slv2_ui_instance_get_handle(inst); if (ui_descriptor->port_event) ui_descriptor->port_event(ui_handle, index, 4, 0, &control); } break; case Atom::STRING: cout << "Port value type is a string? (\"" << value.get_string() << "\")" << endl; break; default: break; } } void NodeModule::embed_gui(bool embed) { if (embed) { if (_gui_window) { cerr << "LV2 GUI already popped up, cannot embed" << endl; return; } if (!_plugin_ui) { const PluginModel* const pm = dynamic_cast<const PluginModel*>(_node->plugin()); assert(pm); _plugin_ui = pm->ui(App::instance().world(), _node); } if (_plugin_ui) { GtkWidget* c_widget = (GtkWidget*)slv2_ui_instance_get_widget(_plugin_ui->instance()); _gui_widget = Glib::wrap(c_widget); assert(_gui_widget); Gtk::Container* container = new Gtk::EventBox(); container->set_name("ingen_embedded_node_gui_container"); container->add(*_gui_widget); FlowCanvas::Module::embed(container); } else { cerr << "ERROR: Failed to create LV2 UI" << endl; } if (_gui_widget) { _gui_widget->show_all(); for (NodeModel::Ports::const_iterator p = _node->ports().begin(); p != _node->ports().end(); ++p) if ((*p)->type().is_control() && (*p)->is_output()) App::instance().engine()->set_property((*p)->path(), "ingen:broadcast", true); } } else { // un-embed FlowCanvas::Module::embed(NULL); _plugin_ui.reset(); for (NodeModel::Ports::const_iterator p = _node->ports().begin(); p != _node->ports().end(); ++p) if ((*p)->type().is_control() && (*p)->is_output()) App::instance().engine()->set_property((*p)->path(), "ingen:broadcast", false); } if (embed && _embed_item) { initialise_gui_values(); set_base_color(0x212222FF); } else { set_default_base_color(); } resize(); } void NodeModule::rename() { set_name(_node->path().name()); resize(); } void NodeModule::add_port(SharedPtr<PortModel> port, bool resize_to_fit) { uint32_t index = _ports.size(); // FIXME: kludge, engine needs to tell us this string name = port->path().name(); if (App::instance().configuration()->name_style() == Configuration::HUMAN && node()->plugin()) name = ((PluginModel*)node()->plugin())->port_human_name(index); Module::add_port(boost::shared_ptr<Port>( new Port(PtrCast<NodeModule>(shared_from_this()), port, name))); port->signal_value_changed.connect(sigc::bind<0>( sigc::mem_fun(this, &NodeModule::value_changed), index)); if (resize_to_fit) resize(); } void NodeModule::remove_port(SharedPtr<PortModel> port) { SharedPtr<FlowCanvas::Port> p = Module::remove_port(port->path().name()); p.reset(); } bool NodeModule::popup_gui() { #ifdef HAVE_SLV2 if (_node->plugin() && _node->plugin()->type() == PluginModel::LV2) { if (_plugin_ui) { cerr << "LV2 GUI already embedded, cannot pop up" << endl; return false; } const PluginModel* const plugin = dynamic_cast<const PluginModel*>(_node->plugin()); assert(plugin); _plugin_ui = plugin->ui(App::instance().world(), _node); if (_plugin_ui) { GtkWidget* c_widget = (GtkWidget*)slv2_ui_instance_get_widget(_plugin_ui->instance()); _gui_widget = Glib::wrap(c_widget); _gui_window = new Gtk::Window(); _gui_window->add(*_gui_widget); _gui_widget->show_all(); initialise_gui_values(); _gui_window->signal_unmap().connect( sigc::mem_fun(this, &NodeModule::on_gui_window_close)); _gui_window->present(); return true; } else { cerr << "No LV2 GUI" << endl; } } #endif return false; } void NodeModule::on_gui_window_close() { delete _gui_window; _gui_window = NULL; _plugin_ui.reset(); _gui_widget = NULL; } void NodeModule::initialise_gui_values() { uint32_t index=0; for (NodeModel::Ports::const_iterator p = _node->ports().begin(); p != _node->ports().end(); ++p) { if ((*p)->type().is_control()) value_changed(index, (*p)->value()); ++index; } } void NodeModule::show_control_window() { App::instance().window_factory()->present_controls(_node); } void NodeModule::on_double_click(GdkEventButton* ev) { if ( ! popup_gui() ) show_control_window(); } void NodeModule::store_location() { const float x = static_cast<float>(property_x()); const float y = static_cast<float>(property_y()); const Atom& existing_x = _node->get_variable("ingenuity:canvas-x"); const Atom& existing_y = _node->get_variable("ingenuity:canvas-y"); if (existing_x.type() != Atom::FLOAT || existing_y.type() != Atom::FLOAT || existing_x.get_float() != x || existing_y.get_float() != y) { App::instance().engine()->set_variable(_node->path(), "ingenuity:canvas-x", Atom(x)); App::instance().engine()->set_variable(_node->path(), "ingenuity:canvas-y", Atom(y)); } } void NodeModule::set_variable(const string& key, const Atom& value) { if (key == "ingenuity:canvas-x" && value.type() == Atom::FLOAT) move_to(value.get_float(), property_y()); else if (key == "ingenuity:canvas-y" && value.type() == Atom::FLOAT) move_to(property_x(), value.get_float()); } void NodeModule::set_property(const string& key, const Atom& value) { if (key == "ingen:polyphonic" && value.type() == Atom::BOOL) { set_stacked_border(value.get_bool()); } else if (key == "ingen:selected" && value.type() == Atom::BOOL) { if (value.get_bool() != selected()) { if (value.get_bool()) _canvas.lock()->select_item(shared_from_this()); else _canvas.lock()->unselect_item(shared_from_this()); } } } void NodeModule::set_selected(bool b) { if (b != selected()) { Module::set_selected(b); if (App::instance().signal()) App::instance().engine()->set_property(_node->path(), "ingen:selected", b); } } } // namespace GUI } // namespace Ingen <|endoftext|>
<commit_before>// ======================================================================== // // Copyright 2009-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 "SceneGraph.h" #include "visitor/VerifyNodes.h" namespace ospray { namespace sg { Frame::Frame() { createChild("frameBuffer", "FrameBuffer"); createChild("camera", "PerspectiveCamera"); createChild("renderer", "Renderer"); createChild("frameAccumulationLimit", "int", -1); } std::string Frame::toString() const { return "ospray::sg::Frame"; } void Frame::preCommit(RenderContext &) { if (child("camera").hasChild("aspect") && child("frameBuffer")["size"].lastModified() > child("camera")["aspect"].lastCommitted()) { auto fbSize = child("frameBuffer")["size"].valueAs<vec2i>(); child("camera")["aspect"] = fbSize.x / float(fbSize.y); } auto rendererNode = child("renderer").nodeAs<Renderer>(); rendererNode->updateRenderer(); auto rHandle = rendererNode->valueAs<OSPRenderer>(); auto cHandle = child("camera").valueAs<OSPCamera>(); // XXX this is not sufficient (at least for FB): // the FB can be released and re-created (i.e. on size change) and per // (high) chance get the same handle (which is just the heap address when // using the local device) bool newRenderer = currentRenderer != rHandle; bool newCamera = currentCamera != cHandle; if (newRenderer) currentRenderer = rHandle; if (newCamera) currentCamera = cHandle; if (newRenderer || newCamera) ospSetObject(rHandle, "camera", cHandle); bool rChanged = rendererNode->subtreeModifiedButNotCommitted(); bool cChanged = child("camera").subtreeModifiedButNotCommitted(); clearFB = newCamera || newRenderer || rChanged || cChanged; frameAccumulationLimit = child("frameAccumulationLimit").valueAs<int>(); } void Frame::postCommit(RenderContext &) { // after commit of child FB, which can lead to a new handle auto fHandle = child("frameBuffer").valueAs<OSPFrameBuffer>(); bool newFB = currentFB != fHandle; if (newFB) currentFB = fHandle; if (newFB || clearFB) { child("frameBuffer").nodeAs<FrameBuffer>()->clear(); clearFB = false; numAccumulatedFrames = 0; etaSeconds = inf; etaVariance = inf; etaAccumulation = inf; } } std::shared_ptr<FrameBuffer> Frame::renderFrame(bool verifyCommit) { if (verifyCommit) { Node::traverse(VerifyNodes{}); commit(); } traverse("render"); auto fb1Node = child("frameBuffer").nodeAs<FrameBuffer>(); auto fb2Node = child("navFrameBuffer").nodeAs<FrameBuffer>(); // use nav FB? auto fbNode = (numAccumulatedFrames == 0 && fb1Node->child("size").valueAs<vec2i>() != fb2Node->child("size").valueAs<vec2i>()) ? fb2Node : fb1Node; auto rendererNode = child("renderer").nodeAs<Renderer>(); const bool accumBudgetReached = frameAccumulationLimit >= 0 && numAccumulatedFrames >= frameAccumulationLimit; const float varianceThreshold = rendererNode->child("varianceThreshold").valueAs<float>(); const float lastVariance = numAccumulatedFrames < 2 ? inf : rendererNode->getLastVariance(); const bool varianceReached = varianceThreshold > 0.f && lastVariance <= varianceThreshold; if (accumBudgetReached || varianceReached) { etaSeconds = elapsedSeconds(); return nullptr; } if (numAccumulatedFrames == 0) accumulationTimer.start(); rendererNode->renderFrame(fbNode); numAccumulatedFrames++; accumulationTimer.stop(); if (frameAccumulationLimit >= 0) etaAccumulation = frameAccumulationLimit * elapsedSeconds() / numAccumulatedFrames; if (varianceThreshold > 0.f) { const float currentVariance = rendererNode->getLastVariance(); if (numAccumulatedFrames == 4) { // need stable variance estimate firstVariance = currentVariance; firstSeconds = elapsedSeconds(); } // update estimate only on even frames (when variance was updated) if (((numAccumulatedFrames&1)==0) && numAccumulatedFrames >= 6) etaVariance = firstSeconds + (elapsedSeconds() - firstSeconds) / (1.f/sqr(currentVariance) - 1.f/sqr(firstVariance)) / sqr(varianceThreshold); } // whichever is earlier etaSeconds = std::min(etaVariance, etaAccumulation); return fbNode; } OSPPickResult Frame::pick(const vec2f &pickPos) { auto rendererNode = child("renderer").nodeAs<Renderer>(); return rendererNode->pick(pickPos); } int Frame::frameId() const { return numAccumulatedFrames; } float Frame::elapsedSeconds() const { return accumulationTimer.seconds(); } float Frame::estimatedSeconds() const { return etaSeconds; } OSP_REGISTER_SG_NODE(Frame); } // ::ospray::sg } // ::ospray <commit_msg>Fix cornercase frameAccumulationLimit==1<commit_after>// ======================================================================== // // Copyright 2009-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 "SceneGraph.h" #include "visitor/VerifyNodes.h" namespace ospray { namespace sg { Frame::Frame() { createChild("frameBuffer", "FrameBuffer"); createChild("camera", "PerspectiveCamera"); createChild("renderer", "Renderer"); createChild("frameAccumulationLimit", "int", -1); } std::string Frame::toString() const { return "ospray::sg::Frame"; } void Frame::preCommit(RenderContext &) { if (child("camera").hasChild("aspect") && child("frameBuffer")["size"].lastModified() > child("camera")["aspect"].lastCommitted()) { auto fbSize = child("frameBuffer")["size"].valueAs<vec2i>(); child("camera")["aspect"] = fbSize.x / float(fbSize.y); } auto rendererNode = child("renderer").nodeAs<Renderer>(); rendererNode->updateRenderer(); auto rHandle = rendererNode->valueAs<OSPRenderer>(); auto cHandle = child("camera").valueAs<OSPCamera>(); // XXX this is not sufficient (at least for FB): // the FB can be released and re-created (i.e. on size change) and per // (high) chance get the same handle (which is just the heap address when // using the local device) bool newRenderer = currentRenderer != rHandle; bool newCamera = currentCamera != cHandle; if (newRenderer) currentRenderer = rHandle; if (newCamera) currentCamera = cHandle; if (newRenderer || newCamera) ospSetObject(rHandle, "camera", cHandle); bool rChanged = rendererNode->subtreeModifiedButNotCommitted(); bool cChanged = child("camera").subtreeModifiedButNotCommitted(); clearFB = newCamera || newRenderer || rChanged || cChanged; frameAccumulationLimit = child("frameAccumulationLimit").valueAs<int>(); // when frameAccumulationLimit is active, render at least 2 frames, // otherwise the view is stuck showing the stale navigation framebuffer // for no accumulation, disable the accumBuffer if (frameAccumulationLimit >= 0) frameAccumulationLimit = std::max(frameAccumulationLimit, 2); } void Frame::postCommit(RenderContext &) { // after commit of child FB, which can lead to a new handle auto fHandle = child("frameBuffer").valueAs<OSPFrameBuffer>(); bool newFB = currentFB != fHandle; if (newFB) currentFB = fHandle; if (newFB || clearFB) { child("frameBuffer").nodeAs<FrameBuffer>()->clear(); clearFB = false; numAccumulatedFrames = 0; etaSeconds = inf; etaVariance = inf; etaAccumulation = inf; } } std::shared_ptr<FrameBuffer> Frame::renderFrame(bool verifyCommit) { if (verifyCommit) { Node::traverse(VerifyNodes{}); commit(); } traverse("render"); auto fb1Node = child("frameBuffer").nodeAs<FrameBuffer>(); auto fb2Node = child("navFrameBuffer").nodeAs<FrameBuffer>(); // use nav FB? auto fbNode = (numAccumulatedFrames == 0 && fb1Node->child("size").valueAs<vec2i>() != fb2Node->child("size").valueAs<vec2i>()) ? fb2Node : fb1Node; auto rendererNode = child("renderer").nodeAs<Renderer>(); const bool accumBudgetReached = frameAccumulationLimit >= 0 && numAccumulatedFrames >= frameAccumulationLimit; const float varianceThreshold = rendererNode->child("varianceThreshold").valueAs<float>(); const float lastVariance = numAccumulatedFrames < 2 ? inf : rendererNode->getLastVariance(); const bool varianceReached = varianceThreshold > 0.f && lastVariance <= varianceThreshold; if (accumBudgetReached || varianceReached) { etaSeconds = elapsedSeconds(); return nullptr; } if (numAccumulatedFrames == 0) accumulationTimer.start(); rendererNode->renderFrame(fbNode); numAccumulatedFrames++; accumulationTimer.stop(); if (frameAccumulationLimit >= 0) etaAccumulation = frameAccumulationLimit * elapsedSeconds() / numAccumulatedFrames; if (varianceThreshold > 0.f) { const float currentVariance = rendererNode->getLastVariance(); if (numAccumulatedFrames == 4) { // need stable variance estimate firstVariance = currentVariance; firstSeconds = elapsedSeconds(); } // update estimate only on even frames (when variance was updated) if (((numAccumulatedFrames&1)==0) && numAccumulatedFrames >= 6) etaVariance = firstSeconds + (elapsedSeconds() - firstSeconds) / (1.f/sqr(currentVariance) - 1.f/sqr(firstVariance)) / sqr(varianceThreshold); } // whichever is earlier etaSeconds = std::min(etaVariance, etaAccumulation); return fbNode; } OSPPickResult Frame::pick(const vec2f &pickPos) { auto rendererNode = child("renderer").nodeAs<Renderer>(); return rendererNode->pick(pickPos); } int Frame::frameId() const { return numAccumulatedFrames; } float Frame::elapsedSeconds() const { return accumulationTimer.seconds(); } float Frame::estimatedSeconds() const { return etaSeconds; } OSP_REGISTER_SG_NODE(Frame); } // ::ospray::sg } // ::ospray <|endoftext|>
<commit_before>#include "parseArgs.h" // parseArgs #include "DelilahConsole.h" // ss::DelilahConsole #include "SamsonSetup.h" // ss::SamsonSetup #include "au/Format.h" // au::Format #include "MemoryManager.h" // ss::MemoryManager #include "Engine.h" // engine::Engine /* **************************************************************************** * * Option variables */ int endpoints; int workers; char controller[80]; int memory_gb; int load_buffer_size_mb; char commandFileName[1024]; #define LOC "localhost:1234" /* **************************************************************************** * * parse arguments */ PaArgument paArgs[] = { { "-controller", controller, "CONTROLLER", PaString, PaOpt, _i LOC, PaNL, PaNL, "controller IP:port" }, { "-endpoints", &endpoints, "ENDPOINTS", PaInt, PaOpt, 80, 3, 100, "number of endpoints" }, { "-workers", &workers, "WORKERS", PaInt, PaOpt, 1, 1, 100, "number of workers" }, { "-memory", &memory_gb, "MEMORY", PaInt, PaOpt, 1, 1, 100, "memory in GBytes" }, { "-load_buffer_size", &load_buffer_size_mb, "LOAD_BUFFER_SIZE", PaInt, PaOpt, 64, 64, 2048, "load buffer size in Mbytes" }, { "-f", commandFileName, "FILE_NAME", PaString, PaOpt, _i "", PaNL, PaNL, "File with commands to run" }, PA_END_OF_ARGS }; /* **************************************************************************** * * logFd - file descriptor for log file used in all libraries */ int logFd = -1; /* **************************************************************************** * * main - */ int main(int argC, const char *argV[]) { paConfig("prefix", (void*) "SSW_"); paConfig("usage and exit on any warning", (void*) true); paConfig("log to screen", (void*) false); paConfig("log file line format", (void*) "TYPE:DATE:EXEC-AUX/FILE[LINE] FUNC: TEXT"); paConfig("log to file", (void*) true); paParse(paArgs, argC, (char**) argV, 1, false); lmAux((char*) "father"); logFd = lmFirstDiskFileDescriptor(); ss::SamsonSetup::load(); // Load the main setup file // Setup parameters from command line ( this is delilah so memory and load buffer size are configurable from command line ) ss::SamsonSetup::shared()->memory = (size_t) memory_gb * (size_t) (1024*1024*1024); ss::SamsonSetup::shared()->load_buffer_size = (size_t) load_buffer_size_mb * (size_t) (1024*1024); engine::Engine::init(); std::cout << "Waiting for network connection ..."; // Init the network element for delilah ss::Network network(ss::Endpoint::Delilah, "delilah", 0, endpoints, workers); network.init(controller); network.runInBackground(); // What until the network is ready while ( !network.ready() ) sleep(1); std::cout << "OK\n"; // Create a DelilahControler once network is ready ss::DelilahConsole delilahConsole( &network ); engine::Engine::runInBackground(); if ( strcmp( commandFileName,"") != 0 ) { FILE *f = fopen( commandFileName , "r" ); if( !f ) { LM_E(("Error opening commands file %s", commandFileName)); exit(0); } char line[1024]; //LM_M(("Processing commands file %s", commandFileName )); while( fgets(line, sizeof(line), f) ) { // Remove the last return of a string while( ( strlen( line ) > 0 ) && ( line[ strlen(line)-1] == '\n') > 0 ) line[ strlen(line)-1]= '\0'; //LM_M(("Processing line: %s", line )); size_t id = delilahConsole.runAsyncCommand( line ); if( id != 0) { //LM_M(("Waiting until delilah-component %ul finish", id )); // Wait until this operation is finished while (delilahConsole.isActive( id ) ) sleep(1); } } fclose(f); LM_M(("samsonLocal exit correctly")); exit(0); } delilahConsole.run(); } <commit_msg>Same trick on delilah to initialize MemoryManager<commit_after>#include "parseArgs.h" // parseArgs #include "DelilahConsole.h" // ss::DelilahConsole #include "SamsonSetup.h" // ss::SamsonSetup #include "au/Format.h" // au::Format #include "MemoryManager.h" // ss::MemoryManager #include "Engine.h" // engine::Engine /* **************************************************************************** * * Option variables */ int endpoints; int workers; char controller[80]; int memory_gb; int load_buffer_size_mb; char commandFileName[1024]; #define LOC "localhost:1234" /* **************************************************************************** * * parse arguments */ PaArgument paArgs[] = { { "-controller", controller, "CONTROLLER", PaString, PaOpt, _i LOC, PaNL, PaNL, "controller IP:port" }, { "-endpoints", &endpoints, "ENDPOINTS", PaInt, PaOpt, 80, 3, 100, "number of endpoints" }, { "-workers", &workers, "WORKERS", PaInt, PaOpt, 1, 1, 100, "number of workers" }, { "-memory", &memory_gb, "MEMORY", PaInt, PaOpt, 1, 1, 100, "memory in GBytes" }, { "-load_buffer_size", &load_buffer_size_mb, "LOAD_BUFFER_SIZE", PaInt, PaOpt, 64, 64, 2048, "load buffer size in Mbytes" }, { "-f", commandFileName, "FILE_NAME", PaString, PaOpt, _i "", PaNL, PaNL, "File with commands to run" }, PA_END_OF_ARGS }; /* **************************************************************************** * * logFd - file descriptor for log file used in all libraries */ int logFd = -1; /* **************************************************************************** * * main - */ int main(int argC, const char *argV[]) { paConfig("prefix", (void*) "SSW_"); paConfig("usage and exit on any warning", (void*) true); paConfig("log to screen", (void*) false); paConfig("log file line format", (void*) "TYPE:DATE:EXEC-AUX/FILE[LINE] FUNC: TEXT"); paConfig("log to file", (void*) true); paParse(paArgs, argC, (char**) argV, 1, false); lmAux((char*) "father"); logFd = lmFirstDiskFileDescriptor(); ss::SamsonSetup::load(); // Load the main setup file // Setup parameters from command line ( this is delilah so memory and load buffer size are configurable from command line ) ss::SamsonSetup::shared()->memory = (size_t) memory_gb * (size_t) (1024*1024*1024); ss::SamsonSetup::shared()->load_buffer_size = (size_t) load_buffer_size_mb * (size_t) (1024*1024); engine::Engine::init(); // Goyo. Groping in the dark (blind sticks for an easier translation) engine::MemoryManager::init( ss::SamsonSetup::shared()->memory ); // Goyo. End of groping in the dark std::cout << "Waiting for network connection ..."; // Init the network element for delilah ss::Network network(ss::Endpoint::Delilah, "delilah", 0, endpoints, workers); network.init(controller); network.runInBackground(); // What until the network is ready while ( !network.ready() ) sleep(1); std::cout << "OK\n"; // Create a DelilahControler once network is ready ss::DelilahConsole delilahConsole( &network ); engine::Engine::runInBackground(); if ( strcmp( commandFileName,"") != 0 ) { FILE *f = fopen( commandFileName , "r" ); if( !f ) { LM_E(("Error opening commands file %s", commandFileName)); exit(0); } char line[1024]; //LM_M(("Processing commands file %s", commandFileName )); while( fgets(line, sizeof(line), f) ) { // Remove the last return of a string while( ( strlen( line ) > 0 ) && ( line[ strlen(line)-1] == '\n') > 0 ) line[ strlen(line)-1]= '\0'; //LM_M(("Processing line: %s", line )); size_t id = delilahConsole.runAsyncCommand( line ); if( id != 0) { //LM_M(("Waiting until delilah-component %ul finish", id )); // Wait until this operation is finished while (delilahConsole.isActive( id ) ) sleep(1); } } fclose(f); LM_M(("samsonLocal exit correctly")); exit(0); } delilahConsole.run(); } <|endoftext|>
<commit_before>#include "Application.h" using namespace ShadowMapping; CApplication::CApplication() : m_mousePosition(0, 0) , m_elapsed(0) { m_globalPackage = Athena::CPackage::Create("global"); CreateScene(); CreateUi(); Athena::CGraphicDevice::GetInstance().AddViewport(m_mainViewport.get()); Athena::CGraphicDevice::GetInstance().AddViewport(m_uiViewport.get()); } CApplication::~CApplication() { Athena::CGraphicDevice::GetInstance().RemoveViewport(m_mainViewport.get()); Athena::CGraphicDevice::GetInstance().RemoveViewport(m_uiViewport.get()); } void CApplication::CreateScene() { auto screenSize = Athena::CGraphicDevice::GetInstance().GetScreenSize(); m_mainViewport = Athena::CViewport::Create(); { auto camera = CTouchFreeCamera::Create(); camera->SetPerspectiveProjection(M_PI / 4, screenSize.x / screenSize.y, 1, 10000); camera->SetPosition(CVector3(350, 700, -350)); camera->SetHorizontalAngle(-M_PI / 4.f); camera->SetVerticalAngle(5.f * M_PI / 16.f); m_mainViewport->SetCamera(camera); m_mainCamera = camera; } { auto camera = Athena::CCamera::Create(); // camera->SetOrthoProjection(512, 512, 1, 1000); camera->SetPerspectiveProjection(M_PI / 2, 1, 100, 1000); m_mainViewport->SetShadowCamera(camera); m_shadowCamera = camera; } // m_mainViewport->SetCamera(m_shadowCamera); auto sceneRoot = m_mainViewport->GetSceneRoot(); static const float areaSize = 256; static const int sphereCount = 50; { auto cube = Athena::CCubeMesh::Create(); cube->SetScale(CVector3(areaSize, 50, areaSize)); cube->SetPosition(CVector3(0, -200, 0)); cube->GetMaterial()->SetColor(CColor(0, 0, 1, 1)); cube->GetMaterial()->SetShadowReceiving(true); sceneRoot->AppendChild(cube); } #ifdef BOUNDING_BOX { CQuaternion rot(CVector3(0, 0, 1), -M_PI / 2); auto mat = rot.ToMatrix(); // auto rot2 = CQuaternion(mat); auto view = m_shadowCamera->GetViewMatrix(); view(3, 0) = 0; view(3, 1) = 0; view(3, 2) = 0; auto invView = view.Inverse(); auto quat = CQuaternion(invView); CVector3 axisX(1, 0, 0); CVector3 axisY(0, 1, 0); CVector3 axisZ(0, 0, 1); auto resX = axisX * invView; auto resY = axisY * invView; auto resZ = axisZ * invView; quat.Normalize(); auto shadowProjVolume = Athena::CCubeMesh::Create(); // shadowProjVolume->SetPosition(CVector3(0, 200, 0)); shadowProjVolume->SetRotation(quat); shadowProjVolume->SetScale(CVector3(512 / 2, 512 / 2, 999)); shadowProjVolume->GetMaterial()->SetColor(CColor(0.5f, 0.5f, 0.5f, 0.5f)); shadowProjVolume->GetMaterial()->SetAlphaBlendingMode(Athena::ALPHA_BLENDING_LERP); sceneRoot->AppendChild(shadowProjVolume); } #endif //Show camera position { auto sphere = Athena::CSphereMesh::Create(); sphere->SetScale(CVector3(10, 10, 10)); sphere->GetMaterial()->SetColor(CColor(0, 1, 0, 1)); sceneRoot->AppendChild(sphere); m_shadowCameraSphere = sphere; } srand(10); for(unsigned int i = 0; i < sphereCount; i++) { float xPos = ((static_cast<float>(rand()) / static_cast<float>(RAND_MAX)) - 0.5f) * 2.f * areaSize; float zPos = ((static_cast<float>(rand()) / static_cast<float>(RAND_MAX)) - 0.5f) * 2.f * areaSize; auto sphere = Athena::CSphereMesh::Create(); sphere->SetScale(CVector3(20, 20, 20)); sphere->SetPosition(CVector3(xPos, 0, zPos)); sphere->GetMaterial()->SetColor(CColor(1, 0, 0, 1)); sphere->GetMaterial()->SetShadowCasting(true); sceneRoot->AppendChild(sphere); } } void CApplication::CreateUi() { auto screenSize = Athena::CGraphicDevice::GetInstance().GetScreenSize(); m_uiViewport = Athena::CViewport::Create(); { auto camera = Athena::CCamera::Create(); camera->SetupOrthoCamera(screenSize.x, screenSize.y); m_uiViewport->SetCamera(camera); } { auto sceneRoot = m_uiViewport->GetSceneRoot(); { auto scene = Athena::CScene::Create(Athena::CResourceManager::GetInstance().GetResource<Athena::CSceneDescriptor>("main_scene.xml")); { auto sprite = scene->FindNode<Athena::CSprite>("BackwardSprite"); m_backwardButtonBoundingBox.position = sprite->GetPosition().xy(); m_backwardButtonBoundingBox.size = sprite->GetSize(); } { auto sprite = scene->FindNode<Athena::CSprite>("ForwardSprite"); m_forwardButtonBoundingBox.position = sprite->GetPosition().xy(); m_forwardButtonBoundingBox.size = sprite->GetSize(); } sceneRoot->AppendChild(scene); } } } void CApplication::Update(float dt) { UpdateShadowCamera(); m_mainCamera->Update(dt); m_mainViewport->GetSceneRoot()->Update(dt); m_mainViewport->GetSceneRoot()->UpdateTransformations(); m_uiViewport->GetSceneRoot()->Update(dt); m_uiViewport->GetSceneRoot()->UpdateTransformations(); m_elapsed += dt; } void CApplication::UpdateShadowCamera() { CVector3 shadowCameraPosition(0, 384.f + 128.f * sin(m_elapsed), 0); m_shadowCamera->LookAt(shadowCameraPosition, CVector3(0, 0, 0), CVector3(0, 0, -1)); m_shadowCameraSphere->SetPosition(shadowCameraPosition); } void CApplication::NotifyMouseMove(int x, int y) { m_mousePosition = CVector2(x, y); m_mainCamera->NotifyMouseMove(x, y); } void CApplication::NotifyMouseDown() { Athena::CInputManager::SendInputEventToTree(m_uiViewport->GetSceneRoot(), m_mousePosition, Athena::INPUT_EVENT_PRESSED); if(m_forwardButtonBoundingBox.Intersects(CBox2(m_mousePosition.x, m_mousePosition.y, 4, 4))) { m_mainCamera->NotifyMouseDown_MoveForward(); } else if(m_backwardButtonBoundingBox.Intersects(CBox2(m_mousePosition.x, m_mousePosition.y, 4, 4))) { m_mainCamera->NotifyMouseDown_MoveBackward(); } else { m_mainCamera->NotifyMouseDown_Center(); } } void CApplication::NotifyMouseUp() { Athena::CInputManager::SendInputEventToTree(m_uiViewport->GetSceneRoot(), m_mousePosition, Athena::INPUT_EVENT_RELEASED); m_mainCamera->NotifyMouseUp(); } Athena::CApplication* CreateApplication() { return new CApplication(); } <commit_msg>Compilation fix.<commit_after>#include <cstdlib> #include "Application.h" using namespace ShadowMapping; CApplication::CApplication() : m_mousePosition(0, 0) , m_elapsed(0) { m_globalPackage = Athena::CPackage::Create("global"); CreateScene(); CreateUi(); Athena::CGraphicDevice::GetInstance().AddViewport(m_mainViewport.get()); Athena::CGraphicDevice::GetInstance().AddViewport(m_uiViewport.get()); } CApplication::~CApplication() { Athena::CGraphicDevice::GetInstance().RemoveViewport(m_mainViewport.get()); Athena::CGraphicDevice::GetInstance().RemoveViewport(m_uiViewport.get()); } void CApplication::CreateScene() { auto screenSize = Athena::CGraphicDevice::GetInstance().GetScreenSize(); m_mainViewport = Athena::CViewport::Create(); { auto camera = CTouchFreeCamera::Create(); camera->SetPerspectiveProjection(M_PI / 4, screenSize.x / screenSize.y, 1, 10000); camera->SetPosition(CVector3(350, 700, -350)); camera->SetHorizontalAngle(-M_PI / 4.f); camera->SetVerticalAngle(5.f * M_PI / 16.f); m_mainViewport->SetCamera(camera); m_mainCamera = camera; } { auto camera = Athena::CCamera::Create(); // camera->SetOrthoProjection(512, 512, 1, 1000); camera->SetPerspectiveProjection(M_PI / 2, 1, 100, 1000); m_mainViewport->SetShadowCamera(camera); m_shadowCamera = camera; } // m_mainViewport->SetCamera(m_shadowCamera); auto sceneRoot = m_mainViewport->GetSceneRoot(); static const float areaSize = 256; static const int sphereCount = 50; { auto cube = Athena::CCubeMesh::Create(); cube->SetScale(CVector3(areaSize, 50, areaSize)); cube->SetPosition(CVector3(0, -200, 0)); cube->GetMaterial()->SetColor(CColor(0, 0, 1, 1)); cube->GetMaterial()->SetShadowReceiving(true); sceneRoot->AppendChild(cube); } #ifdef BOUNDING_BOX { CQuaternion rot(CVector3(0, 0, 1), -M_PI / 2); auto mat = rot.ToMatrix(); // auto rot2 = CQuaternion(mat); auto view = m_shadowCamera->GetViewMatrix(); view(3, 0) = 0; view(3, 1) = 0; view(3, 2) = 0; auto invView = view.Inverse(); auto quat = CQuaternion(invView); CVector3 axisX(1, 0, 0); CVector3 axisY(0, 1, 0); CVector3 axisZ(0, 0, 1); auto resX = axisX * invView; auto resY = axisY * invView; auto resZ = axisZ * invView; quat.Normalize(); auto shadowProjVolume = Athena::CCubeMesh::Create(); // shadowProjVolume->SetPosition(CVector3(0, 200, 0)); shadowProjVolume->SetRotation(quat); shadowProjVolume->SetScale(CVector3(512 / 2, 512 / 2, 999)); shadowProjVolume->GetMaterial()->SetColor(CColor(0.5f, 0.5f, 0.5f, 0.5f)); shadowProjVolume->GetMaterial()->SetAlphaBlendingMode(Athena::ALPHA_BLENDING_LERP); sceneRoot->AppendChild(shadowProjVolume); } #endif //Show camera position { auto sphere = Athena::CSphereMesh::Create(); sphere->SetScale(CVector3(10, 10, 10)); sphere->GetMaterial()->SetColor(CColor(0, 1, 0, 1)); sceneRoot->AppendChild(sphere); m_shadowCameraSphere = sphere; } srand(10); for(unsigned int i = 0; i < sphereCount; i++) { float xPos = ((static_cast<float>(rand()) / static_cast<float>(RAND_MAX)) - 0.5f) * 2.f * areaSize; float zPos = ((static_cast<float>(rand()) / static_cast<float>(RAND_MAX)) - 0.5f) * 2.f * areaSize; auto sphere = Athena::CSphereMesh::Create(); sphere->SetScale(CVector3(20, 20, 20)); sphere->SetPosition(CVector3(xPos, 0, zPos)); sphere->GetMaterial()->SetColor(CColor(1, 0, 0, 1)); sphere->GetMaterial()->SetShadowCasting(true); sceneRoot->AppendChild(sphere); } } void CApplication::CreateUi() { auto screenSize = Athena::CGraphicDevice::GetInstance().GetScreenSize(); m_uiViewport = Athena::CViewport::Create(); { auto camera = Athena::CCamera::Create(); camera->SetupOrthoCamera(screenSize.x, screenSize.y); m_uiViewport->SetCamera(camera); } { auto sceneRoot = m_uiViewport->GetSceneRoot(); { auto scene = Athena::CScene::Create(Athena::CResourceManager::GetInstance().GetResource<Athena::CSceneDescriptor>("main_scene.xml")); { auto sprite = scene->FindNode<Athena::CSprite>("BackwardSprite"); m_backwardButtonBoundingBox.position = sprite->GetPosition().xy(); m_backwardButtonBoundingBox.size = sprite->GetSize(); } { auto sprite = scene->FindNode<Athena::CSprite>("ForwardSprite"); m_forwardButtonBoundingBox.position = sprite->GetPosition().xy(); m_forwardButtonBoundingBox.size = sprite->GetSize(); } sceneRoot->AppendChild(scene); } } } void CApplication::Update(float dt) { UpdateShadowCamera(); m_mainCamera->Update(dt); m_mainViewport->GetSceneRoot()->Update(dt); m_mainViewport->GetSceneRoot()->UpdateTransformations(); m_uiViewport->GetSceneRoot()->Update(dt); m_uiViewport->GetSceneRoot()->UpdateTransformations(); m_elapsed += dt; } void CApplication::UpdateShadowCamera() { CVector3 shadowCameraPosition(0, 384.f + 128.f * sin(m_elapsed), 0); m_shadowCamera->LookAt(shadowCameraPosition, CVector3(0, 0, 0), CVector3(0, 0, -1)); m_shadowCameraSphere->SetPosition(shadowCameraPosition); } void CApplication::NotifyMouseMove(int x, int y) { m_mousePosition = CVector2(x, y); m_mainCamera->NotifyMouseMove(x, y); } void CApplication::NotifyMouseDown() { Athena::CInputManager::SendInputEventToTree(m_uiViewport->GetSceneRoot(), m_mousePosition, Athena::INPUT_EVENT_PRESSED); if(m_forwardButtonBoundingBox.Intersects(CBox2(m_mousePosition.x, m_mousePosition.y, 4, 4))) { m_mainCamera->NotifyMouseDown_MoveForward(); } else if(m_backwardButtonBoundingBox.Intersects(CBox2(m_mousePosition.x, m_mousePosition.y, 4, 4))) { m_mainCamera->NotifyMouseDown_MoveBackward(); } else { m_mainCamera->NotifyMouseDown_Center(); } } void CApplication::NotifyMouseUp() { Athena::CInputManager::SendInputEventToTree(m_uiViewport->GetSceneRoot(), m_mousePosition, Athena::INPUT_EVENT_RELEASED); m_mainCamera->NotifyMouseUp(); } Athena::CApplication* CreateApplication() { return new CApplication(); } <|endoftext|>
<commit_before>#ifndef VSMC_CORE_WEIGHT_HPP #define VSMC_CORE_WEIGHT_HPP #include <vsmc/internal/common.hpp> namespace vsmc { /// \brief Weight set class /// \ingroup Core class WeightSetBase { public : /// The type of the size of the weight set typedef std::size_t size_type; explicit WeightSetBase (size_type N) : ess_(static_cast<double>(N)), weight_(N), log_weight_(N) {} /// Read only access to the weights template <typename OutputIter> void read_weight (OutputIter first) const { std::copy(&weight_[0], &weight_[0] + weight_.size(), first); } /// Read only access to the log weights template <typename OutputIter> void read_log_weight (OutputIter first) const { std::copy(&log_weight_[0], &log_weight_[0] + log_weight_.size(), first); } /// Read only access to the weight of a particle double weight (size_type id) const { return weight_[id]; } /// Read only access to the log weight of a particle double log_weight (size_type id) const { return log_weight_[id]; } /// Set equal weights for all particles void set_equal_weight () { ess_ = static_cast<double>(weight_.size()); std::fill(&weight_[0], &weight_[0] + weight_.size(), 1.0 / weight_.size()); std::fill(&log_weight_[0], &log_weight_[0] + log_weight_.size(), 0); } /// \brief Set the log weights with a pointer /// /// \param nw The position to start the reading, it shall be valid /// after increments of size() times. void set_log_weight (const double *nw) { std::copy(nw, nw + log_weight_.size(), &log_weight_[0]); set_weight(); } /// \brief Add to the log weights with a pointer /// /// \param iw The position to start the reading, it shall be valid /// after increments of size() times. void add_log_weight (const double *iw) { for (size_type i = 0; i != log_weight_.size(); ++i) log_weight_[i] += iw[i]; set_weight(); } /// The current ESS (Effective Sample Size) double ess () const { return ess_; } private : mutable double ess_; mutable std::valarray<double> weight_; mutable std::valarray<double> log_weight_; void set_weight () { using std::exp; double max_weight = log_weight_.max(); log_weight_ -= max_weight; weight_ = exp(log_weight_); double sum = weight_.sum(); weight_ *= 1 / sum; ess_ = 1 / (weight_ * weight_).sum(); } }; // class WeightSetBase } // namespace vsmc VSMC_DEFINE_TYPE_DISPATCH_TRAIT(WeightSetType, weight_set_type, WeightSetBase); #endif // VSMC_CORE_WEIGHT_HPP <commit_msg>Revert "use compound operator of valarray instead loop"<commit_after>#ifndef VSMC_CORE_WEIGHT_HPP #define VSMC_CORE_WEIGHT_HPP #include <vsmc/internal/common.hpp> namespace vsmc { /// \brief Weight set class /// \ingroup Core class WeightSetBase { public : /// The type of the size of the weight set typedef std::size_t size_type; explicit WeightSetBase (size_type N) : ess_(static_cast<double>(N)), weight_(N), log_weight_(N) {} /// Read only access to the weights template <typename OutputIter> void read_weight (OutputIter first) const { std::copy(&weight_[0], &weight_[0] + weight_.size(), first); } /// Read only access to the log weights template <typename OutputIter> void read_log_weight (OutputIter first) const { std::copy(&log_weight_[0], &log_weight_[0] + log_weight_.size(), first); } /// Read only access to the weight of a particle double weight (size_type id) const { return weight_[id]; } /// Read only access to the log weight of a particle double log_weight (size_type id) const { return log_weight_[id]; } /// Set equal weights for all particles void set_equal_weight () { ess_ = static_cast<double>(weight_.size()); std::fill(&weight_[0], &weight_[0] + weight_.size(), 1.0 / weight_.size()); std::fill(&log_weight_[0], &log_weight_[0] + log_weight_.size(), 0); } /// \brief Set the log weights with a pointer /// /// \param nw The position to start the reading, it shall be valid /// after increments of size() times. void set_log_weight (const double *nw) { std::copy(nw, nw + log_weight_.size(), &log_weight_[0]); set_weight(); } /// \brief Add to the log weights with a pointer /// /// \param iw The position to start the reading, it shall be valid /// after increments of size() times. void add_log_weight (const double *iw) { for (size_type i = 0; i != log_weight_.size(); ++i) log_weight_[i] += iw[i]; set_weight(); } /// The current ESS (Effective Sample Size) double ess () const { return ess_; } private : mutable double ess_; mutable std::valarray<double> weight_; mutable std::valarray<double> log_weight_; void set_weight () { using std::exp; double max_weight = log_weight_.max(); for (size_type i = 0; i != log_weight_.size(); ++i) log_weight_[i] -= max_weight; weight_ = exp(log_weight_); double sum = weight_.sum(); weight_ *= 1 / sum; ess_ = 1 / (weight_ * weight_).sum(); } }; // class WeightSetBase } // namespace vsmc VSMC_DEFINE_TYPE_DISPATCH_TRAIT(WeightSetType, weight_set_type, WeightSetBase); #endif // VSMC_CORE_WEIGHT_HPP <|endoftext|>
<commit_before>/* * Copyright 2007-2021 CM4all GmbH * All rights reserved. * * author: Max Kellermann <mk@cm4all.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. * * 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 * FOUNDATION 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 "RFC.hxx" #include "Document.hxx" #include "Internal.hxx" #include "strmap.hxx" #include "ResourceAddress.hxx" #include "io/Logger.hxx" #include "http/Date.hxx" #include "http/PHeaderUtil.hxx" #include "http/PList.hxx" #include "util/StringView.hxx" #include "util/IterableSplitString.hxx" #include "AllocatorPtr.hxx" #include <stdlib.h> /* check whether the request could produce a cacheable response */ std::optional<HttpCacheRequestInfo> http_cache_request_evaluate(http_method_t method, const ResourceAddress &address, const StringMap &headers, bool obey_no_cache, bool has_request_body) noexcept { if (method != HTTP_METHOD_GET || has_request_body) /* RFC 2616 13.11 "Write-Through Mandatory" */ return std::nullopt; const char *p = headers.Get("range"); if (p != nullptr) return std::nullopt; /* RFC 2616 14.8: "When a shared cache receives a request containing an Authorization field, it MUST NOT return the corresponding response as a reply to any other request [...] */ if (headers.Get("authorization") != nullptr) return std::nullopt; bool only_if_cached = false; p = headers.Get("cache-control"); if (p != nullptr) { for (auto s : IterableSplitString(p, ',')) { s.Strip(); if (obey_no_cache && (s.Equals("no-cache") || s.Equals("no-store"))) return std::nullopt; if (s.Equals("only-if-cached")) only_if_cached = true; } } else if (obey_no_cache) { p = headers.Get("pragma"); if (p != nullptr && strcmp(p, "no-cache") == 0) return std::nullopt; } HttpCacheRequestInfo info; info.is_remote = address.type == ResourceAddress::Type::HTTP; info.only_if_cached = only_if_cached; info.has_query_string = address.HasQueryString(); info.if_match = headers.Get("if-match"); info.if_none_match = headers.Get("if-none-match"); info.if_modified_since = headers.Get("if-modified-since"); info.if_unmodified_since = headers.Get("if-unmodified-since"); return info; } bool http_cache_vary_fits(const StringMap &vary, const StringMap &headers) noexcept { for (const auto &i : vary) { const char *value = headers.Get(i.key); if (value == nullptr) value = ""; if (strcmp(i.value, value) != 0) /* mismatch in one of the "Vary" request headers */ return false; } return true; } bool http_cache_vary_fits(const StringMap *vary, const StringMap &headers) noexcept { return vary == nullptr || http_cache_vary_fits(*vary, headers); } bool http_cache_request_invalidate(http_method_t method) noexcept { /* RFC 2616 13.10 "Invalidation After Updates or Deletions" */ return method == HTTP_METHOD_PUT || method == HTTP_METHOD_DELETE || method == HTTP_METHOD_POST; } [[gnu::pure]] static std::chrono::system_clock::time_point parse_translate_time(const char *p, std::chrono::system_clock::duration offset) noexcept { if (p == nullptr) return std::chrono::system_clock::from_time_t(-1); auto t = http_date_parse(p); if (t != std::chrono::system_clock::from_time_t(-1)) t += offset; return t; } /** * RFC 2616 13.4 */ static constexpr bool http_status_cacheable(http_status_t status) noexcept { return status == HTTP_STATUS_OK || status == HTTP_STATUS_NON_AUTHORITATIVE_INFORMATION || status == HTTP_STATUS_PARTIAL_CONTENT || status == HTTP_STATUS_MULTIPLE_CHOICES || status == HTTP_STATUS_MOVED_PERMANENTLY || status == HTTP_STATUS_GONE; } /** * Determine the difference between this host's real-time clock and * the server's clock. This is used to adjust the "Expires" time * stamp. * * @return the difference or min() if the server did not send a valid * "Date" header */ [[gnu::pure]] static std::chrono::system_clock::duration GetServerDateOffset(const HttpCacheRequestInfo &request_info, std::chrono::system_clock::time_point now, const StringMap &response_headers) noexcept { if (!request_info.is_remote) /* server is local (e.g. FastCGI); we don't need an offset */ return std::chrono::system_clock::duration::zero(); const auto server_date = GetServerDate(response_headers); if (server_date == std::chrono::system_clock::from_time_t(-1)) return std::chrono::system_clock::duration::min(); return now - server_date; } std::optional<HttpCacheResponseInfo> http_cache_response_evaluate(const HttpCacheRequestInfo &request_info, AllocatorPtr alloc, bool eager_cache, http_status_t status, const StringMap &headers, off_t body_available) noexcept { const char *p; if (!http_status_cacheable(status)) return std::nullopt; if (body_available != (off_t)-1 && body_available > cacheable_size_limit) /* too large for the cache */ return std::nullopt; HttpCacheResponseInfo info; info.expires = std::chrono::system_clock::from_time_t(-1); p = headers.Get("cache-control"); if (p != nullptr) { for (auto s : IterableSplitString(p, ',')) { s.Strip(); if (s.StartsWith("private") || s.Equals("no-cache") || s.Equals("no-store")) return std::nullopt; if (s.StartsWith("max-age=")) { /* RFC 2616 14.9.3 */ char value[16]; int seconds; StringView param(s.data + 8, s.size - 8); if (param.size >= sizeof(value)) continue; memcpy(value, param.data, param.size); value[param.size] = 0; seconds = atoi(value); if (seconds > 0) info.expires = std::chrono::system_clock::now() + std::chrono::seconds(seconds); } } } const auto now = std::chrono::system_clock::now(); const auto offset = GetServerDateOffset(request_info, now, headers); if (offset == std::chrono::system_clock::duration::min()) /* we cannot determine whether to cache a resource if the server does not provide its system time */ return std::nullopt; if (info.expires == std::chrono::system_clock::from_time_t(-1)) { /* RFC 2616 14.9.3: "If a response includes both an Expires header and a max-age directive, the max-age directive overrides the Expires header" */ info.expires = parse_translate_time(headers.Get("expires"), offset); if (info.expires != std::chrono::system_clock::from_time_t(-1) && info.expires < now) LogConcat(4, "HttpCache", "invalid 'expires' header"); } if (request_info.has_query_string && !eager_cache && info.expires == std::chrono::system_clock::from_time_t(-1)) /* RFC 2616 13.9: "since some applications have traditionally used GETs and HEADs with query URLs (those containing a "?" in the rel_path part) to perform operations with significant side effects, caches MUST NOT treat responses to such URIs as fresh unless the server provides an explicit expiration time" */ return std::nullopt; info.last_modified = headers.Get("last-modified"); info.etag = headers.Get("etag"); info.vary = nullptr; const auto vary = headers.EqualRange("vary"); for (auto i = vary.first; i != vary.second; ++i) { const char *value = i->value; if (*value == 0) continue; if (strcmp(value, "*") == 0) /* RFC 2616 13.6: A Vary header field-value of "*" always fails to match and subsequent requests on that resource can only be properly interpreted by the origin server. */ return std::nullopt; if (info.vary == nullptr) info.vary = value; else info.vary = alloc.Concat(info.vary, ", ", value); } if (info.expires == std::chrono::system_clock::from_time_t(-1) && info.last_modified == nullptr && info.etag == nullptr) { if (eager_cache) // TODO info.expires = std::chrono::system_clock::now() + std::chrono::hours(1); else return std::nullopt; } return info; } void http_cache_copy_vary(StringMap &dest, AllocatorPtr alloc, const char *vary, const StringMap &request_headers) noexcept { for (const char *const*list = http_list_split(alloc, vary); *list != nullptr; ++list) { const char *name = *list; const char *value = request_headers.Get(name); if (value == nullptr) value = ""; else value = alloc.Dup(value); dest.Set(alloc, name, value); } } bool http_cache_prefer_cached(const HttpCacheDocument &document, const StringMap &response_headers) noexcept { if (document.info.etag == nullptr) return false; const char *etag = response_headers.Get("etag"); /* if the ETags are the same, then the resource hasn't changed, but the server was too lazy to check that properly */ return etag != nullptr && strcmp(etag, document.info.etag) == 0; } <commit_msg>http/cache/Info: eliminate local variables<commit_after>/* * Copyright 2007-2021 CM4all GmbH * All rights reserved. * * author: Max Kellermann <mk@cm4all.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. * * 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 * FOUNDATION 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 "RFC.hxx" #include "Document.hxx" #include "Internal.hxx" #include "strmap.hxx" #include "ResourceAddress.hxx" #include "io/Logger.hxx" #include "http/Date.hxx" #include "http/PHeaderUtil.hxx" #include "http/PList.hxx" #include "util/StringView.hxx" #include "util/IterableSplitString.hxx" #include "AllocatorPtr.hxx" #include <stdlib.h> /* check whether the request could produce a cacheable response */ std::optional<HttpCacheRequestInfo> http_cache_request_evaluate(http_method_t method, const ResourceAddress &address, const StringMap &headers, bool obey_no_cache, bool has_request_body) noexcept { if (method != HTTP_METHOD_GET || has_request_body) /* RFC 2616 13.11 "Write-Through Mandatory" */ return std::nullopt; if (headers.Contains("range")) return std::nullopt; /* RFC 2616 14.8: "When a shared cache receives a request containing an Authorization field, it MUST NOT return the corresponding response as a reply to any other request [...] */ if (headers.Get("authorization") != nullptr) return std::nullopt; bool only_if_cached = false; if (const char *cache_control = headers.Get("cache-control")) { for (auto s : IterableSplitString(cache_control, ',')) { s.Strip(); if (obey_no_cache && (s.Equals("no-cache") || s.Equals("no-store"))) return std::nullopt; if (s.Equals("only-if-cached")) only_if_cached = true; } } else if (obey_no_cache) { if (const char *pragma = headers.Get("pragma"); pragma != nullptr && strcmp(pragma, "no-cache") == 0) return std::nullopt; } HttpCacheRequestInfo info; info.is_remote = address.type == ResourceAddress::Type::HTTP; info.only_if_cached = only_if_cached; info.has_query_string = address.HasQueryString(); info.if_match = headers.Get("if-match"); info.if_none_match = headers.Get("if-none-match"); info.if_modified_since = headers.Get("if-modified-since"); info.if_unmodified_since = headers.Get("if-unmodified-since"); return info; } bool http_cache_vary_fits(const StringMap &vary, const StringMap &headers) noexcept { for (const auto &i : vary) { const char *value = headers.Get(i.key); if (value == nullptr) value = ""; if (strcmp(i.value, value) != 0) /* mismatch in one of the "Vary" request headers */ return false; } return true; } bool http_cache_vary_fits(const StringMap *vary, const StringMap &headers) noexcept { return vary == nullptr || http_cache_vary_fits(*vary, headers); } bool http_cache_request_invalidate(http_method_t method) noexcept { /* RFC 2616 13.10 "Invalidation After Updates or Deletions" */ return method == HTTP_METHOD_PUT || method == HTTP_METHOD_DELETE || method == HTTP_METHOD_POST; } [[gnu::pure]] static std::chrono::system_clock::time_point parse_translate_time(const char *p, std::chrono::system_clock::duration offset) noexcept { if (p == nullptr) return std::chrono::system_clock::from_time_t(-1); auto t = http_date_parse(p); if (t != std::chrono::system_clock::from_time_t(-1)) t += offset; return t; } /** * RFC 2616 13.4 */ static constexpr bool http_status_cacheable(http_status_t status) noexcept { return status == HTTP_STATUS_OK || status == HTTP_STATUS_NON_AUTHORITATIVE_INFORMATION || status == HTTP_STATUS_PARTIAL_CONTENT || status == HTTP_STATUS_MULTIPLE_CHOICES || status == HTTP_STATUS_MOVED_PERMANENTLY || status == HTTP_STATUS_GONE; } /** * Determine the difference between this host's real-time clock and * the server's clock. This is used to adjust the "Expires" time * stamp. * * @return the difference or min() if the server did not send a valid * "Date" header */ [[gnu::pure]] static std::chrono::system_clock::duration GetServerDateOffset(const HttpCacheRequestInfo &request_info, std::chrono::system_clock::time_point now, const StringMap &response_headers) noexcept { if (!request_info.is_remote) /* server is local (e.g. FastCGI); we don't need an offset */ return std::chrono::system_clock::duration::zero(); const auto server_date = GetServerDate(response_headers); if (server_date == std::chrono::system_clock::from_time_t(-1)) return std::chrono::system_clock::duration::min(); return now - server_date; } std::optional<HttpCacheResponseInfo> http_cache_response_evaluate(const HttpCacheRequestInfo &request_info, AllocatorPtr alloc, bool eager_cache, http_status_t status, const StringMap &headers, off_t body_available) noexcept { if (!http_status_cacheable(status)) return std::nullopt; if (body_available != (off_t)-1 && body_available > cacheable_size_limit) /* too large for the cache */ return std::nullopt; HttpCacheResponseInfo info; info.expires = std::chrono::system_clock::from_time_t(-1); if (const char *cache_control = headers.Get("cache-control")) { for (auto s : IterableSplitString(cache_control, ',')) { s.Strip(); if (s.StartsWith("private") || s.Equals("no-cache") || s.Equals("no-store")) return std::nullopt; if (s.StartsWith("max-age=")) { /* RFC 2616 14.9.3 */ char value[16]; int seconds; StringView param(s.data + 8, s.size - 8); if (param.size >= sizeof(value)) continue; memcpy(value, param.data, param.size); value[param.size] = 0; seconds = atoi(value); if (seconds > 0) info.expires = std::chrono::system_clock::now() + std::chrono::seconds(seconds); } } } const auto now = std::chrono::system_clock::now(); const auto offset = GetServerDateOffset(request_info, now, headers); if (offset == std::chrono::system_clock::duration::min()) /* we cannot determine whether to cache a resource if the server does not provide its system time */ return std::nullopt; if (info.expires == std::chrono::system_clock::from_time_t(-1)) { /* RFC 2616 14.9.3: "If a response includes both an Expires header and a max-age directive, the max-age directive overrides the Expires header" */ info.expires = parse_translate_time(headers.Get("expires"), offset); if (info.expires != std::chrono::system_clock::from_time_t(-1) && info.expires < now) LogConcat(4, "HttpCache", "invalid 'expires' header"); } if (request_info.has_query_string && !eager_cache && info.expires == std::chrono::system_clock::from_time_t(-1)) /* RFC 2616 13.9: "since some applications have traditionally used GETs and HEADs with query URLs (those containing a "?" in the rel_path part) to perform operations with significant side effects, caches MUST NOT treat responses to such URIs as fresh unless the server provides an explicit expiration time" */ return std::nullopt; info.last_modified = headers.Get("last-modified"); info.etag = headers.Get("etag"); info.vary = nullptr; const auto vary = headers.EqualRange("vary"); for (auto i = vary.first; i != vary.second; ++i) { const char *value = i->value; if (*value == 0) continue; if (strcmp(value, "*") == 0) /* RFC 2616 13.6: A Vary header field-value of "*" always fails to match and subsequent requests on that resource can only be properly interpreted by the origin server. */ return std::nullopt; if (info.vary == nullptr) info.vary = value; else info.vary = alloc.Concat(info.vary, ", ", value); } if (info.expires == std::chrono::system_clock::from_time_t(-1) && info.last_modified == nullptr && info.etag == nullptr) { if (eager_cache) // TODO info.expires = std::chrono::system_clock::now() + std::chrono::hours(1); else return std::nullopt; } return info; } void http_cache_copy_vary(StringMap &dest, AllocatorPtr alloc, const char *vary, const StringMap &request_headers) noexcept { for (const char *const*list = http_list_split(alloc, vary); *list != nullptr; ++list) { const char *name = *list; const char *value = request_headers.Get(name); if (value == nullptr) value = ""; else value = alloc.Dup(value); dest.Set(alloc, name, value); } } bool http_cache_prefer_cached(const HttpCacheDocument &document, const StringMap &response_headers) noexcept { if (document.info.etag == nullptr) return false; const char *etag = response_headers.Get("etag"); /* if the ETags are the same, then the resource hasn't changed, but the server was too lazy to check that properly */ return etag != nullptr && strcmp(etag, document.info.etag) == 0; } <|endoftext|>
<commit_before>#pragma once #include <string> #include <string_view> #include <type_traits> #include <utility> #include <gcl/cx/crc32_hash.hpp> // todo : move to cx namespace gcl::cx::typeinfo { // constexpr typeinfo that does not relies on __cpp_rtti // // Known limitations : // type_name : type aliases // ex : std::string // std::basic_string<char> // std::__cxx11::basic_string<char> // std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>> // // value_name : values representation // ex : int(42) // 0x2a ont MsVC/CL // use <charconv> std::to_chars into std::string_view for reliable basic numerical values template <typename T> static constexpr /*consteval*/ std::string_view type_name(/*no parameters allowed*/) { #if defined(__GNUC__) std::string_view str_view = __PRETTY_FUNCTION__; str_view.remove_prefix(str_view.find(__FUNCTION__) + sizeof(__FUNCTION__)); const char prefix[] = "T = "; str_view.remove_prefix(str_view.find(prefix) + sizeof(prefix) - 1); str_view.remove_suffix(str_view.length() - str_view.find_first_of(";]")); #elif defined(_MSC_VER) std::string_view str_view = __FUNCSIG__; str_view.remove_prefix(str_view.find(__func__) + sizeof(__func__)); if (auto enum_token_pos = str_view.find("enum "); enum_token_pos == 0) str_view.remove_prefix(enum_token_pos + sizeof("enum ") - 1); str_view.remove_suffix(str_view.length() - str_view.rfind(">(void)")); #else static_assert(false, "gcl::cx::typeinfo : unhandled plateform"); #endif return str_view; } template <typename T> static constexpr inline auto type_name_v = type_name<T>(); template <auto value> static constexpr std::string_view type_name(/*no parameters allowed*/) { return type_name<decltype(value)>(); } template <auto value> static constexpr std::string_view value_name(/*no parameters allowed*/) { #if defined(__GNUC__) std::string_view str_view = __PRETTY_FUNCTION__; str_view.remove_prefix(str_view.find(__FUNCTION__) + sizeof(__FUNCTION__)); const char prefix[] = "value = "; str_view.remove_prefix(str_view.find(prefix) + sizeof(prefix) - 1); str_view.remove_suffix(str_view.length() - str_view.find_first_of(";]")); #elif defined(_MSC_VER) std::string_view str_view = __FUNCSIG__; str_view.remove_prefix(str_view.find(__func__) + sizeof(__func__)); if (auto enum_token_pos = str_view.find("enum "); enum_token_pos == 0) str_view.remove_prefix(enum_token_pos + sizeof("enum ") - 1); str_view.remove_suffix(str_view.length() - str_view.rfind(">(void)")); #else static_assert(false, "gcl::cx::typeinfo : unhandled plateform"); #endif return str_view; } template <auto value> static constexpr inline auto value_name_v = value_name<value>(); template <typename T> static constexpr auto hashcode() { // as template<> struct hash<std::string_view>; is not consteval constexpr auto type_name = gcl::cx::typeinfo::type_name<T>(); return gcl::cx::crc_32::hash(type_name); } template <typename T> static constexpr inline auto hashcode_v = hashcode<T>(); } #include <gcl/mp/pack_traits.hpp> #include <array> namespace gcl::cx::typeinfo { template <typename Type> constexpr auto to_hashcode_array() { using type_arguments_as_tuple = typename gcl::mp::pack_traits<Type>::template arguments_as<std::tuple>; using index_type = std::make_index_sequence<std::tuple_size_v<type_arguments_as_tuple>>; constexpr auto generate_mapping_impl = []<typename TupleType, std::size_t... Index>(TupleType, std::index_sequence<Index...>) { static_assert(sizeof...(Index) == std::tuple_size_v<TupleType>); using hash_type = decltype(gcl::cx::typeinfo::hashcode_v<std::tuple_element_t<0, TupleType>>); using mapping_type = std::array<hash_type, sizeof...(Index)>; return mapping_type{gcl::cx::typeinfo::hashcode_v<std::tuple_element_t<Index, TupleType>>...}; }; return generate_mapping_impl(type_arguments_as_tuple{}, index_type{}); } } namespace gcl::cx::typeinfo::test { // basic type static_assert(gcl::cx::typeinfo::type_name<int(42)>() == "int"); #if defined(_MSC_VER) static_assert(gcl::cx::typeinfo::value_name<int(42)>() == "0x2a"); #else static_assert(gcl::cx::typeinfo::value_name<int(42)>() == "42"); #endif // namespace, scoped enum global_ns_colors : int { red, blue, yellow, orange, green, purple }; static_assert(gcl::cx::typeinfo::type_name<global_ns_colors::red>() == "gcl::cx::typeinfo::test::global_ns_colors"); static_assert(gcl::cx::typeinfo::value_name<global_ns_colors::red>() == "gcl::cx::typeinfo::test::red"); // to_hashcode_array template <typename ... Ts> struct type_with_variadic_type_parameters{}; using type = type_with_variadic_type_parameters<int, bool, float>; constexpr auto mapping = to_hashcode_array<type>(); static_assert(mapping[0] == gcl::cx::typeinfo::hashcode_v<int>); static_assert(mapping[1] == gcl::cx::typeinfo::hashcode_v<bool>); static_assert(mapping[2] == gcl::cx::typeinfo::hashcode_v<float>); }<commit_msg>[cx::typeinfo] add maybe_unused attributes to suppress warnings on gnuc compilers<commit_after>#pragma once #include <string> #include <string_view> #include <type_traits> #include <utility> #include <gcl/cx/crc32_hash.hpp> namespace gcl::cx::typeinfo { // constexpr typeinfo that does not relies on __cpp_rtti // // Known limitations : // type_name : type aliases // ex : std::string // std::basic_string<char> // std::__cxx11::basic_string<char> // std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>> // // value_name : values representation // ex : int(42) // 0x2a ont MsVC/CL // use <charconv> std::to_chars into std::string_view for reliable basic numerical values template <typename T> static constexpr /*consteval*/ std::string_view type_name(/*no parameters allowed*/) { #if defined(__GNUC__) std::string_view str_view = __PRETTY_FUNCTION__; str_view.remove_prefix(str_view.find(__FUNCTION__) + sizeof(__FUNCTION__)); const char prefix[] = "T = "; str_view.remove_prefix(str_view.find(prefix) + sizeof(prefix) - 1); str_view.remove_suffix(str_view.length() - str_view.find_first_of(";]")); #elif defined(_MSC_VER) std::string_view str_view = __FUNCSIG__; str_view.remove_prefix(str_view.find(__func__) + sizeof(__func__)); if (auto enum_token_pos = str_view.find("enum "); enum_token_pos == 0) str_view.remove_prefix(enum_token_pos + sizeof("enum ") - 1); str_view.remove_suffix(str_view.length() - str_view.rfind(">(void)")); #else static_assert(false, "gcl::cx::typeinfo : unhandled plateform"); #endif return str_view; } template <typename T> [[maybe_unused]] static constexpr inline auto type_name_v = type_name<T>(); template <auto value> static constexpr std::string_view type_name(/*no parameters allowed*/) { return type_name<decltype(value)>(); } template <auto value> static constexpr std::string_view value_name(/*no parameters allowed*/) { #if defined(__GNUC__) std::string_view str_view = __PRETTY_FUNCTION__; str_view.remove_prefix(str_view.find(__FUNCTION__) + sizeof(__FUNCTION__)); const char prefix[] = "value = "; str_view.remove_prefix(str_view.find(prefix) + sizeof(prefix) - 1); str_view.remove_suffix(str_view.length() - str_view.find_first_of(";]")); #elif defined(_MSC_VER) std::string_view str_view = __FUNCSIG__; str_view.remove_prefix(str_view.find(__func__) + sizeof(__func__)); if (auto enum_token_pos = str_view.find("enum "); enum_token_pos == 0) str_view.remove_prefix(enum_token_pos + sizeof("enum ") - 1); str_view.remove_suffix(str_view.length() - str_view.rfind(">(void)")); #else static_assert(false, "gcl::cx::typeinfo : unhandled plateform"); #endif return str_view; } template <auto value> [[maybe_unused]] static constexpr inline auto value_name_v = value_name<value>(); template <typename T> static constexpr auto hashcode() { // as template<> struct hash<std::string_view>; is not consteval constexpr auto type_name = gcl::cx::typeinfo::type_name<T>(); return gcl::cx::crc_32::hash(type_name); } template <typename T> [[maybe_unused]] static constexpr inline auto hashcode_v = hashcode<T>(); } #include <gcl/mp/pack_traits.hpp> #include <array> namespace gcl::cx::typeinfo { template <typename Type> constexpr auto to_hashcode_array() { using type_arguments_as_tuple = typename gcl::mp::pack_traits<Type>::template arguments_as<std::tuple>; using index_type = std::make_index_sequence<std::tuple_size_v<type_arguments_as_tuple>>; constexpr auto generate_mapping_impl = []<typename TupleType, std::size_t... Index>(TupleType, std::index_sequence<Index...>) { static_assert(sizeof...(Index) == std::tuple_size_v<TupleType>); using hash_type = decltype(gcl::cx::typeinfo::hashcode_v<std::tuple_element_t<0, TupleType>>); using mapping_type = std::array<hash_type, sizeof...(Index)>; return mapping_type{gcl::cx::typeinfo::hashcode_v<std::tuple_element_t<Index, TupleType>>...}; }; return generate_mapping_impl(type_arguments_as_tuple{}, index_type{}); } } namespace gcl::cx::typeinfo::test { // basic type static_assert(gcl::cx::typeinfo::type_name<int(42)>() == "int"); #if defined(_MSC_VER) static_assert(gcl::cx::typeinfo::value_name<int(42)>() == "0x2a"); #else static_assert(gcl::cx::typeinfo::value_name<int(42)>() == "42"); #endif // namespace, scoped enum global_ns_colors : int { red, blue, yellow, orange, green, purple }; static_assert(gcl::cx::typeinfo::type_name<global_ns_colors::red>() == "gcl::cx::typeinfo::test::global_ns_colors"); static_assert(gcl::cx::typeinfo::value_name<global_ns_colors::red>() == "gcl::cx::typeinfo::test::red"); // to_hashcode_array template <typename ... Ts> struct type_with_variadic_type_parameters{}; using type = type_with_variadic_type_parameters<int, bool, float>; constexpr auto mapping = to_hashcode_array<type>(); static_assert(mapping[0] == gcl::cx::typeinfo::hashcode_v<int>); static_assert(mapping[1] == gcl::cx::typeinfo::hashcode_v<bool>); static_assert(mapping[2] == gcl::cx::typeinfo::hashcode_v<float>); }<|endoftext|>
<commit_before>// Copyright (c) 2011, Cornell 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 HyperDex 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. #define __STDC_LIMIT_MACROS // Google Log #include <glog/logging.h> // HyperDex #include <hyperdex/city.h> #include <hyperdex/hyperspace.h> #include <hyperdex/region.h> hyperdex :: region :: region(const regionid& ri, const po6::pathname& directory, uint16_t nc) : m_ref(0) , m_numcolumns(nc) , m_point_mask(get_point_for(UINT64_MAX)) , m_log() , m_rwlock() , m_disks() { std::ostringstream ostr; ostr << ri; // Create one disk to start. It will split as necessary. // XXX Implement splitting. po6::pathname path = join(directory, ostr.str()); e::intrusive_ptr<disk> d = new disk(join(directory, ostr.str())); m_disks.push_back(std::make_pair(ri, d)); } hyperdex :: result_t hyperdex :: region :: get(const e::buffer& key, std::vector<e::buffer>* value, uint64_t* version) { log::iterator it(m_log.iterate()); bool found = false; *version = 0; // Scan the in-memory WAL. for (; it.valid(); it.next()) { if (it.key() == key) { if (it.op() == PUT) { *value = it.value(); *version = it.version(); } else if (it.op() == DEL) { *version = 0; } found = true; } } // We know that the log is a suffix of the linear ordering of all updates to // this region. If we found something in the log, it is *guaranteed* to be // more recent than anything on-disk, so we just return. In the uncommon // case this means that we'll not have to touch memory-mapped files. We // have to iterate this part of the log anyway so it's not a big deal to do // part of it before touching disk. if (found) { return *version == 0 ? NOTFOUND : SUCCESS; } std::vector<e::buffer> tmp_value; uint64_t tmp_version = 0; uint64_t key_hash = CityHash64(key); uint64_t key_point = get_point_for(key_hash); po6::threads::rwlock::rdhold hold(&m_rwlock); for (disk_vector::iterator i = m_disks.begin(); i != m_disks.end(); ++i) { uint64_t pmask = prefixmask(i->first.prefix); if ((i->first.mask & m_point_mask & pmask) != (key_point & pmask)) { continue; } result_t res = i->second->get(key, key_hash, &tmp_value, &tmp_version); if (res == SUCCESS) { if (tmp_version > *version) { value->swap(tmp_value); *version = tmp_version; } break; } else if (res != NOTFOUND) { return res; } } found = false; // Scan the in-memory WAL again. for (; it.valid(); it.next()) { if (it.key() == key) { if (it.op() == PUT) { *value = it.value(); *version = it.version(); } else if (it.op() == DEL) { *version = 0; } found = true; } } if (*version > 0 || found) { return SUCCESS; } else { return NOTFOUND; } } hyperdex :: result_t hyperdex :: region :: put(const e::buffer& key, const std::vector<e::buffer>& value, uint64_t version) { uint64_t key_hash = CityHash64(key); std::vector<uint64_t> value_hashes; get_value_hashes(value, &value_hashes); uint64_t point = get_point_for(key_hash, value_hashes); if (value.size() + 1 != m_numcolumns) { return INVALID; } else if (m_log.append(point, key, key_hash, value, value_hashes, version)) { return SUCCESS; } else { LOG(INFO) << "Could not append to in-memory WAL."; return ERROR; } } hyperdex :: result_t hyperdex :: region :: del(const e::buffer& key) { uint64_t key_hash = CityHash64(key); uint64_t point = get_point_for(key_hash); if (m_log.append(point, key, key_hash)) { return SUCCESS; } else { LOG(INFO) << "Could not append to in-memory WAL."; return ERROR; } } size_t hyperdex :: region :: flush() { using std::tr1::placeholders::_1; using std::tr1::placeholders::_2; using std::tr1::placeholders::_3; using std::tr1::placeholders::_4; using std::tr1::placeholders::_5; using std::tr1::placeholders::_6; using std::tr1::placeholders::_7; return m_log.flush(std::tr1::bind(&region::flush_one, this, _1, _2, _3, _4, _5, _6, _7)); } void hyperdex :: region :: flush_one(op_t op, uint64_t point, const e::buffer& key, uint64_t key_hash, const std::vector<e::buffer>& value, const std::vector<uint64_t>& value_hashes, uint64_t version) { // XXX to prevent excessive failures, we should probably add some logic here // to block until a split occurs to resolve disk space issues. // Delete from every disk po6::threads::rwlock::rdhold hold(&m_rwlock); for (disk_vector::iterator i = m_disks.begin(); i != m_disks.end(); ++i) { // Use m_point_mask because we want every disk which could have this // key. uint64_t pmask = prefixmask(i->first.prefix) & m_point_mask; if ((i->first.mask & pmask) != (point & pmask)) { continue; } result_t res = i->second->del(key, key_hash); if (res != SUCCESS && res != NOTFOUND) { // XXX FAIL DISK LOG(INFO) << "Disk has failed."; } } // Put to one disk if (op == PUT) { for (disk_vector::iterator i = m_disks.begin(); i != m_disks.end(); ++i) { uint64_t pmask = prefixmask(i->first.prefix); if ((i->first.mask & pmask) != (point & pmask)) { continue; } result_t res = i->second->put(key, key_hash, value, value_hashes, version); if (res != SUCCESS) { // XXX FAIL DISK LOG(INFO) << "Disk has failed."; } } } } void hyperdex :: region :: async() { po6::threads::rwlock::rdhold hold(&m_rwlock); for (disk_vector::iterator i = m_disks.begin(); i != m_disks.end(); ++i) { i->second->async(); } } void hyperdex :: region :: sync() { po6::threads::rwlock::rdhold hold(&m_rwlock); for (disk_vector::iterator i = m_disks.begin(); i != m_disks.end(); ++i) { i->second->sync(); } } void hyperdex :: region :: get_value_hashes(const std::vector<e::buffer>& value, std::vector<uint64_t>* value_hashes) { for (size_t i = 0; i < value.size(); ++i) { value_hashes->push_back(CityHash64(value[i])); } } uint64_t hyperdex :: region :: get_point_for(uint64_t key_hash) { std::vector<uint64_t> points; points.push_back(key_hash); for (size_t i = 0; i < m_numcolumns; ++i) { points.push_back(0); } return interlace(points); } uint64_t hyperdex :: region :: get_point_for(uint64_t key_hash, const std::vector<uint64_t>& value_hashes) { std::vector<uint64_t> points; points.push_back(key_hash); for (size_t i = 0; i < value_hashes.size(); ++i) { points.push_back(value_hashes[i]); } return interlace(points); } <commit_msg>get_point_for(key) was broken.<commit_after>// Copyright (c) 2011, Cornell 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 HyperDex 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. #define __STDC_LIMIT_MACROS // Google Log #include <glog/logging.h> // HyperDex #include <hyperdex/city.h> #include <hyperdex/hyperspace.h> #include <hyperdex/region.h> hyperdex :: region :: region(const regionid& ri, const po6::pathname& directory, uint16_t nc) : m_ref(0) , m_numcolumns(nc) , m_point_mask(get_point_for(UINT64_MAX)) , m_log() , m_rwlock() , m_disks() { std::ostringstream ostr; ostr << ri; // Create one disk to start. It will split as necessary. // XXX Implement splitting. po6::pathname path = join(directory, ostr.str()); e::intrusive_ptr<disk> d = new disk(join(directory, ostr.str())); m_disks.push_back(std::make_pair(ri, d)); } hyperdex :: result_t hyperdex :: region :: get(const e::buffer& key, std::vector<e::buffer>* value, uint64_t* version) { log::iterator it(m_log.iterate()); bool found = false; *version = 0; // Scan the in-memory WAL. for (; it.valid(); it.next()) { if (it.key() == key) { if (it.op() == PUT) { *value = it.value(); *version = it.version(); } else if (it.op() == DEL) { *version = 0; } found = true; } } // We know that the log is a suffix of the linear ordering of all updates to // this region. If we found something in the log, it is *guaranteed* to be // more recent than anything on-disk, so we just return. In the uncommon // case this means that we'll not have to touch memory-mapped files. We // have to iterate this part of the log anyway so it's not a big deal to do // part of it before touching disk. if (found) { return *version == 0 ? NOTFOUND : SUCCESS; } std::vector<e::buffer> tmp_value; uint64_t tmp_version = 0; uint64_t key_hash = CityHash64(key); uint64_t key_point = get_point_for(key_hash); po6::threads::rwlock::rdhold hold(&m_rwlock); for (disk_vector::iterator i = m_disks.begin(); i != m_disks.end(); ++i) { uint64_t pmask = prefixmask(i->first.prefix); if ((i->first.mask & m_point_mask & pmask) != (key_point & pmask)) { continue; } result_t res = i->second->get(key, key_hash, &tmp_value, &tmp_version); if (res == SUCCESS) { if (tmp_version > *version) { value->swap(tmp_value); *version = tmp_version; } break; } else if (res != NOTFOUND) { return res; } } found = false; // Scan the in-memory WAL again. for (; it.valid(); it.next()) { if (it.key() == key) { if (it.op() == PUT) { *value = it.value(); *version = it.version(); } else if (it.op() == DEL) { *version = 0; } found = true; } } if (*version > 0 || found) { return SUCCESS; } else { return NOTFOUND; } } hyperdex :: result_t hyperdex :: region :: put(const e::buffer& key, const std::vector<e::buffer>& value, uint64_t version) { uint64_t key_hash = CityHash64(key); std::vector<uint64_t> value_hashes; get_value_hashes(value, &value_hashes); uint64_t point = get_point_for(key_hash, value_hashes); if (value.size() + 1 != m_numcolumns) { return INVALID; } else if (m_log.append(point, key, key_hash, value, value_hashes, version)) { return SUCCESS; } else { LOG(INFO) << "Could not append to in-memory WAL."; return ERROR; } } hyperdex :: result_t hyperdex :: region :: del(const e::buffer& key) { uint64_t key_hash = CityHash64(key); uint64_t point = get_point_for(key_hash); if (m_log.append(point, key, key_hash)) { return SUCCESS; } else { LOG(INFO) << "Could not append to in-memory WAL."; return ERROR; } } size_t hyperdex :: region :: flush() { using std::tr1::placeholders::_1; using std::tr1::placeholders::_2; using std::tr1::placeholders::_3; using std::tr1::placeholders::_4; using std::tr1::placeholders::_5; using std::tr1::placeholders::_6; using std::tr1::placeholders::_7; return m_log.flush(std::tr1::bind(&region::flush_one, this, _1, _2, _3, _4, _5, _6, _7)); } void hyperdex :: region :: flush_one(op_t op, uint64_t point, const e::buffer& key, uint64_t key_hash, const std::vector<e::buffer>& value, const std::vector<uint64_t>& value_hashes, uint64_t version) { // XXX to prevent excessive failures, we should probably add some logic here // to block until a split occurs to resolve disk space issues. // Delete from every disk po6::threads::rwlock::rdhold hold(&m_rwlock); for (disk_vector::iterator i = m_disks.begin(); i != m_disks.end(); ++i) { // Use m_point_mask because we want every disk which could have this // key. uint64_t pmask = prefixmask(i->first.prefix) & m_point_mask; if ((i->first.mask & pmask) != (point & pmask)) { continue; } result_t res = i->second->del(key, key_hash); if (res != SUCCESS && res != NOTFOUND) { // XXX FAIL DISK LOG(INFO) << "Disk has failed."; } } // Put to one disk if (op == PUT) { for (disk_vector::iterator i = m_disks.begin(); i != m_disks.end(); ++i) { uint64_t pmask = prefixmask(i->first.prefix); if ((i->first.mask & pmask) != (point & pmask)) { continue; } result_t res = i->second->put(key, key_hash, value, value_hashes, version); if (res != SUCCESS) { // XXX FAIL DISK LOG(INFO) << "Disk has failed."; } } } } void hyperdex :: region :: async() { po6::threads::rwlock::rdhold hold(&m_rwlock); for (disk_vector::iterator i = m_disks.begin(); i != m_disks.end(); ++i) { i->second->async(); } } void hyperdex :: region :: sync() { po6::threads::rwlock::rdhold hold(&m_rwlock); for (disk_vector::iterator i = m_disks.begin(); i != m_disks.end(); ++i) { i->second->sync(); } } void hyperdex :: region :: get_value_hashes(const std::vector<e::buffer>& value, std::vector<uint64_t>* value_hashes) { for (size_t i = 0; i < value.size(); ++i) { value_hashes->push_back(CityHash64(value[i])); } } uint64_t hyperdex :: region :: get_point_for(uint64_t key_hash) { std::vector<uint64_t> points; points.push_back(key_hash); for (size_t i = 1; i < m_numcolumns; ++i) { points.push_back(0); } return interlace(points); } uint64_t hyperdex :: region :: get_point_for(uint64_t key_hash, const std::vector<uint64_t>& value_hashes) { std::vector<uint64_t> points; points.push_back(key_hash); for (size_t i = 0; i < value_hashes.size(); ++i) { points.push_back(value_hashes[i]); } return interlace(points); } <|endoftext|>
<commit_before>#include <iostream> #include <sstream> #include <string> #include <vector> template<typename T = char> void print_binary(T src, const size_t & byte_size) { const char zerobit = 0; const char nonzerobit = 1; int bpos = 0; while(src != 0) { char buffer[byte_size] = { 0, }; for(bpos = byte_size - 1; bpos >= 0; --bpos) { buffer[bpos] = ((src % 2 == 0) ? zerobit : nonzerobit); src = src >> 1; } if(bpos < 0) bpos = 0; for(int i = 0; i < byte_size; ++i) { if(i != 0 && i % 4 == 0) printf(" "); printf("%d", buffer[i]); } //printf("(%d) ", bpos); printf(" "); } } int main(void) { typedef uint32_t CodewordType; typedef size_t SizeType; typedef std::pair<CodewordType, SizeType> CodewordPairType; typedef std::vector<CodewordPairType> CodewordListType; CodewordListType vin; do { CodewordType codeword; std::cout << "Codeword: "; std::cin >> codeword; SizeType size; std::cout << "Size: "; std::cin >> size; vin.push_back(std::make_pair(codeword, size)); } while(vin.size() < 5); std::cout << "Size of source: " << vin.size() << std::endl; std::ostringstream fout (std::ios::binary); { fout.clear(); fout.seekp(0, fout.beg); const SizeType buf_cnt_max = 8; const SizeType buf_size_max = 255; CodewordType buffer = 5; SizeType buf_cnt_blank = 3; while(vin.size() > 0) { CodewordPairType pair = vin.front(); vin.erase(vin.begin()); CodewordType codeword = pair.first; SizeType codeword_len = pair.second; while(codeword_len >= buf_cnt_blank) { { printf("[INP] %2x (%lu)\t: ", codeword, codeword_len); print_binary<uint32_t> (codeword, 8); printf("\n"); } buffer <<= buf_cnt_blank; buffer += (codeword >> (codeword_len - buf_cnt_blank)); codeword = codeword % (0x1 << codeword_len - buf_cnt_blank); codeword_len -= buf_cnt_blank; { printf("[BUF] %02x (%lu)\t: ", buffer, buf_cnt_blank); print_binary<uint32_t> (buffer, 8); printf("\n"); } fout.write((char *)&buffer, buf_cnt_max); buffer = 0; buf_cnt_blank = buf_cnt_max; } { printf("[INP] %2x (%lu)\t: ", codeword, codeword_len); print_binary<uint32_t> (codeword, 8); printf("\n"); } buffer <<= codeword_len; buffer += codeword; buf_cnt_blank -= codeword_len; } } CodewordPairType pair = vin.front(); vin.erase(vin.begin()); CodewordType codeword = pair.first; SizeType codeword_len = pair.second; while(codeword_len >= buf_cnt_blank) { { printf("[INP] %2x (%lu)\t: ", codeword, codeword_len); print_binary<uint32_t> (codeword, 8); printf("\n"); } buffer <<= buf_cnt_blank; buffer += (codeword >> (codeword_len - buf_cnt_blank)); codeword = codeword % (0x1 << codeword_len - buf_cnt_blank); codeword_len -= buf_cnt_blank; { printf("[BUF] %02x (%lu)\t: ", buffer, buf_cnt_blank); print_binary<uint32_t> (buffer, 8); printf("\n"); } fout.write((char *)&buffer, buf_cnt_max); buffer = 0; buf_cnt_blank = buf_cnt_max; } { printf("[INP] %2x (%lu)\t: ", codeword, codeword_len); print_binary<uint32_t> (codeword, 8); printf("\n"); } buffer <<= codeword_len; buffer += codeword; buf_cnt_blank -= codeword_len; { fout.clear(); fout.seekp(0, fout.end); std::cout << "Size of result: " << fout.tellp() << std::endl; } return 0; } <commit_msg>Finishing the demo_fstream<commit_after>#include <iostream> #include <sstream> #include <string> #include <queue> template<typename T = uint8_t> void print_binary(T src, const size_t & byte_size) { const uint8_t zerobit = 0; const uint8_t nonzerobit = 1; int bpos = 0; while(src != 0) { uint8_t buffer[byte_size] = { 0, }; for(bpos = byte_size - 1; bpos >= 0; --bpos) { buffer[bpos] = ((src % 2 == 0) ? zerobit : nonzerobit); src = src >> 1; } if(bpos < 0) bpos = 0; for(int i = 0; i < byte_size; ++i) { if(i != 0 && i % 4 == 0) printf(" "); printf("%d", buffer[i]); } //printf("(%d) ", bpos); printf(" "); } } int main(void) { typedef uint32_t CodewordType; typedef size_t SizeType; typedef std::pair<CodewordType, SizeType> CodewordPairType; typedef std::queue<CodewordPairType> CodewordListType; const SizeType byte_size = 32; const SizeType bufcharr_size = byte_size / 8; CodewordListType qin; do { CodewordType codeword; std::cout << "Codeword: "; std::cin >> codeword; SizeType size; std::cout << "Size: "; std::cin >> size; qin.push(std::make_pair(codeword, size)); } while(qin.size() < 5); std::cout << "Size of source: " << qin.size() << std::endl; std::ostringstream fout (std::ios::binary); { fout.clear(); fout.seekp(0, fout.beg); const SizeType bufstat_max = byte_size; SizeType bufstat_free = byte_size - 5; CodewordType buffer = 0x5; CodewordType codeword; SizeType codeword_len; while(qin.size() > 0) { codeword = qin.front().first; codeword_len = qin.front().second; qin.pop(); while(codeword_len >= bufstat_free) { { printf("[INP] %02x (%lu)\t: ", codeword, codeword_len); print_binary<CodewordType> (codeword, byte_size); printf("\n"); } buffer <<= bufstat_free; buffer += (codeword >> (codeword_len - bufstat_free)); codeword = codeword % (0x1 << codeword_len - bufstat_free); codeword_len -= bufstat_free; { printf("[BUF] %02x (%lu)\t: ", buffer, bufstat_free); print_binary<CodewordType> (buffer, byte_size); printf("\n"); } unsigned char bufcharr[bufcharr_size] = { 0, }; for(int i = bufcharr_size - 1; i >= 0; --i) { bufcharr[i] = buffer % (0x1 << 8); buffer >>= 8; } fout.write((char *)&bufcharr, sizeof(unsigned char) * bufcharr_size); buffer = 0; bufstat_free = bufstat_max; } { printf("[INP] %02x (%lu)\t: ", codeword, codeword_len); print_binary<CodewordType> (codeword, byte_size); printf("\n"); } buffer <<= codeword_len; buffer += codeword; bufstat_free -= codeword_len; } if(bufstat_free != bufstat_max) { buffer <<= bufstat_free; { printf("[BUF] %02x (%lu)\t: ", buffer, bufstat_free); print_binary<CodewordType> (buffer, byte_size); printf("\n"); } unsigned char bufcharr[bufcharr_size] = { 0, }; for(int i = bufcharr_size - 1; i >= 0; --i) { bufcharr[i] = buffer % (0x1 << 8); buffer >>= 8; } SizeType last_pos; for(last_pos = bufcharr_size - 1; last_pos > 0 && bufcharr[last_pos] == 0x0; --last_pos); fout.write((char *)&bufcharr, sizeof(unsigned char) * (last_pos + 1)); buffer = 0; bufstat_free = bufstat_max; } } { printf("[FIN] "); for(uint8_t ch : fout.str()) printf("%02x ", ch); printf("\n"); for(uint8_t ch : fout.str()) { printf(" %02x: ", ch); print_binary<CodewordType> (ch, bufcharr_size); printf("\n"); } } { fout.clear(); fout.seekp(0, fout.end); std::cout << "Size of result: " << fout.tellp() << std::endl; } return 0; } <|endoftext|>
<commit_before>/******************************************************************************\ * ___ __ * * /\_ \ __/\ \ * * \//\ \ /\_\ \ \____ ___ _____ _____ __ * * \ \ \ \/\ \ \ '__`\ /'___\/\ '__`\/\ '__`\ /'__`\ * * \_\ \_\ \ \ \ \L\ \/\ \__/\ \ \L\ \ \ \L\ \/\ \L\.\_ * * /\____\\ \_\ \_,__/\ \____\\ \ ,__/\ \ ,__/\ \__/.\_\ * * \/____/ \/_/\/___/ \/____/ \ \ \/ \ \ \/ \/__/\/_/ * * \ \_\ \ \_\ * * \/_/ \/_/ * * * * Copyright (C) 2011, 2012 * * Dominik Charousset <dominik.charousset@haw-hamburg.de> * * * * This file is part of libcppa. * * libcppa 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. * * * * libcppa 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 libcppa. If not, see <http://www.gnu.org/licenses/>. * \******************************************************************************/ #include <ios> #include <cstring> #include <errno.h> #include <iostream> #include "cppa/exception.hpp" #include "cppa/detail/fd_util.hpp" #include "cppa/detail/logging.hpp" #include "cppa/network/ipv4_io_stream.hpp" #ifdef CPPA_WINDOWS #else # include <netdb.h> # include <unistd.h> # include <sys/types.h> # include <sys/socket.h> # include <netinet/in.h> # include <netinet/tcp.h> #endif namespace cppa { namespace network { using namespace ::cppa::detail::fd_util; ipv4_io_stream::ipv4_io_stream(native_socket_type fd) : m_fd(fd) { } native_socket_type ipv4_io_stream::read_handle() const { return m_fd; } native_socket_type ipv4_io_stream::write_handle() const { return m_fd; } void ipv4_io_stream::read(void* vbuf, size_t len) { auto buf = reinterpret_cast<char*>(vbuf); size_t rd = 0; while (rd < len) { auto recv_result = ::recv(m_fd, buf + rd, len - rd, 0); handle_read_result(recv_result, true); if (recv_result > 0) { rd += static_cast<size_t>(recv_result); } if (rd < len) { fd_set rdset; FD_ZERO(&rdset); FD_SET(m_fd, &rdset); if (select(m_fd + 1, &rdset, nullptr, nullptr, nullptr) < 0) { throw network_error("select() failed"); } } } } size_t ipv4_io_stream::read_some(void* buf, size_t len) { auto recv_result = ::recv(m_fd, buf, len, 0); handle_read_result(recv_result, true); return (recv_result > 0) ? static_cast<size_t>(recv_result) : 0; } void ipv4_io_stream::write(const void* vbuf, size_t len) { auto buf = reinterpret_cast<const char*>(vbuf); size_t written = 0; while (written < len) { auto send_result = ::send(m_fd, buf + written, len - written, 0); handle_write_result(send_result, true); if (send_result > 0) { written += static_cast<size_t>(send_result); } if (written < len) { // block until socked is writable again fd_set wrset; FD_ZERO(&wrset); FD_SET(m_fd, &wrset); if (select(m_fd + 1, nullptr, &wrset, nullptr, nullptr) < 0) { throw network_error("select() failed"); } } } } size_t ipv4_io_stream::write_some(const void* buf, size_t len) { auto send_result = ::send(m_fd, buf, len, 0); handle_write_result(send_result, true); return static_cast<size_t>(send_result); } network::io_stream_ptr ipv4_io_stream::from_native_socket(native_socket_type fd) { tcp_nodelay(fd, true); nonblocking(fd, true); return new ipv4_io_stream(fd); } network::io_stream_ptr ipv4_io_stream::connect_to(const char* host, std::uint16_t port) { CPPA_LOG_INFO("try to connect to " << host << " on port " << port); struct sockaddr_in serv_addr; struct hostent* server; native_socket_type fd = socket(AF_INET, SOCK_STREAM, 0); if (fd == invalid_socket) { throw network_error("socket creation failed"); } server = gethostbyname(host); if (!server) { std::string errstr = "no such host: "; errstr += host; throw network_error(std::move(errstr)); } memset(&serv_addr, 0, sizeof(serv_addr)); serv_addr.sin_family = AF_INET; memmove(&serv_addr.sin_addr.s_addr, server->h_addr, server->h_length); serv_addr.sin_port = htons(port); if (connect(fd, (const sockaddr*) &serv_addr, sizeof(serv_addr)) != 0) { throw network_error("could not connect to host"); } tcp_nodelay(fd, true); nonblocking(fd, true); return new ipv4_io_stream(fd); } } } // namespace cppa::detail <commit_msg>fixed bug when compiling in debug mode<commit_after>/******************************************************************************\ * ___ __ * * /\_ \ __/\ \ * * \//\ \ /\_\ \ \____ ___ _____ _____ __ * * \ \ \ \/\ \ \ '__`\ /'___\/\ '__`\/\ '__`\ /'__`\ * * \_\ \_\ \ \ \ \L\ \/\ \__/\ \ \L\ \ \ \L\ \/\ \L\.\_ * * /\____\\ \_\ \_,__/\ \____\\ \ ,__/\ \ ,__/\ \__/.\_\ * * \/____/ \/_/\/___/ \/____/ \ \ \/ \ \ \/ \/__/\/_/ * * \ \_\ \ \_\ * * \/_/ \/_/ * * * * Copyright (C) 2011, 2012 * * Dominik Charousset <dominik.charousset@haw-hamburg.de> * * * * This file is part of libcppa. * * libcppa 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. * * * * libcppa 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 libcppa. If not, see <http://www.gnu.org/licenses/>. * \******************************************************************************/ #include <ios> #include <cstring> #include <errno.h> #include <iostream> #include "cppa/exception.hpp" #include "cppa/detail/fd_util.hpp" #include "cppa/detail/logging.hpp" #include "cppa/network/ipv4_io_stream.hpp" #ifdef CPPA_WINDOWS #else # include <netdb.h> # include <unistd.h> # include <sys/types.h> # include <sys/socket.h> # include <netinet/in.h> # include <netinet/tcp.h> #endif namespace cppa { namespace network { using namespace ::cppa::detail::fd_util; ipv4_io_stream::ipv4_io_stream(native_socket_type fd) : m_fd(fd) { } native_socket_type ipv4_io_stream::read_handle() const { return m_fd; } native_socket_type ipv4_io_stream::write_handle() const { return m_fd; } void ipv4_io_stream::read(void* vbuf, size_t len) { auto buf = reinterpret_cast<char*>(vbuf); size_t rd = 0; while (rd < len) { auto recv_result = ::recv(m_fd, buf + rd, len - rd, 0); handle_read_result(recv_result, true); if (recv_result > 0) { rd += static_cast<size_t>(recv_result); } if (rd < len) { fd_set rdset; FD_ZERO(&rdset); FD_SET(m_fd, &rdset); if (select(m_fd + 1, &rdset, nullptr, nullptr, nullptr) < 0) { throw network_error("select() failed"); } } } } size_t ipv4_io_stream::read_some(void* buf, size_t len) { auto recv_result = ::recv(m_fd, buf, len, 0); handle_read_result(recv_result, true); return (recv_result > 0) ? static_cast<size_t>(recv_result) : 0; } void ipv4_io_stream::write(const void* vbuf, size_t len) { auto buf = reinterpret_cast<const char*>(vbuf); size_t written = 0; while (written < len) { auto send_result = ::send(m_fd, buf + written, len - written, 0); handle_write_result(send_result, true); if (send_result > 0) { written += static_cast<size_t>(send_result); } if (written < len) { // block until socked is writable again fd_set wrset; FD_ZERO(&wrset); FD_SET(m_fd, &wrset); if (select(m_fd + 1, nullptr, &wrset, nullptr, nullptr) < 0) { throw network_error("select() failed"); } } } } size_t ipv4_io_stream::write_some(const void* buf, size_t len) { auto send_result = ::send(m_fd, buf, len, 0); handle_write_result(send_result, true); return static_cast<size_t>(send_result); } network::io_stream_ptr ipv4_io_stream::from_native_socket(native_socket_type fd) { tcp_nodelay(fd, true); nonblocking(fd, true); return new ipv4_io_stream(fd); } network::io_stream_ptr ipv4_io_stream::connect_to(const char* host, std::uint16_t port) { CPPA_LOGF_INFO("try to connect to " << host << " on port " << port); struct sockaddr_in serv_addr; struct hostent* server; native_socket_type fd = socket(AF_INET, SOCK_STREAM, 0); if (fd == invalid_socket) { throw network_error("socket creation failed"); } server = gethostbyname(host); if (!server) { std::string errstr = "no such host: "; errstr += host; throw network_error(std::move(errstr)); } memset(&serv_addr, 0, sizeof(serv_addr)); serv_addr.sin_family = AF_INET; memmove(&serv_addr.sin_addr.s_addr, server->h_addr, server->h_length); serv_addr.sin_port = htons(port); if (connect(fd, (const sockaddr*) &serv_addr, sizeof(serv_addr)) != 0) { throw network_error("could not connect to host"); } tcp_nodelay(fd, true); nonblocking(fd, true); return new ipv4_io_stream(fd); } } } // namespace cppa::detail <|endoftext|>
<commit_before> #include <cppunit/config/SourcePrefix.h> #include <cppunit/extensions/HelperMacros.h> // include examples. order matters! #include "../examples/silence.cpp" #include "../examples/workhorse.cpp" #include <lvtk/ext/urid.hpp> #include <lvtk/host/uri_directory.hpp> using TestFixutre = CPPUNIT_NS::TestFixture; class Registration : public TestFixutre { CPPUNIT_TEST_SUITE (Registration); CPPUNIT_TEST (two_descriptors); CPPUNIT_TEST (instantiation); CPPUNIT_TEST (missing_host_feature); CPPUNIT_TEST_SUITE_END(); protected: lvtk::URIDirectory urids; uint32_t urid_A; uint32_t urid_B; public: void setUp() { urid_A = urids.map ("https://dummy.org/A"); urid_B = urids.map ("https://dummy.org/B"); } protected: void two_descriptors() { CPPUNIT_ASSERT_EQUAL(lvtk::descriptors().size(), (size_t)2); } void instantiation() { const auto desc = lvtk::descriptors().front(); const LV2_Feature* features[] = { urids.get_map_feature(), urids.get_unmap_feature(), nullptr }; LV2_Handle handle = desc.instantiate (&desc, 44100.0, "/usr/local/lv2", features); CPPUNIT_ASSERT (handle != nullptr); desc.activate (handle); float buffer [64]; desc.connect_port (handle, 0, buffer); desc.run (handle, 64); desc.deactivate (handle); desc.cleanup (handle); } void missing_host_feature() { const auto& desc = lvtk::descriptors()[1]; const LV2_Feature* features[] = { nullptr }; LV2_Handle handle = desc.instantiate (&desc, 44100.0, "/usr/local/lv2", features); CPPUNIT_ASSERT (handle == nullptr); } }; CPPUNIT_TEST_SUITE_REGISTRATION(Registration); <commit_msg>check correct descriptors<commit_after> #include <cppunit/config/SourcePrefix.h> #include <cppunit/extensions/HelperMacros.h> // include examples. order matters! #include "../examples/silence.cpp" #include "../examples/workhorse.cpp" #include <lvtk/ext/urid.hpp> #include <lvtk/host/uri_directory.hpp> using TestFixutre = CPPUNIT_NS::TestFixture; class Registration : public TestFixutre { CPPUNIT_TEST_SUITE (Registration); CPPUNIT_TEST (two_descriptors); CPPUNIT_TEST (instantiation); CPPUNIT_TEST (missing_host_feature); CPPUNIT_TEST_SUITE_END(); protected: lvtk::URIDirectory urids; uint32_t urid_A; uint32_t urid_B; public: void setUp() { urid_A = urids.map ("https://dummy.org/A"); urid_B = urids.map ("https://dummy.org/B"); } protected: void two_descriptors() { CPPUNIT_ASSERT_EQUAL(lvtk::descriptors().size(), (size_t)2); CPPUNIT_ASSERT_EQUAL (strcmp (lvtk::descriptors()[0].URI, LVTK_SILENCE_URI), (int)0); CPPUNIT_ASSERT_EQUAL (strcmp (lvtk::descriptors()[1].URI, "http://lvtoolkit.org/plugins/workhorse"), (int)0); } void instantiation() { const auto desc = lvtk::descriptors().front(); const LV2_Feature* features[] = { urids.get_map_feature(), urids.get_unmap_feature(), nullptr }; LV2_Handle handle = desc.instantiate (&desc, 44100.0, "/usr/local/lv2", features); CPPUNIT_ASSERT (handle != nullptr); desc.activate (handle); float buffer [64]; desc.connect_port (handle, 0, buffer); desc.run (handle, 64); desc.deactivate (handle); desc.cleanup (handle); } void missing_host_feature() { const auto& desc = lvtk::descriptors()[1]; const LV2_Feature* features[] = { nullptr }; LV2_Handle handle = desc.instantiate (&desc, 44100.0, "/usr/local/lv2", features); CPPUNIT_ASSERT (handle == nullptr); } }; CPPUNIT_TEST_SUITE_REGISTRATION(Registration); <|endoftext|>
<commit_before>// Copyright (c) 2013 Joshua Beitler, Mirus contributors // 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 <cpu/isr.hpp> #include <sys/panic.hpp> extern "C" { void isr0(); void isr1(); void isr2(); void isr3(); void isr4(); void isr5(); void isr6(); void isr7(); void isr8(); void isr9(); void isr10(); void isr11(); void isr12(); void isr13(); void isr14(); void isr15(); void isr16(); void isr17(); void isr18(); void isr19(); void isr20(); void isr21(); void isr22(); void isr23(); void isr24(); void isr25(); void isr26(); void isr27(); void isr28(); void isr29(); void isr30(); void isr31(); } void mirus::isr::install() { using namespace mirus; idt::set_gate(0, (unsigned long)isr0, 0x08, 0x8E); idt::set_gate(1, (unsigned long)isr1, 0x08, 0x8E); idt::set_gate(2, (unsigned long)isr2, 0x08, 0x8E); idt::set_gate(3, (unsigned long)isr3, 0x08, 0x8E); idt::set_gate(4, (unsigned long)isr4, 0x08, 0x8E); idt::set_gate(5, (unsigned long)isr5, 0x08, 0x8E); idt::set_gate(6, (unsigned long)isr6, 0x08, 0x8E); idt::set_gate(7, (unsigned long)isr7, 0x08, 0x8E); idt::set_gate(8, (unsigned long)isr8, 0x08, 0x8E); idt::set_gate(9, (unsigned long)isr9, 0x08, 0x8E); idt::set_gate(10, (unsigned long)isr10, 0x08, 0x8E); idt::set_gate(11, (unsigned long)isr11, 0x08, 0x8E); idt::set_gate(12, (unsigned long)isr12, 0x08, 0x8E); idt::set_gate(13, (unsigned long)isr13, 0x08, 0x8E); idt::set_gate(14, (unsigned long)isr14, 0x08, 0x8E); idt::set_gate(15, (unsigned long)isr15, 0x08, 0x8E); idt::set_gate(16, (unsigned long)isr16, 0x08, 0x8E); idt::set_gate(17, (unsigned long)isr17, 0x08, 0x8E); idt::set_gate(18, (unsigned long)isr18, 0x08, 0x8E); idt::set_gate(19, (unsigned long)isr19, 0x08, 0x8E); idt::set_gate(20, (unsigned long)isr20, 0x08, 0x8E); idt::set_gate(21, (unsigned long)isr21, 0x08, 0x8E); idt::set_gate(22, (unsigned long)isr22, 0x08, 0x8E); idt::set_gate(23, (unsigned long)isr23, 0x08, 0x8E); idt::set_gate(24, (unsigned long)isr24, 0x08, 0x8E); idt::set_gate(25, (unsigned long)isr25, 0x08, 0x8E); idt::set_gate(26, (unsigned long)isr26, 0x08, 0x8E); idt::set_gate(27, (unsigned long)isr27, 0x08, 0x8E); idt::set_gate(28, (unsigned long)isr28, 0x08, 0x8E); idt::set_gate(29, (unsigned long)isr29, 0x08, 0x8E); idt::set_gate(30, (unsigned long)isr30, 0x08, 0x8E); idt::set_gate(31, (unsigned long)isr31, 0x08, 0x8E); } const char* exception_messages[] = { "Division By Zero", "Debug", "Non Maskable Interrupt", "Breakpoint", "Into Detected Overflow", "Out of Bounds", "Invalid Opcode", "No Coprocessor", "Double Fault", "Coprocessor Segment Overrun", "Bad TSS", "Segment Not Present", "Stack Fault", "General Protection Fault", "Page Fault", "Unknown Interrupt", "Coprocessor Fault", "Alignment Check", "Machine Check", "Reserved", "Reserved", "Reserved", "Reserved", "Reserved", "Reserved", "Reserved", "Reserved", "Reserved", "Reserved", "Reserved", "Reserved", "Reserved" }; void mirus::fault_handler(struct regs* r) { mirus::panic(r); }<commit_msg>Removed double exception_messages[]'<commit_after>// Copyright (c) 2013 Joshua Beitler, Mirus contributors // 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 <cpu/isr.hpp> #include <sys/panic.hpp> extern "C" { void isr0(); void isr1(); void isr2(); void isr3(); void isr4(); void isr5(); void isr6(); void isr7(); void isr8(); void isr9(); void isr10(); void isr11(); void isr12(); void isr13(); void isr14(); void isr15(); void isr16(); void isr17(); void isr18(); void isr19(); void isr20(); void isr21(); void isr22(); void isr23(); void isr24(); void isr25(); void isr26(); void isr27(); void isr28(); void isr29(); void isr30(); void isr31(); } void mirus::isr::install() { using namespace mirus; idt::set_gate(0, (unsigned long)isr0, 0x08, 0x8E); idt::set_gate(1, (unsigned long)isr1, 0x08, 0x8E); idt::set_gate(2, (unsigned long)isr2, 0x08, 0x8E); idt::set_gate(3, (unsigned long)isr3, 0x08, 0x8E); idt::set_gate(4, (unsigned long)isr4, 0x08, 0x8E); idt::set_gate(5, (unsigned long)isr5, 0x08, 0x8E); idt::set_gate(6, (unsigned long)isr6, 0x08, 0x8E); idt::set_gate(7, (unsigned long)isr7, 0x08, 0x8E); idt::set_gate(8, (unsigned long)isr8, 0x08, 0x8E); idt::set_gate(9, (unsigned long)isr9, 0x08, 0x8E); idt::set_gate(10, (unsigned long)isr10, 0x08, 0x8E); idt::set_gate(11, (unsigned long)isr11, 0x08, 0x8E); idt::set_gate(12, (unsigned long)isr12, 0x08, 0x8E); idt::set_gate(13, (unsigned long)isr13, 0x08, 0x8E); idt::set_gate(14, (unsigned long)isr14, 0x08, 0x8E); idt::set_gate(15, (unsigned long)isr15, 0x08, 0x8E); idt::set_gate(16, (unsigned long)isr16, 0x08, 0x8E); idt::set_gate(17, (unsigned long)isr17, 0x08, 0x8E); idt::set_gate(18, (unsigned long)isr18, 0x08, 0x8E); idt::set_gate(19, (unsigned long)isr19, 0x08, 0x8E); idt::set_gate(20, (unsigned long)isr20, 0x08, 0x8E); idt::set_gate(21, (unsigned long)isr21, 0x08, 0x8E); idt::set_gate(22, (unsigned long)isr22, 0x08, 0x8E); idt::set_gate(23, (unsigned long)isr23, 0x08, 0x8E); idt::set_gate(24, (unsigned long)isr24, 0x08, 0x8E); idt::set_gate(25, (unsigned long)isr25, 0x08, 0x8E); idt::set_gate(26, (unsigned long)isr26, 0x08, 0x8E); idt::set_gate(27, (unsigned long)isr27, 0x08, 0x8E); idt::set_gate(28, (unsigned long)isr28, 0x08, 0x8E); idt::set_gate(29, (unsigned long)isr29, 0x08, 0x8E); idt::set_gate(30, (unsigned long)isr30, 0x08, 0x8E); idt::set_gate(31, (unsigned long)isr31, 0x08, 0x8E); } void mirus::fault_handler(struct regs* r) { mirus::panic(r); }<|endoftext|>
<commit_before>// Copyright 2013-2015 Eric Schkufza, Rahul Sharma, Berkeley Churchill, Stefan Heule // // 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 <cstdlib> #include <stdint.h> extern void saxpy(uint32_t a, uint32_t* x, uint32_t* y, int i); int main(int argc, char** argv) { const auto itr = argc > 1 ? atoi(argv[1]) : 1024; const auto seed = argc > 2 ? atoi(argv[2]) : 0; srand(seed); for (auto i = 0; i < itr; ++i) { auto a = rand(); auto x = new uint32_t[16]; auto y = new uint32_t[16]; auto idx = 4 * (rand() % 4); for (auto j = 0; j < 4; ++j) { x[idx+j] = rand(); y[idx+j] = rand(); } saxpy(a, x, y, idx); } return 0; } <commit_msg>astyleee<commit_after>// Copyright 2013-2015 Eric Schkufza, Rahul Sharma, Berkeley Churchill, Stefan Heule // // 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 <cstdlib> #include <stdint.h> extern void saxpy(uint32_t a, uint32_t* x, uint32_t* y, int i); int main(int argc, char** argv) { const auto itr = argc > 1 ? atoi(argv[1]) : 1024; const auto seed = argc > 2 ? atoi(argv[2]) : 0; srand(seed); for (auto i = 0; i < itr; ++i) { auto a = rand(); auto x = new uint32_t[16]; auto y = new uint32_t[16]; auto idx = 4 * (rand() % 4); for (auto j = 0; j < 4; ++j) { x[idx+j] = rand(); y[idx+j] = rand(); } saxpy(a, x, y, idx); } return 0; } <|endoftext|>
<commit_before>#include "db_impl.h" #include <sstream> DBImpl::DBImpl(zlog::Log *log) : log_(log), cache_(this) { root_ = Node::Nil(); root_pos_ = 0; last_pos_ = 0; stop_ = false; // todo: enable/disable debug validate_rb_tree(root_); log_processor_ = std::thread(&DBImpl::process_log_entry, this); } int DB::Open(zlog::Log *log, bool create_if_empty, DB **db) { uint64_t tail; int ret = log->CheckTail(&tail); assert(ret == 0); // empty log if (tail == 0) { if (!create_if_empty) return -EINVAL; std::string blob; kvstore_proto::Intention intention; intention.set_snapshot(-1); assert(intention.IsInitialized()); assert(intention.SerializeToString(&blob)); ret = log->Append(blob, &tail); assert(ret == 0); assert(tail == 0); ret = log->CheckTail(&tail); assert(ret == 0); assert(tail == 1); } DBImpl *impl = new DBImpl(log); *db = impl; return 0; } DB::~DB() { } DBImpl::~DBImpl() { lock_.lock(); stop_ = true; log_cond_.notify_all(); lock_.unlock(); log_processor_.join(); } std::ostream& operator<<(std::ostream& out, const NodeRef& n) { out << "node(" << n.get() << "):" << n->key() << ": "; out << (n->red() ? "red " : "blk "); out << "fi " << n->field_index() << " "; out << "left=[p" << n->left.csn() << ",o" << n->left.offset() << ","; if (n->left.ref() == Node::Nil()) out << "nil"; else out << n->left.ref().get(); out << "] "; out << "right=[p" << n->right.csn() << ",o" << n->right.offset() << ","; if (n->right.ref() == Node::Nil()) out << "nil"; else out << n->right.ref().get(); out << "] "; return out; } std::ostream& operator<<(std::ostream& out, const kvstore_proto::NodePtr& p) { out << "[n" << p.nil() << ",s" << p.self() << ",p" << p.csn() << ",o" << p.off() << "]"; return out; } std::ostream& operator<<(std::ostream& out, const kvstore_proto::Node& n) { out << "key " << n.key() << " val " << n.val() << " "; out << (n.red() ? "red" : "blk") << " "; out << "left " << n.left() << " right " << n.right(); return out; } std::ostream& operator<<(std::ostream& out, const kvstore_proto::Intention& i) { out << "- intention tree_size = " << i.tree_size() << std::endl; for (int idx = 0; idx < i.tree_size(); idx++) { out << " " << idx << ": " << i.tree(idx) << std::endl; } return out; } uint64_t DBImpl::root_id_ = 928734; void DBImpl::write_dot_null(std::ostream& out, NodeRef node, uint64_t& nullcount) { nullcount++; out << "null" << nullcount << " [shape=point];" << std::endl; out << "\"" << node.get() << "\" -> " << "null" << nullcount << " [label=\"nil\"];" << std::endl; } void DBImpl::write_dot_node(std::ostream& out, NodeRef parent, NodePtr& child, const std::string& dir) { out << "\"" << parent.get() << "\":" << dir << " -> "; out << "\"" << child.ref().get() << "\""; out << " [label=\"" << child.csn() << ":" << child.offset() << "\"];" << std::endl; } void DBImpl::write_dot_recursive(std::ostream& out, uint64_t rid, NodeRef node, uint64_t& nullcount, bool scoped) { if (scoped && node->rid() != rid) return; out << "\"" << node.get() << "\" [" << "label=\"" << node->key() << "_" << node->val() << "\",style=filled," << "fillcolor=" << (node->red() ? "red" : "black,fontcolor=white") << "]" << std::endl; assert(node->left.ref() != nullptr); if (node->left.ref() == Node::Nil()) write_dot_null(out, node, nullcount); else { write_dot_node(out, node, node->left, "sw"); write_dot_recursive(out, rid, node->left.ref(), nullcount, scoped); } assert(node->right.ref() != nullptr); if (node->right.ref() == Node::Nil()) write_dot_null(out, node, nullcount); else { write_dot_node(out, node, node->right, "se"); write_dot_recursive(out, rid, node->right.ref(), nullcount, scoped); } } void DBImpl::_write_dot(std::ostream& out, NodeRef root, uint64_t& nullcount, bool scoped) { assert(root != nullptr); write_dot_recursive(out, root->rid(), root, nullcount, scoped); } void DBImpl::write_dot(std::ostream& out, bool scoped) { auto root = root_; uint64_t nullcount = 0; out << "digraph ptree {" << std::endl; _write_dot(out, root, nullcount, scoped); out << "}" << std::endl; } void DBImpl::write_dot_history(std::ostream& out, std::vector<Snapshot*>& snapshots) { uint64_t trees = 0; uint64_t nullcount = 0; out << "digraph ptree {" << std::endl; std::string prev_root = ""; for (auto it = snapshots.cbegin(); it != snapshots.end(); it++) { // build sub-graph label std::stringstream label; label << "label = \"root: " << (*it)->seq; for (const auto& s : (*it)->desc) label << "\n" << s; label << "\""; out << "subgraph cluster_" << trees++ << " {" << std::endl; if ((*it)->root == Node::Nil()) { out << "null" << ++nullcount << " [label=nil];" << std::endl; } else { _write_dot(out, (*it)->root, nullcount, true); } #if 0 if (prev_root != "") out << "\"" << prev_root << "\" -> \"" << it->root.get() << "\" [style=invis];" << std::endl; std::stringstream ss; ss << it->root.get(); prev_root = ss.str(); #endif out << label.str() << std::endl; out << "}" << std::endl; } out << "}" << std::endl; } void DBImpl::print_node(NodeRef node) { if (node == Node::Nil()) std::cout << "nil:" << (node->red() ? "r" : "b"); else std::cout << node->key() << ":" << (node->red() ? "r" : "b"); } void DBImpl::print_path(std::ostream& out, std::deque<NodeRef>& path) { out << "path: "; if (path.empty()) { out << "<empty>"; } else { out << "["; for (auto node : path) { if (node == Node::Nil()) out << "nil:" << (node->red() ? "r " : "b "); else out << node->key() << ":" << (node->red() ? "r " : "b "); } out << "]"; } out << std::endl; } /* * */ int DBImpl::_validate_rb_tree(const NodeRef root) { assert(root != nullptr); assert(root->read_only()); if (!root->read_only()) return 0; if (root == Node::Nil()) return 1; assert(root->left.ref()); assert(root->right.ref()); NodeRef ln = root->left.ref(); NodeRef rn = root->right.ref(); if (root->red() && (ln->red() || rn->red())) return 0; int lh = _validate_rb_tree(ln); int rh = _validate_rb_tree(rn); if ((ln != Node::Nil() && ln->key() >= root->key()) || (rn != Node::Nil() && rn->key() <= root->key())) return 0; if (lh != 0 && rh != 0 && lh != rh) return 0; if (lh != 0 && rh != 0) return root->red() ? lh : lh + 1; return 0; } void DBImpl::validate_rb_tree(NodeRef root) { assert(_validate_rb_tree(root) != 0); } Transaction *DBImpl::BeginTransaction() { std::lock_guard<std::mutex> l(lock_); return new TransactionImpl(this, root_, root_pos_, root_id_++); } void DBImpl::process_log_entry() { for (;;) { std::unique_lock<std::mutex> l(lock_); if (stop_) return; uint64_t tail; int ret = log_->CheckTail(&tail); assert(ret == 0); assert(last_pos_ < tail); if ((last_pos_ + 1) == tail) { log_cond_.wait(l); continue; // try again } // process log in strict serial order uint64_t next = last_pos_ + 1; assert(next < tail); // read and deserialize intention from log std::string i_snapshot; ret = log_->Read(next, &i_snapshot); assert(ret == 0); kvstore_proto::Intention i; assert(i.ParseFromString(i_snapshot)); assert(i.IsInitialized()); // meld-subset: only allow serial intentions if (i.snapshot() == -1) assert(next == 0); if (i.snapshot() != -1) assert(next > 0); if (i.snapshot() == (int64_t)last_pos_) { auto root = cache_.CacheIntention(i, next); validate_rb_tree(root); root_ = root; root_pos_ = next; root_desc_.clear(); for (int idx = 0; idx < i.description_size(); idx++) root_desc_.push_back(i.description(idx)); auto res = committed_.emplace(std::make_pair(next, true)); assert(res.second); } else { auto res = committed_.emplace(std::make_pair(next, false)); assert(res.second); } result_cv_.notify_all(); last_pos_ = next; } } bool DBImpl::CommitResult(uint64_t pos) { for (;;) { std::unique_lock<std::mutex> l(lock_); auto it = committed_.find(pos); if (it != committed_.end()) { bool ret = it->second; committed_.erase(it); return ret; } result_cv_.wait(l); } } <commit_msg>kvs: retry if position not available<commit_after>#include "db_impl.h" #include <sstream> DBImpl::DBImpl(zlog::Log *log) : log_(log), cache_(this) { root_ = Node::Nil(); root_pos_ = 0; last_pos_ = 0; stop_ = false; // todo: enable/disable debug validate_rb_tree(root_); log_processor_ = std::thread(&DBImpl::process_log_entry, this); } int DB::Open(zlog::Log *log, bool create_if_empty, DB **db) { uint64_t tail; int ret = log->CheckTail(&tail); assert(ret == 0); // empty log if (tail == 0) { if (!create_if_empty) return -EINVAL; std::string blob; kvstore_proto::Intention intention; intention.set_snapshot(-1); assert(intention.IsInitialized()); assert(intention.SerializeToString(&blob)); ret = log->Append(blob, &tail); assert(ret == 0); assert(tail == 0); ret = log->CheckTail(&tail); assert(ret == 0); assert(tail == 1); } DBImpl *impl = new DBImpl(log); *db = impl; return 0; } DB::~DB() { } DBImpl::~DBImpl() { lock_.lock(); stop_ = true; log_cond_.notify_all(); lock_.unlock(); log_processor_.join(); } std::ostream& operator<<(std::ostream& out, const NodeRef& n) { out << "node(" << n.get() << "):" << n->key() << ": "; out << (n->red() ? "red " : "blk "); out << "fi " << n->field_index() << " "; out << "left=[p" << n->left.csn() << ",o" << n->left.offset() << ","; if (n->left.ref() == Node::Nil()) out << "nil"; else out << n->left.ref().get(); out << "] "; out << "right=[p" << n->right.csn() << ",o" << n->right.offset() << ","; if (n->right.ref() == Node::Nil()) out << "nil"; else out << n->right.ref().get(); out << "] "; return out; } std::ostream& operator<<(std::ostream& out, const kvstore_proto::NodePtr& p) { out << "[n" << p.nil() << ",s" << p.self() << ",p" << p.csn() << ",o" << p.off() << "]"; return out; } std::ostream& operator<<(std::ostream& out, const kvstore_proto::Node& n) { out << "key " << n.key() << " val " << n.val() << " "; out << (n.red() ? "red" : "blk") << " "; out << "left " << n.left() << " right " << n.right(); return out; } std::ostream& operator<<(std::ostream& out, const kvstore_proto::Intention& i) { out << "- intention tree_size = " << i.tree_size() << std::endl; for (int idx = 0; idx < i.tree_size(); idx++) { out << " " << idx << ": " << i.tree(idx) << std::endl; } return out; } uint64_t DBImpl::root_id_ = 928734; void DBImpl::write_dot_null(std::ostream& out, NodeRef node, uint64_t& nullcount) { nullcount++; out << "null" << nullcount << " [shape=point];" << std::endl; out << "\"" << node.get() << "\" -> " << "null" << nullcount << " [label=\"nil\"];" << std::endl; } void DBImpl::write_dot_node(std::ostream& out, NodeRef parent, NodePtr& child, const std::string& dir) { out << "\"" << parent.get() << "\":" << dir << " -> "; out << "\"" << child.ref().get() << "\""; out << " [label=\"" << child.csn() << ":" << child.offset() << "\"];" << std::endl; } void DBImpl::write_dot_recursive(std::ostream& out, uint64_t rid, NodeRef node, uint64_t& nullcount, bool scoped) { if (scoped && node->rid() != rid) return; out << "\"" << node.get() << "\" [" << "label=\"" << node->key() << "_" << node->val() << "\",style=filled," << "fillcolor=" << (node->red() ? "red" : "black,fontcolor=white") << "]" << std::endl; assert(node->left.ref() != nullptr); if (node->left.ref() == Node::Nil()) write_dot_null(out, node, nullcount); else { write_dot_node(out, node, node->left, "sw"); write_dot_recursive(out, rid, node->left.ref(), nullcount, scoped); } assert(node->right.ref() != nullptr); if (node->right.ref() == Node::Nil()) write_dot_null(out, node, nullcount); else { write_dot_node(out, node, node->right, "se"); write_dot_recursive(out, rid, node->right.ref(), nullcount, scoped); } } void DBImpl::_write_dot(std::ostream& out, NodeRef root, uint64_t& nullcount, bool scoped) { assert(root != nullptr); write_dot_recursive(out, root->rid(), root, nullcount, scoped); } void DBImpl::write_dot(std::ostream& out, bool scoped) { auto root = root_; uint64_t nullcount = 0; out << "digraph ptree {" << std::endl; _write_dot(out, root, nullcount, scoped); out << "}" << std::endl; } void DBImpl::write_dot_history(std::ostream& out, std::vector<Snapshot*>& snapshots) { uint64_t trees = 0; uint64_t nullcount = 0; out << "digraph ptree {" << std::endl; std::string prev_root = ""; for (auto it = snapshots.cbegin(); it != snapshots.end(); it++) { // build sub-graph label std::stringstream label; label << "label = \"root: " << (*it)->seq; for (const auto& s : (*it)->desc) label << "\n" << s; label << "\""; out << "subgraph cluster_" << trees++ << " {" << std::endl; if ((*it)->root == Node::Nil()) { out << "null" << ++nullcount << " [label=nil];" << std::endl; } else { _write_dot(out, (*it)->root, nullcount, true); } #if 0 if (prev_root != "") out << "\"" << prev_root << "\" -> \"" << it->root.get() << "\" [style=invis];" << std::endl; std::stringstream ss; ss << it->root.get(); prev_root = ss.str(); #endif out << label.str() << std::endl; out << "}" << std::endl; } out << "}" << std::endl; } void DBImpl::print_node(NodeRef node) { if (node == Node::Nil()) std::cout << "nil:" << (node->red() ? "r" : "b"); else std::cout << node->key() << ":" << (node->red() ? "r" : "b"); } void DBImpl::print_path(std::ostream& out, std::deque<NodeRef>& path) { out << "path: "; if (path.empty()) { out << "<empty>"; } else { out << "["; for (auto node : path) { if (node == Node::Nil()) out << "nil:" << (node->red() ? "r " : "b "); else out << node->key() << ":" << (node->red() ? "r " : "b "); } out << "]"; } out << std::endl; } /* * */ int DBImpl::_validate_rb_tree(const NodeRef root) { assert(root != nullptr); assert(root->read_only()); if (!root->read_only()) return 0; if (root == Node::Nil()) return 1; assert(root->left.ref()); assert(root->right.ref()); NodeRef ln = root->left.ref(); NodeRef rn = root->right.ref(); if (root->red() && (ln->red() || rn->red())) return 0; int lh = _validate_rb_tree(ln); int rh = _validate_rb_tree(rn); if ((ln != Node::Nil() && ln->key() >= root->key()) || (rn != Node::Nil() && rn->key() <= root->key())) return 0; if (lh != 0 && rh != 0 && lh != rh) return 0; if (lh != 0 && rh != 0) return root->red() ? lh : lh + 1; return 0; } void DBImpl::validate_rb_tree(NodeRef root) { assert(_validate_rb_tree(root) != 0); } Transaction *DBImpl::BeginTransaction() { std::lock_guard<std::mutex> l(lock_); return new TransactionImpl(this, root_, root_pos_, root_id_++); } void DBImpl::process_log_entry() { for (;;) { std::unique_lock<std::mutex> l(lock_); if (stop_) return; uint64_t tail; int ret = log_->CheckTail(&tail); assert(ret == 0); assert(last_pos_ < tail); if ((last_pos_ + 1) == tail) { log_cond_.wait(l); continue; // try again } // process log in strict serial order uint64_t next = last_pos_ + 1; assert(next < tail); // read and deserialize intention from log std::string i_snapshot; ret = log_->Read(next, &i_snapshot); if (ret == -ENODEV) continue; assert(ret == 0); kvstore_proto::Intention i; assert(i.ParseFromString(i_snapshot)); assert(i.IsInitialized()); // meld-subset: only allow serial intentions if (i.snapshot() == -1) assert(next == 0); if (i.snapshot() != -1) assert(next > 0); if (i.snapshot() == (int64_t)last_pos_) { auto root = cache_.CacheIntention(i, next); validate_rb_tree(root); root_ = root; root_pos_ = next; root_desc_.clear(); for (int idx = 0; idx < i.description_size(); idx++) root_desc_.push_back(i.description(idx)); auto res = committed_.emplace(std::make_pair(next, true)); assert(res.second); } else { auto res = committed_.emplace(std::make_pair(next, false)); assert(res.second); } result_cv_.notify_all(); last_pos_ = next; } } bool DBImpl::CommitResult(uint64_t pos) { for (;;) { std::unique_lock<std::mutex> l(lock_); auto it = committed_.find(pos); if (it != committed_.end()) { bool ret = it->second; committed_.erase(it); return ret; } result_cv_.wait(l); } } <|endoftext|>
<commit_before>// Copyright 2011 Google 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. // // Author: jdtang@google.com (Jonathan Tang) #include "string_buffer.h" #include <stdlib.h> #include <string.h> #include "gtest/gtest.h" #include "test_utils.h" #include "util.h" namespace { #define INIT_GUMBO_STRING(varname, literal) \ GumboStringPiece varname = { literal, sizeof(literal) - 1 } class GumboStringBufferTest : public GumboTest { protected: GumboStringBufferTest() { gumbo_string_buffer_init(&parser_, &buffer_); } ~GumboStringBufferTest() { gumbo_string_buffer_destroy(&parser_, &buffer_); } void NullTerminateBuffer() { buffer_.data[buffer_.length++] = 0; } GumboStringBuffer buffer_; }; TEST_F(GumboStringBufferTest, Reserve) { gumbo_string_buffer_reserve(&parser_, 21, &buffer_); EXPECT_EQ(40, buffer_.capacity); strcpy(buffer_.data, "01234567890123456789"); buffer_.length = 20; NullTerminateBuffer(); EXPECT_EQ(21, buffer_.length); EXPECT_STREQ("01234567890123456789", buffer_.data); } TEST_F(GumboStringBufferTest, AppendString) { INIT_GUMBO_STRING(str, "01234567"); gumbo_string_buffer_append_string(&parser_, &str, &buffer_); NullTerminateBuffer(); EXPECT_STREQ("01234567", buffer_.data); } TEST_F(GumboStringBufferTest, AppendStringWithResize) { INIT_GUMBO_STRING(str, "01234567"); gumbo_string_buffer_append_string(&parser_, &str, &buffer_); gumbo_string_buffer_append_string(&parser_, &str, &buffer_); NullTerminateBuffer(); EXPECT_STREQ("0123456701234567", buffer_.data); } TEST_F(GumboStringBufferTest, AppendCodepoint_1Byte) { gumbo_string_buffer_append_codepoint(&parser_, 'a', &buffer_); NullTerminateBuffer(); EXPECT_STREQ("a", buffer_.data); } TEST_F(GumboStringBufferTest, AppendCodepoint_2Bytes) { gumbo_string_buffer_append_codepoint(&parser_, 0xE5, &buffer_); NullTerminateBuffer(); EXPECT_STREQ("\xC3\xA5", buffer_.data); } TEST_F(GumboStringBufferTest, AppendCodepoint_3Bytes) { gumbo_string_buffer_append_codepoint(&parser_, 0x39E7, &buffer_); NullTerminateBuffer(); EXPECT_STREQ("\xE3\xA7\xA7", buffer_.data); } TEST_F(GumboStringBufferTest, AppendCodepoint_4Bytes) { gumbo_string_buffer_append_codepoint(&parser_, 0x679E7, &buffer_); NullTerminateBuffer(); EXPECT_STREQ("\xF1\xA7\xA7\xA7", buffer_.data); } TEST_F(GumboStringBufferTest, ToString) { strcpy(buffer_.data, "012345"); buffer_.length = 7; char* dest = gumbo_string_buffer_to_string(&parser_, &buffer_); EXPECT_STREQ("012345", dest); gumbo_parser_deallocate(&parser_, dest); } } // namespace <commit_msg>Fix bug in StringBuffer tests that depends upon the default size of a stringbuffer (it fails if there are less than 7 characters available and doesn't explicitly reserve space).<commit_after>// Copyright 2011 Google 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. // // Author: jdtang@google.com (Jonathan Tang) #include "string_buffer.h" #include <stdlib.h> #include <string.h> #include "gtest/gtest.h" #include "test_utils.h" #include "util.h" namespace { #define INIT_GUMBO_STRING(varname, literal) \ GumboStringPiece varname = { literal, sizeof(literal) - 1 } class GumboStringBufferTest : public GumboTest { protected: GumboStringBufferTest() { gumbo_string_buffer_init(&parser_, &buffer_); } ~GumboStringBufferTest() { gumbo_string_buffer_destroy(&parser_, &buffer_); } void NullTerminateBuffer() { buffer_.data[buffer_.length++] = 0; } GumboStringBuffer buffer_; }; TEST_F(GumboStringBufferTest, Reserve) { gumbo_string_buffer_reserve(&parser_, 21, &buffer_); EXPECT_EQ(40, buffer_.capacity); strcpy(buffer_.data, "01234567890123456789"); buffer_.length = 20; NullTerminateBuffer(); EXPECT_EQ(21, buffer_.length); EXPECT_STREQ("01234567890123456789", buffer_.data); } TEST_F(GumboStringBufferTest, AppendString) { INIT_GUMBO_STRING(str, "01234567"); gumbo_string_buffer_append_string(&parser_, &str, &buffer_); NullTerminateBuffer(); EXPECT_STREQ("01234567", buffer_.data); } TEST_F(GumboStringBufferTest, AppendStringWithResize) { INIT_GUMBO_STRING(str, "01234567"); gumbo_string_buffer_append_string(&parser_, &str, &buffer_); gumbo_string_buffer_append_string(&parser_, &str, &buffer_); NullTerminateBuffer(); EXPECT_STREQ("0123456701234567", buffer_.data); } TEST_F(GumboStringBufferTest, AppendCodepoint_1Byte) { gumbo_string_buffer_append_codepoint(&parser_, 'a', &buffer_); NullTerminateBuffer(); EXPECT_STREQ("a", buffer_.data); } TEST_F(GumboStringBufferTest, AppendCodepoint_2Bytes) { gumbo_string_buffer_append_codepoint(&parser_, 0xE5, &buffer_); NullTerminateBuffer(); EXPECT_STREQ("\xC3\xA5", buffer_.data); } TEST_F(GumboStringBufferTest, AppendCodepoint_3Bytes) { gumbo_string_buffer_append_codepoint(&parser_, 0x39E7, &buffer_); NullTerminateBuffer(); EXPECT_STREQ("\xE3\xA7\xA7", buffer_.data); } TEST_F(GumboStringBufferTest, AppendCodepoint_4Bytes) { gumbo_string_buffer_append_codepoint(&parser_, 0x679E7, &buffer_); NullTerminateBuffer(); EXPECT_STREQ("\xF1\xA7\xA7\xA7", buffer_.data); } TEST_F(GumboStringBufferTest, ToString) { gumbo_string_buffer_reserve(&parser_, 8, &buffer_); strcpy(buffer_.data, "012345"); buffer_.length = 7; char* dest = gumbo_string_buffer_to_string(&parser_, &buffer_); EXPECT_STREQ("012345", dest); gumbo_parser_deallocate(&parser_, dest); } } // namespace <|endoftext|>
<commit_before>#include <stdio.h> #include <iostream> #include "log4cpp/Category.hh" #include "log4cpp/Appender.hh" #include "log4cpp/OstreamAppender.hh" #include "log4cpp/Layout.hh" #include "log4cpp/BasicLayout.hh" #include "log4cpp/Priority.hh" #include "log4cpp/NDC.hh" void testLogva(log4cpp::Category& category, log4cpp::Priority::Value priority, const char* stringFormat, ...) { va_list va; va_start(va, stringFormat); category.logva(priority, stringFormat, va); va_end(va); } /* end testLogva */ void testGetAppender(log4cpp::Category& category, log4cpp::Appender* appender, log4cpp::Appender* appender2, log4cpp::Appender& appender3) { // test getAppender() - should return one of the three appenders log4cpp::Appender *tmpAppender = category.getAppender(); if ((tmpAppender == appender) || (tmpAppender == appender2) || (tmpAppender == &appender3)) { std::cout << "tmpAppender == appender, appender2, appender2" << std::endl; } else { std::cout << "tmpAppender != appender, appender2, appender2" << std::endl; } /* end if-else */ // test getAppender(const std::string& name) const tmpAppender = category.getAppender("appender2"); if (tmpAppender == appender2) { std::cout << "tmpAppender == appender2" << std::endl; } else { std::cout << "tmpAppender != appender2" << std::endl; } /* end if-else */ tmpAppender = category.getAppender("appender3"); if (tmpAppender == &appender3) { std::cout << "tmpAppender == appender3" << std::endl; } else { std::cout << "tmpAppender != appender3" << std::endl; } /* end if-else */ } /* end testGetAppender() */ void testMultiAppenders() { log4cpp::Appender* appender = new log4cpp::OstreamAppender("appender", &std::cout); log4cpp::Appender* appender2 = new log4cpp::OstreamAppender("appender2", &std::cout); log4cpp::OstreamAppender appender3("appender3", &std::cout); log4cpp::Layout* layout = new log4cpp::BasicLayout(); log4cpp::Layout* layout2 = new log4cpp::BasicLayout(); log4cpp::Layout* layout3 = new log4cpp::BasicLayout(); appender->setLayout(layout); appender2->setLayout(layout2); appender3.setLayout(layout3); // add three appenders to root category log4cpp::Category& root = log4cpp::Category::getRoot(); root.setPriority(log4cpp::Priority::ERROR); // clear root's initial appender root.removeAllAppenders(); root.setAppender(appender); root.setAppender(appender2); root.setAppender(appender3); // dump a message - should see three on the screen std::cout << "You should see three lines of \"root error #1\"" << std::endl; root.error("root error #1"); std::cout << "Did you?" << std::endl; // get getAppender() changes on category with appenders std::cout << "You should see messages that tmpAppender == other appenders" << std::endl; testGetAppender(root, appender, appender2, appender3); std::cout << "Did you?" << std::endl; // add appender by reference to sub1 category log4cpp::Category& sub1 = log4cpp::Category::getInstance(std::string("sub1")); sub1.setAppender(appender3); // clear all appenders root.removeAllAppenders(); sub1.removeAllAppenders(); // dump a message - should not see it on the screen std::cout << "You should not see any lines of \"root error #2\"" << std::endl; root.error("root error #2"); std::cout << "Did you?" << std::endl; // get getAppender() changes on category with no appenders std::cout << "You should see messages that tmpAppender != other appenders" << std::endl; testGetAppender(root, appender, appender2, appender3); std::cout << "Did you?" << std::endl; // add three appenders to root category appender = new log4cpp::OstreamAppender("appender", &std::cout); appender2 = new log4cpp::OstreamAppender("appender2", &std::cout); root.setAppender(appender); root.setAppender(appender2); root.setAppender(appender3); // test removing valid and invalid root.removeAppender(appender); root.removeAppender(appender2); root.removeAppender(&appender3); } /* end testMultiAppenders() */ int main(int argc, char** argv) { testMultiAppenders(); log4cpp::Appender* appender = new log4cpp::OstreamAppender("default", &std::cout); log4cpp::Appender* appender2 = new log4cpp::OstreamAppender("default", &std::cout); log4cpp::Layout* layout = new log4cpp::BasicLayout(); log4cpp::Layout* layout2 = new log4cpp::BasicLayout(); appender->setLayout(layout); appender2->setLayout(layout2); log4cpp::Category& root = log4cpp::Category::getRoot(); root.setAppender(appender); root.setPriority(log4cpp::Priority::ERROR); log4cpp::Category& sub1 = log4cpp::Category::getInstance(std::string("sub1")); sub1.setAppender(appender2); sub1.setAdditivity(false); log4cpp::Category& sub2 = log4cpp::Category::getInstance(std::string("sub1.sub2")); std::cout << " root priority = " << root.getPriority() << std::endl; std::cout << " sub1 priority = " << sub1.getPriority() << std::endl; std::cout << " sub2 priority = " << sub2.getPriority() << std::endl; root.error("root error"); root.warn("root warn"); sub1.error("sub1 error"); sub1.warn("sub1 warn"); sub2.error("sub2 error"); sub2.warn("sub2 warn"); testLogva(root, log4cpp::Priority::EMERG, "This contains %d %s", 2, "variable arguments"); testLogva(root, log4cpp::Priority::ALERT, "This contains %d %s", 2, "variable arguments"); testLogva(root, log4cpp::Priority::CRIT, "This contains %d %s", 2, "variable arguments"); testLogva(root, log4cpp::Priority::ERROR, "This contains %d %s", 2, "variable arguments"); testLogva(root, log4cpp::Priority::WARN, "This contains %d %s", 2, "variable arguments"); testLogva(root, log4cpp::Priority::INFO, "This contains %d %s", 2, "variable arguments"); testLogva(root, log4cpp::Priority::NOTICE, "This contains %d %s", 2, "variable arguments"); testLogva(root, log4cpp::Priority::DEBUG, "This contains %d %s", 2, "variable arguments"); sub1.setPriority(log4cpp::Priority::INFO); std::cout << " root priority = " << root.getPriority() << std::endl; std::cout << " sub1 priority = " << sub1.getPriority() << std::endl; std::cout << " sub2 priority = " << sub2.getPriority() << std::endl; std::cout << "priority info" << std::endl; root.error("root error"); root.warn("root warn"); sub1.error("sub1 error"); sub1.warn("sub1 warn"); sub2.error("sub2 error"); sub2.warn("sub2 warn"); sub2.error("%s %s %d", "test", "vform", 123); sub2.warnStream() << "streamed warn"; sub2 << log4cpp::Priority::WARN << "warn2.." << "..warn3..value=" << 0 << log4cpp::CategoryStream::ENDLINE << "..warn4"; log4cpp::Category::shutdown(); return 0; } <commit_msg>rename appender 'default' to 'default2'.<commit_after>#include <stdio.h> #include <iostream> #include "log4cpp/Category.hh" #include "log4cpp/Appender.hh" #include "log4cpp/OstreamAppender.hh" #include "log4cpp/Layout.hh" #include "log4cpp/BasicLayout.hh" #include "log4cpp/Priority.hh" #include "log4cpp/NDC.hh" void testLogva(log4cpp::Category& category, log4cpp::Priority::Value priority, const char* stringFormat, ...) { va_list va; va_start(va, stringFormat); category.logva(priority, stringFormat, va); va_end(va); } /* end testLogva */ void testGetAppender(log4cpp::Category& category, log4cpp::Appender* appender, log4cpp::Appender* appender2, log4cpp::Appender& appender3) { // test getAppender() - should return one of the three appenders log4cpp::Appender *tmpAppender = category.getAppender(); if ((tmpAppender == appender) || (tmpAppender == appender2) || (tmpAppender == &appender3)) { std::cout << "tmpAppender == appender or appender2 or appender3" << std::endl; } else { std::cout << "tmpAppender != appender or appender2 or appender3" << std::endl; } /* end if-else */ // test getAppender(const std::string& name) const tmpAppender = category.getAppender("appender2"); if (tmpAppender == appender2) { std::cout << "tmpAppender == appender2" << std::endl; } else { std::cout << "tmpAppender != appender2" << std::endl; } /* end if-else */ tmpAppender = category.getAppender("appender3"); if (tmpAppender == &appender3) { std::cout << "tmpAppender == appender3" << std::endl; } else { std::cout << "tmpAppender != appender3" << std::endl; } /* end if-else */ } /* end testGetAppender() */ void testMultiAppenders() { log4cpp::Appender* appender = new log4cpp::OstreamAppender("appender", &std::cout); log4cpp::Appender* appender2 = new log4cpp::OstreamAppender("appender2", &std::cout); log4cpp::OstreamAppender appender3("appender3", &std::cout); log4cpp::Layout* layout = new log4cpp::BasicLayout(); log4cpp::Layout* layout2 = new log4cpp::BasicLayout(); log4cpp::Layout* layout3 = new log4cpp::BasicLayout(); appender->setLayout(layout); appender2->setLayout(layout2); appender3.setLayout(layout3); // add three appenders to root category log4cpp::Category& root = log4cpp::Category::getRoot(); root.setPriority(log4cpp::Priority::ERROR); // clear root's initial appender root.removeAllAppenders(); root.addAppender(appender); root.addAppender(appender2); root.addAppender(appender3); // dump a message - should see three on the screen std::cout << "You should see three lines of \"root error #1\"" << std::endl; root.error("root error #1"); std::cout << "Did you?" << std::endl; // get getAppender() changes on category with appenders std::cout << "You should see messages that tmpAppender == other appenders" << std::endl; testGetAppender(root, appender, appender2, appender3); std::cout << "Did you?" << std::endl; // add appender by reference to sub1 category log4cpp::Category& sub1 = log4cpp::Category::getInstance(std::string("sub1")); sub1.addAppender(appender3); // clear all appenders root.removeAllAppenders(); sub1.removeAllAppenders(); // dump a message - should not see it on the screen std::cout << "You should not see any lines of \"root error #2\"" << std::endl; root.error("root error #2"); std::cout << "Did you?" << std::endl; // get getAppender() changes on category with no appenders std::cout << "You should see messages that tmpAppender != other appenders" << std::endl; testGetAppender(root, appender, appender2, appender3); std::cout << "Did you?" << std::endl; // add three appenders to root category appender = new log4cpp::OstreamAppender("appender", &std::cout); appender2 = new log4cpp::OstreamAppender("appender2", &std::cout); root.addAppender(appender); root.addAppender(appender2); root.addAppender(appender3); // test removing valid and invalid root.removeAppender(appender); root.removeAppender(appender2); root.removeAppender(&appender3); } /* end testMultiAppenders() */ int main(int argc, char** argv) { testMultiAppenders(); log4cpp::Appender* appender = new log4cpp::OstreamAppender("default", &std::cout); log4cpp::Appender* appender2 = new log4cpp::OstreamAppender("default2", &std::cout); log4cpp::Layout* layout = new log4cpp::BasicLayout(); log4cpp::Layout* layout2 = new log4cpp::BasicLayout(); appender->setLayout(layout); appender2->setLayout(layout2); log4cpp::Category& root = log4cpp::Category::getRoot(); root.addAppender(appender); root.setPriority(log4cpp::Priority::ERROR); log4cpp::Category& sub1 = log4cpp::Category::getInstance(std::string("sub1")); sub1.addAppender(appender2); sub1.setAdditivity(false); log4cpp::Category& sub2 = log4cpp::Category::getInstance(std::string("sub1.sub2")); std::cout << " root priority = " << root.getPriority() << std::endl; std::cout << " sub1 priority = " << sub1.getPriority() << std::endl; std::cout << " sub2 priority = " << sub2.getPriority() << std::endl; root.error("root error"); root.warn("root warn"); sub1.error("sub1 error"); sub1.warn("sub1 warn"); sub2.error("sub2 error"); sub2.warn("sub2 warn"); testLogva(root, log4cpp::Priority::EMERG, "This contains %d %s", 2, "variable arguments"); testLogva(root, log4cpp::Priority::ALERT, "This contains %d %s", 2, "variable arguments"); testLogva(root, log4cpp::Priority::CRIT, "This contains %d %s", 2, "variable arguments"); testLogva(root, log4cpp::Priority::ERROR, "This contains %d %s", 2, "variable arguments"); testLogva(root, log4cpp::Priority::WARN, "This contains %d %s", 2, "variable arguments"); testLogva(root, log4cpp::Priority::INFO, "This contains %d %s", 2, "variable arguments"); testLogva(root, log4cpp::Priority::NOTICE, "This contains %d %s", 2, "variable arguments"); testLogva(root, log4cpp::Priority::DEBUG, "This contains %d %s", 2, "variable arguments"); sub1.setPriority(log4cpp::Priority::INFO); std::cout << " root priority = " << root.getPriority() << std::endl; std::cout << " sub1 priority = " << sub1.getPriority() << std::endl; std::cout << " sub2 priority = " << sub2.getPriority() << std::endl; std::cout << "priority info" << std::endl; root.error("root error"); root.warn("root warn"); sub1.error("sub1 error"); sub1.warn("sub1 warn"); sub2.error("sub2 error"); sub2.warn("sub2 warn"); sub2.error("%s %s %d", "test", "vform", 123); sub2.warnStream() << "streamed warn"; sub2 << log4cpp::Priority::WARN << "warn2.." << "..warn3..value=" << 0 << log4cpp::CategoryStream::ENDLINE << "..warn4"; log4cpp::Category::shutdown(); return 0; } <|endoftext|>
<commit_before>// // inpalprime.cpp // InPal // // Created by Bryan Triana on 6/21/16. // Copyright © 2016 Inverse Palindrome. All rights reserved. // #include "inpalprime.hpp" #include <cmath> #include <vector> #include <string> #include <algorithm> long long inpal::max_prime(long long n) { auto primes = prime_sieve(n); auto it = std::find(primes.rbegin(), primes.rend(), true); return primes.size()-std::distance(primes.rbegin(), it)-1; } long long inpal::count_primes(long long n) { auto primes = prime_sieve(n); return std::count(primes.begin(), primes.end(), true); } long double inpal::prime_density(long double h) { return count_primes(h)/h; } bool inpal::prime_test(long long p) { return p == max_prime(p); } bool inpal::twin_test(long long p) { auto primes = prime_sieve(p+2); return p!=2 && primes[primes.size()-3] && (primes[primes.size()-1] || primes[primes.size()-5]); } bool inpal::cousin_test(long long p) { auto primes = prime_sieve(p+4); return p!=2 && primes[primes.size()-5] && (primes[primes.size()-1] || primes[primes.size()-9]); } bool inpal::sexy_test(long long p) { auto primes = prime_sieve(p+6); return (p!=2 && p!=3) && primes[primes.size()-7] && (primes[primes.size()-1] || primes[primes.size()-13]); } long long inpal::max_palprime(long long n) { auto primes = prime_sieve(n); for(std::vector<bool>::size_type it=primes.size()-1; it!=1; it--) { if(primes[it] && pal_test(it)) { return it; } } return 0; } long long inpal::max_factor(long long f) { return factorizer(f).back(); } long long inpal::count_factors(long long f) { return factorizer(f).size(); } std::vector<bool> inpal::prime_sieve(long long m) { std::vector<bool> p_test(m+1, false); //defines square root of m unsigned long long root = ceil(sqrt(m)); //sieve axioms for(unsigned long long x=1; x<=root; x++) { for(long long y=1; y<=root; y++) { long long i=(4*x*x)+(y*y); if (i<=m && (i%12==1 || i%12==5)) { p_test[i].flip(); } i=(3*x*x)+(y*y); if(i<=m && i%12==7) { p_test[i].flip(); } i=(3*x*x)-(y*y); if(x>y && i<=m && i%12==11) { p_test[i].flip(); } } } //marks 2,3,5 and 7 as prime numbers p_test[2]=p_test[3]=p_test[5]=p_test[7]=true; //marks all multiples of primes as non primes for(long long r=5; r<=root; r++) { if((p_test[r])) { for(long long j=r*r; j<=m; j+=r*r) { p_test[j]=false; } } } return p_test; } std::vector<long long> inpal::factorizer(long long f) { std::vector<long long> p_fac; long long p = 2; //trial division while(p<=f) { while(f%p==0) { p_fac.push_back(p); f=f/p; } p+= p==2 ? 1 : 2; } return p_fac; } bool inpal::pal_test(long long n) { //converts n to a string std::string rev = std::to_string(n); //checks if the reverse of rev is equal to rev for(int i=0; i<rev.size()/2; i++) { if(rev[i]!=rev[rev.size()-1-i]) { return false; } } return true; } <commit_msg>Update inpalprime.cpp<commit_after>// // inpalprime.cpp // InPal // // Created by Bryan Triana on 6/21/16. // Copyright © 2016 Inverse Palindrome. All rights reserved. // #include "inpalprime.hpp" #include <cmath> #include <vector> #include <string> #include <algorithm> long long inpal::max_prime(long long n) { auto primes = prime_sieve(n); auto it = std::find(primes.rbegin(), primes.rend(), true); return primes.size()-std::distance(primes.rbegin(), it)-1; } long long inpal::count_primes(long long n) { auto primes = prime_sieve(n); return std::count(primes.begin(), primes.end(), true); } long double inpal::prime_density(long double h) { return count_primes(h)/h; } bool inpal::prime_test(long long p) { return p == max_prime(p); } bool inpal::twin_test(long long p) { auto primes = prime_sieve(p+2); return p!=2 && primes[primes.size()-3] && (primes[primes.size()-1] || primes[primes.size()-5]); } bool inpal::cousin_test(long long p) { auto primes = prime_sieve(p+4); return p!=2 && primes[primes.size()-5] && (primes[primes.size()-1] || primes[primes.size()-9]); } bool inpal::sexy_test(long long p) { auto primes = prime_sieve(p+6); return (p!=2 && p!=3) && primes[primes.size()-7] && (primes[primes.size()-1] || primes[primes.size()-13]); } long long inpal::max_palprime(long long n) { auto primes = prime_sieve(n); for(std::vector<bool>::size_type it=primes.size()-1; it!=1; it--) { if(primes[it] && pal_test(it)) { return it; } } return 0; } long long inpal::max_factor(long long f) { return factorizer(f).back(); } long long inpal::count_factors(long long f) { return factorizer(f).size(); } std::vector<bool> inpal::prime_sieve(long long m) { std::vector<bool> p_test(m+1, false); //defines square root of m unsigned long long root = ceil(sqrt(m)); //sieve axioms for(unsigned long long x=1; x<=root; x++) { for(long long y=1; y<=root; y++) { long long i=(4*x*x)+(y*y); if (i<=m && (i%12==1 || i%12==5)) { p_test[i].flip(); } i=(3*x*x)+(y*y); if(i<=m && i%12==7) { p_test[i].flip(); } i=(3*x*x)-(y*y); if(x>y && i<=m && i%12==11) { p_test[i].flip(); } } } //marks 2,3,5 and 7 as prime numbers p_test[2]=p_test[3]=p_test[5]=p_test[7]=true; //marks all multiples of primes as non primes for(long long r=5; r<=root; r++) { if((p_test[r])) { for(long long j=r*r; j<=m; j+=r*r) { p_test[j]=false; } } } return p_test; } std::vector<long long> inpal::factorizer(long long f) { std::vector<long long> p_fac; long long p = 2; //trial division while(p<=f) { while(f%p==0) { p_fac.push_back(p); f=f/p; } p+= p==2 ? 1 : 2; } return p_fac; } bool inpal::pal_test(long long n) { //converts n to a string std::string rev = std::to_string(n); //checks if the reverse of rev is equal to rev if(std::equal(rev.begin(), rev.begin()+rev.size()/2, rev.rbegin())) { return true; } return false; } <|endoftext|>
<commit_before>/** {%partial doc .%} */ NAN_METHOD({{ cppClassName }}::{{ cppFunctionName }}) { NanScope(); {%partial guardArguments .%} {%each argsInfo as arg %} {%if arg.isReturn %} {%if arg.shouldAlloc %} {{ arg.cType }}{{ arg.name }} = ({{ arg.cType }})malloc(sizeof({{ arg.cType|unPointer }})); {%else%} {{ arg.cType|unPointer }} {{ arg.name }} = {{ arg.cType|unPointer|defaultValue }}; {%endif%} {%endif%} {%endeach%} {%each argsInfo as arg %} {%partial convertFromV8 arg %} {%endeach%} {%if hasReturns %} {{ return.cType }} result = {%endif%}{{ cFunctionName }}( {%each argsInfo as arg %} {%if arg.isReturn %} {%if not arg.shouldAlloc %} & {%endif%} {%endif%} {%if arg.isSelf %} ObjectWrap::Unwrap<{{ arg.cppClassName }}>(args.This())->GetValue() {%elsif arg.isReturn %} {{ arg.name }} {%else%} from_{{ arg.name }} {%endif%} {%if not arg.lastArg %},{%endif%} {%endeach%} ); {%each argsInfo as arg %} {%if arg.isCppClassStringOrArray %} {%if arg.freeFunctionName %} {{ arg.freeFunctionName }}(from_{{ arg.name }}); {%else%} free((void *)from_{{ arg.name }}); {%endif%} {%endif%} {%endeach%} {%if return.isErrorCode %} if (result != GIT_OK) { {%each argsInfo as arg %} {%if arg.shouldAlloc %} free(<%= arg.name %>); {%endif%} {%endeach%} if (giterr_last()) { return NanThrowError(giterr_last()->message); } else { return NanThrowError("Unknown Error"); } } {%endif%} {%if not returns.length %} NanReturnUndefined(); {%else%} Handle<Value> to; {%if returns.length > 1 %} Handle<Object> toReturn = NanNew<Object>(); {%endif%} {%each returns as _return %} {%partial convertToV8 _return %} {%if returns.length > 1 %} toReturn->Set(NanNew<String>("{{ _return.jsNameOrName }}"), to); {%endif%} {%endeach%} {%if returns.length == 1 %} NanReturnValue(to); {%else%} NanReturnValue(toReturn); {%endif%} {%endif%} } <commit_msg>Fixed sync_function.cc calling convertFromV8 for returns and self vars<commit_after>/** {%partial doc .%} */ NAN_METHOD({{ cppClassName }}::{{ cppFunctionName }}) { NanScope(); {%partial guardArguments .%} {%each argsInfo as arg %} {%if arg.isReturn %} {%if arg.shouldAlloc %} {{ arg.cType }}{{ arg.name }} = ({{ arg.cType }})malloc(sizeof({{ arg.cType|unPointer }})); {%else%} {{ arg.cType|unPointer }} {{ arg.name }} = {{ arg.cType|unPointer|defaultValue }}; {%endif%} {%endif%} {%endeach%} {%each argsInfo as arg %} {%if not arg.isSelf %} {%if not arg.isReturn %} {%partial convertFromV8 arg %} {%endif%} {%endif%} {%endeach%} {%if hasReturns %} {{ return.cType }} result = {%endif%}{{ cFunctionName }}( {%each argsInfo as arg %} {%if arg.isReturn %} {%if not arg.shouldAlloc %} & {%endif%} {%endif%} {%if arg.isSelf %} ObjectWrap::Unwrap<{{ arg.cppClassName }}>(args.This())->GetValue() {%elsif arg.isReturn %} {{ arg.name }} {%else%} from_{{ arg.name }} {%endif%} {%if not arg.lastArg %},{%endif%} {%endeach%} ); {%each argsInfo as arg %} {%if arg.isCppClassStringOrArray %} {%if arg.freeFunctionName %} {{ arg.freeFunctionName }}(from_{{ arg.name }}); {%else%} free((void *)from_{{ arg.name }}); {%endif%} {%endif%} {%endeach%} {%if return.isErrorCode %} if (result != GIT_OK) { {%each argsInfo as arg %} {%if arg.shouldAlloc %} free(<%= arg.name %>); {%endif%} {%endeach%} if (giterr_last()) { return NanThrowError(giterr_last()->message); } else { return NanThrowError("Unknown Error"); } } {%endif%} {%if not returns.length %} NanReturnUndefined(); {%else%} Handle<Value> to; {%if returns.length > 1 %} Handle<Object> toReturn = NanNew<Object>(); {%endif%} {%each returns as _return %} {%partial convertToV8 _return %} {%if returns.length > 1 %} toReturn->Set(NanNew<String>("{{ _return.jsNameOrName }}"), to); {%endif%} {%endeach%} {%if returns.length == 1 %} NanReturnValue(to); {%else%} NanReturnValue(toReturn); {%endif%} {%endif%} } <|endoftext|>
<commit_before>#if defined(LINUX) #include "user/util.h" #include "types.h" #include <fcntl.h> #include <unistd.h> #include <assert.h> #include <sys/stat.h> #define O_CREATE O_CREAT #define xfork() fork() #define xexit() exit(EXIT_SUCCESS) #define xmkdir(pathname) mkdir((pathname), S_IWUSR|S_IRUSR); #define mtenable(x) do { } while(0) #define mtdisable(x) do { } while(0) #else #include "types.h" #include "stat.h" #include "user.h" #include "mtrace.h" #include "amd64.h" #include "fcntl.h" #define xfork() fork(0) #define xexit() exit() #define xmkdir(pathname) mkdir((pathname)) #endif static const bool pinit = true; enum { nfile = 10 }; enum { nlookup = 100 }; void bench(u32 tid, int nloop, const char* path) { char pn[MAXNAME]; if (pinit) setaffinity(tid); for (u32 x = 0; x < nloop; x++) { for (u32 i = 0; i < nfile; i++) { snprintf(pn, sizeof(pn), "%s/f:%d:%d", path, tid, i); int fd = open(pn, O_CREATE | O_RDWR); if (fd < 0) die("create failed\n"); close(fd); } for (u32 i = 0; i < nlookup; i++) { snprintf(pn, sizeof(pn), "%s/f:%d:%d", path, tid, (i % nfile)); int fd = open(pn, O_RDWR); if (fd < 0) die("open failed\n"); close(fd); } for (u32 i = 0; i < nfile; i++) { snprintf(pn, sizeof(pn), "%s/f:%d:%d", path, tid, i); if (unlink(pn) < 0) die("unlink failed\n"); } } xexit(); } int main(int ac, char** av) { const char* path; int nthread; int nloop; #ifdef HW_qemu nloop = 50; #else nloop = 1000; #endif path = "/dbx"; if (ac < 2) die("usage: %s nthreads [nloop] [path]", av[0]); nthread = atoi(av[1]); if (ac > 2) nloop = atoi(av[2]); if (ac > 3) path = av[3]; xmkdir(path); mtenable("xv6-dirbench"); u64 t0 = rdtsc(); for(u32 i = 0; i < nthread; i++) { int pid = xfork(); if (pid == 0) bench(i, nloop, path); else if (pid < 0) die("fork"); } for (u32 i = 0; i < nthread; i++) wait(); u64 t1 = rdtsc(); mtdisable("xv6-dirbench"); printf("dirbench: %lu\n", t1-t0); return 0; } <commit_msg>Linux dirbench fixes<commit_after>#if defined(LINUX) #include "user/util.h" #include "types.h" #include <fcntl.h> #include <unistd.h> #include <assert.h> #include <sys/stat.h> #include <sys/wait.h> #define O_CREATE O_CREAT #define xfork() fork() #define xexit() exit(EXIT_SUCCESS) static inline void xwait() { int status; if (wait(&status) < 0) edie("wait"); if (!WIFEXITED(status)) die("bad status %u", status); } #define xmkdir(pathname) mkdir((pathname), S_IWUSR|S_IRUSR); #define xcreat(name) open((name), O_CREATE, S_IRUSR|S_IWUSR) #define mtenable(x) do { } while(0) #define mtdisable(x) do { } while(0) #else #include "types.h" #include "stat.h" #include "user.h" #include "mtrace.h" #include "amd64.h" #include "fcntl.h" #define xfork() fork(0) #define xexit() exit() #define xmkdir(pathname) mkdir((pathname)) #define xcreat(name) open((name), O_CREATE) #define xwait() wait() #endif static const bool pinit = true; enum { nfile = 10 }; enum { nlookup = 100 }; void bench(u32 tid, int nloop, const char* path) { char pn[32]; if (pinit) setaffinity(tid); for (u32 x = 0; x < nloop; x++) { for (u32 i = 0; i < nfile; i++) { snprintf(pn, sizeof(pn), "%s/f:%d:%d", path, tid, i); int fd = xcreat(pn); if (fd < 0) die("create failed\n"); close(fd); } for (u32 i = 0; i < nlookup; i++) { snprintf(pn, sizeof(pn), "%s/f:%d:%d", path, tid, (i % nfile)); int fd = open(pn, O_RDWR); if (fd < 0) die("open failed %s", pn); close(fd); } for (u32 i = 0; i < nfile; i++) { snprintf(pn, sizeof(pn), "%s/f:%d:%d", path, tid, i); if (unlink(pn) < 0) die("unlink failed\n"); } } xexit(); } int main(int ac, char** av) { const char* path; int nthread; int nloop; #ifdef HW_qemu nloop = 50; #else nloop = 1000; #endif path = "/dbx"; if (ac < 2) die("usage: %s nthreads [nloop] [path]", av[0]); nthread = atoi(av[1]); if (ac > 2) nloop = atoi(av[2]); if (ac > 3) path = av[3]; xmkdir(path); mtenable("xv6-dirbench"); u64 t0 = rdtsc(); for(u32 i = 0; i < nthread; i++) { int pid = xfork(); if (pid == 0) bench(i, nloop, path); else if (pid < 0) die("fork"); } for (u32 i = 0; i < nthread; i++) xwait(); u64 t1 = rdtsc(); mtdisable("xv6-dirbench"); printf("dirbench: %lu\n", t1-t0); return 0; } <|endoftext|>
<commit_before>#include <QDebug> #include "FakeConnectionService.h" FakeConnectionService::FakeConnectionService() { } bool FakeConnectionService::isConnected() { qDebug() << "isConnected was Called"; return true; } void FakeConnectionService::connectDataSource(QString portName, int baudRate) { qDebug() << "connectDataSource with portname: " << portName << " and baud rate of " << baudRate; } void FakeConnectionService::disconnectDataSource() { qDebug() << "disconnectDataSource"; } void FakeConnectionService::emitSignalConnectionSucceeded() { emit connectionSucceeded(); } <commit_msg>resolved fakeconnectionservice<commit_after>#include <QDebug> #include "FakeConnectionService.h" FakeConnectionService::FakeConnectionService() { } bool FakeConnectionService::isConnected() { qDebug() << "isConnected was Called"; return true; } void FakeConnectionService::connectDataSource(QString portName, int baudRate) { qDebug() << "connectDataSource with portname: " << portName << " and baud rate of " << baudRate; } void FakeConnectionService::disconnectDataSource() { qDebug() << "disconnectDataSource"; } void FakeConnectionService::emitSignalConnectionSucceeded() { emit connectionSucceeded("Connected"); } <|endoftext|>
<commit_before>/*========================================================================= Program: Medical Imaging & Interaction Toolkit Module: $RCSfile$ Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "mitkGlobalInteraction.h" #include "mitkInteractionConst.h" #include "mitkEventMapper.h" #include "mitkEvent.h" #include "mitkInteractor.h" #include "mitkAction.h" #include <mitkStatusBar.h> #include <mitkPositionEvent.h> #include <vtkWorldPointPicker.h> #include <mitkOpenGLRenderer.h> //##ModelId=3EAD420E0088 mitk::GlobalInteraction::GlobalInteraction(const char * type) : StateMachine(type) { //build up the FocusManager m_FocusManager = new mitk::FocusManager(); m_InteractionDebugger = InteractionDebugger::New(); InteractionDebugger::Deactivate(); } inline mitk::StateEvent* GenerateEmptyStateEvent(int eventId) { mitk::Event *noEvent = new mitk::Event(NULL, mitk::Type_User, mitk::BS_NoButton, mitk::BS_NoButton, mitk::Key_none); mitk::StateEvent *stateEvent = new mitk::StateEvent(eventId, noEvent); return stateEvent; } void mitk::GlobalInteraction::AddListener(mitk::StateMachine* listener) { if ( std::find(m_ListenerList.begin(), m_ListenerList.end(),listener) == m_ListenerList.end() ) { m_ListenerList.push_back(listener); } } bool mitk::GlobalInteraction::RemoveListener(mitk::StateMachine* listener) { // Try find StateMachineListIter position = std::find(m_ListenerList.begin(), m_ListenerList.end(),listener); if (position == m_ListenerList.end()) return false; position = m_ListenerList.erase(position); return true; } void mitk::GlobalInteraction::AddInteractor(mitk::Interactor* interactor) { if ( std::find(m_InteractorList.begin(), m_InteractorList.end(),interactor) == m_InteractorList.end() ) { m_InteractorList.push_back(interactor); //if Interactor already selected, then add to selected list if (interactor->GetMode()==Interactor::SMSELECTED) m_SelectedList.push_back(interactor); } } bool mitk::GlobalInteraction::InteractorRegistered (mitk::Interactor* interactor) { if ( std::find(m_InteractorList.begin(), m_InteractorList.end(), interactor) == m_InteractorList.end() ) return false; else return true; } bool mitk::GlobalInteraction::ListenerRegistered (mitk::Interactor* interactor) { if ( std::find(m_ListenerList.begin(), m_ListenerList.end(), interactor) == m_ListenerList.end() ) return false; else return true; } bool mitk::GlobalInteraction::RemoveInteractor(mitk::Interactor* interactor) { InteractorListIter position = std::find(m_InteractorList.begin(), m_InteractorList.end(),interactor); if (position == m_InteractorList.end()) return false; position = m_InteractorList.erase(position); //ether in JurisdictionMap or in SelectedList position = std::find(m_SelectedList.begin(), m_SelectedList.end(),interactor); if (position != m_SelectedList.end()) position = m_SelectedList.erase(position); else { for (InteractorMapIter it = m_JurisdictionMap.begin(); it != m_JurisdictionMap.end(); it++) { if ((*it).second == interactor) { m_JurisdictionMap.erase(it); if (m_CurrentInteractorIter == it) m_CurrentInteractorIter == m_JurisdictionMap.end(); break; } } } return true; } void mitk::GlobalInteraction::InformListeners(mitk::StateEvent const* stateEvent) { for (StateMachineListIter it = m_ListenerList.begin(); it != m_ListenerList.end(); it++) { if((*it)!=NULL) (*it)->HandleEvent(stateEvent); } } bool mitk::GlobalInteraction::AskSelected(mitk::StateEvent const* stateEvent) { bool ok, oneOk; ok = false; InteractorListIter it = m_SelectedList.begin(); while ( it != m_SelectedList.end()) { if((*it)!=NULL && !m_SelectedList.empty()) { //Interactor are in Mode SELECTED or SUBSELECTED oneOk = (*it)->HandleEvent(stateEvent); //if one HandleEvent did succeed, then set returnvalue on true; if (oneOk) ok = true; //if mode changed, then erase from selectedList if ((*it)->GetMode()==Interactor::SMDESELECTED) { it = m_SelectedList.erase(it); } else { ++it; } } else ++it; } return ok; } void mitk::GlobalInteraction::FillJurisdictionMap(mitk::StateEvent const* stateEvent, float threshold) { for (InteractorListIter it = m_InteractorList.begin(); it != m_InteractorList.end(); it++) { if((*it)!=NULL) { //first ask for CalculateJurisdiction(..) and write it into the map if > 0 float value = (*it)->CalculateJurisdiction(stateEvent); if (value > threshold) { ///TODO: hier werden die gleichen IDs berschrieben! von map auf vector umndern! m_JurisdictionMap.insert(InteractorMap::value_type(value, (*it))); } } } //set the iterator to the first element to start stepping through interactors if (! m_JurisdictionMap.empty()) m_CurrentInteractorIter = m_JurisdictionMap.begin(); else m_CurrentInteractorIter = m_JurisdictionMap.end(); } void mitk::GlobalInteraction::AskCurrentInteractor(mitk::StateEvent const* stateEvent) { if (m_JurisdictionMap.empty()) return; bool handled = false; while ( m_CurrentInteractorIter != m_JurisdictionMap.end()&& !handled) { handled = (*m_CurrentInteractorIter).second->HandleEvent(stateEvent); //if after handling an event Interactor is in mode SELECTED or SUBSELECTED //then make sure, that this sub-/ selected interactor gets the next event if ( ((*m_CurrentInteractorIter).second->GetMode() == mitk::Interactor::SMSELECTED ) || ((*m_CurrentInteractorIter).second->GetMode() == mitk::Interactor::SMSUBSELECTED) ) { m_SelectedList.clear(); m_SelectedList.push_back((*m_CurrentInteractorIter).second); //clear the map cause we have found an selected interactor so we can directly take that interactor the next time m_JurisdictionMap.clear(); m_CurrentInteractorIter = m_JurisdictionMap.end(); } else //if the event could not be handled, then go to next interactor { if (!handled) m_CurrentInteractorIter++; //if at end, then loop to the begining /*if (m_CurrentInteractorIter == m_JurisdictionMap.end()) m_CurrentInteractorIter= m_JurisdictionMap.begin();*/ } } } bool mitk::GlobalInteraction::AddFocusElement(mitk::FocusManager::FocusElement* element) { return m_FocusManager->AddElement(element); } bool mitk::GlobalInteraction::RemoveFocusElement(mitk::FocusManager::FocusElement* element) { return m_FocusManager->RemoveElement(element); } const mitk::FocusManager::FocusElement* mitk::GlobalInteraction::GetFocus() { return m_FocusManager->GetFocused(); } bool mitk::GlobalInteraction::SetFocus(mitk::FocusManager::FocusElement* element) { return m_FocusManager->SetFocused(element); } mitk::FocusManager* mitk::GlobalInteraction::GetFocusManager() { return m_FocusManager; } //##ModelId=3E7F497F01AE bool mitk::GlobalInteraction::ExecuteAction(Action* action, mitk::StateEvent const* stateEvent) { bool ok = false; ok = false; switch (action->GetActionId()) { case AcDONOTHING: ok = true; break; case AcINFORMLISTENERS: InformListeners(stateEvent); ok = true; break; case AcASKINTERACTORS: if (! AskSelected(stateEvent))//no selected { //if m_JurisdictionMap is empty, then fill it. if (m_JurisdictionMap.empty()) FillJurisdictionMap(stateEvent, 0); //no jurisdiction value above 0 could be found, so take all to convert to old scheme if (m_JurisdictionMap.empty()) FillJurisdictionMap(stateEvent, -1); //ask the next Interactor to handle that event AskCurrentInteractor(stateEvent); //after asking for jurisdiction and sending the events to the interactors, //interactors should change the mode. We can now clear the jurisdictionmap. m_JurisdictionMap.clear(); } else { //checking if the selected one is still in Mode Subselected or selected //...//todo } ok = true; break; default: ok = true; } return ok; } #include <mitkStateMachineFactory.h> #include <mitkEventMapper.h> bool mitk::GlobalInteraction::StandardInteractionSetup(const char * XMLbehaviorFile) { bool result; // load interaction patterns from XML-file if(XMLbehaviorFile==NULL) result=mitk::StateMachineFactory::LoadStandardBehavior(); else result=mitk::StateMachineFactory::LoadBehavior(XMLbehaviorFile); if(result==false) return false; // load event-mappings from XML-file if(XMLbehaviorFile==NULL) result=mitk::EventMapper::LoadStandardBehavior(); else result=mitk::EventMapper::LoadBehavior(XMLbehaviorFile); if(result==false) return false; // setup interaction mechanism by creating GlobalInteraction and // registering it to EventMapper mitk::EventMapper::SetGlobalStateMachine(new mitk::GlobalInteraction("global")); return true; } mitk::GlobalInteraction* mitk::GlobalInteraction::GetGlobalInteraction() { return dynamic_cast<mitk::GlobalInteraction*>(mitk::EventMapper::GetGlobalStateMachine()); } <commit_msg>ENH: Major change in Interaction! Now Interactors aren't called anymore, if they don't send >0 from CalculateInteraction. Before, after no interactor could be found, all interactors were collected in the JurisdictionMap and the event was passed to the first in this list. Done because of the need of interaction of several PointSetInteractors. Documented what to do if interactors doesn't do their job anymore.<commit_after>/*========================================================================= Program: Medical Imaging & Interaction Toolkit Module: $RCSfile$ Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "mitkGlobalInteraction.h" #include "mitkInteractionConst.h" #include "mitkEventMapper.h" #include "mitkEvent.h" #include "mitkInteractor.h" #include "mitkAction.h" #include <mitkStatusBar.h> #include <mitkPositionEvent.h> #include <vtkWorldPointPicker.h> #include <mitkOpenGLRenderer.h> //##ModelId=3EAD420E0088 mitk::GlobalInteraction::GlobalInteraction(const char * type) : StateMachine(type) { //build up the FocusManager m_FocusManager = new mitk::FocusManager(); m_InteractionDebugger = InteractionDebugger::New(); InteractionDebugger::Deactivate(); } inline mitk::StateEvent* GenerateEmptyStateEvent(int eventId) { mitk::Event *noEvent = new mitk::Event(NULL, mitk::Type_User, mitk::BS_NoButton, mitk::BS_NoButton, mitk::Key_none); mitk::StateEvent *stateEvent = new mitk::StateEvent(eventId, noEvent); return stateEvent; } void mitk::GlobalInteraction::AddListener(mitk::StateMachine* listener) { if ( std::find(m_ListenerList.begin(), m_ListenerList.end(),listener) == m_ListenerList.end() ) { m_ListenerList.push_back(listener); } } bool mitk::GlobalInteraction::RemoveListener(mitk::StateMachine* listener) { // Try find StateMachineListIter position = std::find(m_ListenerList.begin(), m_ListenerList.end(),listener); if (position == m_ListenerList.end()) return false; position = m_ListenerList.erase(position); return true; } void mitk::GlobalInteraction::AddInteractor(mitk::Interactor* interactor) { if ( std::find(m_InteractorList.begin(), m_InteractorList.end(),interactor) == m_InteractorList.end() ) { m_InteractorList.push_back(interactor); //if Interactor already selected, then add to selected list if (interactor->GetMode()==Interactor::SMSELECTED) m_SelectedList.push_back(interactor); } } bool mitk::GlobalInteraction::InteractorRegistered (mitk::Interactor* interactor) { if ( std::find(m_InteractorList.begin(), m_InteractorList.end(), interactor) == m_InteractorList.end() ) return false; else return true; } bool mitk::GlobalInteraction::ListenerRegistered (mitk::Interactor* interactor) { if ( std::find(m_ListenerList.begin(), m_ListenerList.end(), interactor) == m_ListenerList.end() ) return false; else return true; } bool mitk::GlobalInteraction::RemoveInteractor(mitk::Interactor* interactor) { InteractorListIter position = std::find(m_InteractorList.begin(), m_InteractorList.end(),interactor); if (position == m_InteractorList.end()) return false; position = m_InteractorList.erase(position); //ether in JurisdictionMap or in SelectedList position = std::find(m_SelectedList.begin(), m_SelectedList.end(),interactor); if (position != m_SelectedList.end()) position = m_SelectedList.erase(position); else { for (InteractorMapIter it = m_JurisdictionMap.begin(); it != m_JurisdictionMap.end(); it++) { if ((*it).second == interactor) { m_JurisdictionMap.erase(it); if (m_CurrentInteractorIter == it) m_CurrentInteractorIter == m_JurisdictionMap.end(); break; } } } return true; } void mitk::GlobalInteraction::InformListeners(mitk::StateEvent const* stateEvent) { for (StateMachineListIter it = m_ListenerList.begin(); it != m_ListenerList.end(); it++) { if((*it)!=NULL) (*it)->HandleEvent(stateEvent); } } bool mitk::GlobalInteraction::AskSelected(mitk::StateEvent const* stateEvent) { bool ok, oneOk; ok = false; InteractorListIter it = m_SelectedList.begin(); while ( it != m_SelectedList.end()) { if((*it)!=NULL && !m_SelectedList.empty()) { //Interactor are in Mode SELECTED or SUBSELECTED oneOk = (*it)->HandleEvent(stateEvent); //if one HandleEvent did succeed, then set returnvalue on true; if (oneOk) ok = true; //if mode changed, then erase from selectedList if ((*it)->GetMode()==Interactor::SMDESELECTED) { it = m_SelectedList.erase(it); } else { ++it; } } else ++it; } return ok; } void mitk::GlobalInteraction::FillJurisdictionMap(mitk::StateEvent const* stateEvent, float threshold) { for (InteractorListIter it = m_InteractorList.begin(); it != m_InteractorList.end(); it++) { if((*it)!=NULL) { //first ask for CalculateJurisdiction(..) and write it into the map if > 0 float value = (*it)->CalculateJurisdiction(stateEvent); if (value > threshold) { ///TODO: hier werden die gleichen IDs berschrieben! von map auf vector umndern! m_JurisdictionMap.insert(InteractorMap::value_type(value, (*it))); } } } //set the iterator to the first element to start stepping through interactors if (! m_JurisdictionMap.empty()) m_CurrentInteractorIter = m_JurisdictionMap.begin(); else m_CurrentInteractorIter = m_JurisdictionMap.end(); } /* * Go through the list of interactors, that could possibly handle an event and ask if it has handled the event. * If an interactor has handled an event, then it gets set as an selected Interactor (m_SelectedInteractors) */ void mitk::GlobalInteraction::AskCurrentInteractor(mitk::StateEvent const* stateEvent) { if (m_JurisdictionMap.empty()) return; bool handled = false; while ( m_CurrentInteractorIter != m_JurisdictionMap.end()&& !handled) { handled = (*m_CurrentInteractorIter).second->HandleEvent(stateEvent); //if after handling an event Interactor is in mode SELECTED or SUBSELECTED //then make sure, that this sub-/ selected interactor gets the next event if ( ((*m_CurrentInteractorIter).second->GetMode() == mitk::Interactor::SMSELECTED ) || ((*m_CurrentInteractorIter).second->GetMode() == mitk::Interactor::SMSUBSELECTED) ) { m_SelectedList.clear(); m_SelectedList.push_back((*m_CurrentInteractorIter).second); //clear the map cause we have found an selected interactor so we can directly take that interactor the next time m_JurisdictionMap.clear(); m_CurrentInteractorIter = m_JurisdictionMap.end(); } else //if the event could not be handled, then go to next interactor { if (!handled) m_CurrentInteractorIter++; //looping to the beginning would make a change.If the first couldn't handle it once, then a second try won't make a change! } } } bool mitk::GlobalInteraction::AddFocusElement(mitk::FocusManager::FocusElement* element) { return m_FocusManager->AddElement(element); } bool mitk::GlobalInteraction::RemoveFocusElement(mitk::FocusManager::FocusElement* element) { return m_FocusManager->RemoveElement(element); } const mitk::FocusManager::FocusElement* mitk::GlobalInteraction::GetFocus() { return m_FocusManager->GetFocused(); } bool mitk::GlobalInteraction::SetFocus(mitk::FocusManager::FocusElement* element) { return m_FocusManager->SetFocused(element); } mitk::FocusManager* mitk::GlobalInteraction::GetFocusManager() { return m_FocusManager; } //##ModelId=3E7F497F01AE bool mitk::GlobalInteraction::ExecuteAction(Action* action, mitk::StateEvent const* stateEvent) { bool ok = false; ok = false; switch (action->GetActionId()) { case AcDONOTHING: ok = true; break; case AcINFORMLISTENERS: InformListeners(stateEvent); ok = true; break; case AcASKINTERACTORS: if (! AskSelected(stateEvent))//no interactor selected anymore { //if m_JurisdictionMap is empty, then fill it. if (m_JurisdictionMap.empty()) FillJurisdictionMap(stateEvent, 0); /* * Commented out, because this is the old sceme to send events to all interactors. * If Interactors doesn't answer anymore, uncomment these two lines and send a message to ingmar. */ //no jurisdiction value above 0 could be found, so take all to convert to old scheme //that way only the first statemachine, that handles the interaction can get the event. /* if (m_JurisdictionMap.empty()) FillJurisdictionMap(stateEvent, -1); */ //ask the next Interactor to handle that event AskCurrentInteractor(stateEvent); //after asking for jurisdiction and sending the events to the interactors, //interactors should change the mode. We can now clear the jurisdictionmap. m_JurisdictionMap.clear(); } else { //checking if the selected one is still in Mode Subselected or selected //...//todo } ok = true; break; default: ok = true; } return ok; } #include <mitkStateMachineFactory.h> #include <mitkEventMapper.h> bool mitk::GlobalInteraction::StandardInteractionSetup(const char * XMLbehaviorFile) { bool result; // load interaction patterns from XML-file if(XMLbehaviorFile==NULL) result=mitk::StateMachineFactory::LoadStandardBehavior(); else result=mitk::StateMachineFactory::LoadBehavior(XMLbehaviorFile); if(result==false) return false; // load event-mappings from XML-file if(XMLbehaviorFile==NULL) result=mitk::EventMapper::LoadStandardBehavior(); else result=mitk::EventMapper::LoadBehavior(XMLbehaviorFile); if(result==false) return false; // setup interaction mechanism by creating GlobalInteraction and // registering it to EventMapper mitk::EventMapper::SetGlobalStateMachine(new mitk::GlobalInteraction("global")); return true; } mitk::GlobalInteraction* mitk::GlobalInteraction::GetGlobalInteraction() { return dynamic_cast<mitk::GlobalInteraction*>(mitk::EventMapper::GetGlobalStateMachine()); } <|endoftext|>
<commit_before>#include <sys/time.h> #include "xxHash/xxh3.h" #define WYHASH_EVIL_FAST #include "wyhash.h" #include <iostream> #include <fstream> #include <vector> using namespace std; #define _PADr_KAZE(x, n) ( ((x) << (n))>>(n) ) uint32_t FNV1A_Pippip_Yurii(const char *str, size_t wrdlen) { const uint32_t PRIME = 591798841; uint32_t hash32; uint64_t hash64 = 14695981039346656037ull; size_t Cycles, NDhead; if (wrdlen > 8) { Cycles = ((wrdlen - 1)>>4) + 1; NDhead = wrdlen - (Cycles<<3); for(; Cycles--; str += 8) { hash64 = ( hash64 ^ (*(uint64_t *)(str)) ) * PRIME; hash64 = ( hash64 ^ (*(uint64_t *)(str+NDhead)) ) * PRIME; } } else hash64 = ( hash64 ^ _PADr_KAZE(*(uint64_t *)(str+0), (8-wrdlen)<<3) ) * PRIME; hash32 = (uint32_t)(hash64 ^ (hash64>>32)); return hash32 ^ (hash32 >> 16); } int main(int ac, char **av){ if(ac!=3){ cerr<<"hashbench corpus repeats\n"; return 0; } ifstream fi(av[1]); if(!fi) return 0; vector<string> v; string s; for(fi>>s; !fi.eof(); fi>>s) v.push_back(s); fi.close(); size_t R=atoi(av[2]); cerr<<"benchmarking "<<v.size()<<'*'<<R<<" words\n"; timeval beg, end; uint64_t dummy=0, N=v.size(); double dt; for(size_t i=0; i<N; i++) dummy+=XXH3_64bits_withSeed(v[i].c_str(), v[i].size(), 0); gettimeofday(&beg,NULL); for(size_t r=0; r<R; r++) for(size_t i=0; i<N; i++) dummy+=XXH3_64bits_withSeed(v[i].c_str(), v[i].size(), r); gettimeofday(&end,NULL); dt=end.tv_sec-beg.tv_sec+1e-6*(end.tv_usec-beg.tv_usec); cerr<<"xxh3\t"<<1e-6*R*N/dt<<"\thashes/us\n"; for(size_t i=0; i<N; i++) dummy+=wyhash(v[i].c_str(), v[i].size(), 0); gettimeofday(&beg,NULL); for(size_t r=0; r<R; r++) for(size_t i=0; i<N; i++) dummy+=wyhash(v[i].c_str(), v[i].size(), r); gettimeofday(&end,NULL); dt=end.tv_sec-beg.tv_sec+1e-6*(end.tv_usec-beg.tv_usec); cerr<<"wyhash_v3\t"<<1e-6*R*N/dt<<"\thashes/us\n"; for(size_t i=0; i<N; i++) dummy+=FNV1A_Pippip_Yurii(v[i].c_str(), v[i].size()); gettimeofday(&beg,NULL); for(size_t r=0; r<R; r++) for(size_t i=0; i<N; i++) dummy+=FNV1A_Pippip_Yurii(v[i].c_str(), v[i].size()); gettimeofday(&end,NULL); dt=end.tv_sec-beg.tv_sec+1e-6*(end.tv_usec-beg.tv_usec); cerr<<"FNV1A_Pippip_Yurii\t"<<1e-6*R*N/dt<<"\thashes/us\n"; return dummy; } <commit_msg>Delete hashbench.cpp<commit_after><|endoftext|>
<commit_before>//===- Expressions.cpp - Expression Analysis Utilities --------------------===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines a package of expression analysis utilties: // // ClassifyExpression: Analyze an expression to determine the complexity of the // expression, and which other variables it depends on. // //===----------------------------------------------------------------------===// #include "llvm/Analysis/Expressions.h" #include "llvm/Constants.h" #include "llvm/Function.h" #include "llvm/Type.h" #include <iostream> using namespace llvm; ExprType::ExprType(Value *Val) { if (Val) if (ConstantInt *CPI = dyn_cast<ConstantInt>(Val)) { Offset = CPI; Var = 0; ExprTy = Constant; Scale = 0; return; } Var = Val; Offset = 0; ExprTy = Var ? Linear : Constant; Scale = 0; } ExprType::ExprType(const ConstantInt *scale, Value *var, const ConstantInt *offset) { Scale = var ? scale : 0; Var = var; Offset = offset; ExprTy = Scale ? ScaledLinear : (Var ? Linear : Constant); if (Scale && Scale->isNullValue()) { // Simplify 0*Var + const Scale = 0; Var = 0; ExprTy = Constant; } } const Type *ExprType::getExprType(const Type *Default) const { if (Offset) return Offset->getType(); if (Scale) return Scale->getType(); return Var ? Var->getType() : Default; } namespace { class DefVal { const ConstantInt * const Val; const Type * const Ty; protected: inline DefVal(const ConstantInt *val, const Type *ty) : Val(val), Ty(ty) {} public: inline const Type *getType() const { return Ty; } inline const ConstantInt *getVal() const { return Val; } inline operator const ConstantInt * () const { return Val; } inline const ConstantInt *operator->() const { return Val; } }; struct DefZero : public DefVal { inline DefZero(const ConstantInt *val, const Type *ty) : DefVal(val, ty) {} inline DefZero(const ConstantInt *val) : DefVal(val, val->getType()) {} }; struct DefOne : public DefVal { inline DefOne(const ConstantInt *val, const Type *ty) : DefVal(val, ty) {} }; } // getUnsignedConstant - Return a constant value of the specified type. If the // constant value is not valid for the specified type, return null. This cannot // happen for values in the range of 0 to 127. // static ConstantInt *getUnsignedConstant(uint64_t V, const Type *Ty) { if (isa<PointerType>(Ty)) Ty = Type::ULongTy; if (Ty->isSigned()) { // If this value is not a valid unsigned value for this type, return null! if (V > 127 && ((int64_t)V < 0 || !ConstantSInt::isValueValidForType(Ty, (int64_t)V))) return 0; return ConstantSInt::get(Ty, V); } else { // If this value is not a valid unsigned value for this type, return null! if (V > 255 && !ConstantUInt::isValueValidForType(Ty, V)) return 0; return ConstantUInt::get(Ty, V); } } // Add - Helper function to make later code simpler. Basically it just adds // the two constants together, inserts the result into the constant pool, and // returns it. Of course life is not simple, and this is no exception. Factors // that complicate matters: // 1. Either argument may be null. If this is the case, the null argument is // treated as either 0 (if DefOne = false) or 1 (if DefOne = true) // 2. Types get in the way. We want to do arithmetic operations without // regard for the underlying types. It is assumed that the constants are // integral constants. The new value takes the type of the left argument. // 3. If DefOne is true, a null return value indicates a value of 1, if DefOne // is false, a null return value indicates a value of 0. // static const ConstantInt *Add(const ConstantInt *Arg1, const ConstantInt *Arg2, bool DefOne) { assert(Arg1 && Arg2 && "No null arguments should exist now!"); assert(Arg1->getType() == Arg2->getType() && "Types must be compatible!"); // Actually perform the computation now! Constant *Result = ConstantExpr::get(Instruction::Add, (Constant*)Arg1, (Constant*)Arg2); ConstantInt *ResultI = cast<ConstantInt>(Result); // Check to see if the result is one of the special cases that we want to // recognize... if (ResultI->equalsInt(DefOne ? 1 : 0)) return 0; // Yes it is, simply return null. return ResultI; } static inline const ConstantInt *operator+(const DefZero &L, const DefZero &R) { if (L == 0) return R; if (R == 0) return L; return Add(L, R, false); } static inline const ConstantInt *operator+(const DefOne &L, const DefOne &R) { if (L == 0) { if (R == 0) return getUnsignedConstant(2, L.getType()); else return Add(getUnsignedConstant(1, L.getType()), R, true); } else if (R == 0) { return Add(L, getUnsignedConstant(1, L.getType()), true); } return Add(L, R, true); } // Mul - Helper function to make later code simpler. Basically it just // multiplies the two constants together, inserts the result into the constant // pool, and returns it. Of course life is not simple, and this is no // exception. Factors that complicate matters: // 1. Either argument may be null. If this is the case, the null argument is // treated as either 0 (if DefOne = false) or 1 (if DefOne = true) // 2. Types get in the way. We want to do arithmetic operations without // regard for the underlying types. It is assumed that the constants are // integral constants. // 3. If DefOne is true, a null return value indicates a value of 1, if DefOne // is false, a null return value indicates a value of 0. // static inline const ConstantInt *Mul(const ConstantInt *Arg1, const ConstantInt *Arg2, bool DefOne) { assert(Arg1 && Arg2 && "No null arguments should exist now!"); assert(Arg1->getType() == Arg2->getType() && "Types must be compatible!"); // Actually perform the computation now! Constant *Result = ConstantExpr::get(Instruction::Mul, (Constant*)Arg1, (Constant*)Arg2); assert(Result && Result->getType() == Arg1->getType() && "Couldn't perform multiplication!"); ConstantInt *ResultI = cast<ConstantInt>(Result); // Check to see if the result is one of the special cases that we want to // recognize... if (ResultI->equalsInt(DefOne ? 1 : 0)) return 0; // Yes it is, simply return null. return ResultI; } namespace { inline const ConstantInt *operator*(const DefZero &L, const DefZero &R) { if (L == 0 || R == 0) return 0; return Mul(L, R, false); } inline const ConstantInt *operator*(const DefOne &L, const DefZero &R) { if (R == 0) return getUnsignedConstant(0, L.getType()); if (L == 0) return R->equalsInt(1) ? 0 : R.getVal(); return Mul(L, R, true); } inline const ConstantInt *operator*(const DefZero &L, const DefOne &R) { if (L == 0 || R == 0) return L.getVal(); return Mul(R, L, false); } } // handleAddition - Add two expressions together, creating a new expression that // represents the composite of the two... // static ExprType handleAddition(ExprType Left, ExprType Right, Value *V) { const Type *Ty = V->getType(); if (Left.ExprTy > Right.ExprTy) std::swap(Left, Right); // Make left be simpler than right switch (Left.ExprTy) { case ExprType::Constant: return ExprType(Right.Scale, Right.Var, DefZero(Right.Offset, Ty) + DefZero(Left.Offset, Ty)); case ExprType::Linear: // RHS side must be linear or scaled case ExprType::ScaledLinear: // RHS must be scaled if (Left.Var != Right.Var) // Are they the same variables? return V; // if not, we don't know anything! return ExprType(DefOne(Left.Scale , Ty) + DefOne(Right.Scale , Ty), Right.Var, DefZero(Left.Offset, Ty) + DefZero(Right.Offset, Ty)); default: assert(0 && "Dont' know how to handle this case!"); return ExprType(); } } // negate - Negate the value of the specified expression... // static inline ExprType negate(const ExprType &E, Value *V) { const Type *Ty = V->getType(); ConstantInt *Zero = getUnsignedConstant(0, Ty); ConstantInt *One = getUnsignedConstant(1, Ty); ConstantInt *NegOne = cast<ConstantInt>(ConstantExpr::get(Instruction::Sub, Zero, One)); if (NegOne == 0) return V; // Couldn't subtract values... return ExprType(DefOne (E.Scale , Ty) * NegOne, E.Var, DefZero(E.Offset, Ty) * NegOne); } // ClassifyExpr: Analyze an expression to determine the complexity of the // expression, and which other values it depends on. // // Note that this analysis cannot get into infinite loops because it treats PHI // nodes as being an unknown linear expression. // ExprType llvm::ClassifyExpr(Value *Expr) { assert(Expr != 0 && "Can't classify a null expression!"); if (Expr->getType()->isFloatingPoint()) return Expr; // FIXME: Can't handle FP expressions if (Constant *C = dyn_cast<Constant>(Expr)) { if (ConstantInt *CPI = dyn_cast<ConstantInt>(cast<Constant>(Expr))) // It's an integral constant! return ExprType(CPI->isNullValue() ? 0 : CPI); return Expr; } else if (!isa<Instruction>(Expr)) { return Expr; } Instruction *I = cast<Instruction>(Expr); const Type *Ty = I->getType(); switch (I->getOpcode()) { // Handle each instruction type separately case Instruction::Add: { ExprType Left (ClassifyExpr(I->getOperand(0))); ExprType Right(ClassifyExpr(I->getOperand(1))); return handleAddition(Left, Right, I); } // end case Instruction::Add case Instruction::Sub: { ExprType Left (ClassifyExpr(I->getOperand(0))); ExprType Right(ClassifyExpr(I->getOperand(1))); ExprType RightNeg = negate(Right, I); if (RightNeg.Var == I && !RightNeg.Offset && !RightNeg.Scale) return I; // Could not negate value... return handleAddition(Left, RightNeg, I); } // end case Instruction::Sub case Instruction::Shl: { ExprType Right(ClassifyExpr(I->getOperand(1))); if (Right.ExprTy != ExprType::Constant) break; ExprType Left(ClassifyExpr(I->getOperand(0))); if (Right.Offset == 0) return Left; // shl x, 0 = x assert(Right.Offset->getType() == Type::UByteTy && "Shift amount must always be a unsigned byte!"); uint64_t ShiftAmount = cast<ConstantUInt>(Right.Offset)->getValue(); ConstantInt *Multiplier = getUnsignedConstant(1ULL << ShiftAmount, Ty); // We don't know how to classify it if they are shifting by more than what // is reasonable. In most cases, the result will be zero, but there is one // class of cases where it is not, so we cannot optimize without checking // for it. The case is when you are shifting a signed value by 1 less than // the number of bits in the value. For example: // %X = shl sbyte %Y, ubyte 7 // will try to form an sbyte multiplier of 128, which will give a null // multiplier, even though the result is not 0. Until we can check for this // case, be conservative. TODO. // if (Multiplier == 0) return Expr; return ExprType(DefOne(Left.Scale, Ty) * Multiplier, Left.Var, DefZero(Left.Offset, Ty) * Multiplier); } // end case Instruction::Shl case Instruction::Mul: { ExprType Left (ClassifyExpr(I->getOperand(0))); ExprType Right(ClassifyExpr(I->getOperand(1))); if (Left.ExprTy > Right.ExprTy) std::swap(Left, Right); // Make left be simpler than right if (Left.ExprTy != ExprType::Constant) // RHS must be > constant return I; // Quadratic eqn! :( const ConstantInt *Offs = Left.Offset; if (Offs == 0) return ExprType(); return ExprType( DefOne(Right.Scale , Ty) * Offs, Right.Var, DefZero(Right.Offset, Ty) * Offs); } // end case Instruction::Mul case Instruction::Cast: { ExprType Src(ClassifyExpr(I->getOperand(0))); const Type *DestTy = I->getType(); if (isa<PointerType>(DestTy)) DestTy = Type::ULongTy; // Pointer types are represented as ulong const Type *SrcValTy = Src.getExprType(0); if (!SrcValTy) return I; if (!SrcValTy->isLosslesslyConvertibleTo(DestTy)) { if (Src.ExprTy != ExprType::Constant) return I; // Converting cast, and not a constant value... } const ConstantInt *Offset = Src.Offset; const ConstantInt *Scale = Src.Scale; if (Offset) { const Constant *CPV = ConstantExpr::getCast((Constant*)Offset, DestTy); if (!isa<ConstantInt>(CPV)) return I; Offset = cast<ConstantInt>(CPV); } if (Scale) { const Constant *CPV = ConstantExpr::getCast((Constant*)Scale, DestTy); if (!CPV) return I; Scale = cast<ConstantInt>(CPV); } return ExprType(Scale, Src.Var, Offset); } // end case Instruction::Cast // TODO: Handle SUB, SHR? } // end switch // Otherwise, I don't know anything about this value! return I; } <commit_msg>remove a dead file<commit_after><|endoftext|>
<commit_before>// @(#)root/base:$Id$ // Author: Fons Rademakers 11/10/95 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // TStopwatch // // // // Stopwatch class. This class returns the real and cpu time between // // the start and stop events. // // // ////////////////////////////////////////////////////////////////////////// #include "TStopwatch.h" #include "TTimeStamp.h" #include "TString.h" #if defined(R__UNIX) # include <sys/times.h> # include <unistd.h> static Double_t gTicks = 0; #elif defined(WIN32) # include "TError.h" const Double_t gTicks = 1.0e-7; # include "Windows4Root.h" #endif ClassImp(TStopwatch) //______________________________________________________________________________ TStopwatch::TStopwatch() { // Create a stopwatch and start it. #ifdef R__UNIX //if (!gTicks) gTicks = (Double_t)sysconf(_SC_CLK_TCK); gTicks = (Double_t)sysconf(_SC_CLK_TCK); #endif Start(); } //______________________________________________________________________________ void TStopwatch::Start(Bool_t reset) { // Start the stopwatch. If reset is kTRUE reset the stopwatch before // starting it (including the stopwatch counter). // Use kFALSE to continue timing after a Stop() without // resetting the stopwatch. if (reset) { fState = kUndefined; fTotalCpuTime = 0; fTotalRealTime = 0; fCounter = 0; } if (fState != kRunning) { fStartRealTime = GetRealTime(); fStartCpuTime = GetCPUTime(); } fState = kRunning; fCounter++; } //______________________________________________________________________________ void TStopwatch::Stop() { // Stop the stopwatch. fStopRealTime = GetRealTime(); fStopCpuTime = GetCPUTime(); if (fState == kRunning) { fTotalCpuTime += fStopCpuTime - fStartCpuTime; fTotalRealTime += fStopRealTime - fStartRealTime; } fState = kStopped; } //______________________________________________________________________________ void TStopwatch::Continue() { // Resume a stopped stopwatch. The stopwatch continues counting from the last // Start() onwards (this is like the laptimer function). if (fState == kUndefined) Error("Continue", "stopwatch not started"); if (fState == kStopped) { fTotalCpuTime -= fStopCpuTime - fStartCpuTime; fTotalRealTime -= fStopRealTime - fStartRealTime; } fState = kRunning; } //______________________________________________________________________________ Double_t TStopwatch::RealTime() { // Return the realtime passed between the start and stop events. If the // stopwatch was still running stop it first. if (fState == kUndefined) Error("RealTime", "stopwatch not started"); if (fState == kRunning) Stop(); return fTotalRealTime; } //______________________________________________________________________________ Double_t TStopwatch::CpuTime() { // Return the cputime passed between the start and stop events. If the // stopwatch was still running stop it first. if (fState == kUndefined) Error("CpuTime", "stopwatch not started"); if (fState == kRunning) Stop(); return fTotalCpuTime; } //______________________________________________________________________________ Double_t TStopwatch::GetRealTime() { // Private static method returning system realtime. #if defined(R__UNIX) return TTimeStamp(); #elif defined(WIN32) union { FILETIME ftFileTime; __int64 ftInt64; } ftRealTime; // time the process has spent in kernel mode SYSTEMTIME st; GetSystemTime(&st); SystemTimeToFileTime(&st,&ftRealTime.ftFileTime); return (Double_t)ftRealTime.ftInt64 * gTicks; #endif } //______________________________________________________________________________ Double_t TStopwatch::GetCPUTime() { // Private static method returning system CPU time. #if defined(R__UNIX) struct tms cpt; times(&cpt); return (Double_t)(cpt.tms_utime+cpt.tms_stime) / gTicks; #elif defined(WIN32) OSVERSIONINFO OsVersionInfo; // Value Platform //---------------------------------------------------- // VER_PLATFORM_WIN32s Win32s on Windows 3.1 // VER_PLATFORM_WIN32_WINDOWS Win32 on Windows 95 // VER_PLATFORM_WIN32_NT Windows NT // OsVersionInfo.dwOSVersionInfoSize=sizeof(OSVERSIONINFO); GetVersionEx(&OsVersionInfo); if (OsVersionInfo.dwPlatformId == VER_PLATFORM_WIN32_NT) { DWORD ret; FILETIME ftCreate, // when the process was created ftExit; // when the process exited union { FILETIME ftFileTime; __int64 ftInt64; } ftKernel; // time the process has spent in kernel mode union { FILETIME ftFileTime; __int64 ftInt64; } ftUser; // time the process has spent in user mode HANDLE hThread = GetCurrentThread(); ret = GetThreadTimes (hThread, &ftCreate, &ftExit, &ftKernel.ftFileTime, &ftUser.ftFileTime); if (ret != TRUE) { ret = GetLastError (); ::Error ("GetCPUTime", " Error on GetProcessTimes 0x%lx", (int)ret); } // Process times are returned in a 64-bit structure, as the number of // 100 nanosecond ticks since 1 January 1601. User mode and kernel mode // times for this process are in separate 64-bit structures. // To convert to floating point seconds, we will: // // Convert sum of high 32-bit quantities to 64-bit int return (Double_t) (ftKernel.ftInt64 + ftUser.ftInt64) * gTicks; } else return GetRealTime(); #endif } //______________________________________________________________________________ void TStopwatch::Print(Option_t *opt) const { // Print the real and cpu time passed between the start and stop events. // and the number of times (slices) this TStopwatch was called // (if this number > 1). If opt="m" print out realtime in milli second // precision. If opt="u" print out realtime in micro second precision. Double_t realt = const_cast<TStopwatch*>(this)->RealTime(); Double_t cput = const_cast<TStopwatch*>(this)->CpuTime(); Int_t hours = Int_t(realt / 3600); realt -= hours * 3600; Int_t min = Int_t(realt / 60); realt -= min * 60; Int_t sec = Int_t(realt); if (realt < 0) realt = 0; if (cput < 0) cput = 0; if (opt && *opt == 'm') { if (Counter() > 1) { Printf("Real time %d:%02d:%06.3f, CP time %.3f, %d slices", hours, min, realt, cput, Counter()); } else { Printf("Real time %d:%02d:%06.3f, CP time %.3f", hours, min, realt, cput); } } else if (opt && *opt == 'u') { if (Counter() > 1) { Printf("Real time %d:%02d:%09.6f, CP time %.3f, %d slices", hours, min, realt, cput, Counter()); } else { Printf("Real time %d:%02d:%09.6f, CP time %.3f", hours, min, realt, cput); } } else { if (Counter() > 1) { Printf("Real time %d:%02d:%02d, CP time %.3f, %d slices", hours, min, sec, cput, Counter()); } else { Printf("Real time %d:%02d:%02d, CP time %.3f", hours, min, sec, cput); } } } <commit_msg>fix check on gTicks.<commit_after>// @(#)root/base:$Id$ // Author: Fons Rademakers 11/10/95 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // TStopwatch // // // // Stopwatch class. This class returns the real and cpu time between // // the start and stop events. // // // ////////////////////////////////////////////////////////////////////////// #include "TStopwatch.h" #include "TTimeStamp.h" #include "TString.h" #if defined(R__UNIX) # include <sys/times.h> # include <unistd.h> static Double_t gTicks = 0; #elif defined(WIN32) # include "TError.h" const Double_t gTicks = 1.0e-7; # include "Windows4Root.h" #endif ClassImp(TStopwatch) //______________________________________________________________________________ TStopwatch::TStopwatch() { // Create a stopwatch and start it. #ifdef R__UNIX if (gTicks <= 0.0) gTicks = (Double_t)sysconf(_SC_CLK_TCK); #endif Start(); } //______________________________________________________________________________ void TStopwatch::Start(Bool_t reset) { // Start the stopwatch. If reset is kTRUE reset the stopwatch before // starting it (including the stopwatch counter). // Use kFALSE to continue timing after a Stop() without // resetting the stopwatch. if (reset) { fState = kUndefined; fTotalCpuTime = 0; fTotalRealTime = 0; fCounter = 0; } if (fState != kRunning) { fStartRealTime = GetRealTime(); fStartCpuTime = GetCPUTime(); } fState = kRunning; fCounter++; } //______________________________________________________________________________ void TStopwatch::Stop() { // Stop the stopwatch. fStopRealTime = GetRealTime(); fStopCpuTime = GetCPUTime(); if (fState == kRunning) { fTotalCpuTime += fStopCpuTime - fStartCpuTime; fTotalRealTime += fStopRealTime - fStartRealTime; } fState = kStopped; } //______________________________________________________________________________ void TStopwatch::Continue() { // Resume a stopped stopwatch. The stopwatch continues counting from the last // Start() onwards (this is like the laptimer function). if (fState == kUndefined) Error("Continue", "stopwatch not started"); if (fState == kStopped) { fTotalCpuTime -= fStopCpuTime - fStartCpuTime; fTotalRealTime -= fStopRealTime - fStartRealTime; } fState = kRunning; } //______________________________________________________________________________ Double_t TStopwatch::RealTime() { // Return the realtime passed between the start and stop events. If the // stopwatch was still running stop it first. if (fState == kUndefined) Error("RealTime", "stopwatch not started"); if (fState == kRunning) Stop(); return fTotalRealTime; } //______________________________________________________________________________ Double_t TStopwatch::CpuTime() { // Return the cputime passed between the start and stop events. If the // stopwatch was still running stop it first. if (fState == kUndefined) Error("CpuTime", "stopwatch not started"); if (fState == kRunning) Stop(); return fTotalCpuTime; } //______________________________________________________________________________ Double_t TStopwatch::GetRealTime() { // Private static method returning system realtime. #if defined(R__UNIX) return TTimeStamp(); #elif defined(WIN32) union { FILETIME ftFileTime; __int64 ftInt64; } ftRealTime; // time the process has spent in kernel mode SYSTEMTIME st; GetSystemTime(&st); SystemTimeToFileTime(&st,&ftRealTime.ftFileTime); return (Double_t)ftRealTime.ftInt64 * gTicks; #endif } //______________________________________________________________________________ Double_t TStopwatch::GetCPUTime() { // Private static method returning system CPU time. #if defined(R__UNIX) struct tms cpt; times(&cpt); return (Double_t)(cpt.tms_utime+cpt.tms_stime) / gTicks; #elif defined(WIN32) OSVERSIONINFO OsVersionInfo; // Value Platform //---------------------------------------------------- // VER_PLATFORM_WIN32s Win32s on Windows 3.1 // VER_PLATFORM_WIN32_WINDOWS Win32 on Windows 95 // VER_PLATFORM_WIN32_NT Windows NT // OsVersionInfo.dwOSVersionInfoSize=sizeof(OSVERSIONINFO); GetVersionEx(&OsVersionInfo); if (OsVersionInfo.dwPlatformId == VER_PLATFORM_WIN32_NT) { DWORD ret; FILETIME ftCreate, // when the process was created ftExit; // when the process exited union { FILETIME ftFileTime; __int64 ftInt64; } ftKernel; // time the process has spent in kernel mode union { FILETIME ftFileTime; __int64 ftInt64; } ftUser; // time the process has spent in user mode HANDLE hThread = GetCurrentThread(); ret = GetThreadTimes (hThread, &ftCreate, &ftExit, &ftKernel.ftFileTime, &ftUser.ftFileTime); if (ret != TRUE) { ret = GetLastError (); ::Error ("GetCPUTime", " Error on GetProcessTimes 0x%lx", (int)ret); } // Process times are returned in a 64-bit structure, as the number of // 100 nanosecond ticks since 1 January 1601. User mode and kernel mode // times for this process are in separate 64-bit structures. // To convert to floating point seconds, we will: // // Convert sum of high 32-bit quantities to 64-bit int return (Double_t) (ftKernel.ftInt64 + ftUser.ftInt64) * gTicks; } else return GetRealTime(); #endif } //______________________________________________________________________________ void TStopwatch::Print(Option_t *opt) const { // Print the real and cpu time passed between the start and stop events. // and the number of times (slices) this TStopwatch was called // (if this number > 1). If opt="m" print out realtime in milli second // precision. If opt="u" print out realtime in micro second precision. Double_t realt = const_cast<TStopwatch*>(this)->RealTime(); Double_t cput = const_cast<TStopwatch*>(this)->CpuTime(); Int_t hours = Int_t(realt / 3600); realt -= hours * 3600; Int_t min = Int_t(realt / 60); realt -= min * 60; Int_t sec = Int_t(realt); if (realt < 0) realt = 0; if (cput < 0) cput = 0; if (opt && *opt == 'm') { if (Counter() > 1) { Printf("Real time %d:%02d:%06.3f, CP time %.3f, %d slices", hours, min, realt, cput, Counter()); } else { Printf("Real time %d:%02d:%06.3f, CP time %.3f", hours, min, realt, cput); } } else if (opt && *opt == 'u') { if (Counter() > 1) { Printf("Real time %d:%02d:%09.6f, CP time %.3f, %d slices", hours, min, realt, cput, Counter()); } else { Printf("Real time %d:%02d:%09.6f, CP time %.3f", hours, min, realt, cput); } } else { if (Counter() > 1) { Printf("Real time %d:%02d:%02d, CP time %.3f, %d slices", hours, min, sec, cput, Counter()); } else { Printf("Real time %d:%02d:%02d, CP time %.3f", hours, min, sec, cput); } } } <|endoftext|>
<commit_before>#include <iostream> #include <string> #include <stdlib.h> using namespace std; class Matrix { private: int columns; int strings; int **matrix; public: Matrix() { }; Matrix(int a, int b) { columns = b; strings = a; matrix = new int*[a]; for (int i = 0; i < a; i++) { matrix[i] = new int[b]{0}; } }; void print(void) const { for (int i = 0; i < strings; i++) { for (int j = 0; j < columns; j++) { cout << get(i, j) << " "; } cout << endl; } cout << endl; }; void input(char *path) { ifstream file; file.open(path); for (int i = 0; i < strings; i++) { for (int j = 0; j < columns; j++) { char *temp = new char[5]; file.getline(temp, 5); set(i, j, atoi(temp)); } } }; void set(int x, int y, int z) { matrix[x][y] = z; }; int get(int x, int y) const { return matrix[x][y]; }; Matrix operator+ (Matrix a) const { Matrix c(strings, columns); for (int i = 0; i < strings; i++) { for (int j = 0; j < columns; j++) { c.set(i, j, a.get(i, j) + get(i, j)); } } return c; }; Matrix operator* (Matrix a) const { Matrix c(strings, a.columns); for (int i = 0; i < strings; i++) { for (int j = 0; j < a.columns; j++) { int temp = 0; for (int k = 0; k < strings; k++) { temp += get(i, k) * a.get(k, j); } c.set(i, j, temp); } } return c; }; Matrix& operator= (Matrix &other) { if (this != &other) { for (int i = 0; i < strings; i++) { delete[] matrix[i]; } delete[] matrix; columns = other.columns; strings = other.strings; matrix = new int*[strings]; for (int i = 0; i < strings; i++) { matrix[i] = new int[columns]{0}; } matrix = other.matrix; } return *this; }; bool operator== (Matrix &a) const { bool k = false; for (int i = 0; i < strings; i++){ for (int j = 0; j < columns; j++){ if (matrix[i][j] == a.matrix[i][j]) k = true; } } return k; } friend istream& operator>> (istream& infile, const Matrix& result) { for (int i = 0; i < result.strings; i++) for (int j = 0; j < result.columns; j++) infile >> result.matrix[i][j]; return infile; } friend ostream& operator<< (ostream& os, const Matrix& a) { for (int i = 0; i < a.strings; i++) { for (int j = 0; j < a.columns; j++) { os << a.get(i, j) << " "; } os << endl; } os << endl; return os; } ~Matrix() { /*for (int i = 0; i < strings; i++) { delete[] matrix[i]; } delete[] matrix;*/ }; }; int main() { Matrix a = Matrix(2, 2); a.input("D://test.txt"); cout << a; Matrix c = a + a; cout << a; c = a * a; cout << c; system("pause"); } <commit_msg>Update matrix.cpp<commit_after>#include <iostream> #include <string> #include <stdlib.h> using namespace std; class Matrix { private: int columns; int strings; int **matrix; public: Matrix() { }; Matrix(int a, int b) { columns = b; strings = a; matrix = new int*[a]; for (int i = 0; i < a; i++) { matrix[i] = new int[b]{0}; } }; void print(void) const { for (int i = 0; i < strings; i++) { for (int j = 0; j < columns; j++) { cout << get(i, j) << " "; } cout << endl; } cout << endl; }; void input(char *path) { ifstream file; file.open(path); for (int i = 0; i < strings; i++) { for (int j = 0; j < columns; j++) { char *temp = new char[5]; file.getline(temp, 5); set(i, j, atoi(temp)); } } }; void set(int x, int y, int z) { matrix[x][y] = z; }; int get(int x, int y) const { return matrix[x][y]; }; Matrix operator+ (Matrix a) const { Matrix c(strings, columns); for (int i = 0; i < strings; i++) { for (int j = 0; j < columns; j++) { c.set(i, j, a.get(i, j) + get(i, j)); } } return c; }; Matrix operator* (Matrix a) const { Matrix c(strings, a.columns); for (int i = 0; i < strings; i++) { for (int j = 0; j < a.columns; j++) { int temp = 0; for (int k = 0; k < strings; k++) { temp += get(i, k) * a.get(k, j); } c.set(i, j, temp); } } return c; }; Matrix& operator= (Matrix &other) { if (this != &other) { for (int i = 0; i < strings; i++) { delete[] matrix[i]; } delete[] matrix; columns = other.columns; strings = other.strings; matrix = new int*[strings]; for (int i = 0; i < strings; i++) { matrix[i] = new int[columns]{0}; } matrix = other.matrix; } return *this; }; bool operator== (Matrix &a) const { bool k = false; for (int i = 0; i < strings; i++){ for (int j = 0; j < columns; j++){ if (matrix[i][j] == a.matrix[i][j]) k = true; } } return k; } friend istream& operator>> (istream& infile, const Matrix& result) { for (int i = 0; i < result.strings; i++) for (int j = 0; j < result.columns; j++) infile >> result.matrix[i][j]; return infile; } friend ostream& operator<< (ostream& os, const Matrix& a) { for (int i = 0; i < a.strings; i++) { for (int j = 0; j < a.columns; j++) { os << a.get(i, j) << " "; } os << endl; } os << endl; return os; } ~Matrix() { /*for (int i = 0; i < strings; i++) { delete[] matrix[i]; } delete[] matrix;*/ }; }; <|endoftext|>
<commit_before>//===- RemarkParser.cpp --------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This file provides utility methods used by clients that want to use the // parser for remark diagnostics in LLVM. // //===----------------------------------------------------------------------===// #include "llvm/Remarks/RemarkParser.h" #include "YAMLRemarkParser.h" #include "llvm-c/Remarks.h" #include "llvm/ADT/STLExtras.h" #include "llvm/Support/CBindingWrapping.h" using namespace llvm; using namespace llvm::remarks; static std::unique_ptr<ParserImpl> formatToParserImpl(ParserFormat Format, StringRef Buf) { switch (Format) { case ParserFormat::YAML: return llvm::make_unique<YAMLParserImpl>(Buf); }; } static std::unique_ptr<ParserImpl> formatToParserImpl(ParserFormat Format, StringRef Buf, const ParsedStringTable &StrTab) { switch (Format) { case ParserFormat::YAML: return llvm::make_unique<YAMLParserImpl>(Buf, &StrTab); }; } Parser::Parser(ParserFormat Format, StringRef Buf) : Impl(formatToParserImpl(Format, Buf)) {} Parser::Parser(ParserFormat Format, StringRef Buf, const ParsedStringTable &StrTab) : Impl(formatToParserImpl(Format, Buf, StrTab)) {} Parser::~Parser() = default; static Expected<const Remark *> getNextYAML(YAMLParserImpl &Impl) { YAMLRemarkParser &YAMLParser = Impl.YAMLParser; // Check for EOF. if (Impl.YAMLIt == Impl.YAMLParser.Stream.end()) return nullptr; auto CurrentIt = Impl.YAMLIt; // Try to parse an entry. if (Error E = YAMLParser.parseYAMLElement(*CurrentIt)) { // Set the iterator to the end, in case the user calls getNext again. Impl.YAMLIt = Impl.YAMLParser.Stream.end(); return std::move(E); } // Move on. ++Impl.YAMLIt; // Return the just-parsed remark. if (const Optional<YAMLRemarkParser::ParseState> &State = YAMLParser.State) return &State->TheRemark; else return createStringError(std::make_error_code(std::errc::invalid_argument), "unexpected error while parsing."); } Expected<const Remark *> Parser::getNext() const { if (auto *Impl = dyn_cast<YAMLParserImpl>(this->Impl.get())) return getNextYAML(*Impl); llvm_unreachable("Get next called with an unknown parsing implementation."); } ParsedStringTable::ParsedStringTable(StringRef InBuffer) : Buffer(InBuffer) { while (!InBuffer.empty()) { // Strings are separated by '\0' bytes. std::pair<StringRef, StringRef> Split = InBuffer.split('\0'); // We only store the offset from the beginning of the buffer. Offsets.push_back(Split.first.data() - Buffer.data()); InBuffer = Split.second; } } Expected<StringRef> ParsedStringTable::operator[](size_t Index) const { if (Index >= Offsets.size()) return createStringError( std::make_error_code(std::errc::invalid_argument), "String with index %u is out of bounds (size = %u).", Index, Offsets.size()); size_t Offset = Offsets[Index]; // If it's the last offset, we can't use the next offset to know the size of // the string. size_t NextOffset = (Index == Offsets.size() - 1) ? Buffer.size() : Offsets[Index + 1]; return StringRef(Buffer.data() + Offset, NextOffset - Offset - 1); } // Create wrappers for C Binding types (see CBindingWrapping.h). DEFINE_SIMPLE_CONVERSION_FUNCTIONS(remarks::Parser, LLVMRemarkParserRef) extern "C" LLVMRemarkParserRef LLVMRemarkParserCreateYAML(const void *Buf, uint64_t Size) { return wrap( new remarks::Parser(remarks::ParserFormat::YAML, StringRef(static_cast<const char *>(Buf), Size))); } static void handleYAMLError(remarks::YAMLParserImpl &Impl, Error E) { handleAllErrors( std::move(E), [&](const YAMLParseError &PE) { Impl.YAMLParser.Stream.printError(&PE.getNode(), Twine(PE.getMessage()) + Twine('\n')); }, [&](const ErrorInfoBase &EIB) { EIB.log(Impl.YAMLParser.ErrorStream); }); Impl.HasErrors = true; } extern "C" LLVMRemarkEntryRef LLVMRemarkParserGetNext(LLVMRemarkParserRef Parser) { remarks::Parser &TheParser = *unwrap(Parser); Expected<const remarks::Remark *> RemarkOrErr = TheParser.getNext(); if (!RemarkOrErr) { // Error during parsing. if (auto *Impl = dyn_cast<remarks::YAMLParserImpl>(TheParser.Impl.get())) handleYAMLError(*Impl, RemarkOrErr.takeError()); else llvm_unreachable("unkown parser implementation."); return nullptr; } if (*RemarkOrErr == nullptr) return nullptr; // Valid remark. return wrap(*RemarkOrErr); } extern "C" LLVMBool LLVMRemarkParserHasError(LLVMRemarkParserRef Parser) { if (auto *Impl = dyn_cast<remarks::YAMLParserImpl>(unwrap(Parser)->Impl.get())) return Impl->HasErrors; llvm_unreachable("unkown parser implementation."); } extern "C" const char * LLVMRemarkParserGetErrorMessage(LLVMRemarkParserRef Parser) { if (auto *Impl = dyn_cast<remarks::YAMLParserImpl>(unwrap(Parser)->Impl.get())) return Impl->YAMLParser.ErrorStream.str().c_str(); llvm_unreachable("unkown parser implementation."); } extern "C" void LLVMRemarkParserDispose(LLVMRemarkParserRef Parser) { delete unwrap(Parser); } <commit_msg>[Remarks] Silence gcc warning by catching unhandled values in switches<commit_after>//===- RemarkParser.cpp --------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This file provides utility methods used by clients that want to use the // parser for remark diagnostics in LLVM. // //===----------------------------------------------------------------------===// #include "llvm/Remarks/RemarkParser.h" #include "YAMLRemarkParser.h" #include "llvm-c/Remarks.h" #include "llvm/ADT/STLExtras.h" #include "llvm/Support/CBindingWrapping.h" using namespace llvm; using namespace llvm::remarks; static std::unique_ptr<ParserImpl> formatToParserImpl(ParserFormat Format, StringRef Buf) { switch (Format) { case ParserFormat::YAML: return llvm::make_unique<YAMLParserImpl>(Buf); default: llvm_unreachable("Unknown format encountered!"); }; } static std::unique_ptr<ParserImpl> formatToParserImpl(ParserFormat Format, StringRef Buf, const ParsedStringTable &StrTab) { switch (Format) { case ParserFormat::YAML: return llvm::make_unique<YAMLParserImpl>(Buf, &StrTab); default: llvm_unreachable("Unknown format encountered!"); }; } Parser::Parser(ParserFormat Format, StringRef Buf) : Impl(formatToParserImpl(Format, Buf)) {} Parser::Parser(ParserFormat Format, StringRef Buf, const ParsedStringTable &StrTab) : Impl(formatToParserImpl(Format, Buf, StrTab)) {} Parser::~Parser() = default; static Expected<const Remark *> getNextYAML(YAMLParserImpl &Impl) { YAMLRemarkParser &YAMLParser = Impl.YAMLParser; // Check for EOF. if (Impl.YAMLIt == Impl.YAMLParser.Stream.end()) return nullptr; auto CurrentIt = Impl.YAMLIt; // Try to parse an entry. if (Error E = YAMLParser.parseYAMLElement(*CurrentIt)) { // Set the iterator to the end, in case the user calls getNext again. Impl.YAMLIt = Impl.YAMLParser.Stream.end(); return std::move(E); } // Move on. ++Impl.YAMLIt; // Return the just-parsed remark. if (const Optional<YAMLRemarkParser::ParseState> &State = YAMLParser.State) return &State->TheRemark; else return createStringError(std::make_error_code(std::errc::invalid_argument), "unexpected error while parsing."); } Expected<const Remark *> Parser::getNext() const { if (auto *Impl = dyn_cast<YAMLParserImpl>(this->Impl.get())) return getNextYAML(*Impl); llvm_unreachable("Get next called with an unknown parsing implementation."); } ParsedStringTable::ParsedStringTable(StringRef InBuffer) : Buffer(InBuffer) { while (!InBuffer.empty()) { // Strings are separated by '\0' bytes. std::pair<StringRef, StringRef> Split = InBuffer.split('\0'); // We only store the offset from the beginning of the buffer. Offsets.push_back(Split.first.data() - Buffer.data()); InBuffer = Split.second; } } Expected<StringRef> ParsedStringTable::operator[](size_t Index) const { if (Index >= Offsets.size()) return createStringError( std::make_error_code(std::errc::invalid_argument), "String with index %u is out of bounds (size = %u).", Index, Offsets.size()); size_t Offset = Offsets[Index]; // If it's the last offset, we can't use the next offset to know the size of // the string. size_t NextOffset = (Index == Offsets.size() - 1) ? Buffer.size() : Offsets[Index + 1]; return StringRef(Buffer.data() + Offset, NextOffset - Offset - 1); } // Create wrappers for C Binding types (see CBindingWrapping.h). DEFINE_SIMPLE_CONVERSION_FUNCTIONS(remarks::Parser, LLVMRemarkParserRef) extern "C" LLVMRemarkParserRef LLVMRemarkParserCreateYAML(const void *Buf, uint64_t Size) { return wrap( new remarks::Parser(remarks::ParserFormat::YAML, StringRef(static_cast<const char *>(Buf), Size))); } static void handleYAMLError(remarks::YAMLParserImpl &Impl, Error E) { handleAllErrors( std::move(E), [&](const YAMLParseError &PE) { Impl.YAMLParser.Stream.printError(&PE.getNode(), Twine(PE.getMessage()) + Twine('\n')); }, [&](const ErrorInfoBase &EIB) { EIB.log(Impl.YAMLParser.ErrorStream); }); Impl.HasErrors = true; } extern "C" LLVMRemarkEntryRef LLVMRemarkParserGetNext(LLVMRemarkParserRef Parser) { remarks::Parser &TheParser = *unwrap(Parser); Expected<const remarks::Remark *> RemarkOrErr = TheParser.getNext(); if (!RemarkOrErr) { // Error during parsing. if (auto *Impl = dyn_cast<remarks::YAMLParserImpl>(TheParser.Impl.get())) handleYAMLError(*Impl, RemarkOrErr.takeError()); else llvm_unreachable("unkown parser implementation."); return nullptr; } if (*RemarkOrErr == nullptr) return nullptr; // Valid remark. return wrap(*RemarkOrErr); } extern "C" LLVMBool LLVMRemarkParserHasError(LLVMRemarkParserRef Parser) { if (auto *Impl = dyn_cast<remarks::YAMLParserImpl>(unwrap(Parser)->Impl.get())) return Impl->HasErrors; llvm_unreachable("unkown parser implementation."); } extern "C" const char * LLVMRemarkParserGetErrorMessage(LLVMRemarkParserRef Parser) { if (auto *Impl = dyn_cast<remarks::YAMLParserImpl>(unwrap(Parser)->Impl.get())) return Impl->YAMLParser.ErrorStream.str().c_str(); llvm_unreachable("unkown parser implementation."); } extern "C" void LLVMRemarkParserDispose(LLVMRemarkParserRef Parser) { delete unwrap(Parser); } <|endoftext|>
<commit_before>//===-- SILCleanup.cpp - Removes diagnostics instructions -----------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // Cleanup SIL to make it suitable for IRGen. Specifically, removes the calls to // Builtin.staticReport(), which are not needed post SIL. // //===----------------------------------------------------------------------===// #include "swift/SILPasses/Passes.h" #include "swift/SIL/SILFunction.h" #include "swift/SIL/SILInstruction.h" #include "swift/SIL/SILModule.h" #include "swift/SILPasses/Utils/Local.h" #include "swift/SILPasses/Transforms.h" using namespace swift; static void cleanFunction(SILFunction &Fn) { for (auto &BB : Fn) { auto I = BB.begin(), E = BB.end(); while (I != E) { // Make sure there is no iterator invalidation if the inspected // instruction gets removed from the block. SILInstruction *Inst = I++; // Remove calls to Builtin.staticReport(). if (ApplyInst *AI = dyn_cast<ApplyInst>(Inst)) if (BuiltinFunctionRefInst *FR = dyn_cast<BuiltinFunctionRefInst>(AI->getCallee())) { const BuiltinInfo &B = FR->getBuiltinInfo(); if (B.ID == BuiltinValueKind::StaticReport) { // The call to the builtin should get removed before we reach // IRGen. recursivelyDeleteTriviallyDeadInstructions(AI, /* Force */true); } } } } } void swift::performSILCleanup(SILModule *M) { for (auto &Fn : *M) cleanFunction(Fn); } namespace { class SILCleanup : public swift::SILFunctionTransform { /// The entry point to the transformation. void run() { cleanFunction(*getFunction()); invalidateAnalysis(SILAnalysis::InvalidationKind::All); } StringRef getName() override { return "SIL Cleanup"; } }; } // end anonymous namespace SILTransform *swift::createSILCleanup() { return new SILCleanup(); } <commit_msg>Change the linkage kind fron PublicExternal to Shared to make IRGen generate the linkonce_odr linkage type. Using linkonce_odr will make sure we use the symbol from the executable and not from the dylib.<commit_after>//===-- SILCleanup.cpp - Removes diagnostics instructions -----------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // Cleanup SIL to make it suitable for IRGen. Specifically, removes the calls to // Builtin.staticReport(), which are not needed post SIL. // //===----------------------------------------------------------------------===// #include "swift/SILPasses/Passes.h" #include "swift/SIL/SILFunction.h" #include "swift/SIL/SILInstruction.h" #include "swift/SIL/SILModule.h" #include "swift/SILPasses/Utils/Local.h" #include "swift/SILPasses/Transforms.h" #include "llvm/ADT/SmallString.h" using namespace swift; static void cleanFunction(SILFunction &Fn) { for (auto &BB : Fn) { auto I = BB.begin(), E = BB.end(); while (I != E) { // Make sure there is no iterator invalidation if the inspected // instruction gets removed from the block. SILInstruction *Inst = I++; // Remove calls to Builtin.staticReport(). if (ApplyInst *AI = dyn_cast<ApplyInst>(Inst)) if (BuiltinFunctionRefInst *FR = dyn_cast<BuiltinFunctionRefInst>(AI->getCallee())) { const BuiltinInfo &B = FR->getBuiltinInfo(); if (B.ID == BuiltinValueKind::StaticReport) { // The call to the builtin should get removed before we reach // IRGen. recursivelyDeleteTriviallyDeadInstructions(AI, /* Force */true); } } } } // Rename functions with public_external linkage to prevent symbol conflict // with stdlib. if (Fn.isDefinition() && Fn.getLinkage() == SILLinkage::PublicExternal) { Fn.setLinkage(SILLinkage::Shared); } } void swift::performSILCleanup(SILModule *M) { for (auto &Fn : *M) cleanFunction(Fn); } namespace { class SILCleanup : public swift::SILFunctionTransform { /// The entry point to the transformation. void run() { cleanFunction(*getFunction()); invalidateAnalysis(SILAnalysis::InvalidationKind::All); } StringRef getName() override { return "SIL Cleanup"; } }; } // end anonymous namespace SILTransform *swift::createSILCleanup() { return new SILCleanup(); } <|endoftext|>
<commit_before>#include "../columns/Communicator.hpp" #include <assert.h> #include <gdal_priv.h> #include <mpi.h> #include <ogr_spatialref.h> #undef DEBUG_OUTPUT static void copyToLocBuffer(int buf[], LayerLoc * loc) { buf[0] = loc->nx; buf[1] = loc->ny; buf[2] = loc->nxGlobal; buf[3] = loc->nyGlobal; buf[4] = loc->kx0; buf[5] = loc->ky0; buf[6] = loc->nPad; buf[7] = loc->nBands; } static void copyFromLocBuffer(int buf[], LayerLoc * loc) { loc->nx = buf[0]; loc->ny = buf[1]; loc->nxGlobal = buf[2]; loc->nyGlobal = buf[3]; loc->kx0 = buf[4]; loc->ky0 = buf[5]; loc->nPad = buf[6]; loc->nBands = buf[7]; } /** * Calculates location information given processor distribution and the * size of the image. * * @filename the name of the image file (in) * @ic the inter-column communicator (in) * @loc location information (inout) (loc->nx and loc->ny are out) */ int getImageInfo(const char* filename, PV::Communicator * comm, LayerLoc * loc) { const int locSize = sizeof(LayerLoc) / sizeof(int); int locBuf[locSize]; int err = 0; // LayerLoc should contain 8 ints assert(locSize == 8); const int nxProcs = comm->numCommColumns(); const int nyProcs = comm->numCommRows(); const int icCol = comm->commColumn(); const int icRow = comm->commRow(); #ifdef DEBUG_OUTPUT fprintf(stderr, "[%2d]: nxProcs==%d nyProcs==%d icRow==%d icCol==%d\n", comm->commRank(), nxProcs, nyProcs, icRow, icCol); #endif if (comm->commRank() == 0) { GDALAllRegister(); GDALDataset * dataset = (GDALDataset *) GDALOpen(filename, GA_ReadOnly); if (dataset == NULL) return 1; int xImageSize = dataset->GetRasterXSize(); int yImageSize = dataset->GetRasterYSize(); loc->nBands = dataset->GetRasterCount(); // calculate local layer size int nx = xImageSize / nxProcs; int ny = yImageSize / nyProcs; loc->nx = nx; loc->ny = ny; loc->nxGlobal = nxProcs * nx; loc->nyGlobal = nyProcs * ny; copyToLocBuffer(locBuf, loc); GDALClose(dataset); } // broadcast location information MPI_Bcast(locBuf, 1+locSize, MPI_INT, 0, comm->communicator()); copyFromLocBuffer(locBuf, loc); // fix up layer indices loc->kx0 = loc->nx * icCol; loc->ky0 = loc->ny * icRow; return err; } /** * @filename */ int scatterImageFile(const char * filename, PV::Communicator * comm, LayerLoc * loc, float * buf) { int err = 0; const int tag = 13; const MPI_Comm icComm = comm->communicator(); const int nxProcs = comm->numCommColumns(); const int nyProcs = comm->numCommRows(); const int icRank = comm->commRank(); const int nx = loc->nx; const int ny = loc->ny; if (icRank > 0) { const int src = 0; MPI_Recv(buf, nx*ny, MPI_FLOAT, src, tag, icComm, MPI_STATUS_IGNORE); #ifdef DEBUG_OUTPUT fprintf(stderr, "[%2d]: scatter: received from 0, nx==%d ny==%d size==%d\n", comm->commRank(), nx, ny, nx*ny); #endif } else { GDALAllRegister(); GDALDataset * dataset = (GDALDataset *) GDALOpen(filename, GA_ReadOnly); int xImageSize = dataset->GetRasterXSize(); int yImageSize = dataset->GetRasterYSize(); int xTotalSize = nx * nxProcs; int yTotalSize = ny * nyProcs; if (xTotalSize > xImageSize || yTotalSize > yImageSize) { fprintf(stderr, "[ 0]: scatterImageFile: image size too small, " "xTotalSize==%d xImageSize==%d yTotalSize==%d yImageSize==%d\n", xTotalSize, xImageSize, yTotalSize, yImageSize); fprintf(stderr, "[ 0]: xSize==%d ySize==%d nxProcs==%d nyProcs==%d\n", nx, ny, nxProcs, nyProcs); GDALClose(dataset); return -1; } // TODO - decide what to do about multiband images (color) // include each band GDALRasterBand * band = dataset->GetRasterBand(1); int dest = -1; for (int py = 0; py < nyProcs; py++) { for (int px = 0; px < nxProcs; px++) { if (++dest == 0) continue; int kx = nx * px; int ky = ny * py; #ifdef DEBUG_OUTPUT fprintf(stderr, "[%2d]: scatter: sending to %d xSize==%d" " ySize==%d size==%d total==%d\n", comm->commRank(), dest, nx, ny, nx*ny, nx*ny*comm->commSize()); #endif band->RasterIO(GF_Read, kx, ky, nx, ny, buf, nx, ny, GDT_Float32, 0, 0); MPI_Send(buf, nx*ny, MPI_FLOAT, dest, tag, icComm); } } // get local image portion band->RasterIO(GF_Read, 0, 0, nx, ny, buf, nx, ny, GDT_Float32, 0, 0); GDALClose(dataset); } return err; } /** * @filename */ int gatherImageFile(const char * filename, PV::Communicator * comm, LayerLoc * loc, float * buf) { int err = 0; const int tag = 14; const MPI_Comm icComm = comm->communicator(); const int nxProcs = comm->numCommColumns(); const int nyProcs = comm->numCommRows(); const int icRank = comm->commRank(); const int nx = loc->nx; const int ny = loc->ny; //TODO - color const int numBands = loc->nBands; if (icRank > 0) { const int dest = 0; MPI_Send(buf, nx*ny, MPI_FLOAT, dest, tag, icComm); #ifdef DEBUG_OUTPUT fprintf(stderr, "[%2d]: gather: sent to 0, nx==%d ny==%d size==%d\n", comm->commRank(), nx, ny, nx*ny); #endif } else { //#include "cpl_string.h" GDALAllRegister(); char ** metadata; GDALDriver * driver = GetGDALDriverManager()->GetDriverByName("GTiff"); if( driver == NULL ) exit( 1 ); metadata = driver->GetMetadata(); if( CSLFetchBoolean( metadata, GDAL_DCAP_CREATE, FALSE ) ) { // printf("Driver %s supports Create() method.\n", "GTiff"); } GDALDataset * dataset; char ** options = NULL; int xImageSize = nx * nxProcs; int yImageSize = ny * nyProcs; dataset = driver->Create(filename, xImageSize, yImageSize, numBands, GDT_Byte, options); if (dataset == NULL) { fprintf(stderr, "[%2d]: gather: failed to open file %s\n", comm->commRank(), filename); } else { #ifdef DEBUG_OUTPUT fprintf(stderr, "[%2d]: gather: opened file %s\n", comm->commRank(), filename); #endif } double adfGeoTransform[6] = { 444720, 30, 0, 3751320, 0, -30 }; OGRSpatialReference oSRS; char *pszSRS_WKT = NULL; dataset->SetGeoTransform( adfGeoTransform ); oSRS.SetUTM( 11, TRUE ); oSRS.SetWellKnownGeogCS( "NAD27" ); oSRS.exportToWkt( &pszSRS_WKT ); dataset->SetProjection( pszSRS_WKT ); CPLFree( pszSRS_WKT ); // TODO - decide what to do about multiband images (color) // include each band GDALRasterBand * band = dataset->GetRasterBand(1); // write local image portion band->RasterIO(GF_Write, 0, 0, nx, ny, buf, nx, ny, GDT_Float32, 0, 0); int src = -1; for (int py = 0; py < nyProcs; py++) { for (int px = 0; px < nxProcs; px++) { if (++src == 0) continue; int kx = nx * px; int ky = ny * py; #ifdef DEBUG_OUTPUT fprintf(stderr, "[%2d]: gather: receiving from %d xSize==%d" " ySize==%d size==%d total==%d\n", comm->commRank(), src, nx, ny, nx*ny, nx*ny*comm->commSize()); #endif MPI_Recv(buf, nx*ny, MPI_FLOAT, src, tag, icComm, MPI_STATUS_IGNORE); band->RasterIO(GF_Write, kx, ky, nx, ny, buf, nx, ny, GDT_Float32, 0, 0); } } GDALClose(dataset); } return err; } int scatterImageBlocks(const char* filename, PV::Communicator * comm, LayerLoc * loc, float * buf) { int err = 0; #ifdef UNIMPLEMENTED const MPI_Comm icComm = comm->communicator(); const int nxProcs = comm->numCommColumns(); const int nyProcs = comm->numCommRows(); const int icRank = comm->commRank(); const int icCol = comm->commColumn(); const int icRow = comm->commRow(); const int nx = loc->nx; const int ny = loc->ny; const int nxGlobal = loc->nxGlobal; const int nyBorder = loc->nyBorder; const int xSize = nx + 2 * nxGlobal; const int ySize = ny + 2 * nyBorder; if (icRank > 0) { } else { int nxBlocks, nyBlocks, nxBlockSize, nyBlockSize; int ixBlock, iyBlock; GDALAllRegister(); GDALDataset * dataset = (GDALDataset *) GDALOpen(filename, GA_ReadOnly); GDALRasterBand * band = dataset->GetRasterBand(1); CPLAssert(band->GetRasterDataType() == GDT_Byte); band->GetBlockSize(&nxBlockSize, &nyBlockSize); nxBlocks = (band->GetXSize() + nxBlockSize - 1) / nxBlockSize; nyBlocks = (band->GetYSize() + nyBlockSize - 1) / nyBlockSize; GByte * data = (GByte *) CPLMalloc(nxBlockSize * nyBlockSize); fprintf(stderr, "[ 0]: nxBlockSize==%d nyBlockSize==%d" " nxBlocks==%d nyBlocks==%d\n", nxBlockSize, nyBlockSize, nxBlocks, nyBlocks); for (iyBlock = 0; iyBlock < nyBlocks; iyBlock++) { for (ixBlock = 0; ixBlock < nxBlocks; ixBlock++) { int nxValid, nyValid; band->ReadBlock(ixBlock, ixBlock, data); } } } #endif return err; } /** * gather relevant portions of buf on root process from all others * NOTE: buf is np times larger on root process */ int gather (PV::Communicator * comm, LayerLoc * loc, float * buf) { return -1; } /** * scatter relevant portions of buf from root process to all others * NOTE: buf is np times larger on root process */ int scatter(PV::Communicator * comm, LayerLoc * loc, float * buf) { return -1; } int writeWithBorders(const char * filename, LayerLoc * loc, float * buf) { int X = loc->nx + 2 * loc->nPad; int Y = loc->ny + 2 * loc->nPad; int B = loc->nBands; GDALDriver * driver = GetGDALDriverManager()->GetDriverByName("GTiff"); GDALDataset* layer_file = driver->Create(filename, X, Y, B, GDT_Byte, NULL); // TODO - add multiple raster bands GDALRasterBand * band = layer_file->GetRasterBand(1); band->RasterIO(GF_Write, 0, 0, X, Y, buf, X, Y, GDT_Float32, 0, 0); GDALClose(layer_file); return 0; } <commit_msg>Added handling of color bands.<commit_after>#include "../columns/Communicator.hpp" #include <assert.h> #include <gdal_priv.h> #include <mpi.h> #include <ogr_spatialref.h> #undef DEBUG_OUTPUT static void copyToLocBuffer(int buf[], LayerLoc * loc) { buf[0] = loc->nx; buf[1] = loc->ny; buf[2] = loc->nxGlobal; buf[3] = loc->nyGlobal; buf[4] = loc->kx0; buf[5] = loc->ky0; buf[6] = loc->nPad; buf[7] = loc->nBands; } static void copyFromLocBuffer(int buf[], LayerLoc * loc) { loc->nx = buf[0]; loc->ny = buf[1]; loc->nxGlobal = buf[2]; loc->nyGlobal = buf[3]; loc->kx0 = buf[4]; loc->ky0 = buf[5]; loc->nPad = buf[6]; loc->nBands = buf[7]; } /** * Calculates location information given processor distribution and the * size of the image. * * @filename the name of the image file (in) * @ic the inter-column communicator (in) * @loc location information (inout) (loc->nx and loc->ny are out) */ int getImageInfo(const char* filename, PV::Communicator * comm, LayerLoc * loc) { const int locSize = sizeof(LayerLoc) / sizeof(int); int locBuf[locSize]; int status = 0; // LayerLoc should contain 8 ints assert(locSize == 8); const int nxProcs = comm->numCommColumns(); const int nyProcs = comm->numCommRows(); const int icCol = comm->commColumn(); const int icRow = comm->commRow(); #ifdef DEBUG_OUTPUT fprintf(stderr, "[%2d]: nxProcs==%d nyProcs==%d icRow==%d icCol==%d\n", comm->commRank(), nxProcs, nyProcs, icRow, icCol); #endif if (comm->commRank() == 0) { GDALAllRegister(); GDALDataset * dataset = (GDALDataset *) GDALOpen(filename, GA_ReadOnly); if (dataset == NULL) return 1; int xImageSize = dataset->GetRasterXSize(); int yImageSize = dataset->GetRasterYSize(); loc->nBands = dataset->GetRasterCount(); // calculate local layer size int nx = xImageSize / nxProcs; int ny = yImageSize / nyProcs; loc->nx = nx; loc->ny = ny; loc->nxGlobal = nxProcs * nx; loc->nyGlobal = nyProcs * ny; copyToLocBuffer(locBuf, loc); GDALClose(dataset); } // broadcast location information MPI_Bcast(locBuf, 1+locSize, MPI_INT, 0, comm->communicator()); copyFromLocBuffer(locBuf, loc); // fix up layer indices loc->kx0 = loc->nx * icCol; loc->ky0 = loc->ny * icRow; return status; } /** * @filename */ int scatterImageFile(const char * filename, PV::Communicator * comm, LayerLoc * loc, float * buf) { int status = 0; const int tag = 13; const int maxBands = 3; const MPI_Comm mpi_comm = comm->communicator(); const int nxProcs = comm->numCommColumns(); const int nyProcs = comm->numCommRows(); const int icRank = comm->commRank(); const int nx = loc->nx; const int ny = loc->ny; const int numBands = loc->nBands; assert(numBands <= maxBands); const int nxny = nx * ny; const int numTotal = nxny * numBands; if (icRank > 0) { const int src = 0; for (int b = 0; b < numBands; b++) { MPI_Recv(&buf[b*nxny], numTotal, MPI_FLOAT, src, tag, mpi_comm, MPI_STATUS_IGNORE); } #ifdef DEBUG_OUTPUT fprintf(stderr, "[%2d]: scatter: received from 0, nx==%d ny==%d size==%d\n", comm->commRank(), nx, ny, numTotal); #endif } else { GDALAllRegister(); GDALDataset * dataset = (GDALDataset *) GDALOpen(filename, GA_ReadOnly); int xImageSize = dataset->GetRasterXSize(); int yImageSize = dataset->GetRasterYSize(); int xTotalSize = nx * nxProcs; int yTotalSize = ny * nyProcs; if (xTotalSize > xImageSize || yTotalSize > yImageSize) { fprintf(stderr, "[ 0]: scatterImageFile: image size too small, " "xTotalSize==%d xImageSize==%d yTotalSize==%d yImageSize==%d\n", xTotalSize, xImageSize, yTotalSize, yImageSize); fprintf(stderr, "[ 0]: xSize==%d ySize==%d nxProcs==%d nyProcs==%d\n", nx, ny, nxProcs, nyProcs); GDALClose(dataset); return -1; } GDALRasterBand * band[maxBands]; assert(numBands <= dataset->GetRasterCount()); for (int b = 0; b < numBands; b++) { band[b] = dataset->GetRasterBand(b+1); } int dest = -1; for (int py = 0; py < nyProcs; py++) { for (int px = 0; px < nxProcs; px++) { if (++dest == 0) continue; int kx = nx * px; int ky = ny * py; #ifdef DEBUG_OUTPUT fprintf(stderr, "[%2d]: scatter: sending to %d xSize==%d" " ySize==%d size==%d total==%d\n", comm->commRank(), dest, nx, ny, nx*ny, nx*ny*comm->commSize()); #endif for (int b = 0; b < numBands; b++) { band[b]->RasterIO(GF_Read, kx, ky, nx, ny, &buf[b*nxny], nx, ny, GDT_Float32, 0, 0); MPI_Send(&buf[b*nxny], nx*ny, MPI_FLOAT, dest, tag, mpi_comm); } } } // get local image portion for (int b = 0; b < numBands; b++) { band[b]->RasterIO(GF_Read, 0, 0, nx, ny, &buf[b*nxny], nx, ny, GDT_Float32, 0, 0); } GDALClose(dataset); } return status; } /** * @filename */ int gatherImageFile(const char * filename, PV::Communicator * comm, LayerLoc * loc, float * buf) { int status = 0; const int tag = 14; const int maxBands = 3; const MPI_Comm mpi_comm = comm->communicator(); const int nxProcs = comm->numCommColumns(); const int nyProcs = comm->numCommRows(); const int icRank = comm->commRank(); const int nx = loc->nx; const int ny = loc->ny; const int numBands = loc->nBands; assert(numBands <= maxBands); const int nxny = nx * ny; const int numTotal = nxny * numBands; if (icRank > 0) { const int dest = 0; for (int b = 0; b < numBands; b++) { MPI_Send(&buf[b*nxny], nx*ny, MPI_FLOAT, dest, tag, mpi_comm); } #ifdef DEBUG_OUTPUT fprintf(stderr, "[%2d]: gather: sent to 0, nx==%d ny==%d size==%d\n", comm->commRank(), nx, ny, nx*ny); #endif } else { //#include "cpl_string.h" GDALAllRegister(); char ** metadata; GDALDriver * driver = GetGDALDriverManager()->GetDriverByName("GTiff"); if( driver == NULL ) exit( 1 ); metadata = driver->GetMetadata(); if( CSLFetchBoolean( metadata, GDAL_DCAP_CREATE, FALSE ) ) { // printf("Driver %s supports Create() method.\n", "GTiff"); } GDALDataset * dataset; char ** options = NULL; int xImageSize = nx * nxProcs; int yImageSize = ny * nyProcs; dataset = driver->Create(filename, xImageSize, yImageSize, numBands, GDT_Byte, options); if (dataset == NULL) { fprintf(stderr, "[%2d]: gather: failed to open file %s\n", comm->commRank(), filename); } else { #ifdef DEBUG_OUTPUT fprintf(stderr, "[%2d]: gather: opened file %s\n", comm->commRank(), filename); #endif } // double adfGeoTransform[6] = { 444720, 30, 0, 3751320, 0, -30 }; // OGRSpatialReference oSRS; // char *pszSRS_WKT = NULL; // dataset->SetGeoTransform( adfGeoTransform ); // oSRS.SetUTM( 11, TRUE ); // oSRS.SetWellKnownGeogCS( "NAD27" ); // oSRS.exportToWkt( &pszSRS_WKT ); // dataset->SetProjection( pszSRS_WKT ); // CPLFree( pszSRS_WKT ); GDALRasterBand * band[maxBands]; assert(numBands <= dataset->GetRasterCount()); for (int b = 0; b < numBands; b++) { band[b] = dataset->GetRasterBand(b+1); } // write local image portion for (int b = 0; b < numBands; b++) { band[b]->RasterIO(GF_Write, 0, 0, nx, ny, &buf[b*nxny], nx, ny, GDT_Float32, 0, 0); } int src = -1; for (int py = 0; py < nyProcs; py++) { for (int px = 0; px < nxProcs; px++) { if (++src == 0) continue; int kx = nx * px; int ky = ny * py; #ifdef DEBUG_OUTPUT fprintf(stderr, "[%2d]: gather: receiving from %d xSize==%d" " ySize==%d size==%d total==%d\n", comm->commRank(), src, nx, ny, numTotal, numTotal*comm->commSize()); #endif for (int b = 0; b < numBands; b++) { MPI_Recv(&buf[b*nxny], numTotal, MPI_FLOAT, src, tag, mpi_comm, MPI_STATUS_IGNORE); band[b]->RasterIO(GF_Write, kx, ky, nx, ny, &buf[b*nxny], nx, ny, GDT_Float32, 0, 0); } } } GDALClose(dataset); } return status; } int scatterImageBlocks(const char* filename, PV::Communicator * comm, LayerLoc * loc, float * buf) { int status = 0; #ifdef UNIMPLEMENTED const MPI_Comm icComm = comm->communicator(); const int nxProcs = comm->numCommColumns(); const int nyProcs = comm->numCommRows(); const int icRank = comm->commRank(); const int icCol = comm->commColumn(); const int icRow = comm->commRow(); const int nx = loc->nx; const int ny = loc->ny; const int nxGlobal = loc->nxGlobal; const int nyBorder = loc->nyBorder; const int xSize = nx + 2 * nxGlobal; const int ySize = ny + 2 * nyBorder; if (icRank > 0) { } else { int nxBlocks, nyBlocks, nxBlockSize, nyBlockSize; int ixBlock, iyBlock; GDALAllRegister(); GDALDataset * dataset = (GDALDataset *) GDALOpen(filename, GA_ReadOnly); GDALRasterBand * band = dataset->GetRasterBand(1); CPLAssert(band->GetRasterDataType() == GDT_Byte); band->GetBlockSize(&nxBlockSize, &nyBlockSize); nxBlocks = (band->GetXSize() + nxBlockSize - 1) / nxBlockSize; nyBlocks = (band->GetYSize() + nyBlockSize - 1) / nyBlockSize; GByte * data = (GByte *) CPLMalloc(nxBlockSize * nyBlockSize); fprintf(stderr, "[ 0]: nxBlockSize==%d nyBlockSize==%d" " nxBlocks==%d nyBlocks==%d\n", nxBlockSize, nyBlockSize, nxBlocks, nyBlocks); for (iyBlock = 0; iyBlock < nyBlocks; iyBlock++) { for (ixBlock = 0; ixBlock < nxBlocks; ixBlock++) { int nxValid, nyValid; band->ReadBlock(ixBlock, ixBlock, data); } } } #endif return status; } /** * gather relevant portions of buf on root process from all others * NOTE: buf is np times larger on root process */ int gather (PV::Communicator * comm, LayerLoc * loc, float * buf) { return -1; } /** * scatter relevant portions of buf from root process to all others * NOTE: buf is np times larger on root process */ int scatter(PV::Communicator * comm, LayerLoc * loc, float * buf) { return -1; } int writeWithBorders(const char * filename, LayerLoc * loc, float * buf) { int X = loc->nx + 2 * loc->nPad; int Y = loc->ny + 2 * loc->nPad; int B = loc->nBands; GDALDriver * driver = GetGDALDriverManager()->GetDriverByName("GTiff"); GDALDataset* layer_file = driver->Create(filename, X, Y, B, GDT_Byte, NULL); // TODO - add multiple raster bands GDALRasterBand * band = layer_file->GetRasterBand(1); band->RasterIO(GF_Write, 0, 0, X, Y, buf, X, Y, GDT_Float32, 0, 0); GDALClose(layer_file); return 0; } <|endoftext|>
<commit_before>// Qt includes #include <QUrl> #include <xbmcvideochecker/XBMCVideoChecker.h> XBMCVideoChecker::XBMCVideoChecker(const std::string & address, uint16_t port, uint64_t interval_ms, bool grabVideo, bool grabPhoto, bool grabAudio, bool grabMenu) : QObject(), _address(QString::fromStdString(address)), _port(port), _request(R"({"jsonrpc":"2.0","method":"Player.GetActivePlayers","id":666})"), _timer(), _socket(), _grabVideo(grabVideo), _grabPhoto(grabPhoto), _grabAudio(grabAudio), _grabMenu(grabMenu), _previousMode(GRABBINGMODE_INVALID) { // setup timer _timer.setSingleShot(false); _timer.setInterval(interval_ms); connect(&_timer, SIGNAL(timeout()), this, SLOT(sendRequest())); // setup socket connect(&_socket, SIGNAL(readyRead()), this, SLOT(receiveReply())); } void XBMCVideoChecker::start() { _timer.start(); } void XBMCVideoChecker::sendRequest() { switch (_socket.state()) { case QTcpSocket::UnconnectedState: // not connected. try to connect std::cout << "Connecting to " << _address.toStdString() << ":" << _port << " to check XBMC player status" << std::endl; _socket.connectToHost(_address, _port); break; case QTcpSocket::ConnectedState: // write the request on the socket _socket.write(_request); break; default: // whatever. let's check again at the next timer tick break; } } void XBMCVideoChecker::receiveReply() { // expect that the reply is received as a single message. Probably oke considering the size of the expected reply QString reply(_socket.readAll()); // check if the resply is a reply to one of my requests if (!reply.contains("\"id\":666")) { // probably not. Leave this mreply as is and don't act on it return; } GrabbingMode newMode = GRABBINGMODE_INVALID; if (reply.contains("video")) { // video is playing newMode = _grabVideo ? GRABBINGMODE_VIDEO : GRABBINGMODE_OFF; } else if (reply.contains("picture")) { // picture viewer is playing newMode = _grabPhoto ? GRABBINGMODE_PHOTO : GRABBINGMODE_OFF; } else if (reply.contains("audio")) { // audio is playing newMode = _grabAudio ? GRABBINGMODE_AUDIO : GRABBINGMODE_OFF; } else { // Nothing is playing. newMode = _grabMenu ? GRABBINGMODE_MENU : GRABBINGMODE_OFF; } // emit new state if applicable if (newMode != _previousMode) { switch (newMode) { case GRABBINGMODE_VIDEO: std::cout << "XBMC checker: switching to VIDEO" << std::endl; break; case GRABBINGMODE_PHOTO: std::cout << "XBMC checker: switching to PHOTO" << std::endl; break; case GRABBINGMODE_AUDIO: std::cout << "XBMC checker: switching to AUDIO" << std::endl; break; case GRABBINGMODE_MENU: std::cout << "XBMC checker: switching to MENU" << std::endl; break; case GRABBINGMODE_OFF: std::cout << "XBMC checker: switching to OFF" << std::endl; break; case GRABBINGMODE_INVALID: std::cout << "XBMC checker: switching to INVALID" << std::endl; break; } emit grabbingMode(newMode); _previousMode = newMode; } } <commit_msg>added extra console output to the xbmc checker<commit_after>// Qt includes #include <QUrl> #include <xbmcvideochecker/XBMCVideoChecker.h> XBMCVideoChecker::XBMCVideoChecker(const std::string & address, uint16_t port, uint64_t interval_ms, bool grabVideo, bool grabPhoto, bool grabAudio, bool grabMenu) : QObject(), _address(QString::fromStdString(address)), _port(port), _request(R"({"jsonrpc":"2.0","method":"Player.GetActivePlayers","id":666})"), _timer(), _socket(), _grabVideo(grabVideo), _grabPhoto(grabPhoto), _grabAudio(grabAudio), _grabMenu(grabMenu), _previousMode(GRABBINGMODE_INVALID) { // setup timer _timer.setSingleShot(false); _timer.setInterval(interval_ms); connect(&_timer, SIGNAL(timeout()), this, SLOT(sendRequest())); // setup socket connect(&_socket, SIGNAL(readyRead()), this, SLOT(receiveReply())); } void XBMCVideoChecker::start() { _timer.start(); } void XBMCVideoChecker::sendRequest() { switch (_socket.state()) { case QTcpSocket::UnconnectedState: // not connected. try to connect std::cout << "Connecting to " << _address.toStdString() << ":" << _port << " to check XBMC player status" << std::endl; _socket.connectToHost(_address, _port); break; case QTcpSocket::ConnectedState: // write the request on the socket _socket.write(_request); break; default: // whatever. let's check again at the next timer tick break; } } void XBMCVideoChecker::receiveReply() { // expect that the reply is received as a single message. Probably oke considering the size of the expected reply QString reply(_socket.readAll()); // check if the resply is a reply to one of my requests if (!reply.contains("\"id\":666")) { // probably not. Leave this mreply as is and don't act on it return; } GrabbingMode newMode = GRABBINGMODE_INVALID; if (reply.contains("video")) { // video is playing newMode = _grabVideo ? GRABBINGMODE_VIDEO : GRABBINGMODE_OFF; } else if (reply.contains("picture")) { // picture viewer is playing newMode = _grabPhoto ? GRABBINGMODE_PHOTO : GRABBINGMODE_OFF; } else if (reply.contains("audio")) { // audio is playing newMode = _grabAudio ? GRABBINGMODE_AUDIO : GRABBINGMODE_OFF; } else { // Nothing is playing. newMode = _grabMenu ? GRABBINGMODE_MENU : GRABBINGMODE_OFF; } // emit new state if applicable if (newMode != _previousMode && newMode != GRABBINGMODE_INVALID) { switch (newMode) { case GRABBINGMODE_VIDEO: std::cout << "XBMC checker: switching to VIDEO" << std::endl; break; case GRABBINGMODE_PHOTO: std::cout << "XBMC checker: switching to PHOTO" << std::endl; break; case GRABBINGMODE_AUDIO: std::cout << "XBMC checker: switching to AUDIO" << std::endl; break; case GRABBINGMODE_MENU: std::cout << "XBMC checker: switching to MENU" << std::endl; break; case GRABBINGMODE_OFF: std::cout << "XBMC checker: switching to OFF" << std::endl; break; case GRABBINGMODE_INVALID: std::cout << "XBMC checker: switching to INVALID" << std::endl; break; } emit grabbingMode(newMode); _previousMode = newMode; } } <|endoftext|>
<commit_before>/** * @file serialization_macros.hpp * @author Simon Lynen <simon.lynen@mavt.ethz.ch> * @date Thu May 22 02:55:13 2013 * * @brief Comparison macros to facilitate checking in serialization methods. * * */ #ifndef SM_SERIALIZATION_MACROS_HPP #define SM_SERIALIZATION_MACROS_HPP #include <type_traits> #include <sstream> #include <ostream> #include <iostream> #include <boost/static_assert.hpp> #include <boost/shared_ptr.hpp> #include <sm/typetraits.hpp> namespace cv{ class Mat; } namespace sm{ namespace serialization{ namespace internal_types{ typedef char yes; typedef int no; } } struct AnyT { template<class T> AnyT(const T &); }; sm::serialization::internal_types::no operator <<(const AnyT &, const AnyT &); namespace serialization{ namespace internal{ template<class T> sm::serialization::internal_types::yes check(const T&); sm::serialization::internal_types::no check(sm::serialization::internal_types::no){return sm::serialization::internal_types::no();}; struct makeCompilerSilent{ //rm warning about unused functions void foo(){ check(sm::serialization::internal_types::no()); AnyT t(5); operator <<(t, t); } }; //this template metaprogramming struct can tell us if there is the operator<< defined somewhere template<typename StreamType, typename T> class HasOStreamOperator { static StreamType & stream; static T & x; public: enum { value = sizeof(check(stream << x)) == sizeof(sm::serialization::internal_types::yes) }; }; template<typename StreamType, typename T> class HasOStreamOperator<StreamType, boost::shared_ptr<T> > { public: enum { value = HasOStreamOperator<StreamType, T>::value }; }; template<typename StreamType, typename T> class HasOStreamOperator<StreamType, T* > { public: enum { value = HasOStreamOperator<StreamType, T>::value }; }; template<typename StreamType, typename T> class HasOStreamOperator<StreamType, T& > { public: enum { value = HasOStreamOperator<StreamType, T>::value }; }; //this template metaprogramming struct can tell us whether a class has a member //function isBinaryEqual template<typename T> class HasIsBinaryEqual { //for non const methods (which is actually wrong) template<typename U, bool (U::*)(const T&)> struct Check; template<typename U> static char func(Check<U, &U::isBinaryEqual> *); template<typename U> static int func(...); //for const methods template<typename U, bool (U::*)(const T&) const> struct CheckConst; template<typename U> static char funcconst(CheckConst<U, &U::isBinaryEqual> *); template<typename U> static int funcconst(...); public: enum { value = (sizeof(func<T>(0)) == sizeof(char)) || (sizeof(funcconst<T>(0)) == sizeof(char)) }; }; template<typename T> class HasIsBinaryEqual<boost::shared_ptr<T> > { public: enum { value = HasIsBinaryEqual<T>::value }; }; template<typename T> class HasIsBinaryEqual<T*> { public: enum { value = HasIsBinaryEqual<T>::value }; }; template<typename T> class HasIsBinaryEqual<T&> { public: enum { value = HasIsBinaryEqual<T>::value }; }; //these structs are used to choose between isBinaryEqual function call and the //default operator== template<bool, typename A> struct isSame; template<typename A> struct isSame<true, A> { static bool eval(const A& lhs, const A& rhs) { return lhs.isBinaryEqual(rhs); } }; template<typename A> struct isSame<true, boost::shared_ptr<A> > { static bool eval(const boost::shared_ptr<A>& lhs, const boost::shared_ptr<A>& rhs) { if (!lhs && !rhs) { return true; } if (!lhs || !rhs) { return false; } return lhs->isBinaryEqual(*rhs); } }; template<typename A> struct isSame<true, A* > { static bool eval(const A* const lhs, const A* const rhs) { if (!lhs && !rhs) { return true; } if (!lhs || !rhs) { return false; } return lhs->isBinaryEqual(*rhs); } }; template<typename A> struct isSame<false, A> { static bool eval(const A& lhs, const A& rhs) { return lhs == rhs; } }; template<typename A> struct isSame<false, A*> { static bool eval(A const * lhs, A const * rhs) { if (!lhs && !rhs) { return true; } if (!lhs || !rhs) { return false; } return *lhs == *rhs; } }; template<typename A> struct isSame<false, boost::shared_ptr<A> > { static bool eval(const boost::shared_ptr<A>& lhs, const boost::shared_ptr<A>& rhs) { if (!lhs && !rhs) { return true; } if (!lhs || !rhs) { return false; } return *lhs == *rhs; } }; //for opencv Mat we have to use the sm opencv isBinaryEqual method otherwise sm_common has to depend on sm_opencv template<typename T, bool B> struct checkTypeIsNotOpencvMat { enum{ value = true, }; }; template<bool B> struct checkTypeIsNotOpencvMat<cv::Mat, B> { enum{ value = true, //yes true is correct here }; BOOST_STATIC_ASSERT_MSG((B == !B) /*false*/, "You cannot use the macro SM_CHECKSAME or SM_CHECKSAMEMEMBER on opencv mat. Use sm::opencv::isBinaryEqual instead"); }; template<bool B> struct checkTypeIsNotOpencvMat<boost::shared_ptr<cv::Mat>, B > { enum{ value = true, //yes true is correct here }; BOOST_STATIC_ASSERT_MSG((B == !B) /*false*/, "You cannot use the macro SM_CHECKSAME or SM_CHECKSAMEMEMBER on opencv mat. Use sm::opencv::isBinaryEqual instead"); }; template<bool B> struct checkTypeIsNotOpencvMat<cv::Mat*, B> { enum{ value = true, //yes true is correct here }; BOOST_STATIC_ASSERT_MSG((B == !B) /*false*/, "You cannot use the macro SM_CHECKSAME or SM_CHECKSAMEMEMBER on opencv mat. Use sm::opencv::isBinaryEqual instead"); }; //if the object supports it stream to ostream, otherwise put NA template<bool, typename A> struct streamIf; template<typename A> struct streamIf<true, A> { static std::string eval(const A& rhs) { std::stringstream ss; ss << rhs; return ss.str(); } }; template<typename A> struct streamIf<true, A*> { static std::string eval(const A* rhs) { if (!rhs) { return "NULL"; } std::stringstream ss; ss << *rhs; return ss.str(); } }; template<typename A> struct streamIf<true, boost::shared_ptr<A> > { static std::string eval(const boost::shared_ptr<A>& rhs) { if (!rhs) { return "NULL"; } std::stringstream ss; ss << *rhs; return ss.str(); } }; template<typename A> struct streamIf<true, boost::shared_ptr<const A> > { static std::string eval(const boost::shared_ptr<const A>& rhs) { if (!rhs) { return "NULL"; } std::stringstream ss; ss << *rhs; return ss.str(); } }; template<typename A> struct streamIf<false, A> { static std::string eval(const A&) { return "NA"; } }; } } } //these defines set the default behaviour if no verbosity argument is given #define SM_SERIALIZATION_CHECKSAME_VERBOSE(THIS, OTHER) SM_SERIALIZATION_CHECKSAME_IMPL(THIS, OTHER, true) #define SM_SERIALIZATION_CHECKMEMBERSSAME_VERBOSE(OTHER, MEMBER) SM_SERIALIZATION_CHECKMEMBERSSAME_IMPL(OTHER, MEMBER, true) #define SM_SERIALIZATION_CHECKSAME_IMPL(THIS, OTHER, VERBOSE) \ (sm::serialization::internal::checkTypeIsNotOpencvMat<typename sm::common::StripConstReference<decltype(OTHER)>::result_t, false>::value && /*for opencvMats we have to use sm::opencv::isBinaryEqual otherwise this code has to depend on opencv*/ \ sm::serialization::internal::isSame<sm::serialization::internal::HasIsBinaryEqual<typename sm::common::StripConstReference<decltype(OTHER)>::result_t>::value, /*first run the test of equality: either isBinaryEqual or op==*/ \ typename sm::common::StripConstReference<decltype(OTHER)>::result_t >::eval(THIS, OTHER)) ? true : /*return true if good*/ \ (VERBOSE ? (std::cout << "*** Validation failed on " << #OTHER << ": "<< /*if not true, check whether VERBOSE and then try to output the failed values using operator<<*/ \ sm::serialization::internal::streamIf<sm::serialization::internal::HasOStreamOperator<std::ostream, typename sm::common::StripConstReference<decltype(OTHER)>::result_t>::value, /*here we check whether operator<< is available*/ \ typename sm::common::StripConstReference<decltype(OTHER)>::result_t >::eval(THIS) << \ " other " << sm::serialization::internal::streamIf<sm::serialization::internal::HasOStreamOperator<std::ostream, typename sm::common::StripConstReference<decltype(OTHER)>::result_t>::value, \ typename sm::common::StripConstReference<decltype(OTHER)>::result_t>::eval(OTHER) \ << " at " << __PRETTY_FUNCTION__ << /*we print the function where this happened*/ \ " In: " << __FILE__ << ":" << __LINE__ << std::endl << std::endl) && false : false) /*we print the line and file where this happened*/ #define SM_SERIALIZATION_CHECKMEMBERSSAME_IMPL(OTHER, MEMBER, VERBOSE) \ ((sm::serialization::internal::checkTypeIsNotOpencvMat<typename sm::common::StripConstReference<decltype(OTHER)>::result_t, false>::value) && /*for opencvMats we have to use sm::opencv::isBinaryEqual otherwise this code has to depend on opencv*/\ (sm::serialization::internal::isSame<sm::serialization::internal::HasIsBinaryEqual<typename sm::common::StripConstReference<decltype(MEMBER)>::result_t>::value, \ typename sm::common::StripConstReference<decltype(MEMBER)>::result_t >::eval(this->MEMBER, OTHER.MEMBER))) ? true :\ (VERBOSE ? (std::cout << "*** Validation failed on " << #MEMBER << ": "<< \ sm::serialization::internal::streamIf<sm::serialization::internal::HasOStreamOperator<std::ostream, typename sm::common::StripConstReference<decltype(MEMBER)>::result_t>::value, \ typename sm::common::StripConstReference<decltype(MEMBER)>::result_t >::eval(this->MEMBER) << \ " other " << sm::serialization::internal::streamIf<sm::serialization::internal::HasOStreamOperator<std::ostream, typename sm::common::StripConstReference<decltype(MEMBER)>::result_t>::value, \ typename sm::common::StripConstReference<decltype(MEMBER)>::result_t >::eval(OTHER.MEMBER) \ << " at " << __PRETTY_FUNCTION__ << \ " In: " << __FILE__ << ":" << __LINE__ << std::endl << std::endl) && false : false) //this is some internal default macro parameter deduction #define SM_SERIALIZATION_GET_3RD_ARG(arg1, arg2, arg3, ...) arg3 #define SM_SERIALIZATION_GET_4TH_ARG(arg1, arg2, arg3, arg4, ...) arg4 #define SM_SERIALIZATION_MACRO_CHOOSER_MEMBER_SAME(...) \ SM_SERIALIZATION_GET_4TH_ARG(__VA_ARGS__, SM_SERIALIZATION_CHECKMEMBERSSAME_IMPL, SM_SERIALIZATION_CHECKMEMBERSSAME_VERBOSE ) #define SM_SERIALIZATION_MACRO_CHOOSER_SAME(...) \ SM_SERIALIZATION_GET_4TH_ARG(__VA_ARGS__, SM_SERIALIZATION_CHECKSAME_IMPL, SM_SERIALIZATION_CHECKSAME_VERBOSE ) //\brief This macro checks this->MEMBER against OTHER.MEMBER with the appropriate IsBinaryEqual or operator==. //Pointers and boost::shared_ptr are handled automatically #define SM_CHECKMEMBERSSAME(...) SM_SERIALIZATION_MACRO_CHOOSER_MEMBER_SAME(__VA_ARGS__)(__VA_ARGS__) //\brief This macro checks THIS against OTHER with the appropriate IsBinaryEqual or operator==. //Pointers and boost::shared_ptr are handled automatically #define SM_CHECKSAME(...) SM_SERIALIZATION_MACRO_CHOOSER_SAME(__VA_ARGS__)(__VA_ARGS__) #endif //SM_SERIALIZATION_MACROS_HPP <commit_msg>removed impl of check(no) to avoid multiple definitions<commit_after>/** * @file serialization_macros.hpp * @author Simon Lynen <simon.lynen@mavt.ethz.ch> * @date Thu May 22 02:55:13 2013 * * @brief Comparison macros to facilitate checking in serialization methods. * * */ #ifndef SM_SERIALIZATION_MACROS_HPP #define SM_SERIALIZATION_MACROS_HPP #include <type_traits> #include <sstream> #include <ostream> #include <iostream> #include <boost/static_assert.hpp> #include <boost/shared_ptr.hpp> #include <sm/typetraits.hpp> namespace cv{ class Mat; } namespace sm{ namespace serialization{ namespace internal_types{ typedef char yes; typedef int no; } } struct AnyT { template<class T> AnyT(const T &); }; sm::serialization::internal_types::no operator <<(const AnyT &, const AnyT &); namespace serialization{ namespace internal{ template<class T> sm::serialization::internal_types::yes check(const T&); sm::serialization::internal_types::no check(sm::serialization::internal_types::no); struct makeCompilerSilent{ //rm warning about unused functions void foo(){ check(sm::serialization::internal_types::no()); AnyT t(5); operator <<(t, t); } }; //this template metaprogramming struct can tell us if there is the operator<< defined somewhere template<typename StreamType, typename T> class HasOStreamOperator { static StreamType & stream; static T & x; public: enum { value = sizeof(check(stream << x)) == sizeof(sm::serialization::internal_types::yes) }; }; template<typename StreamType, typename T> class HasOStreamOperator<StreamType, boost::shared_ptr<T> > { public: enum { value = HasOStreamOperator<StreamType, T>::value }; }; template<typename StreamType, typename T> class HasOStreamOperator<StreamType, T* > { public: enum { value = HasOStreamOperator<StreamType, T>::value }; }; template<typename StreamType, typename T> class HasOStreamOperator<StreamType, T& > { public: enum { value = HasOStreamOperator<StreamType, T>::value }; }; //this template metaprogramming struct can tell us whether a class has a member //function isBinaryEqual template<typename T> class HasIsBinaryEqual { //for non const methods (which is actually wrong) template<typename U, bool (U::*)(const T&)> struct Check; template<typename U> static char func(Check<U, &U::isBinaryEqual> *); template<typename U> static int func(...); //for const methods template<typename U, bool (U::*)(const T&) const> struct CheckConst; template<typename U> static char funcconst(CheckConst<U, &U::isBinaryEqual> *); template<typename U> static int funcconst(...); public: enum { value = (sizeof(func<T>(0)) == sizeof(char)) || (sizeof(funcconst<T>(0)) == sizeof(char)) }; }; template<typename T> class HasIsBinaryEqual<boost::shared_ptr<T> > { public: enum { value = HasIsBinaryEqual<T>::value }; }; template<typename T> class HasIsBinaryEqual<T*> { public: enum { value = HasIsBinaryEqual<T>::value }; }; template<typename T> class HasIsBinaryEqual<T&> { public: enum { value = HasIsBinaryEqual<T>::value }; }; //these structs are used to choose between isBinaryEqual function call and the //default operator== template<bool, typename A> struct isSame; template<typename A> struct isSame<true, A> { static bool eval(const A& lhs, const A& rhs) { return lhs.isBinaryEqual(rhs); } }; template<typename A> struct isSame<true, boost::shared_ptr<A> > { static bool eval(const boost::shared_ptr<A>& lhs, const boost::shared_ptr<A>& rhs) { if (!lhs && !rhs) { return true; } if (!lhs || !rhs) { return false; } return lhs->isBinaryEqual(*rhs); } }; template<typename A> struct isSame<true, A* > { static bool eval(const A* const lhs, const A* const rhs) { if (!lhs && !rhs) { return true; } if (!lhs || !rhs) { return false; } return lhs->isBinaryEqual(*rhs); } }; template<typename A> struct isSame<false, A> { static bool eval(const A& lhs, const A& rhs) { return lhs == rhs; } }; template<typename A> struct isSame<false, A*> { static bool eval(A const * lhs, A const * rhs) { if (!lhs && !rhs) { return true; } if (!lhs || !rhs) { return false; } return *lhs == *rhs; } }; template<typename A> struct isSame<false, boost::shared_ptr<A> > { static bool eval(const boost::shared_ptr<A>& lhs, const boost::shared_ptr<A>& rhs) { if (!lhs && !rhs) { return true; } if (!lhs || !rhs) { return false; } return *lhs == *rhs; } }; //for opencv Mat we have to use the sm opencv isBinaryEqual method otherwise sm_common has to depend on sm_opencv template<typename T, bool B> struct checkTypeIsNotOpencvMat { enum{ value = true, }; }; template<bool B> struct checkTypeIsNotOpencvMat<cv::Mat, B> { enum{ value = true, //yes true is correct here }; BOOST_STATIC_ASSERT_MSG((B == !B) /*false*/, "You cannot use the macro SM_CHECKSAME or SM_CHECKSAMEMEMBER on opencv mat. Use sm::opencv::isBinaryEqual instead"); }; template<bool B> struct checkTypeIsNotOpencvMat<boost::shared_ptr<cv::Mat>, B > { enum{ value = true, //yes true is correct here }; BOOST_STATIC_ASSERT_MSG((B == !B) /*false*/, "You cannot use the macro SM_CHECKSAME or SM_CHECKSAMEMEMBER on opencv mat. Use sm::opencv::isBinaryEqual instead"); }; template<bool B> struct checkTypeIsNotOpencvMat<cv::Mat*, B> { enum{ value = true, //yes true is correct here }; BOOST_STATIC_ASSERT_MSG((B == !B) /*false*/, "You cannot use the macro SM_CHECKSAME or SM_CHECKSAMEMEMBER on opencv mat. Use sm::opencv::isBinaryEqual instead"); }; //if the object supports it stream to ostream, otherwise put NA template<bool, typename A> struct streamIf; template<typename A> struct streamIf<true, A> { static std::string eval(const A& rhs) { std::stringstream ss; ss << rhs; return ss.str(); } }; template<typename A> struct streamIf<true, A*> { static std::string eval(const A* rhs) { if (!rhs) { return "NULL"; } std::stringstream ss; ss << *rhs; return ss.str(); } }; template<typename A> struct streamIf<true, boost::shared_ptr<A> > { static std::string eval(const boost::shared_ptr<A>& rhs) { if (!rhs) { return "NULL"; } std::stringstream ss; ss << *rhs; return ss.str(); } }; template<typename A> struct streamIf<true, boost::shared_ptr<const A> > { static std::string eval(const boost::shared_ptr<const A>& rhs) { if (!rhs) { return "NULL"; } std::stringstream ss; ss << *rhs; return ss.str(); } }; template<typename A> struct streamIf<false, A> { static std::string eval(const A&) { return "NA"; } }; } } } //these defines set the default behaviour if no verbosity argument is given #define SM_SERIALIZATION_CHECKSAME_VERBOSE(THIS, OTHER) SM_SERIALIZATION_CHECKSAME_IMPL(THIS, OTHER, true) #define SM_SERIALIZATION_CHECKMEMBERSSAME_VERBOSE(OTHER, MEMBER) SM_SERIALIZATION_CHECKMEMBERSSAME_IMPL(OTHER, MEMBER, true) #define SM_SERIALIZATION_CHECKSAME_IMPL(THIS, OTHER, VERBOSE) \ (sm::serialization::internal::checkTypeIsNotOpencvMat<typename sm::common::StripConstReference<decltype(OTHER)>::result_t, false>::value && /*for opencvMats we have to use sm::opencv::isBinaryEqual otherwise this code has to depend on opencv*/ \ sm::serialization::internal::isSame<sm::serialization::internal::HasIsBinaryEqual<typename sm::common::StripConstReference<decltype(OTHER)>::result_t>::value, /*first run the test of equality: either isBinaryEqual or op==*/ \ typename sm::common::StripConstReference<decltype(OTHER)>::result_t >::eval(THIS, OTHER)) ? true : /*return true if good*/ \ (VERBOSE ? (std::cout << "*** Validation failed on " << #OTHER << ": "<< /*if not true, check whether VERBOSE and then try to output the failed values using operator<<*/ \ sm::serialization::internal::streamIf<sm::serialization::internal::HasOStreamOperator<std::ostream, typename sm::common::StripConstReference<decltype(OTHER)>::result_t>::value, /*here we check whether operator<< is available*/ \ typename sm::common::StripConstReference<decltype(OTHER)>::result_t >::eval(THIS) << \ " other " << sm::serialization::internal::streamIf<sm::serialization::internal::HasOStreamOperator<std::ostream, typename sm::common::StripConstReference<decltype(OTHER)>::result_t>::value, \ typename sm::common::StripConstReference<decltype(OTHER)>::result_t>::eval(OTHER) \ << " at " << __PRETTY_FUNCTION__ << /*we print the function where this happened*/ \ " In: " << __FILE__ << ":" << __LINE__ << std::endl << std::endl) && false : false) /*we print the line and file where this happened*/ #define SM_SERIALIZATION_CHECKMEMBERSSAME_IMPL(OTHER, MEMBER, VERBOSE) \ ((sm::serialization::internal::checkTypeIsNotOpencvMat<typename sm::common::StripConstReference<decltype(OTHER)>::result_t, false>::value) && /*for opencvMats we have to use sm::opencv::isBinaryEqual otherwise this code has to depend on opencv*/\ (sm::serialization::internal::isSame<sm::serialization::internal::HasIsBinaryEqual<typename sm::common::StripConstReference<decltype(MEMBER)>::result_t>::value, \ typename sm::common::StripConstReference<decltype(MEMBER)>::result_t >::eval(this->MEMBER, OTHER.MEMBER))) ? true :\ (VERBOSE ? (std::cout << "*** Validation failed on " << #MEMBER << ": "<< \ sm::serialization::internal::streamIf<sm::serialization::internal::HasOStreamOperator<std::ostream, typename sm::common::StripConstReference<decltype(MEMBER)>::result_t>::value, \ typename sm::common::StripConstReference<decltype(MEMBER)>::result_t >::eval(this->MEMBER) << \ " other " << sm::serialization::internal::streamIf<sm::serialization::internal::HasOStreamOperator<std::ostream, typename sm::common::StripConstReference<decltype(MEMBER)>::result_t>::value, \ typename sm::common::StripConstReference<decltype(MEMBER)>::result_t >::eval(OTHER.MEMBER) \ << " at " << __PRETTY_FUNCTION__ << \ " In: " << __FILE__ << ":" << __LINE__ << std::endl << std::endl) && false : false) //this is some internal default macro parameter deduction #define SM_SERIALIZATION_GET_3RD_ARG(arg1, arg2, arg3, ...) arg3 #define SM_SERIALIZATION_GET_4TH_ARG(arg1, arg2, arg3, arg4, ...) arg4 #define SM_SERIALIZATION_MACRO_CHOOSER_MEMBER_SAME(...) \ SM_SERIALIZATION_GET_4TH_ARG(__VA_ARGS__, SM_SERIALIZATION_CHECKMEMBERSSAME_IMPL, SM_SERIALIZATION_CHECKMEMBERSSAME_VERBOSE ) #define SM_SERIALIZATION_MACRO_CHOOSER_SAME(...) \ SM_SERIALIZATION_GET_4TH_ARG(__VA_ARGS__, SM_SERIALIZATION_CHECKSAME_IMPL, SM_SERIALIZATION_CHECKSAME_VERBOSE ) //\brief This macro checks this->MEMBER against OTHER.MEMBER with the appropriate IsBinaryEqual or operator==. //Pointers and boost::shared_ptr are handled automatically #define SM_CHECKMEMBERSSAME(...) SM_SERIALIZATION_MACRO_CHOOSER_MEMBER_SAME(__VA_ARGS__)(__VA_ARGS__) //\brief This macro checks THIS against OTHER with the appropriate IsBinaryEqual or operator==. //Pointers and boost::shared_ptr are handled automatically #define SM_CHECKSAME(...) SM_SERIALIZATION_MACRO_CHOOSER_SAME(__VA_ARGS__)(__VA_ARGS__) #endif //SM_SERIALIZATION_MACROS_HPP <|endoftext|>
<commit_before>#include <tellstore/ClientManager.hpp> #include <tellstore/ClientConfig.hpp> #include <crossbow/logger.hpp> #include <sys/mman.h> namespace tell { namespace store { namespace { void checkTableType(const Table& table, TableType type) { if (table.tableType() != type) { throw std::logic_error("Operation not supported on table"); } } std::unique_ptr<commitmanager::SnapshotDescriptor> nonTransactionalSnapshot(uint64_t version) { commitmanager::SnapshotDescriptor::BlockType descriptor = 0x0u; return commitmanager::SnapshotDescriptor::create(0x0u, version, version + 1, reinterpret_cast<const char*>(&descriptor)); } } // anonymous namespace ClientTransaction::ClientTransaction(ClientProcessor& processor, crossbow::infinio::Fiber& fiber, std::unique_ptr<commitmanager::SnapshotDescriptor> snapshot) : mProcessor(processor), mFiber(fiber), mSnapshot(std::move(snapshot)), mCommitted(false) { mModified.set_empty_key(std::make_tuple(0x0u, 0x0u)); } ClientTransaction::~ClientTransaction() { if (!mCommitted) { try { abort(); } catch (std::exception& e) { LOG_ERROR("Exception caught while aborting transaction [error = %1%]", e.what()); } } } ClientTransaction::ClientTransaction(ClientTransaction&& other) : mProcessor(other.mProcessor), mFiber(other.mFiber), mSnapshot(std::move(other.mSnapshot)), mModified(std::move(other.mModified)), mCommitted(other.mCommitted) { other.mCommitted = true; } std::shared_ptr<GetResponse> ClientTransaction::get(const Table& table, uint64_t key) { return executeInTransaction<GetResponse>(table, [this, &table, key] () { return mProcessor.get(mFiber, table.tableId(), key, *mSnapshot); }); } std::shared_ptr<ModificationResponse> ClientTransaction::insert(const Table& table, uint64_t key, const GenericTuple& tuple, bool hasSucceeded /* = true */) { return executeInTransaction<ModificationResponse>(table, [this, &table, key, &tuple, hasSucceeded] () { mModified.insert(std::make_tuple(table.tableId(), key)); return mProcessor.insert(mFiber, table.tableId(), key, table.record(), tuple, *mSnapshot, hasSucceeded); }); } std::shared_ptr<ModificationResponse> ClientTransaction::update(const Table& table, uint64_t key, const GenericTuple& tuple) { return executeInTransaction<ModificationResponse>(table, [this, &table, key, &tuple] () { mModified.insert(std::make_tuple(table.tableId(), key)); return mProcessor.update(mFiber, table.tableId(), key, table.record(), tuple, *mSnapshot); }); } std::shared_ptr<ModificationResponse> ClientTransaction::remove(const Table& table, uint64_t key) { return executeInTransaction<ModificationResponse>(table, [this, &table, key] () { mModified.insert(std::make_tuple(table.tableId(), key)); return mProcessor.remove(mFiber, table.tableId(), key, *mSnapshot); }); } std::shared_ptr<ScanResponse> ClientTransaction::scan(const Table& table, uint32_t queryLength, const char* query) { return executeInTransaction<ScanResponse>(table, [this, &table, queryLength, query] () { return mProcessor.scan(mFiber, table.tableId(), table.record(), queryLength, query, *mSnapshot); }); } void ClientTransaction::commit() { mModified.clear(); mProcessor.commit(mFiber, *mSnapshot); mCommitted = true; } void ClientTransaction::abort() { if (!mModified.empty()) { rollbackModified(); } commit(); } void ClientTransaction::rollbackModified() { std::queue<std::shared_ptr<ModificationResponse>> responses; for (auto& modified : mModified) { auto revertResponse = mProcessor.revert(mFiber, std::get<0>(modified), std::get<1>(modified), *mSnapshot); responses.emplace(std::move(revertResponse)); } responses.back()->waitForResult(); while (!responses.empty()) { auto revertResponse = std::move(responses.front()); responses.pop(); if (!revertResponse->waitForResult()) { throw std::system_error(revertResponse->error()); } if (!revertResponse->get()) { throw std::logic_error("Revert did not succeed"); } } } template <typename Response, typename Fun> std::shared_ptr<Response> ClientTransaction::executeInTransaction(const Table& table, Fun fun) { checkTableType(table, TableType::TRANSACTIONAL); if (mCommitted) { throw std::logic_error("Transaction has already committed"); } return fun(); } ClientHandle::ClientHandle(ClientProcessor& processor, crossbow::infinio::Fiber& fiber) : mProcessor(processor), mFiber(fiber) { } ClientTransaction ClientHandle::startTransaction() { return mProcessor.start(mFiber); } std::shared_ptr<CreateTableResponse> ClientHandle::createTable(const crossbow::string& name, const Schema& schema) { return mProcessor.createTable(mFiber, name, schema); } std::shared_ptr<GetTableResponse> ClientHandle::getTable(const crossbow::string& name) { return mProcessor.getTable(mFiber, name); } std::shared_ptr<GetResponse> ClientHandle::get(const Table& table, uint64_t key) { checkTableType(table, TableType::NON_TRANSACTIONAL); auto snapshot = nonTransactionalSnapshot(std::numeric_limits<uint64_t>::max()); return mProcessor.get(mFiber, table.tableId(), key, *snapshot); } std::shared_ptr<ModificationResponse> ClientHandle::insert(const Table& table, uint64_t key, uint64_t version, const GenericTuple& tuple, bool hasSucceeded) { checkTableType(table, TableType::NON_TRANSACTIONAL); auto snapshot = nonTransactionalSnapshot(version); return mProcessor.insert(mFiber, table.tableId(), key, table.record(), tuple, *snapshot, hasSucceeded); } std::shared_ptr<ModificationResponse> ClientHandle::update(const Table& table, uint64_t key, uint64_t version, const GenericTuple& tuple) { checkTableType(table, TableType::NON_TRANSACTIONAL); auto snapshot = nonTransactionalSnapshot(version); return mProcessor.update(mFiber, table.tableId(), key, table.record(), tuple, *snapshot); } std::shared_ptr<ModificationResponse> ClientHandle::remove(const Table& table, uint64_t key, uint64_t version) { checkTableType(table, TableType::NON_TRANSACTIONAL); auto snapshot = nonTransactionalSnapshot(version); return mProcessor.remove(mFiber, table.tableId(), key, *snapshot); } std::shared_ptr<ScanResponse> ClientHandle::scan(const Table& table, uint32_t queryLength, const char* query) { checkTableType(table, TableType::NON_TRANSACTIONAL); auto snapshot = nonTransactionalSnapshot(std::numeric_limits<uint64_t>::max()); return mProcessor.scan(mFiber, table.tableId(), table.record(), queryLength, query, *snapshot); } ClientProcessor::ClientProcessor(crossbow::infinio::InfinibandService& service, crossbow::infinio::LocalMemoryRegion& scanRegion, const ClientConfig& config, uint64_t processorNum) : mScanRegion(scanRegion), mProcessor(service.createProcessor()), mCommitManagerSocket(service.createSocket(*mProcessor)), mTellStoreSocket(service.createSocket(*mProcessor)), mProcessorNum(processorNum), mTransactionCount(0x0u) { mCommitManagerSocket.connect(config.commitManager); mTellStoreSocket.connect(config.tellStore, mProcessorNum); } void ClientProcessor::execute(const std::function<void(ClientHandle&)>& fun) { ++mTransactionCount; mProcessor->executeFiber([this, fun] (crossbow::infinio::Fiber& fiber) { LOG_TRACE("Proc %1%] Execute client function", mProcessorNum); ClientHandle client(*this, fiber); fun(client); }); } ClientTransaction ClientProcessor::start(crossbow::infinio::Fiber& fiber) { // TODO Return a transaction future? auto startResponse = mCommitManagerSocket.startTransaction(fiber); if (!startResponse->waitForResult()) { throw std::system_error(startResponse->error()); } return {*this, fiber, startResponse->get()}; } void ClientProcessor::commit(crossbow::infinio::Fiber& fiber, const commitmanager::SnapshotDescriptor& snapshot) { // TODO Return a commit future? auto commitResponse = mCommitManagerSocket.commitTransaction(fiber, snapshot.version()); if (!commitResponse->waitForResult()) { throw std::system_error(commitResponse->error()); } if (!commitResponse->get()) { throw std::runtime_error("Commit transaction did not succeed"); } } ClientManager::ClientManager(crossbow::infinio::InfinibandService& service, const ClientConfig& config) { auto data = mmap(nullptr, config.scanMemory, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE, 0, 0); if (data == MAP_FAILED) { // TODO Error handling std::terminate(); } int flags = IBV_ACCESS_REMOTE_WRITE | IBV_ACCESS_LOCAL_WRITE; mScanRegion = service.registerMemoryRegion(data, config.scanMemory, flags); mProcessor.reserve(config.numNetworkThreads); for (decltype(config.numNetworkThreads) i = 0; i < config.numNetworkThreads; ++i) { mProcessor.emplace_back(new ClientProcessor(service, mScanRegion, config, i)); } } void ClientManager::execute(std::function<void(ClientHandle&)> fun) { ClientProcessor* processor = nullptr; uint64_t minCount = std::numeric_limits<uint64_t>::max(); for (auto& proc : mProcessor) { auto count = proc->transactionCount(); if (minCount < count) { continue; } processor = proc.get(); minCount = count; } LOG_ASSERT(processor != nullptr, "Found no processor"); processor->execute(fun); } } // namespace store } // namespace tell <commit_msg>Do not overflow version<commit_after>#include <tellstore/ClientManager.hpp> #include <tellstore/ClientConfig.hpp> #include <crossbow/logger.hpp> #include <sys/mman.h> namespace tell { namespace store { namespace { void checkTableType(const Table& table, TableType type) { if (table.tableType() != type) { throw std::logic_error("Operation not supported on table"); } } std::unique_ptr<commitmanager::SnapshotDescriptor> nonTransactionalSnapshot(uint64_t baseVersion) { auto version = (baseVersion == std::numeric_limits<uint64_t>::max() ? baseVersion : baseVersion + 1); commitmanager::SnapshotDescriptor::BlockType descriptor = 0x0u; return commitmanager::SnapshotDescriptor::create(0x0u, baseVersion, version, reinterpret_cast<const char*>(&descriptor)); } } // anonymous namespace ClientTransaction::ClientTransaction(ClientProcessor& processor, crossbow::infinio::Fiber& fiber, std::unique_ptr<commitmanager::SnapshotDescriptor> snapshot) : mProcessor(processor), mFiber(fiber), mSnapshot(std::move(snapshot)), mCommitted(false) { mModified.set_empty_key(std::make_tuple(0x0u, 0x0u)); } ClientTransaction::~ClientTransaction() { if (!mCommitted) { try { abort(); } catch (std::exception& e) { LOG_ERROR("Exception caught while aborting transaction [error = %1%]", e.what()); } } } ClientTransaction::ClientTransaction(ClientTransaction&& other) : mProcessor(other.mProcessor), mFiber(other.mFiber), mSnapshot(std::move(other.mSnapshot)), mModified(std::move(other.mModified)), mCommitted(other.mCommitted) { other.mCommitted = true; } std::shared_ptr<GetResponse> ClientTransaction::get(const Table& table, uint64_t key) { return executeInTransaction<GetResponse>(table, [this, &table, key] () { return mProcessor.get(mFiber, table.tableId(), key, *mSnapshot); }); } std::shared_ptr<ModificationResponse> ClientTransaction::insert(const Table& table, uint64_t key, const GenericTuple& tuple, bool hasSucceeded /* = true */) { return executeInTransaction<ModificationResponse>(table, [this, &table, key, &tuple, hasSucceeded] () { mModified.insert(std::make_tuple(table.tableId(), key)); return mProcessor.insert(mFiber, table.tableId(), key, table.record(), tuple, *mSnapshot, hasSucceeded); }); } std::shared_ptr<ModificationResponse> ClientTransaction::update(const Table& table, uint64_t key, const GenericTuple& tuple) { return executeInTransaction<ModificationResponse>(table, [this, &table, key, &tuple] () { mModified.insert(std::make_tuple(table.tableId(), key)); return mProcessor.update(mFiber, table.tableId(), key, table.record(), tuple, *mSnapshot); }); } std::shared_ptr<ModificationResponse> ClientTransaction::remove(const Table& table, uint64_t key) { return executeInTransaction<ModificationResponse>(table, [this, &table, key] () { mModified.insert(std::make_tuple(table.tableId(), key)); return mProcessor.remove(mFiber, table.tableId(), key, *mSnapshot); }); } std::shared_ptr<ScanResponse> ClientTransaction::scan(const Table& table, uint32_t queryLength, const char* query) { return executeInTransaction<ScanResponse>(table, [this, &table, queryLength, query] () { return mProcessor.scan(mFiber, table.tableId(), table.record(), queryLength, query, *mSnapshot); }); } void ClientTransaction::commit() { mModified.clear(); mProcessor.commit(mFiber, *mSnapshot); mCommitted = true; } void ClientTransaction::abort() { if (!mModified.empty()) { rollbackModified(); } commit(); } void ClientTransaction::rollbackModified() { std::queue<std::shared_ptr<ModificationResponse>> responses; for (auto& modified : mModified) { auto revertResponse = mProcessor.revert(mFiber, std::get<0>(modified), std::get<1>(modified), *mSnapshot); responses.emplace(std::move(revertResponse)); } responses.back()->waitForResult(); while (!responses.empty()) { auto revertResponse = std::move(responses.front()); responses.pop(); if (!revertResponse->waitForResult()) { throw std::system_error(revertResponse->error()); } if (!revertResponse->get()) { throw std::logic_error("Revert did not succeed"); } } } template <typename Response, typename Fun> std::shared_ptr<Response> ClientTransaction::executeInTransaction(const Table& table, Fun fun) { checkTableType(table, TableType::TRANSACTIONAL); if (mCommitted) { throw std::logic_error("Transaction has already committed"); } return fun(); } ClientHandle::ClientHandle(ClientProcessor& processor, crossbow::infinio::Fiber& fiber) : mProcessor(processor), mFiber(fiber) { } ClientTransaction ClientHandle::startTransaction() { return mProcessor.start(mFiber); } std::shared_ptr<CreateTableResponse> ClientHandle::createTable(const crossbow::string& name, const Schema& schema) { return mProcessor.createTable(mFiber, name, schema); } std::shared_ptr<GetTableResponse> ClientHandle::getTable(const crossbow::string& name) { return mProcessor.getTable(mFiber, name); } std::shared_ptr<GetResponse> ClientHandle::get(const Table& table, uint64_t key) { checkTableType(table, TableType::NON_TRANSACTIONAL); auto snapshot = nonTransactionalSnapshot(std::numeric_limits<uint64_t>::max()); return mProcessor.get(mFiber, table.tableId(), key, *snapshot); } std::shared_ptr<ModificationResponse> ClientHandle::insert(const Table& table, uint64_t key, uint64_t version, const GenericTuple& tuple, bool hasSucceeded) { checkTableType(table, TableType::NON_TRANSACTIONAL); auto snapshot = nonTransactionalSnapshot(version); return mProcessor.insert(mFiber, table.tableId(), key, table.record(), tuple, *snapshot, hasSucceeded); } std::shared_ptr<ModificationResponse> ClientHandle::update(const Table& table, uint64_t key, uint64_t version, const GenericTuple& tuple) { checkTableType(table, TableType::NON_TRANSACTIONAL); auto snapshot = nonTransactionalSnapshot(version); return mProcessor.update(mFiber, table.tableId(), key, table.record(), tuple, *snapshot); } std::shared_ptr<ModificationResponse> ClientHandle::remove(const Table& table, uint64_t key, uint64_t version) { checkTableType(table, TableType::NON_TRANSACTIONAL); auto snapshot = nonTransactionalSnapshot(version); return mProcessor.remove(mFiber, table.tableId(), key, *snapshot); } std::shared_ptr<ScanResponse> ClientHandle::scan(const Table& table, uint32_t queryLength, const char* query) { checkTableType(table, TableType::NON_TRANSACTIONAL); auto snapshot = nonTransactionalSnapshot(std::numeric_limits<uint64_t>::max()); return mProcessor.scan(mFiber, table.tableId(), table.record(), queryLength, query, *snapshot); } ClientProcessor::ClientProcessor(crossbow::infinio::InfinibandService& service, crossbow::infinio::LocalMemoryRegion& scanRegion, const ClientConfig& config, uint64_t processorNum) : mScanRegion(scanRegion), mProcessor(service.createProcessor()), mCommitManagerSocket(service.createSocket(*mProcessor)), mTellStoreSocket(service.createSocket(*mProcessor)), mProcessorNum(processorNum), mTransactionCount(0x0u) { mCommitManagerSocket.connect(config.commitManager); mTellStoreSocket.connect(config.tellStore, mProcessorNum); } void ClientProcessor::execute(const std::function<void(ClientHandle&)>& fun) { ++mTransactionCount; mProcessor->executeFiber([this, fun] (crossbow::infinio::Fiber& fiber) { LOG_TRACE("Proc %1%] Execute client function", mProcessorNum); ClientHandle client(*this, fiber); fun(client); }); } ClientTransaction ClientProcessor::start(crossbow::infinio::Fiber& fiber) { // TODO Return a transaction future? auto startResponse = mCommitManagerSocket.startTransaction(fiber); if (!startResponse->waitForResult()) { throw std::system_error(startResponse->error()); } return {*this, fiber, startResponse->get()}; } void ClientProcessor::commit(crossbow::infinio::Fiber& fiber, const commitmanager::SnapshotDescriptor& snapshot) { // TODO Return a commit future? auto commitResponse = mCommitManagerSocket.commitTransaction(fiber, snapshot.version()); if (!commitResponse->waitForResult()) { throw std::system_error(commitResponse->error()); } if (!commitResponse->get()) { throw std::runtime_error("Commit transaction did not succeed"); } } ClientManager::ClientManager(crossbow::infinio::InfinibandService& service, const ClientConfig& config) { auto data = mmap(nullptr, config.scanMemory, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE, 0, 0); if (data == MAP_FAILED) { // TODO Error handling std::terminate(); } int flags = IBV_ACCESS_REMOTE_WRITE | IBV_ACCESS_LOCAL_WRITE; mScanRegion = service.registerMemoryRegion(data, config.scanMemory, flags); mProcessor.reserve(config.numNetworkThreads); for (decltype(config.numNetworkThreads) i = 0; i < config.numNetworkThreads; ++i) { mProcessor.emplace_back(new ClientProcessor(service, mScanRegion, config, i)); } } void ClientManager::execute(std::function<void(ClientHandle&)> fun) { ClientProcessor* processor = nullptr; uint64_t minCount = std::numeric_limits<uint64_t>::max(); for (auto& proc : mProcessor) { auto count = proc->transactionCount(); if (minCount < count) { continue; } processor = proc.get(); minCount = count; } LOG_ASSERT(processor != nullptr, "Found no processor"); processor->execute(fun); } } // namespace store } // namespace tell <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////////// /// DISCLAIMER /// /// Copyright 2016 ArangoDB GmbH, Cologne, Germany /// /// 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. /// /// Copyright holder is ArangoDB GmbH, Cologne, Germany /// /// @author Dr. Frank Celler //////////////////////////////////////////////////////////////////////////////// #include "ApplicationFeatures/LoggerFeature.h" #include "Logger/Logger.h" #include "ProgramOptions2/ProgramOptions.h" #include "ProgramOptions2/Section.h" using namespace arangodb; using namespace arangodb::options; LoggerFeature::LoggerFeature(application_features::ApplicationServer* server) : ApplicationFeature(server, "Logger"), _output(), _levels(), _useLocalTime(false), _prefix(""), _file(), _lineNumber(false), _thread(false), _performance(false), _daemon(false), _backgrounded(false), _threaded(false) { _levels.push_back("info"); setOptional(false); requiresElevatedPrivileges(false); } void LoggerFeature::collectOptions(std::shared_ptr<ProgramOptions> options) { LOG_TOPIC(TRACE, Logger::STARTUP) << name() << "::collectOptions"; options->addSection("log", "Configure the logging"); options->addOption("--log.output,-o", "log destination(s)", new VectorParameter<StringParameter>(&_output)); options->addOption("--log.level,-l", "the global or topic-specific log level", new VectorParameter<StringParameter>(&_levels)); options->addOption("--log.use-local-time", "use local timezone instead of UTC", new BooleanParameter(&_useLocalTime)); options->addOption("--log.prefix", "prefix log message with this string", new StringParameter(&_prefix)); options->addHiddenOption( "--log.prefix", "adds a prefix in case multiple instances are running", new StringParameter(&_prefix)); options->addOption("--log", "the global or topic-specific log level", new VectorParameter<StringParameter>(&_levels)); options->addHiddenOption("--log.file", "shortcut for '--log.output file://<filename>'", new StringParameter(&_file)); options->addHiddenOption("--log.line-number", "append line number and file name", new BooleanParameter(&_lineNumber)); options->addHiddenOption("--log.thread", "append a thread identifier", new BooleanParameter(&_thread)); options->addHiddenOption("--log.performance", "shortcut for '--log.level requests=trace'", new BooleanParameter(&_performance)); } void LoggerFeature::loadOptions( std::shared_ptr<options::ProgramOptions> options) { LOG_TOPIC(TRACE, Logger::STARTUP) << name() << "::loadOptions"; // for debugging purpose, we set the log levels NOW // this might be overwritten latter Logger::initialize(false); Logger::setLogLevel(_levels); } void LoggerFeature::validateOptions(std::shared_ptr<ProgramOptions> options) { LOG_TOPIC(TRACE, Logger::STARTUP) << name() << "::validateOptions"; if (options->processingResult().touched("log.file")) { std::string definition; if (_file == "+" || _file == "-") { definition = _file; } else if (_daemon) { definition = "file://" + _file + ".daemon"; } else { definition = "file://" + _file; } _output.push_back(definition); } if (_performance) { _levels.push_back("requests=trace"); } if (!_backgrounded && isatty(STDIN_FILENO) != 0) { _output.push_back("*"); } } void LoggerFeature::prepare() { LOG_TOPIC(TRACE, Logger::STARTUP) << name() << "::prepare"; #if _WIN32 if (!TRI_InitWindowsEventLog()) { std::cerr << "failed to init event log" << std::endl; FATAL_ERROR_EXIT(); } #endif Logger::setLogLevel(_levels); Logger::setUseLocalTime(_useLocalTime); Logger::setShowLineNumber(_lineNumber); Logger::setShowThreadIdentifier(_thread); Logger::setOutputPrefix(_prefix); } void LoggerFeature::start() { LOG_TOPIC(TRACE, Logger::STARTUP) << name() << "::start"; if (_threaded) { Logger::flush(); Logger::shutdown(false); Logger::initialize(_threaded); } } void LoggerFeature::stop() { LOG_TOPIC(TRACE, Logger::STARTUP) << name() << "::stop"; Logger::flush(); Logger::shutdown(true); } <commit_msg>added missing section<commit_after>//////////////////////////////////////////////////////////////////////////////// /// DISCLAIMER /// /// Copyright 2016 ArangoDB GmbH, Cologne, Germany /// /// 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. /// /// Copyright holder is ArangoDB GmbH, Cologne, Germany /// /// @author Dr. Frank Celler //////////////////////////////////////////////////////////////////////////////// #include "ApplicationFeatures/LoggerFeature.h" #include "Logger/Logger.h" #include "ProgramOptions2/ProgramOptions.h" #include "ProgramOptions2/Section.h" using namespace arangodb; using namespace arangodb::options; LoggerFeature::LoggerFeature(application_features::ApplicationServer* server) : ApplicationFeature(server, "Logger"), _output(), _levels(), _useLocalTime(false), _prefix(""), _file(), _lineNumber(false), _thread(false), _performance(false), _daemon(false), _backgrounded(false), _threaded(false) { _levels.push_back("info"); setOptional(false); requiresElevatedPrivileges(false); } void LoggerFeature::collectOptions(std::shared_ptr<ProgramOptions> options) { LOG_TOPIC(TRACE, Logger::STARTUP) << name() << "::collectOptions"; options->addSection( Section("", "Global configuration", "global options", false, false)); options->addOption("--log", "the global or topic-specific log level", new VectorParameter<StringParameter>(&_levels)); options->addSection("log", "Configure the logging"); options->addOption("--log.output,-o", "log destination(s)", new VectorParameter<StringParameter>(&_output)); options->addOption("--log.level,-l", "the global or topic-specific log level", new VectorParameter<StringParameter>(&_levels)); options->addOption("--log.use-local-time", "use local timezone instead of UTC", new BooleanParameter(&_useLocalTime)); options->addOption("--log.prefix", "prefix log message with this string", new StringParameter(&_prefix)); options->addHiddenOption( "--log.prefix", "adds a prefix in case multiple instances are running", new StringParameter(&_prefix)); options->addHiddenOption("--log.file", "shortcut for '--log.output file://<filename>'", new StringParameter(&_file)); options->addHiddenOption("--log.line-number", "append line number and file name", new BooleanParameter(&_lineNumber)); options->addHiddenOption("--log.thread", "append a thread identifier", new BooleanParameter(&_thread)); options->addHiddenOption("--log.performance", "shortcut for '--log.level requests=trace'", new BooleanParameter(&_performance)); } void LoggerFeature::loadOptions( std::shared_ptr<options::ProgramOptions> options) { LOG_TOPIC(TRACE, Logger::STARTUP) << name() << "::loadOptions"; // for debugging purpose, we set the log levels NOW // this might be overwritten latter Logger::initialize(false); Logger::setLogLevel(_levels); } void LoggerFeature::validateOptions(std::shared_ptr<ProgramOptions> options) { LOG_TOPIC(TRACE, Logger::STARTUP) << name() << "::validateOptions"; if (options->processingResult().touched("log.file")) { std::string definition; if (_file == "+" || _file == "-") { definition = _file; } else if (_daemon) { definition = "file://" + _file + ".daemon"; } else { definition = "file://" + _file; } _output.push_back(definition); } if (_performance) { _levels.push_back("requests=trace"); } if (!_backgrounded && isatty(STDIN_FILENO) != 0) { _output.push_back("*"); } } void LoggerFeature::prepare() { LOG_TOPIC(TRACE, Logger::STARTUP) << name() << "::prepare"; #if _WIN32 if (!TRI_InitWindowsEventLog()) { std::cerr << "failed to init event log" << std::endl; FATAL_ERROR_EXIT(); } #endif Logger::setLogLevel(_levels); Logger::setUseLocalTime(_useLocalTime); Logger::setShowLineNumber(_lineNumber); Logger::setShowThreadIdentifier(_thread); Logger::setOutputPrefix(_prefix); } void LoggerFeature::start() { LOG_TOPIC(TRACE, Logger::STARTUP) << name() << "::start"; if (_threaded) { Logger::flush(); Logger::shutdown(false); Logger::initialize(_threaded); } } void LoggerFeature::stop() { LOG_TOPIC(TRACE, Logger::STARTUP) << name() << "::stop"; Logger::flush(); Logger::shutdown(true); } <|endoftext|>
<commit_before>#include <common-ee.h> #include "../test_runner.h" static const u32 __attribute__((aligned(16))) C_ZERO[4] = {0x00000000, 0x00000000, 0x00000000, 0x00000000}; static const u32 __attribute__((aligned(16))) C_NEGZERO[4] = {0x80000000, 0x80000000, 0x80000000, 0x80000000}; static const u32 __attribute__((aligned(16))) C_MAX[4] = {0x7FFFFFFF, 0x7FFFFFFF, 0x7FFFFFFF, 0x7FFFFFFF}; static const u32 __attribute__((aligned(16))) C_MIN[4] = {0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF}; static const u32 __attribute__((aligned(16))) C_MAX_MANTISSA[4] = {0x3FFFFFFF, 0x3FFFFFFF, 0x3FFFFFFF, 0x3FFFFFFF}; static const u32 __attribute__((aligned(16))) C_MAX_EXP[4] = {0x7F800001, 0x7F800001, 0x7F800001, 0x7F800001}; static const u32 __attribute__((aligned(16))) C_MIN_EXP[4] = {0x00000001, 0x00000001, 0x00000001, 0x00000001}; static const u32 __attribute__((aligned(16))) C_ONE[4] = {0x3F800000, 0x3F800000, 0x3F800000, 0x3F800000}; static const u32 __attribute__((aligned(16))) C_NEGONE[4] = {0xBF800000, 0xBF800000, 0xBF800000, 0xBF800000}; static const u32 __attribute__((aligned(16))) C_GARBAGE1[4] = {0x00001337, 0x00001337, 0x00001337, 0x00001337}; static const u32 __attribute__((aligned(16))) C_GARBAGE2[4] = {0xDEADBEEF, 0xDEADBEEF, 0xDEADBEEF, 0xDEADBEEF}; static const u32 __attribute__((aligned(16))) C_INCREASING[4] = {0x3F800000, 0x40000000, 0x40400000, 0x40800000}; static const u32 __attribute__((aligned(16))) C_DECREASING[4] = {0x40800000, 0x40400000, 0x40000000, 0x3F800000}; static u32 *const CVF_ZERO = (u32 *)(vu1_mem + 0x0000); static u32 *const CVF_NEGZERO = (u32 *)(vu1_mem + 0x0010); static u32 *const CVF_MAX = (u32 *)(vu1_mem + 0x0020); static u32 *const CVF_MIN = (u32 *)(vu1_mem + 0x0030); static u32 *const CVF_MAX_MANTISSA = (u32 *)(vu1_mem + 0x0040); static u32 *const CVF_MAX_EXP = (u32 *)(vu1_mem + 0x0050); static u32 *const CVF_MIN_EXP = (u32 *)(vu1_mem + 0x0060); static u32 *const CVF_ONE = (u32 *)(vu1_mem + 0x0070); static u32 *const CVF_NEGONE = (u32 *)(vu1_mem + 0x0080); static u32 *const CVF_GARBAGE1 = (u32 *)(vu1_mem + 0x0090); static u32 *const CVF_GARBAGE2 = (u32 *)(vu1_mem + 0x00A0); static u32 *const CVF_INCREASING = (u32 *)(vu1_mem + 0x00B0); static u32 *const CVF_DECREASING = (u32 *)(vu1_mem + 0x00C0); static void setup_vf_constants() { *(vu128 *)CVF_ZERO = *(vu128 *)C_ZERO; *(vu128 *)CVF_NEGZERO = *(vu128 *)C_NEGZERO; *(vu128 *)CVF_MAX = *(vu128 *)C_MAX; *(vu128 *)CVF_MIN = *(vu128 *)C_MIN; *(vu128 *)CVF_MAX_MANTISSA = *(vu128 *)C_MAX_MANTISSA; *(vu128 *)CVF_MAX_EXP = *(vu128 *)C_MAX_EXP; *(vu128 *)CVF_MIN_EXP = *(vu128 *)C_MIN_EXP; *(vu128 *)CVF_ONE = *(vu128 *)C_ONE; *(vu128 *)CVF_NEGONE = *(vu128 *)C_NEGONE; *(vu128 *)CVF_GARBAGE1 = *(vu128 *)C_GARBAGE1; *(vu128 *)CVF_GARBAGE2 = *(vu128 *)C_GARBAGE2; *(vu128 *)CVF_INCREASING = *(vu128 *)C_INCREASING; *(vu128 *)CVF_DECREASING = *(vu128 *)C_DECREASING; } class EfuTestRunner : public TestRunner { public: EfuTestRunner(int vu) : TestRunner(vu) { } typedef VU::LowerOp (*EfuFunctionScalar)(VU::Field field, VU::Reg reg); typedef VU::LowerOp (*EfuFunctionVector)(VU::Reg reg); void PerformS_M(const char *name, EfuFunctionScalar func, const char *tname, const u32 *t) { using namespace VU; Reset(); WrLoadFloatRegister(DEST_XYZW, VF01, t); //Op Wr(func(FIELD_Z, VF01)); Wr(WAITP()); Wr(MFP(DEST_XYZW, VF02)); Execute(); printf(" %s %s: ", name, tname); PrintRegisterField(VF02, FIELD_X, true); } void PerformV_M(const char *name, EfuFunctionVector func, const char *tname, const u32 *t) { using namespace VU; Reset(); WrLoadFloatRegister(DEST_XYZW, VF01, t); //Op Wr(func(VF01)); Wr(WAITP()); Wr(MFP(DEST_XYZW, VF02)); Execute(); printf(" %s %s: ", name, tname); PrintRegisterField(VF02, FIELD_X, true); } #define PerformS_M(name, func, t) PerformS_M(name, func, #t, t) #define PerformV_M(name, func, t) PerformV_M(name, func, #t, t) void PerformS(const char *name, EfuFunctionScalar func) { printf("%s:\n", name); PerformS_M(name, func, CVF_ZERO); PerformS_M(name, func, CVF_NEGZERO); PerformS_M(name, func, CVF_MAX); PerformS_M(name, func, CVF_MIN); PerformS_M(name, func, CVF_MAX_MANTISSA); PerformS_M(name, func, CVF_MAX_EXP); PerformS_M(name, func, CVF_MIN_EXP); PerformS_M(name, func, CVF_ONE); PerformS_M(name, func, CVF_NEGONE); PerformS_M(name, func, CVF_GARBAGE1); PerformS_M(name, func, CVF_GARBAGE2); PerformS_M(name, func, CVF_INCREASING); PerformS_M(name, func, CVF_DECREASING); } void PerformV(const char *name, EfuFunctionVector func) { printf("%s:\n", name); PerformV_M(name, func, CVF_ZERO); PerformV_M(name, func, CVF_NEGZERO); PerformV_M(name, func, CVF_MAX); PerformV_M(name, func, CVF_MIN); PerformV_M(name, func, CVF_MAX_MANTISSA); PerformV_M(name, func, CVF_MAX_EXP); PerformV_M(name, func, CVF_MIN_EXP); PerformV_M(name, func, CVF_ONE); PerformV_M(name, func, CVF_NEGONE); PerformV_M(name, func, CVF_GARBAGE1); PerformV_M(name, func, CVF_GARBAGE2); PerformV_M(name, func, CVF_INCREASING); PerformV_M(name, func, CVF_DECREASING); } }; int main(int argc, char *argv[]) { printf("-- TEST BEGIN\n"); setup_vf_constants(); EfuTestRunner runner(1); runner.PerformS("EATAN", &VU::EATAN); runner.PerformV("EATANxy", &VU::EATANxy); runner.PerformV("EATANxz", &VU::EATANxz); runner.PerformS("EEXP", &VU::EEXP); runner.PerformV("ELENG", &VU::ELENG); runner.PerformS("ERCPR", &VU::ERCPR); runner.PerformV("ERLENG", &VU::ERLENG); runner.PerformV("ERSADD", &VU::ERSADD); runner.PerformS("ERSQRT", &VU::ERSQRT); runner.PerformV("ESADD", &VU::ESADD); runner.PerformS("ESIN", &VU::ESIN); runner.PerformS("ESQRT", &VU::ESQRT); runner.PerformV("ESUM", &VU::ESUM); printf("-- TEST END\n"); return 0; } <commit_msg>Undef macros after we've finished using them.<commit_after>#include <common-ee.h> #include "../test_runner.h" static const u32 __attribute__((aligned(16))) C_ZERO[4] = {0x00000000, 0x00000000, 0x00000000, 0x00000000}; static const u32 __attribute__((aligned(16))) C_NEGZERO[4] = {0x80000000, 0x80000000, 0x80000000, 0x80000000}; static const u32 __attribute__((aligned(16))) C_MAX[4] = {0x7FFFFFFF, 0x7FFFFFFF, 0x7FFFFFFF, 0x7FFFFFFF}; static const u32 __attribute__((aligned(16))) C_MIN[4] = {0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF}; static const u32 __attribute__((aligned(16))) C_MAX_MANTISSA[4] = {0x3FFFFFFF, 0x3FFFFFFF, 0x3FFFFFFF, 0x3FFFFFFF}; static const u32 __attribute__((aligned(16))) C_MAX_EXP[4] = {0x7F800001, 0x7F800001, 0x7F800001, 0x7F800001}; static const u32 __attribute__((aligned(16))) C_MIN_EXP[4] = {0x00000001, 0x00000001, 0x00000001, 0x00000001}; static const u32 __attribute__((aligned(16))) C_ONE[4] = {0x3F800000, 0x3F800000, 0x3F800000, 0x3F800000}; static const u32 __attribute__((aligned(16))) C_NEGONE[4] = {0xBF800000, 0xBF800000, 0xBF800000, 0xBF800000}; static const u32 __attribute__((aligned(16))) C_GARBAGE1[4] = {0x00001337, 0x00001337, 0x00001337, 0x00001337}; static const u32 __attribute__((aligned(16))) C_GARBAGE2[4] = {0xDEADBEEF, 0xDEADBEEF, 0xDEADBEEF, 0xDEADBEEF}; static const u32 __attribute__((aligned(16))) C_INCREASING[4] = {0x3F800000, 0x40000000, 0x40400000, 0x40800000}; static const u32 __attribute__((aligned(16))) C_DECREASING[4] = {0x40800000, 0x40400000, 0x40000000, 0x3F800000}; static u32 *const CVF_ZERO = (u32 *)(vu1_mem + 0x0000); static u32 *const CVF_NEGZERO = (u32 *)(vu1_mem + 0x0010); static u32 *const CVF_MAX = (u32 *)(vu1_mem + 0x0020); static u32 *const CVF_MIN = (u32 *)(vu1_mem + 0x0030); static u32 *const CVF_MAX_MANTISSA = (u32 *)(vu1_mem + 0x0040); static u32 *const CVF_MAX_EXP = (u32 *)(vu1_mem + 0x0050); static u32 *const CVF_MIN_EXP = (u32 *)(vu1_mem + 0x0060); static u32 *const CVF_ONE = (u32 *)(vu1_mem + 0x0070); static u32 *const CVF_NEGONE = (u32 *)(vu1_mem + 0x0080); static u32 *const CVF_GARBAGE1 = (u32 *)(vu1_mem + 0x0090); static u32 *const CVF_GARBAGE2 = (u32 *)(vu1_mem + 0x00A0); static u32 *const CVF_INCREASING = (u32 *)(vu1_mem + 0x00B0); static u32 *const CVF_DECREASING = (u32 *)(vu1_mem + 0x00C0); static void setup_vf_constants() { *(vu128 *)CVF_ZERO = *(vu128 *)C_ZERO; *(vu128 *)CVF_NEGZERO = *(vu128 *)C_NEGZERO; *(vu128 *)CVF_MAX = *(vu128 *)C_MAX; *(vu128 *)CVF_MIN = *(vu128 *)C_MIN; *(vu128 *)CVF_MAX_MANTISSA = *(vu128 *)C_MAX_MANTISSA; *(vu128 *)CVF_MAX_EXP = *(vu128 *)C_MAX_EXP; *(vu128 *)CVF_MIN_EXP = *(vu128 *)C_MIN_EXP; *(vu128 *)CVF_ONE = *(vu128 *)C_ONE; *(vu128 *)CVF_NEGONE = *(vu128 *)C_NEGONE; *(vu128 *)CVF_GARBAGE1 = *(vu128 *)C_GARBAGE1; *(vu128 *)CVF_GARBAGE2 = *(vu128 *)C_GARBAGE2; *(vu128 *)CVF_INCREASING = *(vu128 *)C_INCREASING; *(vu128 *)CVF_DECREASING = *(vu128 *)C_DECREASING; } class EfuTestRunner : public TestRunner { public: EfuTestRunner(int vu) : TestRunner(vu) { } typedef VU::LowerOp (*EfuFunctionScalar)(VU::Field field, VU::Reg reg); typedef VU::LowerOp (*EfuFunctionVector)(VU::Reg reg); void PerformS_M(const char *name, EfuFunctionScalar func, const char *tname, const u32 *t) { using namespace VU; Reset(); WrLoadFloatRegister(DEST_XYZW, VF01, t); //Op Wr(func(FIELD_Z, VF01)); Wr(WAITP()); Wr(MFP(DEST_XYZW, VF02)); Execute(); printf(" %s %s: ", name, tname); PrintRegisterField(VF02, FIELD_X, true); } void PerformV_M(const char *name, EfuFunctionVector func, const char *tname, const u32 *t) { using namespace VU; Reset(); WrLoadFloatRegister(DEST_XYZW, VF01, t); //Op Wr(func(VF01)); Wr(WAITP()); Wr(MFP(DEST_XYZW, VF02)); Execute(); printf(" %s %s: ", name, tname); PrintRegisterField(VF02, FIELD_X, true); } #define PerformS_M(name, func, t) PerformS_M(name, func, #t, t) #define PerformV_M(name, func, t) PerformV_M(name, func, #t, t) void PerformS(const char *name, EfuFunctionScalar func) { printf("%s:\n", name); PerformS_M(name, func, CVF_ZERO); PerformS_M(name, func, CVF_NEGZERO); PerformS_M(name, func, CVF_MAX); PerformS_M(name, func, CVF_MIN); PerformS_M(name, func, CVF_MAX_MANTISSA); PerformS_M(name, func, CVF_MAX_EXP); PerformS_M(name, func, CVF_MIN_EXP); PerformS_M(name, func, CVF_ONE); PerformS_M(name, func, CVF_NEGONE); PerformS_M(name, func, CVF_GARBAGE1); PerformS_M(name, func, CVF_GARBAGE2); PerformS_M(name, func, CVF_INCREASING); PerformS_M(name, func, CVF_DECREASING); } void PerformV(const char *name, EfuFunctionVector func) { printf("%s:\n", name); PerformV_M(name, func, CVF_ZERO); PerformV_M(name, func, CVF_NEGZERO); PerformV_M(name, func, CVF_MAX); PerformV_M(name, func, CVF_MIN); PerformV_M(name, func, CVF_MAX_MANTISSA); PerformV_M(name, func, CVF_MAX_EXP); PerformV_M(name, func, CVF_MIN_EXP); PerformV_M(name, func, CVF_ONE); PerformV_M(name, func, CVF_NEGONE); PerformV_M(name, func, CVF_GARBAGE1); PerformV_M(name, func, CVF_GARBAGE2); PerformV_M(name, func, CVF_INCREASING); PerformV_M(name, func, CVF_DECREASING); } #undef PerformS_M #undef PerformV_M }; int main(int argc, char *argv[]) { printf("-- TEST BEGIN\n"); setup_vf_constants(); EfuTestRunner runner(1); runner.PerformS("EATAN", &VU::EATAN); runner.PerformV("EATANxy", &VU::EATANxy); runner.PerformV("EATANxz", &VU::EATANxz); runner.PerformS("EEXP", &VU::EEXP); runner.PerformV("ELENG", &VU::ELENG); runner.PerformS("ERCPR", &VU::ERCPR); runner.PerformV("ERLENG", &VU::ERLENG); runner.PerformV("ERSADD", &VU::ERSADD); runner.PerformS("ERSQRT", &VU::ERSQRT); runner.PerformV("ESADD", &VU::ESADD); runner.PerformS("ESIN", &VU::ESIN); runner.PerformS("ESQRT", &VU::ESQRT); runner.PerformV("ESUM", &VU::ESUM); printf("-- TEST END\n"); return 0; } <|endoftext|>
<commit_before>// // leaf-node-line.cpp // gepetto-viewer // // Created by Justin Carpentier, Mathieu Geisert in November 2014. // Copyright (c) 2014 LAAS-CNRS. All rights reserved. // #include <gepetto/viewer/leaf-node-line.h> #include <osg/CullFace> #include <osg/LineWidth> #include <gepetto/viewer/node.h> namespace graphics { /* Declaration of private function members */ void LeafNodeLine::init () { /* Init the beam as a Geometry */ beam_ptr_ = new ::osg::Geometry(); /* Define points of the beam */ points_ptr_ = new ::osg::Vec3Array(2); /* Define the color */ color_ptr_ = new ::osg::Vec4Array(1); beam_ptr_->setVertexArray(points_ptr_.get()); beam_ptr_->setColorArray(color_ptr_.get()); beam_ptr_->setColorBinding(::osg::Geometry::BIND_PER_PRIMITIVE_SET); drawArray_ptr_ = new osg::DrawArrays(GL_LINE_STRIP,0,2); beam_ptr_->addPrimitiveSet(drawArray_ptr_.get()); /* Create Geode for adding ShapeDrawable */ geode_ptr_ = new osg::Geode(); geode_ptr_->addDrawable(beam_ptr_); /* Add geode to the queue */ this->asQueue()->addChild(geode_ptr_); /* Allow transparency */ geode_ptr_->getOrCreateStateSet()->setMode(GL_BLEND, ::osg::StateAttribute::ON); /* No light influence */ beam_ptr_->getOrCreateStateSet()->setMode(GL_LIGHTING, ::osg::StateAttribute::OFF | ::osg::StateAttribute::PROTECTED); /* Set a default line width */ osg::LineWidth* linewidth = new osg::LineWidth(); linewidth->setWidth(1.0f); beam_ptr_->getOrCreateStateSet()->setAttributeAndModes(linewidth, osg::StateAttribute::ON); } LeafNodeLine::LeafNodeLine (const std::string& name, const osgVector3& start_point, const osgVector3& end_point) : graphics::Node (name) { init (); setStartPoint(start_point); setEndPoint(end_point); setColor(osgVector4(1.,1.,1.,1.)); } LeafNodeLine::LeafNodeLine (const std::string& name, const osgVector3& start_point, const osgVector3& end_point, const osgVector4& color) : graphics::Node (name) { init (); setStartPoint(start_point); setEndPoint(end_point); setColor(color); } LeafNodeLine::LeafNodeLine (const std::string& name, const ::osg::Vec3ArrayRefPtr& points, const osgVector4& color) : graphics::Node (name) { init (); setPoints(points); setColor(color); } LeafNodeLine::LeafNodeLine (const LeafNodeLine& other) : graphics::Node (other) { init(); setPoints (other.points_ptr_); setColor(other.getColor()); } void LeafNodeLine::initWeakPtr (LeafNodeLineWeakPtr other_weak_ptr ) { weak_ptr_ = other_weak_ptr; } /* End of declaration of private function members */ /* Declaration of protected function members */ LeafNodeLinePtr_t LeafNodeLine::create (const std::string& name, const osgVector3& start_point, const osgVector3& end_point) { LeafNodeLinePtr_t shared_ptr(new LeafNodeLine (name, start_point, end_point)); // Add reference to itself shared_ptr->initWeakPtr (shared_ptr); return shared_ptr; } LeafNodeLinePtr_t LeafNodeLine::create (const std::string& name, const osgVector3& start_point, const osgVector3& end_point, const osgVector4& color) { LeafNodeLinePtr_t shared_ptr(new LeafNodeLine (name, start_point, end_point, color)); // Add reference to itself shared_ptr->initWeakPtr (shared_ptr); return shared_ptr; } LeafNodeLinePtr_t LeafNodeLine::create (const std::string& name, const ::osg::Vec3ArrayRefPtr& points, const osgVector4& color) { LeafNodeLinePtr_t shared_ptr(new LeafNodeLine (name, points, color)); // Add reference to itself shared_ptr->initWeakPtr (shared_ptr); return shared_ptr; } LeafNodeLinePtr_t LeafNodeLine::createCopy (LeafNodeLinePtr_t other) { LeafNodeLinePtr_t shared_ptr(new LeafNodeLine (*other)); // Add reference to itself shared_ptr->initWeakPtr (shared_ptr); return shared_ptr; } /* End of declaration of protected function members */ /* Declaration of public function members */ LeafNodeLinePtr_t LeafNodeLine::clone (void) const { return LeafNodeLine::createCopy(weak_ptr_.lock()); } LeafNodeLinePtr_t LeafNodeLine::self (void) const { return weak_ptr_.lock(); } void LeafNodeLine::setStartPoint (const osgVector3& start_point) { points_ptr_->at(0) = start_point; } osgVector3 LeafNodeLine::getStartPoint() const { return points_ptr_->at(0); } void LeafNodeLine::setEndPoint (const osgVector3& end_point) { points_ptr_->at(1) = end_point; } osgVector3 LeafNodeLine::getEndPoint() const { return points_ptr_->at(1); } void LeafNodeLine::setMode (const GLenum mode) { drawArray_ptr_->set (mode, 0, points_ptr_->size ()); } void LeafNodeLine::setPoints (const osgVector3& start_point, const osgVector3& end_point) { setStartPoint(start_point); setEndPoint(end_point); } void LeafNodeLine::setPoints (const ::osg::Vec3ArrayRefPtr& points) { points_ptr_ = points; beam_ptr_->setVertexArray (points_ptr_.get ()); drawArray_ptr_->setCount (points->size()); } void LeafNodeLine::setColor (const osgVector4& color) { color_ptr_->at(0) = color; } LeafNodeLine::~LeafNodeLine() { /* Proper deletion of all tree scene */ geode_ptr_->removeDrawable(beam_ptr_); //std::cout << "Beam ref count " << beam_ptr_->referenceCount() << std::endl; beam_ptr_ = NULL; this->asQueue()->removeChild(geode_ptr_); //std::cout << "Geode ref count " << geode_ptr_->referenceCount() << std::endl; geode_ptr_ = NULL; weak_ptr_.reset(); //std::cout << "Destruction of line " << getID() << std::endl; } /* End of declaration of public function members */ } /* namespace graphics */ <commit_msg>Force OSG to redraw when LeafNodeLine::color is changed<commit_after>// // leaf-node-line.cpp // gepetto-viewer // // Created by Justin Carpentier, Mathieu Geisert in November 2014. // Copyright (c) 2014 LAAS-CNRS. All rights reserved. // #include <gepetto/viewer/leaf-node-line.h> #include <osg/CullFace> #include <osg/LineWidth> #include <gepetto/viewer/node.h> namespace graphics { /* Declaration of private function members */ void LeafNodeLine::init () { /* Init the beam as a Geometry */ beam_ptr_ = new ::osg::Geometry(); /* Define points of the beam */ points_ptr_ = new ::osg::Vec3Array(2); /* Define the color */ color_ptr_ = new ::osg::Vec4Array(1); beam_ptr_->setVertexArray(points_ptr_.get()); beam_ptr_->setColorArray(color_ptr_.get()); beam_ptr_->setColorBinding(::osg::Geometry::BIND_PER_PRIMITIVE_SET); drawArray_ptr_ = new osg::DrawArrays(GL_LINE_STRIP,0,2); beam_ptr_->addPrimitiveSet(drawArray_ptr_.get()); /* Create Geode for adding ShapeDrawable */ geode_ptr_ = new osg::Geode(); geode_ptr_->addDrawable(beam_ptr_); /* Add geode to the queue */ this->asQueue()->addChild(geode_ptr_); /* Allow transparency */ geode_ptr_->getOrCreateStateSet()->setMode(GL_BLEND, ::osg::StateAttribute::ON); /* No light influence */ beam_ptr_->getOrCreateStateSet()->setMode(GL_LIGHTING, ::osg::StateAttribute::OFF | ::osg::StateAttribute::PROTECTED); /* Set a default line width */ osg::LineWidth* linewidth = new osg::LineWidth(); linewidth->setWidth(1.0f); beam_ptr_->getOrCreateStateSet()->setAttributeAndModes(linewidth, osg::StateAttribute::ON); } LeafNodeLine::LeafNodeLine (const std::string& name, const osgVector3& start_point, const osgVector3& end_point) : graphics::Node (name) { init (); setStartPoint(start_point); setEndPoint(end_point); setColor(osgVector4(1.,1.,1.,1.)); } LeafNodeLine::LeafNodeLine (const std::string& name, const osgVector3& start_point, const osgVector3& end_point, const osgVector4& color) : graphics::Node (name) { init (); setStartPoint(start_point); setEndPoint(end_point); setColor(color); } LeafNodeLine::LeafNodeLine (const std::string& name, const ::osg::Vec3ArrayRefPtr& points, const osgVector4& color) : graphics::Node (name) { init (); setPoints(points); setColor(color); } LeafNodeLine::LeafNodeLine (const LeafNodeLine& other) : graphics::Node (other) { init(); setPoints (other.points_ptr_); setColor(other.getColor()); } void LeafNodeLine::initWeakPtr (LeafNodeLineWeakPtr other_weak_ptr ) { weak_ptr_ = other_weak_ptr; } /* End of declaration of private function members */ /* Declaration of protected function members */ LeafNodeLinePtr_t LeafNodeLine::create (const std::string& name, const osgVector3& start_point, const osgVector3& end_point) { LeafNodeLinePtr_t shared_ptr(new LeafNodeLine (name, start_point, end_point)); // Add reference to itself shared_ptr->initWeakPtr (shared_ptr); return shared_ptr; } LeafNodeLinePtr_t LeafNodeLine::create (const std::string& name, const osgVector3& start_point, const osgVector3& end_point, const osgVector4& color) { LeafNodeLinePtr_t shared_ptr(new LeafNodeLine (name, start_point, end_point, color)); // Add reference to itself shared_ptr->initWeakPtr (shared_ptr); return shared_ptr; } LeafNodeLinePtr_t LeafNodeLine::create (const std::string& name, const ::osg::Vec3ArrayRefPtr& points, const osgVector4& color) { LeafNodeLinePtr_t shared_ptr(new LeafNodeLine (name, points, color)); // Add reference to itself shared_ptr->initWeakPtr (shared_ptr); return shared_ptr; } LeafNodeLinePtr_t LeafNodeLine::createCopy (LeafNodeLinePtr_t other) { LeafNodeLinePtr_t shared_ptr(new LeafNodeLine (*other)); // Add reference to itself shared_ptr->initWeakPtr (shared_ptr); return shared_ptr; } /* End of declaration of protected function members */ /* Declaration of public function members */ LeafNodeLinePtr_t LeafNodeLine::clone (void) const { return LeafNodeLine::createCopy(weak_ptr_.lock()); } LeafNodeLinePtr_t LeafNodeLine::self (void) const { return weak_ptr_.lock(); } void LeafNodeLine::setStartPoint (const osgVector3& start_point) { points_ptr_->at(0) = start_point; } osgVector3 LeafNodeLine::getStartPoint() const { return points_ptr_->at(0); } void LeafNodeLine::setEndPoint (const osgVector3& end_point) { points_ptr_->at(1) = end_point; } osgVector3 LeafNodeLine::getEndPoint() const { return points_ptr_->at(1); } void LeafNodeLine::setMode (const GLenum mode) { drawArray_ptr_->set (mode, 0, points_ptr_->size ()); } void LeafNodeLine::setPoints (const osgVector3& start_point, const osgVector3& end_point) { setStartPoint(start_point); setEndPoint(end_point); } void LeafNodeLine::setPoints (const ::osg::Vec3ArrayRefPtr& points) { points_ptr_ = points; beam_ptr_->setVertexArray (points_ptr_.get ()); drawArray_ptr_->setCount (points->size()); } void LeafNodeLine::setColor (const osgVector4& color) { color_ptr_->at(0) = color; beam_ptr_->dirtyDisplayList(); } LeafNodeLine::~LeafNodeLine() { /* Proper deletion of all tree scene */ geode_ptr_->removeDrawable(beam_ptr_); //std::cout << "Beam ref count " << beam_ptr_->referenceCount() << std::endl; beam_ptr_ = NULL; this->asQueue()->removeChild(geode_ptr_); //std::cout << "Geode ref count " << geode_ptr_->referenceCount() << std::endl; geode_ptr_ = NULL; weak_ptr_.reset(); //std::cout << "Destruction of line " << getID() << std::endl; } /* End of declaration of public function members */ } /* namespace graphics */ <|endoftext|>
<commit_before>//===-- LanaiDelaySlotFiller.cpp - Lanai delay slot filler ----------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // Simple pass to fills delay slots with useful instructions. // //===----------------------------------------------------------------------===// #include "Lanai.h" #include "LanaiTargetMachine.h" #include "llvm/ADT/SmallSet.h" #include "llvm/ADT/Statistic.h" #include "llvm/CodeGen/MachineFunctionPass.h" #include "llvm/CodeGen/MachineInstrBuilder.h" #include "llvm/CodeGen/TargetInstrInfo.h" #include "llvm/Support/CommandLine.h" using namespace llvm; #define DEBUG_TYPE "delay-slot-filler" STATISTIC(FilledSlots, "Number of delay slots filled"); static cl::opt<bool> NopDelaySlotFiller("lanai-nop-delay-filler", cl::init(false), cl::desc("Fill Lanai delay slots with NOPs."), cl::Hidden); namespace { struct Filler : public MachineFunctionPass { // Target machine description which we query for reg. names, data // layout, etc. const TargetInstrInfo *TII; const TargetRegisterInfo *TRI; MachineBasicBlock::instr_iterator LastFiller; static char ID; explicit Filler() : MachineFunctionPass(ID) {} StringRef getPassName() const override { return "Lanai Delay Slot Filler"; } bool runOnMachineBasicBlock(MachineBasicBlock &MBB); bool runOnMachineFunction(MachineFunction &MF) override { const LanaiSubtarget &Subtarget = MF.getSubtarget<LanaiSubtarget>(); TII = Subtarget.getInstrInfo(); TRI = Subtarget.getRegisterInfo(); bool Changed = false; for (MachineFunction::iterator FI = MF.begin(), FE = MF.end(); FI != FE; ++FI) Changed |= runOnMachineBasicBlock(*FI); return Changed; } MachineFunctionProperties getRequiredProperties() const override { return MachineFunctionProperties().set( MachineFunctionProperties::Property::NoVRegs); } void insertDefsUses(MachineBasicBlock::instr_iterator MI, SmallSet<unsigned, 32> &RegDefs, SmallSet<unsigned, 32> &RegUses); bool isRegInSet(SmallSet<unsigned, 32> &RegSet, unsigned Reg); bool delayHasHazard(MachineBasicBlock::instr_iterator MI, bool &SawLoad, bool &SawStore, SmallSet<unsigned, 32> &RegDefs, SmallSet<unsigned, 32> &RegUses); bool findDelayInstr(MachineBasicBlock &MBB, MachineBasicBlock::instr_iterator Slot, MachineBasicBlock::instr_iterator &Filler); }; char Filler::ID = 0; } // end of anonymous namespace // createLanaiDelaySlotFillerPass - Returns a pass that fills in delay // slots in Lanai MachineFunctions FunctionPass * llvm::createLanaiDelaySlotFillerPass(const LanaiTargetMachine & /*tm*/) { return new Filler(); } // runOnMachineBasicBlock - Fill in delay slots for the given basic block. // There is one or two delay slot per delayed instruction. bool Filler::runOnMachineBasicBlock(MachineBasicBlock &MBB) { bool Changed = false; LastFiller = MBB.instr_end(); for (MachineBasicBlock::instr_iterator I = MBB.instr_begin(); I != MBB.instr_end(); ++I) { if (I->getDesc().hasDelaySlot()) { MachineBasicBlock::instr_iterator InstrWithSlot = I; MachineBasicBlock::instr_iterator J = I; // Treat RET specially as it is only instruction with 2 delay slots // generated while all others generated have 1 delay slot. if (I->getOpcode() == Lanai::RET) { // RET is generated as part of epilogue generation and hence we know // what the two instructions preceding it are and that it is safe to // insert RET above them. MachineBasicBlock::reverse_instr_iterator RI = ++I.getReverse(); assert(RI->getOpcode() == Lanai::LDW_RI && RI->getOperand(0).isReg() && RI->getOperand(0).getReg() == Lanai::FP && RI->getOperand(1).isReg() && RI->getOperand(1).getReg() == Lanai::FP && RI->getOperand(2).isImm() && RI->getOperand(2).getImm() == -8); ++RI; assert(RI->getOpcode() == Lanai::ADD_I_LO && RI->getOperand(0).isReg() && RI->getOperand(0).getReg() == Lanai::SP && RI->getOperand(1).isReg() && RI->getOperand(1).getReg() == Lanai::FP); MachineBasicBlock::instr_iterator FI = RI.getReverse(); MBB.splice(std::next(I), &MBB, FI, I); FilledSlots += 2; } else { if (!NopDelaySlotFiller && findDelayInstr(MBB, I, J)) { MBB.splice(std::next(I), &MBB, J); } else { BuildMI(MBB, std::next(I), DebugLoc(), TII->get(Lanai::NOP)); } ++FilledSlots; } Changed = true; // Record the filler instruction that filled the delay slot. // The instruction after it will be visited in the next iteration. LastFiller = ++I; // Bundle the delay slot filler to InstrWithSlot so that the machine // verifier doesn't expect this instruction to be a terminator. MIBundleBuilder(MBB, InstrWithSlot, std::next(LastFiller)); } } return Changed; } bool Filler::findDelayInstr(MachineBasicBlock &MBB, MachineBasicBlock::instr_iterator Slot, MachineBasicBlock::instr_iterator &Filler) { SmallSet<unsigned, 32> RegDefs; SmallSet<unsigned, 32> RegUses; insertDefsUses(Slot, RegDefs, RegUses); bool SawLoad = false; bool SawStore = false; for (MachineBasicBlock::reverse_instr_iterator I = ++Slot.getReverse(); I != MBB.instr_rend(); ++I) { // skip debug value if (I->isDebugInstr()) continue; // Convert to forward iterator. MachineBasicBlock::instr_iterator FI = I.getReverse(); if (I->hasUnmodeledSideEffects() || I->isInlineAsm() || I->isLabel() || FI == LastFiller || I->isPseudo()) break; if (delayHasHazard(FI, SawLoad, SawStore, RegDefs, RegUses)) { insertDefsUses(FI, RegDefs, RegUses); continue; } Filler = FI; return true; } return false; } bool Filler::delayHasHazard(MachineBasicBlock::instr_iterator MI, bool &SawLoad, bool &SawStore, SmallSet<unsigned, 32> &RegDefs, SmallSet<unsigned, 32> &RegUses) { if (MI->isImplicitDef() || MI->isKill()) return true; // Loads or stores cannot be moved past a store to the delay slot // and stores cannot be moved past a load. if (MI->mayLoad()) { if (SawStore) return true; SawLoad = true; } if (MI->mayStore()) { if (SawStore) return true; SawStore = true; if (SawLoad) return true; } assert((!MI->isCall() && !MI->isReturn()) && "Cannot put calls or returns in delay slot."); for (unsigned I = 0, E = MI->getNumOperands(); I != E; ++I) { const MachineOperand &MO = MI->getOperand(I); unsigned Reg; if (!MO.isReg() || !(Reg = MO.getReg())) continue; // skip if (MO.isDef()) { // check whether Reg is defined or used before delay slot. if (isRegInSet(RegDefs, Reg) || isRegInSet(RegUses, Reg)) return true; } if (MO.isUse()) { // check whether Reg is defined before delay slot. if (isRegInSet(RegDefs, Reg)) return true; } } return false; } // Insert Defs and Uses of MI into the sets RegDefs and RegUses. void Filler::insertDefsUses(MachineBasicBlock::instr_iterator MI, SmallSet<unsigned, 32> &RegDefs, SmallSet<unsigned, 32> &RegUses) { // If MI is a call or return, just examine the explicit non-variadic operands. MCInstrDesc MCID = MI->getDesc(); unsigned E = MI->isCall() || MI->isReturn() ? MCID.getNumOperands() : MI->getNumOperands(); for (unsigned I = 0; I != E; ++I) { const MachineOperand &MO = MI->getOperand(I); unsigned Reg; if (!MO.isReg() || !(Reg = MO.getReg())) continue; if (MO.isDef()) RegDefs.insert(Reg); else if (MO.isUse()) RegUses.insert(Reg); } // Call & return instructions defines SP implicitly. Implicit defines are not // included in the RegDefs set of calls but instructions modifying SP cannot // be inserted in the delay slot of a call/return as these instructions are // expanded to multiple instructions with SP modified before the branch that // has the delay slot. if (MI->isCall() || MI->isReturn()) RegDefs.insert(Lanai::SP); } // Returns true if the Reg or its alias is in the RegSet. bool Filler::isRegInSet(SmallSet<unsigned, 32> &RegSet, unsigned Reg) { // Check Reg and all aliased Registers. for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI) if (RegSet.count(*AI)) return true; return false; } <commit_msg>[NFC] Test commit, fix some comment spelling.<commit_after>//===-- LanaiDelaySlotFiller.cpp - Lanai delay slot filler ----------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // Simple pass to fill delay slots with useful instructions. // //===----------------------------------------------------------------------===// #include "Lanai.h" #include "LanaiTargetMachine.h" #include "llvm/ADT/SmallSet.h" #include "llvm/ADT/Statistic.h" #include "llvm/CodeGen/MachineFunctionPass.h" #include "llvm/CodeGen/MachineInstrBuilder.h" #include "llvm/CodeGen/TargetInstrInfo.h" #include "llvm/Support/CommandLine.h" using namespace llvm; #define DEBUG_TYPE "delay-slot-filler" STATISTIC(FilledSlots, "Number of delay slots filled"); static cl::opt<bool> NopDelaySlotFiller("lanai-nop-delay-filler", cl::init(false), cl::desc("Fill Lanai delay slots with NOPs."), cl::Hidden); namespace { struct Filler : public MachineFunctionPass { // Target machine description which we query for reg. names, data // layout, etc. const TargetInstrInfo *TII; const TargetRegisterInfo *TRI; MachineBasicBlock::instr_iterator LastFiller; static char ID; explicit Filler() : MachineFunctionPass(ID) {} StringRef getPassName() const override { return "Lanai Delay Slot Filler"; } bool runOnMachineBasicBlock(MachineBasicBlock &MBB); bool runOnMachineFunction(MachineFunction &MF) override { const LanaiSubtarget &Subtarget = MF.getSubtarget<LanaiSubtarget>(); TII = Subtarget.getInstrInfo(); TRI = Subtarget.getRegisterInfo(); bool Changed = false; for (MachineFunction::iterator FI = MF.begin(), FE = MF.end(); FI != FE; ++FI) Changed |= runOnMachineBasicBlock(*FI); return Changed; } MachineFunctionProperties getRequiredProperties() const override { return MachineFunctionProperties().set( MachineFunctionProperties::Property::NoVRegs); } void insertDefsUses(MachineBasicBlock::instr_iterator MI, SmallSet<unsigned, 32> &RegDefs, SmallSet<unsigned, 32> &RegUses); bool isRegInSet(SmallSet<unsigned, 32> &RegSet, unsigned Reg); bool delayHasHazard(MachineBasicBlock::instr_iterator MI, bool &SawLoad, bool &SawStore, SmallSet<unsigned, 32> &RegDefs, SmallSet<unsigned, 32> &RegUses); bool findDelayInstr(MachineBasicBlock &MBB, MachineBasicBlock::instr_iterator Slot, MachineBasicBlock::instr_iterator &Filler); }; char Filler::ID = 0; } // end of anonymous namespace // createLanaiDelaySlotFillerPass - Returns a pass that fills in delay // slots in Lanai MachineFunctions FunctionPass * llvm::createLanaiDelaySlotFillerPass(const LanaiTargetMachine & /*tm*/) { return new Filler(); } // runOnMachineBasicBlock - Fill in delay slots for the given basic block. // There is one or two delay slot per delayed instruction. bool Filler::runOnMachineBasicBlock(MachineBasicBlock &MBB) { bool Changed = false; LastFiller = MBB.instr_end(); for (MachineBasicBlock::instr_iterator I = MBB.instr_begin(); I != MBB.instr_end(); ++I) { if (I->getDesc().hasDelaySlot()) { MachineBasicBlock::instr_iterator InstrWithSlot = I; MachineBasicBlock::instr_iterator J = I; // Treat RET specially as it is only instruction with 2 delay slots // generated while all others generated have 1 delay slot. if (I->getOpcode() == Lanai::RET) { // RET is generated as part of epilogue generation and hence we know // what the two instructions preceding it are and that it is safe to // insert RET above them. MachineBasicBlock::reverse_instr_iterator RI = ++I.getReverse(); assert(RI->getOpcode() == Lanai::LDW_RI && RI->getOperand(0).isReg() && RI->getOperand(0).getReg() == Lanai::FP && RI->getOperand(1).isReg() && RI->getOperand(1).getReg() == Lanai::FP && RI->getOperand(2).isImm() && RI->getOperand(2).getImm() == -8); ++RI; assert(RI->getOpcode() == Lanai::ADD_I_LO && RI->getOperand(0).isReg() && RI->getOperand(0).getReg() == Lanai::SP && RI->getOperand(1).isReg() && RI->getOperand(1).getReg() == Lanai::FP); MachineBasicBlock::instr_iterator FI = RI.getReverse(); MBB.splice(std::next(I), &MBB, FI, I); FilledSlots += 2; } else { if (!NopDelaySlotFiller && findDelayInstr(MBB, I, J)) { MBB.splice(std::next(I), &MBB, J); } else { BuildMI(MBB, std::next(I), DebugLoc(), TII->get(Lanai::NOP)); } ++FilledSlots; } Changed = true; // Record the filler instruction that filled the delay slot. // The instruction after it will be visited in the next iteration. LastFiller = ++I; // Bundle the delay slot filler to InstrWithSlot so that the machine // verifier doesn't expect this instruction to be a terminator. MIBundleBuilder(MBB, InstrWithSlot, std::next(LastFiller)); } } return Changed; } bool Filler::findDelayInstr(MachineBasicBlock &MBB, MachineBasicBlock::instr_iterator Slot, MachineBasicBlock::instr_iterator &Filler) { SmallSet<unsigned, 32> RegDefs; SmallSet<unsigned, 32> RegUses; insertDefsUses(Slot, RegDefs, RegUses); bool SawLoad = false; bool SawStore = false; for (MachineBasicBlock::reverse_instr_iterator I = ++Slot.getReverse(); I != MBB.instr_rend(); ++I) { // skip debug value if (I->isDebugInstr()) continue; // Convert to forward iterator. MachineBasicBlock::instr_iterator FI = I.getReverse(); if (I->hasUnmodeledSideEffects() || I->isInlineAsm() || I->isLabel() || FI == LastFiller || I->isPseudo()) break; if (delayHasHazard(FI, SawLoad, SawStore, RegDefs, RegUses)) { insertDefsUses(FI, RegDefs, RegUses); continue; } Filler = FI; return true; } return false; } bool Filler::delayHasHazard(MachineBasicBlock::instr_iterator MI, bool &SawLoad, bool &SawStore, SmallSet<unsigned, 32> &RegDefs, SmallSet<unsigned, 32> &RegUses) { if (MI->isImplicitDef() || MI->isKill()) return true; // Loads or stores cannot be moved past a store to the delay slot // and stores cannot be moved past a load. if (MI->mayLoad()) { if (SawStore) return true; SawLoad = true; } if (MI->mayStore()) { if (SawStore) return true; SawStore = true; if (SawLoad) return true; } assert((!MI->isCall() && !MI->isReturn()) && "Cannot put calls or returns in delay slot."); for (unsigned I = 0, E = MI->getNumOperands(); I != E; ++I) { const MachineOperand &MO = MI->getOperand(I); unsigned Reg; if (!MO.isReg() || !(Reg = MO.getReg())) continue; // skip if (MO.isDef()) { // check whether Reg is defined or used before delay slot. if (isRegInSet(RegDefs, Reg) || isRegInSet(RegUses, Reg)) return true; } if (MO.isUse()) { // check whether Reg is defined before delay slot. if (isRegInSet(RegDefs, Reg)) return true; } } return false; } // Insert Defs and Uses of MI into the sets RegDefs and RegUses. void Filler::insertDefsUses(MachineBasicBlock::instr_iterator MI, SmallSet<unsigned, 32> &RegDefs, SmallSet<unsigned, 32> &RegUses) { // If MI is a call or return, just examine the explicit non-variadic operands. MCInstrDesc MCID = MI->getDesc(); unsigned E = MI->isCall() || MI->isReturn() ? MCID.getNumOperands() : MI->getNumOperands(); for (unsigned I = 0; I != E; ++I) { const MachineOperand &MO = MI->getOperand(I); unsigned Reg; if (!MO.isReg() || !(Reg = MO.getReg())) continue; if (MO.isDef()) RegDefs.insert(Reg); else if (MO.isUse()) RegUses.insert(Reg); } // Call & return instructions defines SP implicitly. Implicit defines are not // included in the RegDefs set of calls but instructions modifying SP cannot // be inserted in the delay slot of a call/return as these instructions are // expanded to multiple instructions with SP modified before the branch that // has the delay slot. if (MI->isCall() || MI->isReturn()) RegDefs.insert(Lanai::SP); } // Returns true if the Reg or its alias is in the RegSet. bool Filler::isRegInSet(SmallSet<unsigned, 32> &RegSet, unsigned Reg) { // Check Reg and all aliased Registers. for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI) if (RegSet.count(*AI)) return true; return false; } <|endoftext|>
<commit_before>#pragma once #include "../lexer/position.hpp" #include "../lexer/lexer.hpp" #include <boost/spirit/include/qi_parse.hpp> namespace puppet { namespace compiler { /** * Declare a new terminal for Spirit. */ BOOST_SPIRIT_TERMINAL_EX(token_pos); }} // namespace puppet::compiler namespace boost { namespace spirit { /** * Enables token_pos as a terminal in parser expressions. * @typename A0 The type of the first argument to the terminal. */ template <typename A0> struct use_terminal<qi::domain, terminal_ex<puppet::compiler::tag::token_pos, fusion::vector1<A0>>> : mpl::or_<is_integral<A0>, is_enum<A0>> { }; }} // namespace boost::spirit namespace puppet { namespace compiler { /** * Implements a primitive parser for token positions. * @tparam TokenId The type of token id. */ template <typename TokenId> struct token_pos_parser : boost::spirit::qi::primitive_parser<token_pos_parser<TokenId>> { /** * Defines the attribute for the parser. * @tparam Context The context type. * @tparam Iterator The iterator type. */ template <typename Context, typename Iterator> struct attribute { typedef lexer::position type; }; /** * Constructs a token position parser with the given id. * @param id The token id to match on. */ token_pos_parser(TokenId const& id) : _id(id) { } /** * Parses the input into the attribute. * @tparam Iterator The iterator type. * @tparam Context The context type. * @tparam Skipper The skipper type. * @tparam Attribute The attribute type. * @param first The first iterator. * @param last The last iterator. * @param skipper The skipper instance. * @param attr The attribute instance. * @return Returns true if successfully parsed or false if not. */ template <typename Iterator, typename Context, typename Skipper, typename Attribute> bool parse(Iterator& first, Iterator const& last, Context&, Skipper const& skipper, Attribute& attr) const { boost::spirit::qi::skip_over(first, last, skipper); if (first != last) { if (static_cast<typename Iterator::value_type::id_type>(_id) == first->id()) { attr = boost::apply_visitor(lexer::token_position_visitor(), first->value()); ++first; return true; } } return false; } /** * Describes the parser. * @return Returns the boost::spirit::info about the parser.s */ template <typename Context> boost::spirit::info what(Context&) const { return boost::spirit::info("token_pos", "token_pos(" + boost::lexical_cast<std::string>(_id) + ")"); } private: TokenId _id; }; }} // namespace puppet::compiler namespace boost { namespace spirit { namespace qi { /** * Instantiates a primitive parser. * @tparam Modifiers The modifiers type. * @tparam TokenId The type of token id. */ template <typename Modifiers, typename TokenId> struct make_primitive<terminal_ex<puppet::compiler::tag::token_pos, fusion::vector1<TokenId>>, Modifiers> { /** * Represents the resulting parser type. */ typedef puppet::compiler::token_pos_parser<TokenId> result_type; /** * Constructs the primitive parser. * @tparam Terminal The terminal type. * @param term The terminal. * @return Returns the primitive parser. */ template <typename Terminal> result_type operator()(Terminal const& term, unused_type) const { return result_type(fusion::at_c<0>(term.args)); } }; }}} // namesoace boost::spirit::qi<commit_msg>Fix output of compiler errors when expectations fail on token_pos.<commit_after>#pragma once #include "../lexer/position.hpp" #include "../lexer/lexer.hpp" #include <boost/spirit/include/qi_parse.hpp> namespace puppet { namespace compiler { /** * Declare a new terminal for Spirit. */ BOOST_SPIRIT_TERMINAL_EX(token_pos); }} // namespace puppet::compiler namespace boost { namespace spirit { /** * Enables token_pos as a terminal in parser expressions. * @typename A0 The type of the first argument to the terminal. */ template <typename A0> struct use_terminal<qi::domain, terminal_ex<puppet::compiler::tag::token_pos, fusion::vector1<A0>>> : mpl::or_<is_integral<A0>, is_enum<A0>> { }; }} // namespace boost::spirit namespace puppet { namespace compiler { /** * Implements a primitive parser for token positions. * @tparam TokenId The type of token id. */ template <typename TokenId> struct token_pos_parser : boost::spirit::qi::primitive_parser<token_pos_parser<TokenId>> { /** * Defines the attribute for the parser. * @tparam Context The context type. * @tparam Iterator The iterator type. */ template <typename Context, typename Iterator> struct attribute { typedef lexer::position type; }; /** * Constructs a token position parser with the given id. * @param id The token id to match on. */ token_pos_parser(TokenId const& id) : _id(id) { } /** * Parses the input into the attribute. * @tparam Iterator The iterator type. * @tparam Context The context type. * @tparam Skipper The skipper type. * @tparam Attribute The attribute type. * @param first The first iterator. * @param last The last iterator. * @param skipper The skipper instance. * @param attr The attribute instance. * @return Returns true if successfully parsed or false if not. */ template <typename Iterator, typename Context, typename Skipper, typename Attribute> bool parse(Iterator& first, Iterator const& last, Context&, Skipper const& skipper, Attribute& attr) const { boost::spirit::qi::skip_over(first, last, skipper); if (first != last) { if (static_cast<typename Iterator::value_type::id_type>(_id) == first->id()) { attr = boost::apply_visitor(lexer::token_position_visitor(), first->value()); ++first; return true; } } return false; } /** * Describes the parser. * @return Returns the boost::spirit::info about the parser.s */ template <typename Context> boost::spirit::info what(Context&) const { return boost::spirit::info("token", boost::lexical_cast<std::string>(_id)); } private: TokenId _id; }; }} // namespace puppet::compiler namespace boost { namespace spirit { namespace qi { /** * Instantiates a primitive parser. * @tparam Modifiers The modifiers type. * @tparam TokenId The type of token id. */ template <typename Modifiers, typename TokenId> struct make_primitive<terminal_ex<puppet::compiler::tag::token_pos, fusion::vector1<TokenId>>, Modifiers> { /** * Represents the resulting parser type. */ typedef puppet::compiler::token_pos_parser<TokenId> result_type; /** * Constructs the primitive parser. * @tparam Terminal The terminal type. * @param term The terminal. * @return Returns the primitive parser. */ template <typename Terminal> result_type operator()(Terminal const& term, unused_type) const { return result_type(fusion::at_c<0>(term.args)); } }; }}} // namesoace boost::spirit::qi<|endoftext|>
<commit_before>/* * Copyright 2009-2011 The VOTCA Development Team (http://www.votca.org) * * 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 <votca/csg/topology.h> #include <votca/csg/interaction.h> #include <votca/tools/rangeparser.h> #include <stdexcept> namespace votca { namespace csg { Topology::~Topology() { Cleanup(); if(_bc) delete (_bc); _bc = NULL; } void Topology::Cleanup() { // cleanup beads { BeadContainer::iterator i; for(i=_beads.begin();i<_beads.end();++i) delete *i; _beads.clear(); } // cleanup molecules { MoleculeContainer::iterator i; for(i=_molecules.begin();i<_molecules.end();++i) delete *i; _molecules.clear(); } // cleanup residues { ResidueContainer::iterator i; for(i=_residues.begin();i<_residues.end();++i) delete (*i); _residues.clear(); } // cleanup interactions { InteractionContainer::iterator i; for(i=_interactions.begin();i<_interactions.end();++i) delete (*i); _interactions.clear(); } // cleanup _bc object if(_bc) delete (_bc); _bc = new OpenBox(); } /// \todo implement checking, only used in xml topology reader void Topology::CreateMoleculesByRange(string name, int first, int nbeads, int nmolecules) { Molecule *mol = CreateMolecule(name); int beadcount=0; int res_offset=0; BeadContainer::iterator bead; for(bead=_beads.begin(); bead!=_beads.end(); ++bead) { while(--first > 0) continue; //This is not 100% correct, but let's assume for now that the resnr do increase if ( beadcount == 0 ) { res_offset = (*bead)->getResnr(); } stringstream bname; bname << (*bead)->getResnr() - res_offset + 1 << ":" << getResidue((*bead)->getResnr())->getName() << ":" << (*bead)->getName(); mol->AddBead((*bead), bname.str()); if(++beadcount == nbeads) { if(--nmolecules <= 0) break; mol = CreateMolecule(name); beadcount = 0; } } } /// \todo clean up CreateMoleculesByResidue! void Topology::CreateMoleculesByResidue() { // first create a molecule for each residue ResidueContainer::iterator res; for(res=_residues.begin(); res!=_residues.end(); ++res) { CreateMolecule((*res)->getName()); } // add the beads to the corresponding molecules based on their resid BeadContainer::iterator bead; for(bead=_beads.begin(); bead!=_beads.end(); ++bead) { //MoleculeByIndex((*bead)->getResnr())->AddBead((*bead)->getId(), (*bead)->getName()); MoleculeByIndex((*bead)->getResnr())->AddBead((*bead), string("1:TRI:") + (*bead)->getName()); } /// \todo sort beads in molecules that all beads are stored in the same order. This is needed for the mapping! } void Topology::CreateOneBigMolecule(string name) { Molecule *mi = CreateMolecule(name); BeadContainer::iterator bead; for(bead=_beads.begin(); bead!=_beads.end(); ++bead) { stringstream n(""); n << (*bead)->getResnr() +1 << ":" << _residues[(*bead)->getResnr()]->getName() << ":" << (*bead)->getName(); //cout << n.str() << endl; mi->AddBead((*bead), n.str()); } } void Topology::Add(Topology *top) { BeadContainer::iterator bead; ResidueContainer::iterator res; MoleculeContainer::iterator mol; int res0=ResidueCount(); for(bead=top->_beads.begin(); bead!=top->_beads.end(); ++bead) { Bead *bi = *bead; BeadType *type = GetOrCreateBeadType(bi->getType()->getName()); CreateBead(bi->getSymmetry(), bi->getName(), type, bi->getResnr()+res0, bi->getM(), bi->getQ()); } for(res=top->_residues.begin();res!=top->_residues.end(); ++res) { CreateResidue((*res)->getName()); } // \todo beadnames in molecules!! for(mol=top->_molecules.begin();mol!=top->_molecules.end(); ++mol) { Molecule *mi = CreateMolecule((*mol)->getName()); for(int i=0; i<mi->BeadCount(); i++) { mi->AddBead(mi->getBead(i), "invalid"); } } } void Topology::CopyTopologyData(Topology *top) { BeadContainer::iterator it_bead; ResidueContainer::iterator it_res; MoleculeContainer::iterator it_mol; InteractionContainer::iterator it_ia; _bc->setBox(top->getBox()); _time = top->_time; _step = top->_step; // cleanup old data Cleanup(); // copy all residues for(it_res=top->_residues.begin();it_res!=top->_residues.end(); ++it_res) { CreateResidue((*it_res)->getName()); } // create all beads for(it_bead=top->_beads.begin(); it_bead!=top->_beads.end(); ++it_bead) { Bead *bi = *it_bead; BeadType *type = GetOrCreateBeadType(bi->getType()->getName()); Bead *bn = CreateBead(bi->getSymmetry(), bi->getName(), type, bi->getResnr(), bi->getM(), bi->getQ()); bn->setOptions(bi->Options()); } // copy all molecules for(it_mol=top->_molecules.begin();it_mol!=top->_molecules.end(); ++it_mol) { Molecule *mi = CreateMolecule((*it_mol)->getName()); for(int i=0; i<(*it_mol)->BeadCount(); i++) { int beadid = (*it_mol)->getBead(i)->getId(); mi->AddBead(_beads[beadid], (*it_mol)->getBeadName(i)); } } // TODO: copy interactions //for(it_ia=top->_interaction.begin();it_ia=top->_interactions.end();++it_ia) { //} } void Topology::RenameMolecules(string range, string name) { RangeParser rp; RangeParser::iterator i; rp.Parse(range); for(i=rp.begin();i!=rp.end();++i) { if((unsigned int)*i > _molecules.size()) throw runtime_error(string("RenameMolecules: num molecules smaller than")); getMolecule(*i-1)->setName(name); } } void Topology::RenameBeadType(string name, string newname) { BeadContainer::iterator bead; for(bead=_beads.begin(); bead!=_beads.end(); ++bead) { BeadType *type = GetOrCreateBeadType((*bead)->getType()->getName()); if (wildcmp(name.c_str(),(*bead)->getType()->getName().c_str())) { type->setName(newname); } } } void Topology::SetBeadTypeMass(string name, double value) { BeadContainer::iterator bead; for(bead=_beads.begin(); bead!=_beads.end(); ++bead) { if (wildcmp(name.c_str(),(*bead)->getType()->getName().c_str())) { (*bead)->setM(value); } } } void Topology::CheckMoleculeNaming(void) { map<string,int> nbeads; for(MoleculeContainer::iterator iter = _molecules.begin(); iter!=_molecules.end(); ++iter) { map<string,int>::iterator entry = nbeads.find((*iter)->getName()); if(entry != nbeads.end()) { if(entry->second != (*iter)->BeadCount()) throw runtime_error("There are molecules which have the same name but different number of bead " "please check the section manual topology handling in the votca manual"); continue; } nbeads[(*iter)->getName()] = (*iter)->BeadCount(); } } void Topology::AddBondedInteraction(Interaction *ic) { map<string,int>::iterator iter; iter = _interaction_groups.find(ic->getGroup()); if(iter!=_interaction_groups.end()) ic->setGroupId((*iter).second); else { int i= _interaction_groups.size(); _interaction_groups[ic->getGroup()] = i; ic->setGroupId(i); } _interactions.push_back(ic); _interactions_by_group[ic->getGroup()].push_back(ic); } std::list<Interaction *> Topology::InteractionsInGroup(const string &group) { map<string, list<Interaction*> >::iterator iter; iter = _interactions_by_group.find(group); if(iter == _interactions_by_group.end()) return list<Interaction *>(); return iter->second; } BeadType *Topology::GetOrCreateBeadType(string name) { map<string, int>::iterator iter; iter = _beadtype_map.find(name); if(iter == _beadtype_map.end()) { BeadType *bt = new BeadType(this, _beadtypes.size(), name); _beadtypes.push_back(bt); _beadtype_map[name] = bt->getId(); return bt; } else { return _beadtypes[(*iter).second]; } return NULL; } vec Topology::BCShortestConnection(const vec &r_i, const vec &r_j) const { return _bc->BCShortestConnection(r_i, r_j); } vec Topology::getDist(int bead1, int bead2) const { return BCShortestConnection( getBead(bead1)->getPos(), getBead(bead2)->getPos()); } double Topology::BoxVolume() { return _bc->BoxVolume(); } void Topology::RebuildExclusions() { _exclusions.CreateExclusions(this); } BoundaryCondition::eBoxtype Topology::autoDetectBoxType(const matrix &box) { // set the box type to OpenBox in case "box" is the zero matrix, // to OrthorhombicBox in case "box" is a diagonal matrix, // or to TriclinicBox otherwise if(box.get(0,0)==0 && box.get(0,1)==0 && box.get(0,2)==0 && box.get(1,0)==0 && box.get(1,1)==0 && box.get(1,2)==0 && box.get(2,0)==0 && box.get(2,1)==0 && box.get(2,2)==0) { //cout << "box open\n"; return BoundaryCondition::typeOpen; } else if(box.get(0,1)==0 && box.get(0,2)==0 && box.get(1,0)==0 && box.get(1,2)==0 && box.get(2,0)==0 && box.get(2,1)==0) { //cout << "box orth\n"; return BoundaryCondition::typeOrthorhombic; } else { //cout << "box tric\n"; return BoundaryCondition::typeTriclinic; } return BoundaryCondition::typeOpen; } double Topology::ShortestBoxSize() { vec _box_a = getBox().getCol(0); vec _box_b = getBox().getCol(1); vec _box_c = getBox().getCol(2); // create plane normals vec _norm_a = _box_b ^ _box_c; vec _norm_b = _box_c ^ _box_a; vec _norm_c = _box_a ^ _box_b; _norm_a.normalize(); _norm_b.normalize(); _norm_c.normalize(); double la = _box_a * _norm_a; double lb = _box_b * _norm_b; double lc = _box_c * _norm_c; return min(la, min(lb, lc)); } }} <commit_msg>fix CreateMoleculesByRange for multiple molecule creates again<commit_after>/* * Copyright 2009-2011 The VOTCA Development Team (http://www.votca.org) * * 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 <votca/csg/topology.h> #include <votca/csg/interaction.h> #include <votca/tools/rangeparser.h> #include <stdexcept> namespace votca { namespace csg { Topology::~Topology() { Cleanup(); if(_bc) delete (_bc); _bc = NULL; } void Topology::Cleanup() { // cleanup beads { BeadContainer::iterator i; for(i=_beads.begin();i<_beads.end();++i) delete *i; _beads.clear(); } // cleanup molecules { MoleculeContainer::iterator i; for(i=_molecules.begin();i<_molecules.end();++i) delete *i; _molecules.clear(); } // cleanup residues { ResidueContainer::iterator i; for(i=_residues.begin();i<_residues.end();++i) delete (*i); _residues.clear(); } // cleanup interactions { InteractionContainer::iterator i; for(i=_interactions.begin();i<_interactions.end();++i) delete (*i); _interactions.clear(); } // cleanup _bc object if(_bc) delete (_bc); _bc = new OpenBox(); } /// \todo implement checking, only used in xml topology reader void Topology::CreateMoleculesByRange(string name, int first, int nbeads, int nmolecules) { Molecule *mol = CreateMolecule(name); int beadcount=0; int res_offset=0; BeadContainer::iterator bead; for(bead=_beads.begin(); bead!=_beads.end(); ++bead) { //xml numbering starts with 1 if(--first > 0) continue; //This is not 100% correct, but let's assume for now that the resnr do increase if ( beadcount == 0 ) { res_offset = (*bead)->getResnr(); } stringstream bname; bname << (*bead)->getResnr() - res_offset + 1 << ":" << getResidue((*bead)->getResnr())->getName() << ":" << (*bead)->getName(); mol->AddBead((*bead), bname.str()); if(++beadcount == nbeads) { if(--nmolecules <= 0) break; mol = CreateMolecule(name); beadcount = 0; } } } /// \todo clean up CreateMoleculesByResidue! void Topology::CreateMoleculesByResidue() { // first create a molecule for each residue ResidueContainer::iterator res; for(res=_residues.begin(); res!=_residues.end(); ++res) { CreateMolecule((*res)->getName()); } // add the beads to the corresponding molecules based on their resid BeadContainer::iterator bead; for(bead=_beads.begin(); bead!=_beads.end(); ++bead) { //MoleculeByIndex((*bead)->getResnr())->AddBead((*bead)->getId(), (*bead)->getName()); MoleculeByIndex((*bead)->getResnr())->AddBead((*bead), string("1:TRI:") + (*bead)->getName()); } /// \todo sort beads in molecules that all beads are stored in the same order. This is needed for the mapping! } void Topology::CreateOneBigMolecule(string name) { Molecule *mi = CreateMolecule(name); BeadContainer::iterator bead; for(bead=_beads.begin(); bead!=_beads.end(); ++bead) { stringstream n(""); n << (*bead)->getResnr() +1 << ":" << _residues[(*bead)->getResnr()]->getName() << ":" << (*bead)->getName(); //cout << n.str() << endl; mi->AddBead((*bead), n.str()); } } void Topology::Add(Topology *top) { BeadContainer::iterator bead; ResidueContainer::iterator res; MoleculeContainer::iterator mol; int res0=ResidueCount(); for(bead=top->_beads.begin(); bead!=top->_beads.end(); ++bead) { Bead *bi = *bead; BeadType *type = GetOrCreateBeadType(bi->getType()->getName()); CreateBead(bi->getSymmetry(), bi->getName(), type, bi->getResnr()+res0, bi->getM(), bi->getQ()); } for(res=top->_residues.begin();res!=top->_residues.end(); ++res) { CreateResidue((*res)->getName()); } // \todo beadnames in molecules!! for(mol=top->_molecules.begin();mol!=top->_molecules.end(); ++mol) { Molecule *mi = CreateMolecule((*mol)->getName()); for(int i=0; i<mi->BeadCount(); i++) { mi->AddBead(mi->getBead(i), "invalid"); } } } void Topology::CopyTopologyData(Topology *top) { BeadContainer::iterator it_bead; ResidueContainer::iterator it_res; MoleculeContainer::iterator it_mol; InteractionContainer::iterator it_ia; _bc->setBox(top->getBox()); _time = top->_time; _step = top->_step; // cleanup old data Cleanup(); // copy all residues for(it_res=top->_residues.begin();it_res!=top->_residues.end(); ++it_res) { CreateResidue((*it_res)->getName()); } // create all beads for(it_bead=top->_beads.begin(); it_bead!=top->_beads.end(); ++it_bead) { Bead *bi = *it_bead; BeadType *type = GetOrCreateBeadType(bi->getType()->getName()); Bead *bn = CreateBead(bi->getSymmetry(), bi->getName(), type, bi->getResnr(), bi->getM(), bi->getQ()); bn->setOptions(bi->Options()); } // copy all molecules for(it_mol=top->_molecules.begin();it_mol!=top->_molecules.end(); ++it_mol) { Molecule *mi = CreateMolecule((*it_mol)->getName()); for(int i=0; i<(*it_mol)->BeadCount(); i++) { int beadid = (*it_mol)->getBead(i)->getId(); mi->AddBead(_beads[beadid], (*it_mol)->getBeadName(i)); } } // TODO: copy interactions //for(it_ia=top->_interaction.begin();it_ia=top->_interactions.end();++it_ia) { //} } void Topology::RenameMolecules(string range, string name) { RangeParser rp; RangeParser::iterator i; rp.Parse(range); for(i=rp.begin();i!=rp.end();++i) { if((unsigned int)*i > _molecules.size()) throw runtime_error(string("RenameMolecules: num molecules smaller than")); getMolecule(*i-1)->setName(name); } } void Topology::RenameBeadType(string name, string newname) { BeadContainer::iterator bead; for(bead=_beads.begin(); bead!=_beads.end(); ++bead) { BeadType *type = GetOrCreateBeadType((*bead)->getType()->getName()); if (wildcmp(name.c_str(),(*bead)->getType()->getName().c_str())) { type->setName(newname); } } } void Topology::SetBeadTypeMass(string name, double value) { BeadContainer::iterator bead; for(bead=_beads.begin(); bead!=_beads.end(); ++bead) { if (wildcmp(name.c_str(),(*bead)->getType()->getName().c_str())) { (*bead)->setM(value); } } } void Topology::CheckMoleculeNaming(void) { map<string,int> nbeads; for(MoleculeContainer::iterator iter = _molecules.begin(); iter!=_molecules.end(); ++iter) { map<string,int>::iterator entry = nbeads.find((*iter)->getName()); if(entry != nbeads.end()) { if(entry->second != (*iter)->BeadCount()) throw runtime_error("There are molecules which have the same name but different number of bead " "please check the section manual topology handling in the votca manual"); continue; } nbeads[(*iter)->getName()] = (*iter)->BeadCount(); } } void Topology::AddBondedInteraction(Interaction *ic) { map<string,int>::iterator iter; iter = _interaction_groups.find(ic->getGroup()); if(iter!=_interaction_groups.end()) ic->setGroupId((*iter).second); else { int i= _interaction_groups.size(); _interaction_groups[ic->getGroup()] = i; ic->setGroupId(i); } _interactions.push_back(ic); _interactions_by_group[ic->getGroup()].push_back(ic); } std::list<Interaction *> Topology::InteractionsInGroup(const string &group) { map<string, list<Interaction*> >::iterator iter; iter = _interactions_by_group.find(group); if(iter == _interactions_by_group.end()) return list<Interaction *>(); return iter->second; } BeadType *Topology::GetOrCreateBeadType(string name) { map<string, int>::iterator iter; iter = _beadtype_map.find(name); if(iter == _beadtype_map.end()) { BeadType *bt = new BeadType(this, _beadtypes.size(), name); _beadtypes.push_back(bt); _beadtype_map[name] = bt->getId(); return bt; } else { return _beadtypes[(*iter).second]; } return NULL; } vec Topology::BCShortestConnection(const vec &r_i, const vec &r_j) const { return _bc->BCShortestConnection(r_i, r_j); } vec Topology::getDist(int bead1, int bead2) const { return BCShortestConnection( getBead(bead1)->getPos(), getBead(bead2)->getPos()); } double Topology::BoxVolume() { return _bc->BoxVolume(); } void Topology::RebuildExclusions() { _exclusions.CreateExclusions(this); } BoundaryCondition::eBoxtype Topology::autoDetectBoxType(const matrix &box) { // set the box type to OpenBox in case "box" is the zero matrix, // to OrthorhombicBox in case "box" is a diagonal matrix, // or to TriclinicBox otherwise if(box.get(0,0)==0 && box.get(0,1)==0 && box.get(0,2)==0 && box.get(1,0)==0 && box.get(1,1)==0 && box.get(1,2)==0 && box.get(2,0)==0 && box.get(2,1)==0 && box.get(2,2)==0) { //cout << "box open\n"; return BoundaryCondition::typeOpen; } else if(box.get(0,1)==0 && box.get(0,2)==0 && box.get(1,0)==0 && box.get(1,2)==0 && box.get(2,0)==0 && box.get(2,1)==0) { //cout << "box orth\n"; return BoundaryCondition::typeOrthorhombic; } else { //cout << "box tric\n"; return BoundaryCondition::typeTriclinic; } return BoundaryCondition::typeOpen; } double Topology::ShortestBoxSize() { vec _box_a = getBox().getCol(0); vec _box_b = getBox().getCol(1); vec _box_c = getBox().getCol(2); // create plane normals vec _norm_a = _box_b ^ _box_c; vec _norm_b = _box_c ^ _box_a; vec _norm_c = _box_a ^ _box_b; _norm_a.normalize(); _norm_b.normalize(); _norm_c.normalize(); double la = _box_a * _norm_a; double lb = _box_b * _norm_b; double lc = _box_c * _norm_c; return min(la, min(lb, lc)); } }} <|endoftext|>
<commit_before>/* Copyright 2016 Fixstars 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 <libsgm_wrapper.h> namespace sgm { LibSGMWrapper::LibSGMWrapper(int numDisparity, int P1, int P2, float uniquenessRatio, bool subpixel) : sgm_(nullptr), numDisparity_(numDisparity), param_(P1, P2, uniquenessRatio, subpixel), prev_(nullptr) {} LibSGMWrapper::~LibSGMWrapper() = default; int LibSGMWrapper::getNumDisparities() const { return numDisparity_; } float LibSGMWrapper::getUniquenessRatio() const { return param_.uniqueness; } int LibSGMWrapper::getP1() const { return param_.P1; } int LibSGMWrapper::getP2() const { return param_.P2; } bool LibSGMWrapper::hasSubpixel() const { return param_.subpixel; } struct LibSGMWrapper::Creator { int width; int height; int src_pitch; int dst_pitch; int input_depth_bits; sgm::EXECUTE_INOUT inout_type; bool operator==(const Creator& rhs) const { return width == rhs.width && height == rhs.height && src_pitch == rhs.src_pitch && dst_pitch == rhs.dst_pitch && input_depth_bits == rhs.input_depth_bits && inout_type == rhs.inout_type; } bool operator!=(const Creator& rhs) const { return !(*this == rhs); } StereoSGM* createStereoSGM(int disparity_size, int output_depth_bits, const StereoSGM::Parameters& param_) { return new StereoSGM(width, height, disparity_size, input_depth_bits, output_depth_bits, src_pitch, dst_pitch, inout_type, param_); } #ifdef BUILD_OPENCV_WRAPPER Creator(const cv::cuda::GpuMat& src, const cv::cuda::GpuMat& dst) { const int depth = src.depth(); CV_Assert(depth == CV_8U || depth == CV_16U); width = src.cols; height = src.rows; src_pitch = static_cast<int>(src.step1()); dst_pitch = static_cast<int>(dst.step1()); input_depth_bits = static_cast<int>(src.elemSize1()) * 8; inout_type = sgm::EXECUTE_INOUT_CUDA2CUDA; } Creator(const cv::Mat& src, const cv::Mat& dst) { const int depth = src.depth(); CV_Assert(depth == CV_8U || depth == CV_16U); width = src.cols; height = src.rows; src_pitch = static_cast<int>(src.step1()); dst_pitch = static_cast<int>(dst.step1()); input_depth_bits = static_cast<int>(src.elemSize1()) * 8; inout_type = sgm::EXECUTE_INOUT_HOST2HOST; } #endif }; #ifdef BUILD_OPENCV_WRAPPER void LibSGMWrapper::execute(const cv::cuda::GpuMat& I1, const cv::cuda::GpuMat& I2, cv::cuda::GpuMat& disparity) { const cv::Size size = I1.size(); CV_Assert(size == I2.size()); CV_Assert(I1.type() == I2.type()); const int depth = I1.depth(); CV_Assert(depth == CV_8U || depth == CV_16U); if (disparity.size() != size || disparity.depth() != CV_16U) { disparity.create(size, CV_16U); } std::unique_ptr<Creator> creator(new Creator(I1, disparity)); if (!sgm_ || !prev_ || *creator != *prev_) { sgm_.reset(creator->createStereoSGM(numDisparity_, 16, param_)); } prev_ = std::move(creator); sgm_->execute(I1.data, I2.data, disparity.data); } void LibSGMWrapper::execute(const cv::Mat& I1, const cv::Mat& I2, cv::Mat& disparity) { const cv::Size size = I1.size(); CV_Assert(size == I2.size()); CV_Assert(I1.type() == I2.type()); const int depth = I1.depth(); CV_Assert(depth == CV_8U || depth == CV_16U); if (disparity.size() != size || disparity.depth() != CV_16U) { disparity.create(size, CV_16U); } std::unique_ptr<Creator> creator(new Creator(I1, disparity)); if (!sgm_ || !prev_ || *creator != *prev_) { sgm_.reset(creator->createStereoSGM(numDisparity_, 16, param_)); } prev_ = std::move(creator); sgm_->execute(I1.data, I2.data, disparity.data); } #endif // BUILD_OPENCV_WRAPPER } <commit_msg>Add comment for preprocessor<commit_after>/* Copyright 2016 Fixstars 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 <libsgm_wrapper.h> namespace sgm { LibSGMWrapper::LibSGMWrapper(int numDisparity, int P1, int P2, float uniquenessRatio, bool subpixel) : sgm_(nullptr), numDisparity_(numDisparity), param_(P1, P2, uniquenessRatio, subpixel), prev_(nullptr) {} LibSGMWrapper::~LibSGMWrapper() = default; int LibSGMWrapper::getNumDisparities() const { return numDisparity_; } float LibSGMWrapper::getUniquenessRatio() const { return param_.uniqueness; } int LibSGMWrapper::getP1() const { return param_.P1; } int LibSGMWrapper::getP2() const { return param_.P2; } bool LibSGMWrapper::hasSubpixel() const { return param_.subpixel; } struct LibSGMWrapper::Creator { int width; int height; int src_pitch; int dst_pitch; int input_depth_bits; sgm::EXECUTE_INOUT inout_type; bool operator==(const Creator& rhs) const { return width == rhs.width && height == rhs.height && src_pitch == rhs.src_pitch && dst_pitch == rhs.dst_pitch && input_depth_bits == rhs.input_depth_bits && inout_type == rhs.inout_type; } bool operator!=(const Creator& rhs) const { return !(*this == rhs); } StereoSGM* createStereoSGM(int disparity_size, int output_depth_bits, const StereoSGM::Parameters& param_) { return new StereoSGM(width, height, disparity_size, input_depth_bits, output_depth_bits, src_pitch, dst_pitch, inout_type, param_); } #ifdef BUILD_OPENCV_WRAPPER Creator(const cv::cuda::GpuMat& src, const cv::cuda::GpuMat& dst) { const int depth = src.depth(); CV_Assert(depth == CV_8U || depth == CV_16U); width = src.cols; height = src.rows; src_pitch = static_cast<int>(src.step1()); dst_pitch = static_cast<int>(dst.step1()); input_depth_bits = static_cast<int>(src.elemSize1()) * 8; inout_type = sgm::EXECUTE_INOUT_CUDA2CUDA; } Creator(const cv::Mat& src, const cv::Mat& dst) { const int depth = src.depth(); CV_Assert(depth == CV_8U || depth == CV_16U); width = src.cols; height = src.rows; src_pitch = static_cast<int>(src.step1()); dst_pitch = static_cast<int>(dst.step1()); input_depth_bits = static_cast<int>(src.elemSize1()) * 8; inout_type = sgm::EXECUTE_INOUT_HOST2HOST; } #endif // BUILD_OPRENCV_WRAPPER }; #ifdef BUILD_OPENCV_WRAPPER void LibSGMWrapper::execute(const cv::cuda::GpuMat& I1, const cv::cuda::GpuMat& I2, cv::cuda::GpuMat& disparity) { const cv::Size size = I1.size(); CV_Assert(size == I2.size()); CV_Assert(I1.type() == I2.type()); const int depth = I1.depth(); CV_Assert(depth == CV_8U || depth == CV_16U); if (disparity.size() != size || disparity.depth() != CV_16U) { disparity.create(size, CV_16U); } std::unique_ptr<Creator> creator(new Creator(I1, disparity)); if (!sgm_ || !prev_ || *creator != *prev_) { sgm_.reset(creator->createStereoSGM(numDisparity_, 16, param_)); } prev_ = std::move(creator); sgm_->execute(I1.data, I2.data, disparity.data); } void LibSGMWrapper::execute(const cv::Mat& I1, const cv::Mat& I2, cv::Mat& disparity) { const cv::Size size = I1.size(); CV_Assert(size == I2.size()); CV_Assert(I1.type() == I2.type()); const int depth = I1.depth(); CV_Assert(depth == CV_8U || depth == CV_16U); if (disparity.size() != size || disparity.depth() != CV_16U) { disparity.create(size, CV_16U); } std::unique_ptr<Creator> creator(new Creator(I1, disparity)); if (!sgm_ || !prev_ || *creator != *prev_) { sgm_.reset(creator->createStereoSGM(numDisparity_, 16, param_)); } prev_ = std::move(creator); sgm_->execute(I1.data, I2.data, disparity.data); } #endif // BUILD_OPENCV_WRAPPER } <|endoftext|>
<commit_before>////////////////////////////////////////////////////////////////////////////////////////// // // // The MIT License (MIT) // // // // Copyright (c) 2015 Pablo Ramon Soria // // // // 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 "Svmpp.h" #include <cassert> #include <algorithm> #include <functional> namespace svmpp { //----------------------------------------------------------------------------------------------------------------- // Train struct //----------------------------------------------------------------------------------------------------------------- void TrainSet::addEntry(double * _x, unsigned _dimension, double _y) { addEntry(std::vector<double>(_x, _x+_dimension), _y); } //----------------------------------------------------------------------------------------------------------------- void TrainSet::addEntry(const std::vector<double>& _x, double _y) { mX.push_back(_x); mY.push_back(_y); } //----------------------------------------------------------------------------------------------------------------- void TrainSet::addEntries(const std::vector<std::vector<double>>& _X, const std::vector<double>& _Y){ mX.insert(mX.end(), _X.begin(), _X.end()); mY.insert(mY.end(), _Y.begin(), _Y.end()); } //----------------------------------------------------------------------------------------------------------------- std::vector<double> TrainSet::labels() const { return mY; } //----------------------------------------------------------------------------------------------------------------- TrainSet::Problem TrainSet::problem() const { Problem problem; assert(mX.size() == mY.size()); // Set size of train set. problem.l = mX.size(); // Set labels of data problem.y = new double[problem.l]; for (unsigned i = 0; i < mY.size(); i++) { problem.y[i] = mY[i]; } // Set data unsigned dims = mX[0].size(); problem.x = new svm_node*[problem.l]; for (unsigned i = 0; i < mX.size(); i++) { problem.x[i] = new svm_node[dims+1]; int filledIndex = 0; for (unsigned j = 0; j < dims; j++) { if (mX[i][j] != 0) { problem.x[i][filledIndex].index = j; problem.x[i][filledIndex].value = mX[i][j]; filledIndex++; } } problem.x[i][filledIndex].index = -1; } return problem; } //----------------------------------------------------------------------------------------------------------------- // Query struct //----------------------------------------------------------------------------------------------------------------- Query::Query(double * _x, unsigned _dimension): Query(std::vector<double>(_x, _x + _dimension)) { } //----------------------------------------------------------------------------------------------------------------- Query::Query(const std::vector<double>& _x) { unsigned dims = _x.size(); mNode = new svm_node[dims+1]; int filledIndex=0; for (unsigned i = 0; i < dims; i++) { if (_x[i] != 0) { mNode[filledIndex].index = i; mNode[filledIndex].value = _x[i]; filledIndex++; } } mNode[filledIndex].index = -1; } //----------------------------------------------------------------------------------------------------------------- Query::Node Query::node() const { return mNode; } //----------------------------------------------------------------------------------------------------------------- // Svm class //----------------------------------------------------------------------------------------------------------------- bool Svm::save(std::string _file) const { return svm_save_model(_file.c_str(), mModel) != -1; } //----------------------------------------------------------------------------------------------------------------- bool Svm::load(std::string _file) { mModel = svm_load_model(_file.c_str()); return mModel != nullptr; } //----------------------------------------------------------------------------------------------------------------- void Svm::train(const Params & _params, const TrainSet & _trainSet) { mParams = _params; mModel = svm_train(&(_trainSet.problem()), &_params); } //----------------------------------------------------------------------------------------------------------------- void Svm::trainAuto(const TrainSet & _trainSet, const Params & _initialParams, const std::vector<ParamGrid> &_paramGrids) { Params best; recursiveTrain(_trainSet, _paramGrids, _initialParams, best); train(best, _trainSet); } //----------------------------------------------------------------------------------------------------------------- double Svm::crossValidation(const Params & _params, const TrainSet & _trainSet, int _nFolds) { double *labels = new double[_trainSet.labels().size()]; svm_cross_validation(&_trainSet.problem(), &_params, _nFolds, labels); double successRate = 0; auto groundTruth = _trainSet.labels(); for (unsigned i = 0; i < groundTruth.size(); i++) { if(labels[i] == groundTruth[i]) successRate++; } return successRate/groundTruth.size(); } //----------------------------------------------------------------------------------------------------------------- double Svm::predict(const Query & _query) const { return svm_predict(mModel, _query.node()); } //----------------------------------------------------------------------------------------------------------------- double Svm::predict(const Query & _query, std::vector<double> &_probs) const { assert(hasProbabilities()); double *probs = new double[mModel->nr_class]; svm_predict_probability(mModel, _query.node(), probs); int maxIndex; double maxProb=0; for (int i = 0; i < mModel->nr_class;i++) { _probs.push_back(probs[i]); if (maxProb < probs[i]) { maxProb = probs[i]; maxIndex = i; } } return maxIndex; } //----------------------------------------------------------------------------------------------------------------- bool Svm::hasProbabilities() const { return svm_check_probability_model(mModel) == 1; } //----------------------------------------------------------------------------------------------------------------- Svm::Params Svm::params() const { return mParams; } //----------------------------------------------------------------------------------------------------------------- // Private Interface double Svm::recursiveTrain(const TrainSet &_trainSet, std::vector<ParamGrid> _grids, Params _init, Params & _best) { // Get first grid to this level loop. ParamGrid grid = _grids[0]; // Init variables Params bestParams; double bestScore = 0; // go over params of this grid for (double param = grid.min(); param < grid.max();param *= grid.step()) { // Set params of this step of the grid Params init = _init; setParam(init, grid.type(), param); Params currentParams; double score; // If it is not last grid on the list, go one step deeper if (_grids.size() != 1) { score = recursiveTrain(_trainSet, std::vector<ParamGrid>(_grids.begin()+1, _grids.end()), init, currentParams); } else { // Else, train with this parameters score = crossValidation(init, _trainSet); currentParams = init; } // Get best score and params if (score > bestScore) { bestScore = score; bestParams = currentParams; } } // Save best param on argument and return score. _best = bestParams; return bestScore; } //----------------------------------------------------------------------------------------------------------------- void Svm::setParam(Params & _params, ParamGrid::Type _type, double _value) { switch (_type) { case ParamGrid::Type::C: _params.C = _value; break; case ParamGrid::Type::Gamma: _params.gamma = _value; break; case ParamGrid::Type::Degree: _params.degree = _value; break; case ParamGrid::Type::Coeff0: _params.coef0 = _value; break; } } } // namespace svmpp <commit_msg>Small fix for linux compatibility<commit_after>////////////////////////////////////////////////////////////////////////////////////////// // // // The MIT License (MIT) // // // // Copyright (c) 2015 Pablo Ramon Soria // // // // 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 "Svmpp.h" #include <cassert> #include <algorithm> #include <functional> namespace svmpp { //----------------------------------------------------------------------------------------------------------------- // Train struct //----------------------------------------------------------------------------------------------------------------- void TrainSet::addEntry(double * _x, unsigned _dimension, double _y) { addEntry(std::vector<double>(_x, _x+_dimension), _y); } //----------------------------------------------------------------------------------------------------------------- void TrainSet::addEntry(const std::vector<double>& _x, double _y) { mX.push_back(_x); mY.push_back(_y); } //----------------------------------------------------------------------------------------------------------------- void TrainSet::addEntries(const std::vector<std::vector<double>>& _X, const std::vector<double>& _Y){ mX.insert(mX.end(), _X.begin(), _X.end()); mY.insert(mY.end(), _Y.begin(), _Y.end()); } //----------------------------------------------------------------------------------------------------------------- std::vector<double> TrainSet::labels() const { return mY; } //----------------------------------------------------------------------------------------------------------------- TrainSet::Problem TrainSet::problem() const { Problem problem; assert(mX.size() == mY.size()); // Set size of train set. problem.l = mX.size(); // Set labels of data problem.y = new double[problem.l]; for (unsigned i = 0; i < mY.size(); i++) { problem.y[i] = mY[i]; } // Set data unsigned dims = mX[0].size(); problem.x = new svm_node*[problem.l]; for (unsigned i = 0; i < mX.size(); i++) { problem.x[i] = new svm_node[dims+1]; int filledIndex = 0; for (unsigned j = 0; j < dims; j++) { if (mX[i][j] != 0) { problem.x[i][filledIndex].index = j; problem.x[i][filledIndex].value = mX[i][j]; filledIndex++; } } problem.x[i][filledIndex].index = -1; } return problem; } //----------------------------------------------------------------------------------------------------------------- // Query struct //----------------------------------------------------------------------------------------------------------------- Query::Query(double * _x, unsigned _dimension): Query(std::vector<double>(_x, _x + _dimension)) { } //----------------------------------------------------------------------------------------------------------------- Query::Query(const std::vector<double>& _x) { unsigned dims = _x.size(); mNode = new svm_node[dims+1]; int filledIndex=0; for (unsigned i = 0; i < dims; i++) { if (_x[i] != 0) { mNode[filledIndex].index = i; mNode[filledIndex].value = _x[i]; filledIndex++; } } mNode[filledIndex].index = -1; } //----------------------------------------------------------------------------------------------------------------- Query::Node Query::node() const { return mNode; } //----------------------------------------------------------------------------------------------------------------- // Svm class //----------------------------------------------------------------------------------------------------------------- bool Svm::save(std::string _file) const { return svm_save_model(_file.c_str(), mModel) != -1; } //----------------------------------------------------------------------------------------------------------------- bool Svm::load(std::string _file) { mModel = svm_load_model(_file.c_str()); return mModel != nullptr; } //----------------------------------------------------------------------------------------------------------------- void Svm::train(const Params & _params, const TrainSet & _trainSet) { mParams = _params; auto problem = _trainSet.problem(); mModel = svm_train(&problem, &_params); } //----------------------------------------------------------------------------------------------------------------- void Svm::trainAuto(const TrainSet & _trainSet, const Params & _initialParams, const std::vector<ParamGrid> &_paramGrids) { Params best; recursiveTrain(_trainSet, _paramGrids, _initialParams, best); train(best, _trainSet); } //----------------------------------------------------------------------------------------------------------------- double Svm::crossValidation(const Params & _params, const TrainSet & _trainSet, int _nFolds) { double *labels = new double[_trainSet.labels().size()]; auto problem = _trainSet.problem(); svm_cross_validation(&problem, &_params, _nFolds, labels); double successRate = 0; auto groundTruth = _trainSet.labels(); for (unsigned i = 0; i < groundTruth.size(); i++) { if(labels[i] == groundTruth[i]) successRate++; } return successRate/groundTruth.size(); } //----------------------------------------------------------------------------------------------------------------- double Svm::predict(const Query & _query) const { return svm_predict(mModel, _query.node()); } //----------------------------------------------------------------------------------------------------------------- double Svm::predict(const Query & _query, std::vector<double> &_probs) const { assert(hasProbabilities()); double *probs = new double[mModel->nr_class]; svm_predict_probability(mModel, _query.node(), probs); int maxIndex; double maxProb=0; for (int i = 0; i < mModel->nr_class;i++) { _probs.push_back(probs[i]); if (maxProb < probs[i]) { maxProb = probs[i]; maxIndex = i; } } return maxIndex; } //----------------------------------------------------------------------------------------------------------------- bool Svm::hasProbabilities() const { return svm_check_probability_model(mModel) == 1; } //----------------------------------------------------------------------------------------------------------------- Svm::Params Svm::params() const { return mParams; } //----------------------------------------------------------------------------------------------------------------- // Private Interface double Svm::recursiveTrain(const TrainSet &_trainSet, std::vector<ParamGrid> _grids, Params _init, Params & _best) { // Get first grid to this level loop. ParamGrid grid = _grids[0]; // Init variables Params bestParams; double bestScore = 0; // go over params of this grid for (double param = grid.min(); param < grid.max();param *= grid.step()) { // Set params of this step of the grid Params init = _init; setParam(init, grid.type(), param); Params currentParams; double score; // If it is not last grid on the list, go one step deeper if (_grids.size() != 1) { score = recursiveTrain(_trainSet, std::vector<ParamGrid>(_grids.begin()+1, _grids.end()), init, currentParams); } else { // Else, train with this parameters score = crossValidation(init, _trainSet); currentParams = init; } // Get best score and params if (score > bestScore) { bestScore = score; bestParams = currentParams; } } // Save best param on argument and return score. _best = bestParams; return bestScore; } //----------------------------------------------------------------------------------------------------------------- void Svm::setParam(Params & _params, ParamGrid::Type _type, double _value) { switch (_type) { case ParamGrid::Type::C: _params.C = _value; break; case ParamGrid::Type::Gamma: _params.gamma = _value; break; case ParamGrid::Type::Degree: _params.degree = _value; break; case ParamGrid::Type::Coeff0: _params.coef0 = _value; break; } } } // namespace svmpp <|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2015 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #ifdef HAVE_LIBXML2 // mapnik #include <mapnik/xml_loader.hpp> #include <mapnik/xml_node.hpp> #include <mapnik/config_error.hpp> #include <mapnik/util/trim.hpp> #include <mapnik/util/noncopyable.hpp> #include <mapnik/util/fs.hpp> // libxml #include <libxml/parser.h> #include <libxml/tree.h> #include <libxml/parserInternals.h> #include <libxml/xinclude.h> // libxslt #include <libxslt/xslt.h> #include <libxslt/xsltInternals.h> #include <libxslt/transform.h> #include <libxslt/xsltutils.h> #include <libexslt/exslt.h> // stl #include <stdexcept> #include <iostream> #define DEFAULT_OPTIONS (XML_PARSE_NOENT | XML_PARSE_NOBLANKS | XML_PARSE_DTDLOAD | XML_PARSE_NOCDATA) #define isnbsp(s) ((s)[0] == '\xC2' && (s)[1] == '\xA0') namespace mapnik { class libxml2_loader : util::noncopyable { public: libxml2_loader(const char *encoding = nullptr, int options = DEFAULT_OPTIONS, const char *url = nullptr) : ctx_(0), encoding_(encoding), options_(options), url_(url) { LIBXML_TEST_VERSION; ctx_ = xmlNewParserCtxt(); if (!ctx_) { throw std::runtime_error("Failed to create parser context."); } exsltRegisterAll(); } ~libxml2_loader() { if (ctx_) { xmlFreeParserCtxt(ctx_); } } void load(std::string const& filename, xml_node &node) { if (!mapnik::util::exists(filename)) { throw config_error(std::string("Could not load map file: File does not exist"), 0, filename); } xmlDocPtr doc = xmlCtxtReadFile(ctx_, filename.c_str(), encoding_, options_); if (!doc) { xmlError * error = xmlCtxtGetLastError(ctx_); if (error) { std::string msg("XML document not well formed:\n"); msg += error->message; // remove CR msg = msg.substr(0, msg.size() - 1); throw config_error(msg, error->line, error->file); } } xmlDocPtr res = preprocess(doc); if (res) { xmlFreeDoc(doc); doc = res; } load(doc, node); } void load(const int fd, xml_node &node) { xmlDocPtr doc = xmlCtxtReadFd(ctx_, fd, url_, encoding_, options_); xmlDocPtr res = preprocess(doc); if (res) { xmlFreeDoc(doc); doc = res; } load(doc, node); } void load_string(std::string const& buffer, xml_node &node, std::string const & base_path) { if (!base_path.empty()) { if (!mapnik::util::exists(base_path)) { throw config_error(std::string("Could not locate base_path '") + base_path + "': file or directory does not exist"); } } // NOTE: base_path here helps libxml2 resolve entities correctly: https://github.com/mapnik/mapnik/issues/440 xmlDocPtr doc = xmlCtxtReadMemory(ctx_, buffer.data(), buffer.length(), base_path.c_str(), encoding_, options_); xmlDocPtr res = preprocess(doc); if (res) { xmlFreeDoc(doc); doc = res; } load(doc, node); } xmlDocPtr preprocess(xmlDocPtr doc) { xsltStylesheetPtr style = xsltLoadStylesheetPI(doc); if (style) { xsltTransformContextPtr transform_ctx = xsltNewTransformContext(style, doc); if (transform_ctx) { xsltSetCtxtParseOptions(transform_ctx, options_); xmlDocPtr res = xsltApplyStylesheetUser(style, doc, NULL, NULL, NULL, transform_ctx); xsltFreeTransformContext(transform_ctx); xsltFreeStylesheet(style); return res; } xsltFreeStylesheet(style); } return NULL; } void load(const xmlDocPtr doc, xml_node &node) { if (!doc) { std::string msg("XML document not well formed"); xmlError * error = xmlCtxtGetLastError( ctx_ ); if (error) { msg += ":\n"; msg += error->message; throw config_error(msg, error->line, error->file); } else { throw config_error(msg); } } int iXIncludeReturn = xmlXIncludeProcessFlags(doc, options_); if (iXIncludeReturn < 0) { xmlFreeDoc(doc); throw config_error("XML XInclude error. One or more files failed to load."); } xmlNode * root = xmlDocGetRootElement(doc); if (!root) { xmlFreeDoc(doc); throw config_error("XML document is empty."); } populate_tree(root, node); xmlFreeDoc(doc); } private: void inline append_attributes(xmlAttr *attributes, xml_node & node) { for (; attributes; attributes = attributes->next ) { node.add_attribute(reinterpret_cast<const char *>(attributes->name), reinterpret_cast<const char *>(attributes->children->content)); } } void inline populate_tree(xmlNode *cur_node, xml_node &node) { for (; cur_node; cur_node = cur_node->next ) { switch (cur_node->type) { case XML_ELEMENT_NODE: { xml_node &new_node = node.add_child(reinterpret_cast<const char *>(cur_node->name), cur_node->line, false); append_attributes(cur_node->properties, new_node); populate_tree(cur_node->children, new_node); } break; case XML_TEXT_NODE: { std::string trimmed(reinterpret_cast<const char *>(cur_node->content)); mapnik::util::trim(trimmed); if (trimmed.empty()) break; //Don't add empty text nodes node.add_child(trimmed.c_str(), cur_node->line, true); } break; case XML_COMMENT_NODE: break; default: break; } } } xmlParserCtxtPtr ctx_; const char *encoding_; int options_; const char *url_; }; void read_xml(std::string const & filename, xml_node &node) { libxml2_loader loader; loader.load(filename, node); } void read_xml_string(std::string const & str, xml_node &node, std::string const & base_path) { libxml2_loader loader; loader.load_string(str, node, base_path); } } // end of namespace mapnik #endif <commit_msg>libxml2 parser: improved error handling<commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2015 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #ifdef HAVE_LIBXML2 // mapnik #include <mapnik/xml_loader.hpp> #include <mapnik/xml_node.hpp> #include <mapnik/config_error.hpp> #include <mapnik/util/trim.hpp> #include <mapnik/util/noncopyable.hpp> #include <mapnik/util/fs.hpp> // libxml #include <libxml/parser.h> #include <libxml/tree.h> #include <libxml/parserInternals.h> #include <libxml/xinclude.h> // libxslt #include <libxslt/xslt.h> #include <libxslt/xsltInternals.h> #include <libxslt/transform.h> #include <libxslt/xsltutils.h> #include <libexslt/exslt.h> // stl #include <stdexcept> #include <iostream> #define DEFAULT_OPTIONS (XML_PARSE_NOENT | XML_PARSE_NOBLANKS | XML_PARSE_DTDLOAD | XML_PARSE_NOCDATA) #define isnbsp(s) ((s)[0] == '\xC2' && (s)[1] == '\xA0') namespace mapnik { class libxml2_loader : util::noncopyable { struct xml_error : public config_error { xml_error(xmlError const & error) : config_error(formatMessage(error), error.line, error.file) { } std::string formatMessage(xmlError const & error) const { std::string msg("XML document not well formed: "); msg += error.message; // remove CR msg = msg.substr(0, msg.size() - 1); return msg; } }; public: libxml2_loader(const char *encoding = nullptr, int options = DEFAULT_OPTIONS, const char *url = nullptr) : ctx_(0), encoding_(encoding), options_(options), url_(url) { LIBXML_TEST_VERSION; ctx_ = xmlNewParserCtxt(); if (!ctx_) { throw std::runtime_error("Failed to create parser context."); } exsltRegisterAll(); } ~libxml2_loader() { if (ctx_) { xmlFreeParserCtxt(ctx_); } } void load(std::string const& filename, xml_node &node) { if (!mapnik::util::exists(filename)) { throw config_error(std::string("Could not load map file: File does not exist"), 0, filename); } xmlDocPtr doc = xmlCtxtReadFile(ctx_, filename.c_str(), encoding_, options_); load(doc, node); } void load(const int fd, xml_node &node) { xmlDocPtr doc = xmlCtxtReadFd(ctx_, fd, url_, encoding_, options_); load(doc, node); } void load_string(std::string const& buffer, xml_node &node, std::string const & base_path) { if (!base_path.empty()) { if (!mapnik::util::exists(base_path)) { throw config_error(std::string("Could not locate base_path '") + base_path + "': file or directory does not exist"); } } // NOTE: base_path here helps libxml2 resolve entities correctly: https://github.com/mapnik/mapnik/issues/440 xmlDocPtr doc = xmlCtxtReadMemory(ctx_, buffer.data(), buffer.length(), base_path.c_str(), encoding_, options_); load(doc, node); } xmlDocPtr preprocess(xmlDocPtr doc) { xsltStylesheetPtr style = xsltLoadStylesheetPI(doc); if (style) { xsltTransformContextPtr transform_ctx = xsltNewTransformContext(style, doc); if (transform_ctx) { xsltSetCtxtParseOptions(transform_ctx, options_); xmlDocPtr res = xsltApplyStylesheetUser(style, doc, NULL, NULL, NULL, transform_ctx); xsltFreeTransformContext(transform_ctx); xsltFreeStylesheet(style); return res; } xsltFreeStylesheet(style); } return NULL; } private: void load(xmlDocPtr doc, xml_node &node) { check_error(doc); xmlDocPtr res = preprocess(doc); if (res) { xmlFreeDoc(doc); doc = res; } check_error(doc); int iXIncludeReturn = xmlXIncludeProcessFlags(doc, options_); if (iXIncludeReturn < 0) { xmlFreeDoc(doc); throw config_error("XML XInclude error. One or more files failed to load."); } xmlNode * root = xmlDocGetRootElement(doc); if (!root) { xmlFreeDoc(doc); throw config_error("XML document is empty."); } populate_tree(root, node); xmlFreeDoc(doc); } void inline append_attributes(xmlAttr *attributes, xml_node & node) { for (; attributes; attributes = attributes->next ) { node.add_attribute(reinterpret_cast<const char *>(attributes->name), reinterpret_cast<const char *>(attributes->children->content)); } } void inline populate_tree(xmlNode *cur_node, xml_node &node) { for (; cur_node; cur_node = cur_node->next ) { switch (cur_node->type) { case XML_ELEMENT_NODE: { xml_node &new_node = node.add_child(reinterpret_cast<const char *>(cur_node->name), cur_node->line, false); append_attributes(cur_node->properties, new_node); populate_tree(cur_node->children, new_node); } break; case XML_TEXT_NODE: { std::string trimmed(reinterpret_cast<const char *>(cur_node->content)); mapnik::util::trim(trimmed); if (trimmed.empty()) break; //Don't add empty text nodes node.add_child(trimmed.c_str(), cur_node->line, true); } break; case XML_COMMENT_NODE: break; default: break; } } } void check_error(xmlDocPtr const & doc) const { if (!doc) { if (xmlError * error = xmlCtxtGetLastError(ctx_)) { throw xml_error(*error); } else { throw config_error("XML document not well formed"); } } } xmlParserCtxtPtr ctx_; const char *encoding_; int options_; const char *url_; }; void read_xml(std::string const & filename, xml_node &node) { libxml2_loader loader; loader.load(filename, node); } void read_xml_string(std::string const & str, xml_node &node, std::string const & base_path) { libxml2_loader loader; loader.load_string(str, node, base_path); } } // end of namespace mapnik #endif <|endoftext|>
<commit_before>/* * Copyright 2009-2018 The VOTCA Development Team * (http://www.votca.org) * * 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 "votca/xtp/basisset.h" #include <votca/tools/property.h> namespace votca { namespace xtp { int FindLmax(const std::string& _type ){ int _lmax; // single type shells if ( _type.length() == 1 ){ if ( _type == "S" ){ _lmax = 0;} else if ( _type == "P" ){ _lmax = 1;} else if ( _type == "D" ){ _lmax = 2;} else if ( _type == "F" ){ _lmax = 3;} else if ( _type == "G" ){ _lmax = 4;} else if ( _type == "H" ){ _lmax = 5;} else if ( _type == "I" ){ _lmax = 6;} else{ throw std::runtime_error("FindLmax: Shelltype not known"); } } else { _lmax = -1; for(unsigned i = 0; i < _type.length(); ++i) { std::string local_shell = std::string( _type, i, 1 ); int _test = FindLmax( local_shell ); if ( _test > _lmax ) { _lmax = _test;} } } return _lmax; } int FindLmin(const std::string& _type ){ int _lmin; // single type shells if ( _type.length() == 1 ){ if ( _type == "S" ){ _lmin = 0;} else if ( _type == "P" ){ _lmin = 1;} else if ( _type == "D" ){ _lmin = 2;} else if ( _type == "F" ){ _lmin = 3;} else if ( _type == "G" ){ _lmin = 4;} else if ( _type == "H" ){ _lmin = 5;} else if ( _type == "I" ){ _lmin = 6;} else{ throw std::runtime_error("FindLmax: Shelltype not known"); } } else { _lmin = 10; for(unsigned i = 0; i < _type.length(); ++i) { std::string local_shell = std::string( _type, i, 1 ); int _test = FindLmin( local_shell ); if(_test==0){return 0;} if ( _test < _lmin ) { _lmin = _test;} } } return _lmin; } int OffsetFuncShell(const std::string& shell_type ) { int _nbf; // single type shells if ( shell_type.length() == 1 ){ if ( shell_type == "S" ){ _nbf = 0;} else if ( shell_type == "P" ){ _nbf = 1;} else if ( shell_type == "D" ){ _nbf = 4;} else if ( shell_type == "F" ){ _nbf = 9;} else if ( shell_type == "G" ){ _nbf = 16;} else if ( shell_type == "H" ){ _nbf = 25;} else if ( shell_type == "I" ){ _nbf = 36;} else{ throw std::runtime_error("OffsetFuncShell: Shelltype not known"); } } else { // for combined shells, go over all contributions and find minimal offset _nbf = 1000; for(unsigned i = 0; i < shell_type.length(); ++i) { std::string local_shell = std::string( shell_type, i, 1 ); int _test = OffsetFuncShell( local_shell ); if ( _test < _nbf ) { _nbf = _test;} } } return _nbf; } int NumFuncShell( const std::string& shell_type) { int _nbf = 0; // single type shells if ( shell_type.length() == 1 ){ if ( shell_type == "S" ){ _nbf = 1;} else if ( shell_type == "P" ){ _nbf = 3;} else if ( shell_type == "D" ){ _nbf = 5;} else if ( shell_type == "F" ){ _nbf = 7;} else if ( shell_type == "G" ){ _nbf = 9;} else if ( shell_type == "H" ){ _nbf = 11;} else if ( shell_type == "I" ){ _nbf = 13;} else{ throw std::runtime_error("FindnumofFunc: Shelltype not known"); } } else { // for combined shells, go over all contributions and add functions _nbf = 0; for (unsigned i = 0; i < shell_type.length(); ++i) { std::string local_shell = std::string(shell_type, i, 1); _nbf += NumFuncShell(local_shell); } } return _nbf; } std::vector<int> NumFuncSubShell(const std::string& shell_type) { std::vector <int> subshells; // single type shells if ( shell_type.length() == 1 ){ subshells.push_back( NumFuncShell(shell_type)); // for combined shells, go over all contributions and add functions }else{ for (unsigned i = 0; i < shell_type.length(); ++i) { std::string local_shell = std::string(shell_type, i, 1); subshells.push_back( NumFuncShell(local_shell)); } } return subshells; } int NumFuncShell_cartesian(const std::string& shell_type ) { int _nbf; // single type shells defined here if ( shell_type.length() == 1 ){ if ( shell_type == "S" ){ _nbf = 1;} else if ( shell_type == "P" ){ _nbf = 3;} else if ( shell_type == "D" ){ _nbf = 6;} else if ( shell_type == "F" ){ _nbf = 10;} else if ( shell_type == "G" ){ _nbf = 15;} else if ( shell_type == "H" ){ _nbf = 21;} else if ( shell_type == "I" ){ _nbf = 28;} else { throw std::runtime_error("NumFuncShell_cartesian shell_type not known"); } } else { // for combined shells, sum over all contributions _nbf = 0; for( unsigned i = 0; i < shell_type.length(); ++i) { std::string local_shell = std::string( shell_type, i, 1 ); _nbf += NumFuncShell_cartesian( local_shell ); } } return _nbf; } int OffsetFuncShell_cartesian(const std::string& shell_type ) { int _nbf; // single type shells if ( shell_type.length() == 1 ){ if ( shell_type == "S" ){ _nbf = 0;} else if ( shell_type == "P" ){ _nbf = 1;} else if ( shell_type == "D" ){ _nbf = 4;} else if ( shell_type == "F" ){ _nbf = 10;} else if ( shell_type == "G" ){ _nbf = 20;} else if ( shell_type == "H" ){ _nbf = 35;} else if ( shell_type == "I" ){ _nbf = 56;} else { throw std::runtime_error("OffsetFuncShell_cartesian shell_type not known"); } } else { // for combined shells, go over all contributions and find minimal offset _nbf = 1000; for(unsigned i = 0; i < shell_type.length(); ++i) { std::string local_shell = std::string( shell_type, i, 1 ); int _test = OffsetFuncShell_cartesian( local_shell ); if ( _test < _nbf ) { _nbf = _test;} } } return _nbf; } void BasisSet::LoadBasisSet ( std::string name ) { tools::Property basis_property; _name=name; // if name contains .xml, assume a basisset .xml file is located in the working directory std::size_t found_xml = name.find(".xml"); std::string xmlFile; if (found_xml!=std::string::npos) { xmlFile = name; } else { // get the path to the shared folders with xml files char *votca_share = getenv("VOTCASHARE"); if(votca_share == NULL) throw std::runtime_error("VOTCASHARE not set, cannot open help files."); xmlFile = std::string(getenv("VOTCASHARE")) + std::string("/xtp/basis_sets/") + name + std::string(".xml"); } bool success = load_property_from_xml(basis_property, xmlFile); if ( !success ) {; } std::list<tools::Property*> elementProps = basis_property.Select("basis.element"); for (std::list<tools::Property*> ::iterator ite = elementProps.begin(); ite != elementProps.end(); ++ite) { std::string elementName = (*ite)->getAttribute<std::string>("name"); Element *element = addElement( elementName ); std::list<tools::Property*> shellProps = (*ite)->Select("shell"); for (std::list<tools::Property*> ::iterator its = shellProps.begin(); its != shellProps.end(); ++its) { std::string shellType = (*its)->getAttribute<std::string>("type"); double shellScale = (*its)->getAttribute<double>("scale"); Shell* shell = element->addShell( shellType, shellScale ); std::list<tools::Property*> constProps = (*its)->Select("constant"); for (std::list<tools::Property*> ::iterator itc = constProps.begin(); itc != constProps.end(); ++itc) { double decay = (*itc)->getAttribute<double>("decay"); std::vector<double> contraction=std::vector<double>(shell->getLmax()+1,0.0); std::list<tools::Property*> contrProps = (*itc)->Select("contractions"); for (std::list<tools::Property*> ::iterator itcont = contrProps.begin(); itcont != contrProps.end(); ++itcont){ std::string contrType = (*itcont)->getAttribute<std::string>("type"); double contrFactor = (*itcont)->getAttribute<double>("factor"); if ( contrType == "S" ) contraction[0] = contrFactor; else if ( contrType == "P" ) contraction[1] = contrFactor; else if ( contrType == "D" ) contraction[2] = contrFactor; else if ( contrType == "F" ) contraction[3] = contrFactor; else if ( contrType == "G" ) contraction[4] = contrFactor; else if ( contrType == "H" ) contraction[5] = contrFactor; else if ( contrType == "I" ) contraction[6] = contrFactor; else{ throw std::runtime_error("LoadBasiset:Contractiontype not known"); } } shell->addGaussian(decay, contraction); } } } return; } void BasisSet::LoadPseudopotentialSet ( std::string name ) { tools::Property basis_property; _name=name; // if name contains .xml, assume a ecp .xml file is located in the working directory std::size_t found_xml = name.find(".xml"); std::string xmlFile; if (found_xml!=std::string::npos) { xmlFile = name; } else { // get the path to the shared folders with xml files char *votca_share = getenv("VOTCASHARE"); if(votca_share == NULL) throw std::runtime_error("VOTCASHARE not set, cannot open help files."); xmlFile = std::string(getenv("VOTCASHARE")) + std::string("/xtp/ecps/") + name + std::string(".xml"); } bool success = load_property_from_xml(basis_property, xmlFile); if ( !success ) {; } std::list<tools::Property*> elementProps = basis_property.Select("pseudopotential.element"); for (std::list<tools::Property*> ::iterator ite = elementProps.begin(); ite != elementProps.end(); ++ite) { std::string elementName = (*ite)->getAttribute<std::string>("name"); int lmax = (*ite)->getAttribute<int>("lmax"); int ncore = (*ite)->getAttribute<int>("ncore"); Element *element = addElement( elementName, lmax, ncore ); std::list<tools::Property*> shellProps = (*ite)->Select("shell"); for (std::list<tools::Property*> ::iterator its = shellProps.begin(); its != shellProps.end(); ++its) { std::string shellType = (*its)->getAttribute<std::string>("type"); double shellScale = 1.0; Shell* shell = element->addShell( shellType, shellScale ); std::list<tools::Property*> constProps = (*its)->Select("constant"); for (std::list<tools::Property*> ::iterator itc = constProps.begin(); itc != constProps.end(); ++itc) { int power = (*itc)->getAttribute<int>("power"); double decay = (*itc)->getAttribute<double>("decay"); std::vector<double> contraction; contraction.push_back((*itc)->getAttribute<double>("contraction")); shell->addGaussian(power, decay, contraction); } } } return; } // adding an Element to a Basis Set Element* BasisSet::addElement( std::string elementType ) { Element *element = new Element( elementType ); _elements[elementType] = element; return element; }; // adding an Element to a Pseudopotential Library Element* BasisSet::addElement( std::string elementType, int lmax, int ncore ) { Element *element = new Element( elementType, lmax, ncore ); _elements[elementType] = element; return element; }; // cleanup the basis set BasisSet::~BasisSet() { for ( std::map< std::string,Element* >::iterator it = _elements.begin(); it != _elements.end(); it++ ) { delete (*it).second; } _elements.clear(); }; std::ostream &operator<<(std::ostream &out, const Shell& shell) { out <<"Type:"<<shell.getType() <<" Scale:"<<shell.getScale() << " Func: "<<shell.getnumofFunc()<<"\n"; for (const auto& gaussian:shell._gaussians){ out<<" Gaussian Decay: "<<gaussian->_decay; out<<" Contractions:"; for (const double& contraction:gaussian->_contraction){ out<<" "<<contraction; } out<<"\n"; } } GaussianPrimitive* Shell::addGaussian( double decay, std::vector<double> contraction ){ GaussianPrimitive* gaussian = new GaussianPrimitive(decay, contraction); _gaussians.push_back( gaussian ); return gaussian; } // adds a Gaussian of a pseudopotential GaussianPrimitive* Shell::addGaussian( int power, double decay, std::vector<double> contraction ){ GaussianPrimitive* gaussian = new GaussianPrimitive(power, decay, contraction); _gaussians.push_back( gaussian ); return gaussian; } }} <commit_msg>fixed return type<commit_after>/* * Copyright 2009-2018 The VOTCA Development Team * (http://www.votca.org) * * 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 "votca/xtp/basisset.h" #include <votca/tools/property.h> namespace votca { namespace xtp { int FindLmax(const std::string& _type ){ int _lmax; // single type shells if ( _type.length() == 1 ){ if ( _type == "S" ){ _lmax = 0;} else if ( _type == "P" ){ _lmax = 1;} else if ( _type == "D" ){ _lmax = 2;} else if ( _type == "F" ){ _lmax = 3;} else if ( _type == "G" ){ _lmax = 4;} else if ( _type == "H" ){ _lmax = 5;} else if ( _type == "I" ){ _lmax = 6;} else{ throw std::runtime_error("FindLmax: Shelltype not known"); } } else { _lmax = -1; for(unsigned i = 0; i < _type.length(); ++i) { std::string local_shell = std::string( _type, i, 1 ); int _test = FindLmax( local_shell ); if ( _test > _lmax ) { _lmax = _test;} } } return _lmax; } int FindLmin(const std::string& _type ){ int _lmin; // single type shells if ( _type.length() == 1 ){ if ( _type == "S" ){ _lmin = 0;} else if ( _type == "P" ){ _lmin = 1;} else if ( _type == "D" ){ _lmin = 2;} else if ( _type == "F" ){ _lmin = 3;} else if ( _type == "G" ){ _lmin = 4;} else if ( _type == "H" ){ _lmin = 5;} else if ( _type == "I" ){ _lmin = 6;} else{ throw std::runtime_error("FindLmax: Shelltype not known"); } } else { _lmin = 10; for(unsigned i = 0; i < _type.length(); ++i) { std::string local_shell = std::string( _type, i, 1 ); int _test = FindLmin( local_shell ); if(_test==0){return 0;} if ( _test < _lmin ) { _lmin = _test;} } } return _lmin; } int OffsetFuncShell(const std::string& shell_type ) { int _nbf; // single type shells if ( shell_type.length() == 1 ){ if ( shell_type == "S" ){ _nbf = 0;} else if ( shell_type == "P" ){ _nbf = 1;} else if ( shell_type == "D" ){ _nbf = 4;} else if ( shell_type == "F" ){ _nbf = 9;} else if ( shell_type == "G" ){ _nbf = 16;} else if ( shell_type == "H" ){ _nbf = 25;} else if ( shell_type == "I" ){ _nbf = 36;} else{ throw std::runtime_error("OffsetFuncShell: Shelltype not known"); } } else { // for combined shells, go over all contributions and find minimal offset _nbf = 1000; for(unsigned i = 0; i < shell_type.length(); ++i) { std::string local_shell = std::string( shell_type, i, 1 ); int _test = OffsetFuncShell( local_shell ); if ( _test < _nbf ) { _nbf = _test;} } } return _nbf; } int NumFuncShell( const std::string& shell_type) { int _nbf = 0; // single type shells if ( shell_type.length() == 1 ){ if ( shell_type == "S" ){ _nbf = 1;} else if ( shell_type == "P" ){ _nbf = 3;} else if ( shell_type == "D" ){ _nbf = 5;} else if ( shell_type == "F" ){ _nbf = 7;} else if ( shell_type == "G" ){ _nbf = 9;} else if ( shell_type == "H" ){ _nbf = 11;} else if ( shell_type == "I" ){ _nbf = 13;} else{ throw std::runtime_error("FindnumofFunc: Shelltype not known"); } } else { // for combined shells, go over all contributions and add functions _nbf = 0; for (unsigned i = 0; i < shell_type.length(); ++i) { std::string local_shell = std::string(shell_type, i, 1); _nbf += NumFuncShell(local_shell); } } return _nbf; } std::vector<int> NumFuncSubShell(const std::string& shell_type) { std::vector <int> subshells; // single type shells if ( shell_type.length() == 1 ){ subshells.push_back( NumFuncShell(shell_type)); // for combined shells, go over all contributions and add functions }else{ for (unsigned i = 0; i < shell_type.length(); ++i) { std::string local_shell = std::string(shell_type, i, 1); subshells.push_back( NumFuncShell(local_shell)); } } return subshells; } int NumFuncShell_cartesian(const std::string& shell_type ) { int _nbf; // single type shells defined here if ( shell_type.length() == 1 ){ if ( shell_type == "S" ){ _nbf = 1;} else if ( shell_type == "P" ){ _nbf = 3;} else if ( shell_type == "D" ){ _nbf = 6;} else if ( shell_type == "F" ){ _nbf = 10;} else if ( shell_type == "G" ){ _nbf = 15;} else if ( shell_type == "H" ){ _nbf = 21;} else if ( shell_type == "I" ){ _nbf = 28;} else { throw std::runtime_error("NumFuncShell_cartesian shell_type not known"); } } else { // for combined shells, sum over all contributions _nbf = 0; for( unsigned i = 0; i < shell_type.length(); ++i) { std::string local_shell = std::string( shell_type, i, 1 ); _nbf += NumFuncShell_cartesian( local_shell ); } } return _nbf; } int OffsetFuncShell_cartesian(const std::string& shell_type ) { int _nbf; // single type shells if ( shell_type.length() == 1 ){ if ( shell_type == "S" ){ _nbf = 0;} else if ( shell_type == "P" ){ _nbf = 1;} else if ( shell_type == "D" ){ _nbf = 4;} else if ( shell_type == "F" ){ _nbf = 10;} else if ( shell_type == "G" ){ _nbf = 20;} else if ( shell_type == "H" ){ _nbf = 35;} else if ( shell_type == "I" ){ _nbf = 56;} else { throw std::runtime_error("OffsetFuncShell_cartesian shell_type not known"); } } else { // for combined shells, go over all contributions and find minimal offset _nbf = 1000; for(unsigned i = 0; i < shell_type.length(); ++i) { std::string local_shell = std::string( shell_type, i, 1 ); int _test = OffsetFuncShell_cartesian( local_shell ); if ( _test < _nbf ) { _nbf = _test;} } } return _nbf; } void BasisSet::LoadBasisSet ( std::string name ) { tools::Property basis_property; _name=name; // if name contains .xml, assume a basisset .xml file is located in the working directory std::size_t found_xml = name.find(".xml"); std::string xmlFile; if (found_xml!=std::string::npos) { xmlFile = name; } else { // get the path to the shared folders with xml files char *votca_share = getenv("VOTCASHARE"); if(votca_share == NULL) throw std::runtime_error("VOTCASHARE not set, cannot open help files."); xmlFile = std::string(getenv("VOTCASHARE")) + std::string("/xtp/basis_sets/") + name + std::string(".xml"); } bool success = load_property_from_xml(basis_property, xmlFile); if ( !success ) {; } std::list<tools::Property*> elementProps = basis_property.Select("basis.element"); for (std::list<tools::Property*> ::iterator ite = elementProps.begin(); ite != elementProps.end(); ++ite) { std::string elementName = (*ite)->getAttribute<std::string>("name"); Element *element = addElement( elementName ); std::list<tools::Property*> shellProps = (*ite)->Select("shell"); for (std::list<tools::Property*> ::iterator its = shellProps.begin(); its != shellProps.end(); ++its) { std::string shellType = (*its)->getAttribute<std::string>("type"); double shellScale = (*its)->getAttribute<double>("scale"); Shell* shell = element->addShell( shellType, shellScale ); std::list<tools::Property*> constProps = (*its)->Select("constant"); for (std::list<tools::Property*> ::iterator itc = constProps.begin(); itc != constProps.end(); ++itc) { double decay = (*itc)->getAttribute<double>("decay"); std::vector<double> contraction=std::vector<double>(shell->getLmax()+1,0.0); std::list<tools::Property*> contrProps = (*itc)->Select("contractions"); for (std::list<tools::Property*> ::iterator itcont = contrProps.begin(); itcont != contrProps.end(); ++itcont){ std::string contrType = (*itcont)->getAttribute<std::string>("type"); double contrFactor = (*itcont)->getAttribute<double>("factor"); if ( contrType == "S" ) contraction[0] = contrFactor; else if ( contrType == "P" ) contraction[1] = contrFactor; else if ( contrType == "D" ) contraction[2] = contrFactor; else if ( contrType == "F" ) contraction[3] = contrFactor; else if ( contrType == "G" ) contraction[4] = contrFactor; else if ( contrType == "H" ) contraction[5] = contrFactor; else if ( contrType == "I" ) contraction[6] = contrFactor; else{ throw std::runtime_error("LoadBasiset:Contractiontype not known"); } } shell->addGaussian(decay, contraction); } } } return; } void BasisSet::LoadPseudopotentialSet ( std::string name ) { tools::Property basis_property; _name=name; // if name contains .xml, assume a ecp .xml file is located in the working directory std::size_t found_xml = name.find(".xml"); std::string xmlFile; if (found_xml!=std::string::npos) { xmlFile = name; } else { // get the path to the shared folders with xml files char *votca_share = getenv("VOTCASHARE"); if(votca_share == NULL) throw std::runtime_error("VOTCASHARE not set, cannot open help files."); xmlFile = std::string(getenv("VOTCASHARE")) + std::string("/xtp/ecps/") + name + std::string(".xml"); } bool success = load_property_from_xml(basis_property, xmlFile); if ( !success ) {; } std::list<tools::Property*> elementProps = basis_property.Select("pseudopotential.element"); for (std::list<tools::Property*> ::iterator ite = elementProps.begin(); ite != elementProps.end(); ++ite) { std::string elementName = (*ite)->getAttribute<std::string>("name"); int lmax = (*ite)->getAttribute<int>("lmax"); int ncore = (*ite)->getAttribute<int>("ncore"); Element *element = addElement( elementName, lmax, ncore ); std::list<tools::Property*> shellProps = (*ite)->Select("shell"); for (std::list<tools::Property*> ::iterator its = shellProps.begin(); its != shellProps.end(); ++its) { std::string shellType = (*its)->getAttribute<std::string>("type"); double shellScale = 1.0; Shell* shell = element->addShell( shellType, shellScale ); std::list<tools::Property*> constProps = (*its)->Select("constant"); for (std::list<tools::Property*> ::iterator itc = constProps.begin(); itc != constProps.end(); ++itc) { int power = (*itc)->getAttribute<int>("power"); double decay = (*itc)->getAttribute<double>("decay"); std::vector<double> contraction; contraction.push_back((*itc)->getAttribute<double>("contraction")); shell->addGaussian(power, decay, contraction); } } } return; } // adding an Element to a Basis Set Element* BasisSet::addElement( std::string elementType ) { Element *element = new Element( elementType ); _elements[elementType] = element; return element; }; // adding an Element to a Pseudopotential Library Element* BasisSet::addElement( std::string elementType, int lmax, int ncore ) { Element *element = new Element( elementType, lmax, ncore ); _elements[elementType] = element; return element; }; // cleanup the basis set BasisSet::~BasisSet() { for ( std::map< std::string,Element* >::iterator it = _elements.begin(); it != _elements.end(); it++ ) { delete (*it).second; } _elements.clear(); }; std::ostream &operator<<(std::ostream &out, const Shell& shell) { out <<"Type:"<<shell.getType() <<" Scale:"<<shell.getScale() << " Func: "<<shell.getnumofFunc()<<"\n"; for (const auto& gaussian:shell._gaussians){ out<<" Gaussian Decay: "<<gaussian->_decay; out<<" Contractions:"; for (const double& contraction:gaussian->_contraction){ out<<" "<<contraction; } out<<"\n"; } return out; } GaussianPrimitive* Shell::addGaussian( double decay, std::vector<double> contraction ){ GaussianPrimitive* gaussian = new GaussianPrimitive(decay, contraction); _gaussians.push_back( gaussian ); return gaussian; } // adds a Gaussian of a pseudopotential GaussianPrimitive* Shell::addGaussian( int power, double decay, std::vector<double> contraction ){ GaussianPrimitive* gaussian = new GaussianPrimitive(power, decay, contraction); _gaussians.push_back( gaussian ); return gaussian; } }} <|endoftext|>
<commit_before>/* virtual_keyboard.cpp: Copyright (C) 2006 Steven Yi This file is part of Csound. The Csound 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. Csound 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 Csound; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "csdl.h" #include "csGblMtx.h" #include "midiops.h" #include "oload.h" #include "winFLTK.h" #include "FLTKKeyboardWindow.hpp" #include "FLTKKeyboardWidget.hpp" #include "KeyboardMapping.hpp" #include "SliderData.hpp" static FLTKKeyboardWindow *createWindow(CSOUND *csound, const char *dev) { return new FLTKKeyboardWindow(csound, dev, 624, 270, "Csound Virtual Keyboard"); } static void deleteWindow(CSOUND *csound, FLTKKeyboardWindow * keyWin) { if(keyWin == NULL) { return; } Fl_lock(csound); keyWin->hide(); delete keyWin; Fl_awake(csound); Fl_wait(csound, 0.0); Fl_unlock(csound); } extern "C" { typedef struct { OPDS h; MYFLT *name, *ix, *iy; } FLVKEYBD; static int OpenMidiInDevice_(CSOUND *csound, void **userData, const char *dev) { FLTKKeyboardWindow *keyboard = createWindow(csound, dev); *userData = (void *)keyboard; Fl_lock(csound); keyboard->show(); Fl_wait(csound, 0.0); Fl_unlock(csound); /* report success */ return 0; } static int OpenMidiOutDevice_(CSOUND *csound, void **userData, const char *dev) { /* report success */ return 0; } static int ReadMidiData_(CSOUND *csound, void *userData, unsigned char *mbuf, int nbytes) { FLTKKeyboardWindow *keyWin = (FLTKKeyboardWindow *)userData; int i; Fl_lock(csound); Fl_awake(csound); Fl_wait(csound, 0.0); Fl_unlock(csound); if(!keyWin->visible()) { return 0; } int count = 0; keyWin->lock(); KeyboardMapping* keyboardMapping = keyWin->keyboardMapping; int channel = keyboardMapping->getCurrentChannel(); if(keyboardMapping->getCurrentBank() != keyboardMapping->getPreviousBank()) { int bankNum = keyboardMapping->getCurrentBankMIDINumber(); unsigned char msb = (unsigned char)(bankNum >> 7) & (unsigned char)0x7F; unsigned char lsb = (unsigned char)bankNum & (unsigned char)0x7F; *mbuf++ = (unsigned char)(0xB0 + channel); // MSB *mbuf++ = (unsigned char)0; *mbuf++ = msb; *mbuf++ = (unsigned char)(0xB0 + channel); // LSB *mbuf++ = (unsigned char)32; *mbuf++ = lsb; *mbuf++ = (unsigned char)(0xC0 + channel); // Program Change *mbuf++ = (unsigned char)keyboardMapping->getCurrentProgram(); count += 8; keyboardMapping->setPreviousBank(keyboardMapping->getCurrentBank()); keyboardMapping->setPreviousProgram(keyboardMapping->getCurrentProgram()); } else if(keyboardMapping->getCurrentProgram() != keyboardMapping->getPreviousProgram()) { *mbuf++ = (unsigned char)(0xC0 + channel); // Program Change *mbuf++ = (unsigned char)keyboardMapping->getCurrentProgram(); keyboardMapping->getCurrentProgram(); count += 2; keyboardMapping->setPreviousProgram(keyboardMapping->getCurrentProgram()); } keyWin->sliderBank->lock(); SliderData *sliderData = keyWin->sliderBank->getSliderData(); for(i = 0; i < 10; i++) { if(sliderData->controllerNumber[i] != sliderData->previousControllerNumber[i]) { *mbuf++ = (unsigned char)(0xB0 + channel); *mbuf++ = (unsigned char)sliderData->controllerNumber[i]; *mbuf++ = (unsigned char)sliderData->controllerValue[i]; count += 3; sliderData->previousControllerNumber[i] = sliderData->controllerNumber[i]; sliderData->previousControllerValue[i] = sliderData->controllerValue[i]; } else if(sliderData->controllerValue[i] != sliderData->previousControllerValue[i]) { *mbuf++ = (unsigned char)(0xB0 + channel); *mbuf++ = (unsigned char)sliderData->controllerNumber[i]; *mbuf++ = (unsigned char)sliderData->controllerValue[i]; count += 3; sliderData->previousControllerValue[i] = sliderData->controllerValue[i]; } } keyWin->sliderBank->unlock(); keyWin->unlock(); keyWin->keyboard->lock(); int *changedKeyStates = keyWin->keyboard->changedKeyStates; int *keyStates = keyWin->keyboard->keyStates; for(i = 0; i < 88; i++) { if(keyStates[i] == -1) { *mbuf++ = (unsigned char)0x90 + channel; *mbuf++ = (unsigned char)i + 21; *mbuf++ = (unsigned char)0; count += 3; keyStates[i] = 0; } else if(changedKeyStates[i] != keyStates[i]) { if(keyStates[i] == 1) { *mbuf++ = (unsigned char)0x90 + channel; *mbuf++ = (unsigned char)i + 21; *mbuf++ = (unsigned char)127; count += 3; } else { *mbuf++ = (unsigned char)0x90 + channel; *mbuf++ = (unsigned char)i + 21; *mbuf++ = (unsigned char)0; count += 3; } } changedKeyStates[i] = keyStates[i]; } if(keyWin->keyboard->aNotesOff == 1) { keyWin->keyboard->aNotesOff = 0; *mbuf++ = (unsigned char)0xB0; *mbuf++ = (unsigned char)123; *mbuf++ = (unsigned char)0; count += 3; } keyWin->keyboard->unlock(); return count; } static int WriteMidiData_(CSOUND *csound, void *userData, const unsigned char *mbuf, int nbytes) { /* return the number of bytes written */ return 0; } static int CloseMidiInDevice_(CSOUND *csound, void *userData) { deleteWindow(csound, (FLTKKeyboardWindow *)userData); return 0; } static int CloseMidiOutDevice_(CSOUND *csound, void *userData) { return 0; } /* FLvkeybd Opcode */ static int fl_vkeybd(CSOUND *csound, FLVKEYBD *p) { return OK; } #define S(x) sizeof(x) const OENTRY widgetOpcodes_[] = { { "FLvkeybd", S(FLVKEYBD), 1, "", "Tii", (SUBR) fl_vkeybd, (SUBR) NULL, (SUBR) NULL }, { NULL, 0, 0, NULL, NULL, (SUBR) NULL, (SUBR) NULL,(SUBR) NULL } }; /* module interface functions */ PUBLIC int csoundModuleCreate(CSOUND *csound) { /* nothing to do, report success */ csound->Message(csound, "virtual_keyboard real time MIDI plugin for Csound\n"); return 0; } PUBLIC int csoundModuleInit(CSOUND *csound) { char *drv; const OENTRY *ep = &(widgetOpcodes_[0]); if (csound->QueryGlobalVariable(csound, "FLTK_Flags") == (void*) 0) { if (csound->CreateGlobalVariable(csound, "FLTK_Flags", sizeof(int)) != 0) csound->Die(csound, Str("virtual_keyboard.cpp: error allocating FLTK flags")); } for ( ; ep->opname != NULL; ep++) { if (csound->AppendOpcode(csound, ep->opname, (int)ep->dsblksiz, (int)ep->thread, ep->outypes, ep->intypes, ep->iopadr, ep->kopadr, ep->aopadr) != 0) { csound->ErrorMsg(csound, Str("Error registering opcode '%s'"), ep->opname); return -1; } } drv = (char*) (csound->QueryGlobalVariable(csound, "_RTMIDI")); if (drv == NULL) return 0; if (!(strcmp(drv, "virtual") == 0)) return 0; csound->Message(csound, "rtmidi: virtual_keyboard module enabled\n"); csound->SetExternalMidiInOpenCallback(csound, OpenMidiInDevice_); csound->SetExternalMidiReadCallback(csound, ReadMidiData_); csound->SetExternalMidiInCloseCallback(csound, CloseMidiInDevice_); csound->SetExternalMidiOutOpenCallback(csound, OpenMidiOutDevice_); csound->SetExternalMidiWriteCallback(csound, WriteMidiData_); csound->SetExternalMidiOutCloseCallback(csound, CloseMidiOutDevice_); return 0; } PUBLIC int csoundModuleInfo(void) { /* does not depend on MYFLT type */ return ((CS_APIVERSION << 16) + (CS_APISUBVER << 8)); } } // END EXTERN C <commit_msg>implemented reading from virtual keyboard widget<commit_after>/* virtual_keyboard.cpp: Copyright (C) 2006 Steven Yi This file is part of Csound. The Csound 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. Csound 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 Csound; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "csdl.h" #include "csGblMtx.h" #include "midiops.h" #include "oload.h" #include "winFLTK.h" #include "FLTKKeyboardWindow.hpp" #include "FLTKKeyboardWidget.hpp" #include "KeyboardMapping.hpp" #include "SliderData.hpp" #include <map> static std::map<CSOUND *, FLTKKeyboardWidget *> keyboardWidgets; static FLTKKeyboardWindow *createWindow(CSOUND *csound, const char *dev) { return new FLTKKeyboardWindow(csound, dev, 624, 270, "Csound Virtual Keyboard"); } static FLTKKeyboardWidget *createWidget(CSOUND *csound, const char *dev, int x, int y) { return new FLTKKeyboardWidget(csound, dev, x, y); } static void deleteWindow(CSOUND *csound, FLTKKeyboardWindow * keyWin) { if(keyWin == NULL) { return; } Fl_lock(csound); keyWin->hide(); delete keyWin; Fl_awake(csound); Fl_wait(csound, 0.0); Fl_unlock(csound); } extern "C" { typedef struct { OPDS h; MYFLT *mapFileName, *ix, *iy; } FLVKEYBD; static int OpenMidiInDevice_(CSOUND *csound, void **userData, const char *dev) { if(keyboardWidgets.find(csound) != keyboardWidgets.end()) { return 0; } // if(csound->QueryGlobalVariable(csound, "FLTK_VKeyboard_Widget") != (void *) // NULL) { // return 0; // } FLTKKeyboardWindow *keyboard = createWindow(csound, dev); *userData = (void *)keyboard; Fl_lock(csound); keyboard->show(); Fl_wait(csound, 0.0); Fl_unlock(csound); /* report success */ return 0; } static int OpenMidiOutDevice_(CSOUND *csound, void **userData, const char *dev) { /* report success */ return 0; } static int ReadMidiWindow(CSOUND *csound, FLTKKeyboardWindow *keyWin, unsigned char *mbuf, int nbytes) { int i; Fl_lock(csound); Fl_awake(csound); Fl_wait(csound, 0.0); Fl_unlock(csound); if(!keyWin->visible()) { return 0; } int count = 0; keyWin->lock(); KeyboardMapping* keyboardMapping = keyWin->keyboardMapping; int channel = keyboardMapping->getCurrentChannel(); if(keyboardMapping->getCurrentBank() != keyboardMapping->getPreviousBank()) { int bankNum = keyboardMapping->getCurrentBankMIDINumber(); unsigned char msb = (unsigned char)(bankNum >> 7) & (unsigned char)0x7F; unsigned char lsb = (unsigned char)bankNum & (unsigned char)0x7F; *mbuf++ = (unsigned char)(0xB0 + channel); // MSB *mbuf++ = (unsigned char)0; *mbuf++ = msb; *mbuf++ = (unsigned char)(0xB0 + channel); // LSB *mbuf++ = (unsigned char)32; *mbuf++ = lsb; *mbuf++ = (unsigned char)(0xC0 + channel); // Program Change *mbuf++ = (unsigned char)keyboardMapping->getCurrentProgram(); count += 8; keyboardMapping->setPreviousBank(keyboardMapping->getCurrentBank()); keyboardMapping->setPreviousProgram(keyboardMapping->getCurrentProgram()); } else if(keyboardMapping->getCurrentProgram() != keyboardMapping->getPreviousProgram()) { *mbuf++ = (unsigned char)(0xC0 + channel); // Program Change *mbuf++ = (unsigned char)keyboardMapping->getCurrentProgram(); keyboardMapping->getCurrentProgram(); count += 2; keyboardMapping->setPreviousProgram(keyboardMapping->getCurrentProgram()); } keyWin->sliderBank->lock(); SliderData *sliderData = keyWin->sliderBank->getSliderData(); for(i = 0; i < 10; i++) { if(sliderData->controllerNumber[i] != sliderData->previousControllerNumber[i]) { *mbuf++ = (unsigned char)(0xB0 + channel); *mbuf++ = (unsigned char)sliderData->controllerNumber[i]; *mbuf++ = (unsigned char)sliderData->controllerValue[i]; count += 3; sliderData->previousControllerNumber[i] = sliderData->controllerNumber[i]; sliderData->previousControllerValue[i] = sliderData->controllerValue[i]; } else if(sliderData->controllerValue[i] != sliderData->previousControllerValue[i]) { *mbuf++ = (unsigned char)(0xB0 + channel); *mbuf++ = (unsigned char)sliderData->controllerNumber[i]; *mbuf++ = (unsigned char)sliderData->controllerValue[i]; count += 3; sliderData->previousControllerValue[i] = sliderData->controllerValue[i]; } } keyWin->sliderBank->unlock(); keyWin->unlock(); keyWin->keyboard->lock(); int *changedKeyStates = keyWin->keyboard->changedKeyStates; int *keyStates = keyWin->keyboard->keyStates; for(i = 0; i < 88; i++) { if(keyStates[i] == -1) { *mbuf++ = (unsigned char)0x90 + channel; *mbuf++ = (unsigned char)i + 21; *mbuf++ = (unsigned char)0; count += 3; keyStates[i] = 0; } else if(changedKeyStates[i] != keyStates[i]) { if(keyStates[i] == 1) { *mbuf++ = (unsigned char)0x90 + channel; *mbuf++ = (unsigned char)i + 21; *mbuf++ = (unsigned char)127; count += 3; } else { *mbuf++ = (unsigned char)0x90 + channel; *mbuf++ = (unsigned char)i + 21; *mbuf++ = (unsigned char)0; count += 3; } } changedKeyStates[i] = keyStates[i]; } if(keyWin->keyboard->aNotesOff == 1) { keyWin->keyboard->aNotesOff = 0; *mbuf++ = (unsigned char)0xB0; *mbuf++ = (unsigned char)123; *mbuf++ = (unsigned char)0; count += 3; } keyWin->keyboard->unlock(); return count; } static int ReadMidiWidget(CSOUND *csound, FLTKKeyboardWidget *widget, unsigned char *mbuf, int nbytes) { int i; if(!widget->visible()) { return 0; } int count = 0; widget->lock(); KeyboardMapping* keyboardMapping = widget->keyboardMapping; int channel = keyboardMapping->getCurrentChannel(); if(keyboardMapping->getCurrentBank() != keyboardMapping->getPreviousBank()) { int bankNum = keyboardMapping->getCurrentBankMIDINumber(); unsigned char msb = (unsigned char)(bankNum >> 7) & (unsigned char)0x7F; unsigned char lsb = (unsigned char)bankNum & (unsigned char)0x7F; *mbuf++ = (unsigned char)(0xB0 + channel); // MSB *mbuf++ = (unsigned char)0; *mbuf++ = msb; *mbuf++ = (unsigned char)(0xB0 + channel); // LSB *mbuf++ = (unsigned char)32; *mbuf++ = lsb; *mbuf++ = (unsigned char)(0xC0 + channel); // Program Change *mbuf++ = (unsigned char)keyboardMapping->getCurrentProgram(); count += 8; keyboardMapping->setPreviousBank(keyboardMapping->getCurrentBank()); keyboardMapping->setPreviousProgram(keyboardMapping->getCurrentProgram()); } else if(keyboardMapping->getCurrentProgram() != keyboardMapping->getPreviousProgram()) { *mbuf++ = (unsigned char)(0xC0 + channel); // Program Change *mbuf++ = (unsigned char)keyboardMapping->getCurrentProgram(); keyboardMapping->getCurrentProgram(); count += 2; keyboardMapping->setPreviousProgram(keyboardMapping->getCurrentProgram()); } widget->unlock(); widget->keyboard->lock(); int *changedKeyStates = widget->keyboard->changedKeyStates; int *keyStates = widget->keyboard->keyStates; for(i = 0; i < 88; i++) { if(keyStates[i] == -1) { *mbuf++ = (unsigned char)0x90 + channel; *mbuf++ = (unsigned char)i + 21; *mbuf++ = (unsigned char)0; count += 3; keyStates[i] = 0; } else if(changedKeyStates[i] != keyStates[i]) { if(keyStates[i] == 1) { *mbuf++ = (unsigned char)0x90 + channel; *mbuf++ = (unsigned char)i + 21; *mbuf++ = (unsigned char)127; count += 3; } else { *mbuf++ = (unsigned char)0x90 + channel; *mbuf++ = (unsigned char)i + 21; *mbuf++ = (unsigned char)0; count += 3; } } changedKeyStates[i] = keyStates[i]; } if(widget->keyboard->aNotesOff == 1) { widget->keyboard->aNotesOff = 0; *mbuf++ = (unsigned char)0xB0; *mbuf++ = (unsigned char)123; *mbuf++ = (unsigned char)0; count += 3; } widget->keyboard->unlock(); return count; } static int ReadMidiData_(CSOUND *csound, void *userData, unsigned char *mbuf, int nbytes) { if(keyboardWidgets.find(csound) == keyboardWidgets.end()) { return ReadMidiWindow(csound, (FLTKKeyboardWindow *)userData, mbuf, nbytes); } // void *v = csound->QueryGlobalVariable(csound, "FLTK_VKeyboard_Widget"); // // if(v == (void *)NULL) { // return ReadMidiWindow(csound, // (FLTKKeyboardWindow *)userData, mbuf, nbytes); // } // return ReadMidiWidget(csound, (FLTKKeyboardWidget *)v, mbuf, nbytes); return ReadMidiWidget(csound, keyboardWidgets[csound], mbuf, nbytes); } static int WriteMidiData_(CSOUND *csound, void *userData, const unsigned char *mbuf, int nbytes) { /* return the number of bytes written */ return 0; } static int CloseMidiInDevice_(CSOUND *csound, void *userData) { deleteWindow(csound, (FLTKKeyboardWindow *)userData); return 0; } static int CloseMidiOutDevice_(CSOUND *csound, void *userData) { return 0; } /* FLvkeybd Opcode */ static int fl_vkeybd(CSOUND *csound, FLVKEYBD *p) { if(keyboardWidgets.find(csound) != keyboardWidgets.end()) { csound->ErrorMsg(csound, "FLvkeybd may only be used once in a project.\n"); return -1; } char *mapFileName = new char[MAXNAME]; csound->strarg2name(csound, mapFileName, p->mapFileName, "", p->XSTRCODE); FLTKKeyboardWidget *widget = createWidget(csound, mapFileName, (int)*p->ix, (int)*p->iy); // if(csound->CreateGlobalVariable(csound, "FLTK_VKeyboard_Widget", // sizeof(widget)) != CSOUND_SUCCESS) { // csound->Die(csound, // Str("FLvkeybd: error allocating global memory for keyboard")); // } // // void *v = csound->QueryGlobalVariable(csound, "FLTK_VKeyboard_Widget"); // // v = &((void *)widget); keyboardWidgets[csound] = widget; return OK; } #define S(x) sizeof(x) const OENTRY widgetOpcodes_[] = { { "FLvkeybd", S(FLVKEYBD), 1, "", "Tii", (SUBR) fl_vkeybd, (SUBR) NULL, (SUBR) NULL }, { NULL, 0, 0, NULL, NULL, (SUBR) NULL, (SUBR) NULL,(SUBR) NULL } }; /* module interface functions */ PUBLIC int csoundModuleCreate(CSOUND *csound) { /* nothing to do, report success */ csound->Message(csound, "virtual_keyboard real time MIDI plugin for Csound\n"); return 0; } PUBLIC int csoundModuleInit(CSOUND *csound) { char *drv; const OENTRY *ep = &(widgetOpcodes_[0]); if (csound->QueryGlobalVariable(csound, "FLTK_Flags") == (void*) 0) { if (csound->CreateGlobalVariable(csound, "FLTK_Flags", sizeof(int)) != 0) csound->Die(csound, Str("virtual_keyboard.cpp: error allocating FLTK flags")); } for ( ; ep->opname != NULL; ep++) { if (csound->AppendOpcode(csound, ep->opname, (int)ep->dsblksiz, (int)ep->thread, ep->outypes, ep->intypes, ep->iopadr, ep->kopadr, ep->aopadr) != 0) { csound->ErrorMsg(csound, Str("Error registering opcode '%s'"), ep->opname); return -1; } } drv = (char*) (csound->QueryGlobalVariable(csound, "_RTMIDI")); if (drv == NULL) return 0; if (!(strcmp(drv, "virtual") == 0)) return 0; csound->Message(csound, "rtmidi: virtual_keyboard module enabled\n"); csound->SetExternalMidiInOpenCallback(csound, OpenMidiInDevice_); csound->SetExternalMidiReadCallback(csound, ReadMidiData_); csound->SetExternalMidiInCloseCallback(csound, CloseMidiInDevice_); csound->SetExternalMidiOutOpenCallback(csound, OpenMidiOutDevice_); csound->SetExternalMidiWriteCallback(csound, WriteMidiData_); csound->SetExternalMidiOutCloseCallback(csound, CloseMidiOutDevice_); return 0; } PUBLIC int csoundModuleInfo(void) { /* does not depend on MYFLT type */ return ((CS_APIVERSION << 16) + (CS_APISUBVER << 8)); } } // END EXTERN C <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef SDEXT_PRESENTER_PRESENTER_THEME_HXX #define SDEXT_PRESENTER_PRESENTER_THEME_HXX #include "PresenterBitmapContainer.hxx" #include "PresenterConfigurationAccess.hxx" #include "PresenterTheme.hxx" #include <com/sun/star/uno/XComponentContext.hpp> #include <com/sun/star/rendering/XCanvas.hpp> #include <com/sun/star/rendering/XCanvasFont.hpp> #include <com/sun/star/rendering/XIntegerBitmap.hpp> #include <com/sun/star/util/Color.hpp> #include <boost/shared_ptr.hpp> namespace css = ::com::sun::star; namespace sdext { namespace presenter { /** A theme is a set of properties describing fonts, colors, and bitmaps to be used to draw background, pane borders, and view content. At the moment the properties can be accessed via the getPropertyValue() method. For a resource URL of a pane or a view you get the name of the associated PaneStyle or ViewStyle. For the name of pane or view style suffixed with and underscore and the name of configuration property, and maybe additionally suffixed by another underscore and sub property name you get the associated property. Example: you want to access the top left bitmap of a pane border (simplified code): String sStyleName = getPropertyValue("private:resource/pane/Presenter/Pane1"); XBitmap xBitmap = getPropertyValue(sStyleName + "_TopLeftBitmap"); For the offset of the bitmap you can call Point aOffset = getPropertyValue(sStyleName + "_TopLeftOffset"); This is work in progress. */ class PresenterTheme { public: PresenterTheme ( const css::uno::Reference<css::uno::XComponentContext>& rxContext, const rtl::OUString& rsThemeName, const css::uno::Reference<css::rendering::XCanvas>& rxCanvas); ~PresenterTheme (void); bool HasCanvas (void) const; void ProvideCanvas (const css::uno::Reference<css::rendering::XCanvas>& rxCanvas); ::rtl::OUString GetStyleName (const ::rtl::OUString& rsResourceURL) const; ::std::vector<sal_Int32> GetBorderSize ( const ::rtl::OUString& rsStyleName, const bool bOuter) const; class Theme; class FontDescriptor { public: explicit FontDescriptor (const ::boost::shared_ptr<FontDescriptor>& rpDescriptor); ::rtl::OUString msFamilyName; ::rtl::OUString msStyleName; sal_Int32 mnSize; sal_uInt32 mnColor; ::rtl::OUString msAnchor; sal_Int32 mnXOffset; sal_Int32 mnYOffset; css::uno::Reference<css::rendering::XCanvasFont> mxFont; bool PrepareFont (const css::uno::Reference<css::rendering::XCanvas>& rxCanvas); private: css::uno::Reference<css::rendering::XCanvasFont> CreateFont ( const css::uno::Reference<css::rendering::XCanvas>& rxCanvas, const double nCellSize) const; double GetCellSizeForDesignSize ( const css::uno::Reference<css::rendering::XCanvas>& rxCanvas, const double nDesignSize) const; }; typedef ::boost::shared_ptr<FontDescriptor> SharedFontDescriptor; SharedBitmapDescriptor GetBitmap ( const ::rtl::OUString& rsStyleName, const ::rtl::OUString& rsBitmapName) const; SharedBitmapDescriptor GetBitmap ( const ::rtl::OUString& rsBitmapName) const; ::boost::shared_ptr<PresenterBitmapContainer> GetBitmapContainer (void) const; SharedFontDescriptor GetFont ( const ::rtl::OUString& rsStyleName) const; static SharedFontDescriptor ReadFont ( const css::uno::Reference<css::container::XHierarchicalNameAccess>& rxNode, const ::rtl::OUString& rsFontPath, const SharedFontDescriptor& rDefaultFount); static bool ConvertToColor ( const css::uno::Any& rColorSequence, sal_uInt32& rColor); ::boost::shared_ptr<PresenterConfigurationAccess> GetNodeForViewStyle ( const ::rtl::OUString& rsStyleName) const; private: css::uno::Reference<css::uno::XComponentContext> mxContext; const ::rtl::OUString msThemeName; ::boost::shared_ptr<Theme> mpTheme; ::boost::shared_ptr<PresenterBitmapContainer> mpBitmapContainer; css::uno::Reference<css::rendering::XCanvas> mxCanvas; ::boost::shared_ptr<Theme> ReadTheme (void); }; } } // end of namespace ::sd::presenter #endif /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>drop #include of itself<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef SDEXT_PRESENTER_PRESENTER_THEME_HXX #define SDEXT_PRESENTER_PRESENTER_THEME_HXX #include "PresenterBitmapContainer.hxx" #include "PresenterConfigurationAccess.hxx" #include <com/sun/star/uno/XComponentContext.hpp> #include <com/sun/star/rendering/XCanvas.hpp> #include <com/sun/star/rendering/XCanvasFont.hpp> #include <com/sun/star/rendering/XIntegerBitmap.hpp> #include <com/sun/star/util/Color.hpp> #include <boost/shared_ptr.hpp> namespace css = ::com::sun::star; namespace sdext { namespace presenter { /** A theme is a set of properties describing fonts, colors, and bitmaps to be used to draw background, pane borders, and view content. At the moment the properties can be accessed via the getPropertyValue() method. For a resource URL of a pane or a view you get the name of the associated PaneStyle or ViewStyle. For the name of pane or view style suffixed with and underscore and the name of configuration property, and maybe additionally suffixed by another underscore and sub property name you get the associated property. Example: you want to access the top left bitmap of a pane border (simplified code): String sStyleName = getPropertyValue("private:resource/pane/Presenter/Pane1"); XBitmap xBitmap = getPropertyValue(sStyleName + "_TopLeftBitmap"); For the offset of the bitmap you can call Point aOffset = getPropertyValue(sStyleName + "_TopLeftOffset"); This is work in progress. */ class PresenterTheme { public: PresenterTheme ( const css::uno::Reference<css::uno::XComponentContext>& rxContext, const rtl::OUString& rsThemeName, const css::uno::Reference<css::rendering::XCanvas>& rxCanvas); ~PresenterTheme (void); bool HasCanvas (void) const; void ProvideCanvas (const css::uno::Reference<css::rendering::XCanvas>& rxCanvas); ::rtl::OUString GetStyleName (const ::rtl::OUString& rsResourceURL) const; ::std::vector<sal_Int32> GetBorderSize ( const ::rtl::OUString& rsStyleName, const bool bOuter) const; class Theme; class FontDescriptor { public: explicit FontDescriptor (const ::boost::shared_ptr<FontDescriptor>& rpDescriptor); ::rtl::OUString msFamilyName; ::rtl::OUString msStyleName; sal_Int32 mnSize; sal_uInt32 mnColor; ::rtl::OUString msAnchor; sal_Int32 mnXOffset; sal_Int32 mnYOffset; css::uno::Reference<css::rendering::XCanvasFont> mxFont; bool PrepareFont (const css::uno::Reference<css::rendering::XCanvas>& rxCanvas); private: css::uno::Reference<css::rendering::XCanvasFont> CreateFont ( const css::uno::Reference<css::rendering::XCanvas>& rxCanvas, const double nCellSize) const; double GetCellSizeForDesignSize ( const css::uno::Reference<css::rendering::XCanvas>& rxCanvas, const double nDesignSize) const; }; typedef ::boost::shared_ptr<FontDescriptor> SharedFontDescriptor; SharedBitmapDescriptor GetBitmap ( const ::rtl::OUString& rsStyleName, const ::rtl::OUString& rsBitmapName) const; SharedBitmapDescriptor GetBitmap ( const ::rtl::OUString& rsBitmapName) const; ::boost::shared_ptr<PresenterBitmapContainer> GetBitmapContainer (void) const; SharedFontDescriptor GetFont ( const ::rtl::OUString& rsStyleName) const; static SharedFontDescriptor ReadFont ( const css::uno::Reference<css::container::XHierarchicalNameAccess>& rxNode, const ::rtl::OUString& rsFontPath, const SharedFontDescriptor& rDefaultFount); static bool ConvertToColor ( const css::uno::Any& rColorSequence, sal_uInt32& rColor); ::boost::shared_ptr<PresenterConfigurationAccess> GetNodeForViewStyle ( const ::rtl::OUString& rsStyleName) const; private: css::uno::Reference<css::uno::XComponentContext> mxContext; const ::rtl::OUString msThemeName; ::boost::shared_ptr<Theme> mpTheme; ::boost::shared_ptr<PresenterBitmapContainer> mpBitmapContainer; css::uno::Reference<css::rendering::XCanvas> mxCanvas; ::boost::shared_ptr<Theme> ReadTheme (void); }; } } // end of namespace ::sd::presenter #endif /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>#include <QVBoxLayout> #include <QHBoxLayout> #include <QJsonObject> #include <QJsonDocument> #include "offroad_alerts.hpp" #include "selfdrive/hardware/hw.h" #include "selfdrive/common/util.h" OffroadAlert::OffroadAlert(QWidget* parent) : QFrame(parent) { QVBoxLayout *layout = new QVBoxLayout(); layout->setMargin(50); layout->setSpacing(30); QWidget *alerts_widget = new QWidget; QVBoxLayout *alerts_layout = new QVBoxLayout; alerts_layout->setMargin(0); alerts_layout->setSpacing(30); alerts_widget->setLayout(alerts_layout); // setup labels for each alert QString json = QString::fromStdString(util::read_file("../controls/lib/alerts_offroad.json")); QJsonObject obj = QJsonDocument::fromJson(json.toUtf8()).object(); for (auto &k : obj.keys()) { QLabel *l = new QLabel(this); alerts[k.toStdString()] = l; int severity = obj[k].toObject()["severity"].toInt(); l->setMargin(60); l->setWordWrap(true); l->setStyleSheet("background-color: " + QString(severity ? "#E22C2C" : "#292929")); l->setVisible(false); alerts_layout->addWidget(l); } alerts_layout->addStretch(1); // release notes releaseNotes.setWordWrap(true); releaseNotes.setVisible(false); releaseNotes.setStyleSheet("font-size: 48px;"); releaseNotes.setAlignment(Qt::AlignTop); releaseNotesScroll = new ScrollView(&releaseNotes, this); layout->addWidget(releaseNotesScroll); alertsScroll = new ScrollView(alerts_widget, this); layout->addWidget(alertsScroll); // bottom footer, dismiss + reboot buttons QHBoxLayout *footer_layout = new QHBoxLayout(); layout->addLayout(footer_layout); QPushButton *dismiss_btn = new QPushButton("Dismiss"); dismiss_btn->setFixedSize(400, 125); footer_layout->addWidget(dismiss_btn, 0, Qt::AlignBottom | Qt::AlignLeft); QObject::connect(dismiss_btn, SIGNAL(released()), this, SIGNAL(closeAlerts())); rebootBtn.setText("Reboot and Update"); rebootBtn.setFixedSize(600, 125); rebootBtn.setVisible(false); footer_layout->addWidget(&rebootBtn, 0, Qt::AlignBottom | Qt::AlignRight); QObject::connect(&rebootBtn, &QPushButton::released, [=]() { Hardware::reboot(); }); setLayout(layout); setStyleSheet(R"( * { font-size: 48px; color: white; } QFrame { border-radius: 30px; background-color: #393939; } QPushButton { color: black; font-weight: 500; border-radius: 30px; background-color: white; } )"); } void OffroadAlert::refresh() { updateAlerts(); rebootBtn.setVisible(updateAvailable); releaseNotesScroll->setVisible(updateAvailable); releaseNotes.setText(QString::fromStdString(params.get("ReleaseNotes"))); alertsScroll->setVisible(!updateAvailable); for (const auto& [k, label] : alerts) { label->setVisible(!label->text().isEmpty()); } } void OffroadAlert::updateAlerts() { alertCount = 0; updateAvailable = params.getBool("UpdateAvailable"); for (const auto& [key, label] : alerts) { auto bytes = params.get(key.c_str()); if (bytes.size()) { QJsonDocument doc_par = QJsonDocument::fromJson(QByteArray(bytes.data(), bytes.size())); QJsonObject obj = doc_par.object(); label->setText(obj.value("text").toString()); alertCount++; } else { label->setText(""); } } } <commit_msg>alerts background color fix (#20568)<commit_after>#include <QVBoxLayout> #include <QHBoxLayout> #include <QJsonObject> #include <QJsonDocument> #include "offroad_alerts.hpp" #include "selfdrive/hardware/hw.h" #include "selfdrive/common/util.h" OffroadAlert::OffroadAlert(QWidget* parent) : QFrame(parent) { QVBoxLayout *layout = new QVBoxLayout(); layout->setMargin(50); layout->setSpacing(30); QWidget *alerts_widget = new QWidget; QVBoxLayout *alerts_layout = new QVBoxLayout; alerts_layout->setMargin(0); alerts_layout->setSpacing(30); alerts_widget->setLayout(alerts_layout); alerts_widget->setStyleSheet("background-color: transparent;"); // setup labels for each alert QString json = QString::fromStdString(util::read_file("../controls/lib/alerts_offroad.json")); QJsonObject obj = QJsonDocument::fromJson(json.toUtf8()).object(); for (auto &k : obj.keys()) { QLabel *l = new QLabel(this); alerts[k.toStdString()] = l; int severity = obj[k].toObject()["severity"].toInt(); l->setMargin(60); l->setWordWrap(true); l->setStyleSheet("background-color: " + QString(severity ? "#E22C2C" : "#292929")); l->setVisible(false); alerts_layout->addWidget(l); } alerts_layout->addStretch(1); // release notes releaseNotes.setWordWrap(true); releaseNotes.setVisible(false); releaseNotes.setStyleSheet("font-size: 48px;"); releaseNotes.setAlignment(Qt::AlignTop); releaseNotesScroll = new ScrollView(&releaseNotes, this); layout->addWidget(releaseNotesScroll); alertsScroll = new ScrollView(alerts_widget, this); layout->addWidget(alertsScroll); // bottom footer, dismiss + reboot buttons QHBoxLayout *footer_layout = new QHBoxLayout(); layout->addLayout(footer_layout); QPushButton *dismiss_btn = new QPushButton("Dismiss"); dismiss_btn->setFixedSize(400, 125); footer_layout->addWidget(dismiss_btn, 0, Qt::AlignBottom | Qt::AlignLeft); QObject::connect(dismiss_btn, SIGNAL(released()), this, SIGNAL(closeAlerts())); rebootBtn.setText("Reboot and Update"); rebootBtn.setFixedSize(600, 125); rebootBtn.setVisible(false); footer_layout->addWidget(&rebootBtn, 0, Qt::AlignBottom | Qt::AlignRight); QObject::connect(&rebootBtn, &QPushButton::released, [=]() { Hardware::reboot(); }); setLayout(layout); setStyleSheet(R"( * { font-size: 48px; color: white; } QFrame { border-radius: 30px; background-color: #393939; } QPushButton { color: black; font-weight: 500; border-radius: 30px; background-color: white; } )"); } void OffroadAlert::refresh() { updateAlerts(); rebootBtn.setVisible(updateAvailable); releaseNotesScroll->setVisible(updateAvailable); releaseNotes.setText(QString::fromStdString(params.get("ReleaseNotes"))); alertsScroll->setVisible(!updateAvailable); for (const auto& [k, label] : alerts) { label->setVisible(!label->text().isEmpty()); } } void OffroadAlert::updateAlerts() { alertCount = 0; updateAvailable = params.getBool("UpdateAvailable"); for (const auto& [key, label] : alerts) { auto bytes = params.get(key.c_str()); if (bytes.size()) { QJsonDocument doc_par = QJsonDocument::fromJson(QByteArray(bytes.data(), bytes.size())); QJsonObject obj = doc_par.object(); label->setText(obj.value("text").toString()); alertCount++; } else { label->setText(""); } } } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: propertysetinfo.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: obo $ $Date: 2006-09-17 17:19:18 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_comphelper.hxx" #include "comphelper/propertysetinfo.hxx" using namespace ::rtl; using namespace ::comphelper; using namespace ::com::sun::star; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::beans; using namespace ::com::sun::star::lang; namespace comphelper { class PropertyMapImpl { public: PropertyMapImpl() throw(); virtual ~PropertyMapImpl() throw(); void add( PropertyMapEntry* pMap, sal_Int32 nCount = -1 ) throw(); void remove( const OUString& aName ) throw(); Sequence< Property > getProperties() throw(); const PropertyMap* getPropertyMap() const throw(); Property getPropertyByName( const OUString& aName ) throw( UnknownPropertyException ); sal_Bool hasPropertyByName( const OUString& aName ) throw(); private: PropertyMap maPropertyMap; Sequence< Property > maProperties; }; } PropertyMapImpl::PropertyMapImpl() throw() { } PropertyMapImpl::~PropertyMapImpl() throw() { } void PropertyMapImpl::add( PropertyMapEntry* pMap, sal_Int32 nCount ) throw() { // nCount < 0 => add all // nCount == 0 => add nothing // nCount > 0 => add at most nCount entries while( pMap->mpName && ( ( nCount < 0) || ( nCount-- > 0 ) ) ) { OUString aName( pMap->mpName, pMap->mnNameLen, RTL_TEXTENCODING_ASCII_US ); #ifndef PRODUCT PropertyMap::iterator aIter = maPropertyMap.find( aName ); if( aIter != maPropertyMap.end() ) { OSL_ENSURE( sal_False, "Warning: PropertyMapEntry added twice, possible error!"); } #endif if( NULL == pMap->mpType ) { OSL_ENSURE( sal_False, "No type in PropertyMapEntry!"); pMap->mpType = &::getCppuType((const sal_Int32*)0); } maPropertyMap[aName] = pMap; if( maProperties.getLength() ) maProperties.realloc( 0 ); pMap = &pMap[1]; } } void PropertyMapImpl::remove( const OUString& aName ) throw() { maPropertyMap.erase( aName ); if( maProperties.getLength() ) maProperties.realloc( 0 ); } Sequence< Property > PropertyMapImpl::getProperties() throw() { // maybe we have to generate the properties after // a change in the property map or at first call // to getProperties if( maProperties.getLength() != (sal_Int32)maPropertyMap.size() ) { maProperties = Sequence< Property >( maPropertyMap.size() ); Property* pProperties = maProperties.getArray(); PropertyMap::iterator aIter = maPropertyMap.begin(); const PropertyMap::iterator aEnd = maPropertyMap.end(); while( aIter != aEnd ) { PropertyMapEntry* pEntry = (*aIter).second; pProperties->Name = OUString( pEntry->mpName, pEntry->mnNameLen, RTL_TEXTENCODING_ASCII_US ); pProperties->Handle = pEntry->mnHandle; pProperties->Type = *pEntry->mpType; pProperties->Attributes = pEntry->mnAttributes; pProperties++; aIter++; } } return maProperties; } const PropertyMap* PropertyMapImpl::getPropertyMap() const throw() { return &maPropertyMap; } Property PropertyMapImpl::getPropertyByName( const OUString& aName ) throw( UnknownPropertyException ) { PropertyMap::iterator aIter = maPropertyMap.find( aName ); if( maPropertyMap.end() == aIter ) throw UnknownPropertyException(); PropertyMapEntry* pEntry = (*aIter).second; return Property( aName, pEntry->mnHandle, *pEntry->mpType, pEntry->mnAttributes ); } sal_Bool PropertyMapImpl::hasPropertyByName( const OUString& aName ) throw() { return maPropertyMap.find( aName ) != maPropertyMap.end(); } /////////////////////////////////////////////////////////////////////// PropertySetInfo::PropertySetInfo() throw() { mpMap = new PropertyMapImpl(); } PropertySetInfo::PropertySetInfo( PropertyMapEntry* pMap ) throw() { mpMap = new PropertyMapImpl(); mpMap->add( pMap ); } PropertySetInfo::~PropertySetInfo() throw() { delete mpMap; } void PropertySetInfo::add( PropertyMapEntry* pMap ) throw() { mpMap->add( pMap ); } void PropertySetInfo::add( PropertyMapEntry* pMap, sal_Int32 nCount ) throw() { mpMap->add( pMap, nCount ); } void PropertySetInfo::remove( const rtl::OUString& aName ) throw() { mpMap->remove( aName ); } Sequence< ::com::sun::star::beans::Property > SAL_CALL PropertySetInfo::getProperties() throw(::com::sun::star::uno::RuntimeException) { return mpMap->getProperties(); } Property SAL_CALL PropertySetInfo::getPropertyByName( const ::rtl::OUString& aName ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::uno::RuntimeException) { return mpMap->getPropertyByName( aName ); } sal_Bool SAL_CALL PropertySetInfo::hasPropertyByName( const ::rtl::OUString& Name ) throw(::com::sun::star::uno::RuntimeException) { return mpMap->hasPropertyByName( Name ); } const PropertyMap* PropertySetInfo::getPropertyMap() const throw() { return mpMap->getPropertyMap(); } <commit_msg>INTEGRATION: CWS changefileheader (1.5.160); FILE MERGED 2008/03/31 12:19:36 rt 1.5.160.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: propertysetinfo.cxx,v $ * $Revision: 1.6 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_comphelper.hxx" #include "comphelper/propertysetinfo.hxx" using namespace ::rtl; using namespace ::comphelper; using namespace ::com::sun::star; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::beans; using namespace ::com::sun::star::lang; namespace comphelper { class PropertyMapImpl { public: PropertyMapImpl() throw(); virtual ~PropertyMapImpl() throw(); void add( PropertyMapEntry* pMap, sal_Int32 nCount = -1 ) throw(); void remove( const OUString& aName ) throw(); Sequence< Property > getProperties() throw(); const PropertyMap* getPropertyMap() const throw(); Property getPropertyByName( const OUString& aName ) throw( UnknownPropertyException ); sal_Bool hasPropertyByName( const OUString& aName ) throw(); private: PropertyMap maPropertyMap; Sequence< Property > maProperties; }; } PropertyMapImpl::PropertyMapImpl() throw() { } PropertyMapImpl::~PropertyMapImpl() throw() { } void PropertyMapImpl::add( PropertyMapEntry* pMap, sal_Int32 nCount ) throw() { // nCount < 0 => add all // nCount == 0 => add nothing // nCount > 0 => add at most nCount entries while( pMap->mpName && ( ( nCount < 0) || ( nCount-- > 0 ) ) ) { OUString aName( pMap->mpName, pMap->mnNameLen, RTL_TEXTENCODING_ASCII_US ); #ifndef PRODUCT PropertyMap::iterator aIter = maPropertyMap.find( aName ); if( aIter != maPropertyMap.end() ) { OSL_ENSURE( sal_False, "Warning: PropertyMapEntry added twice, possible error!"); } #endif if( NULL == pMap->mpType ) { OSL_ENSURE( sal_False, "No type in PropertyMapEntry!"); pMap->mpType = &::getCppuType((const sal_Int32*)0); } maPropertyMap[aName] = pMap; if( maProperties.getLength() ) maProperties.realloc( 0 ); pMap = &pMap[1]; } } void PropertyMapImpl::remove( const OUString& aName ) throw() { maPropertyMap.erase( aName ); if( maProperties.getLength() ) maProperties.realloc( 0 ); } Sequence< Property > PropertyMapImpl::getProperties() throw() { // maybe we have to generate the properties after // a change in the property map or at first call // to getProperties if( maProperties.getLength() != (sal_Int32)maPropertyMap.size() ) { maProperties = Sequence< Property >( maPropertyMap.size() ); Property* pProperties = maProperties.getArray(); PropertyMap::iterator aIter = maPropertyMap.begin(); const PropertyMap::iterator aEnd = maPropertyMap.end(); while( aIter != aEnd ) { PropertyMapEntry* pEntry = (*aIter).second; pProperties->Name = OUString( pEntry->mpName, pEntry->mnNameLen, RTL_TEXTENCODING_ASCII_US ); pProperties->Handle = pEntry->mnHandle; pProperties->Type = *pEntry->mpType; pProperties->Attributes = pEntry->mnAttributes; pProperties++; aIter++; } } return maProperties; } const PropertyMap* PropertyMapImpl::getPropertyMap() const throw() { return &maPropertyMap; } Property PropertyMapImpl::getPropertyByName( const OUString& aName ) throw( UnknownPropertyException ) { PropertyMap::iterator aIter = maPropertyMap.find( aName ); if( maPropertyMap.end() == aIter ) throw UnknownPropertyException(); PropertyMapEntry* pEntry = (*aIter).second; return Property( aName, pEntry->mnHandle, *pEntry->mpType, pEntry->mnAttributes ); } sal_Bool PropertyMapImpl::hasPropertyByName( const OUString& aName ) throw() { return maPropertyMap.find( aName ) != maPropertyMap.end(); } /////////////////////////////////////////////////////////////////////// PropertySetInfo::PropertySetInfo() throw() { mpMap = new PropertyMapImpl(); } PropertySetInfo::PropertySetInfo( PropertyMapEntry* pMap ) throw() { mpMap = new PropertyMapImpl(); mpMap->add( pMap ); } PropertySetInfo::~PropertySetInfo() throw() { delete mpMap; } void PropertySetInfo::add( PropertyMapEntry* pMap ) throw() { mpMap->add( pMap ); } void PropertySetInfo::add( PropertyMapEntry* pMap, sal_Int32 nCount ) throw() { mpMap->add( pMap, nCount ); } void PropertySetInfo::remove( const rtl::OUString& aName ) throw() { mpMap->remove( aName ); } Sequence< ::com::sun::star::beans::Property > SAL_CALL PropertySetInfo::getProperties() throw(::com::sun::star::uno::RuntimeException) { return mpMap->getProperties(); } Property SAL_CALL PropertySetInfo::getPropertyByName( const ::rtl::OUString& aName ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::uno::RuntimeException) { return mpMap->getPropertyByName( aName ); } sal_Bool SAL_CALL PropertySetInfo::hasPropertyByName( const ::rtl::OUString& Name ) throw(::com::sun::star::uno::RuntimeException) { return mpMap->hasPropertyByName( Name ); } const PropertyMap* PropertySetInfo::getPropertyMap() const throw() { return mpMap->getPropertyMap(); } <|endoftext|>
<commit_before>//===--- ASTUnit.cpp - ASTUnit utility ------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // ASTUnit Implementation. // //===----------------------------------------------------------------------===// #include "clang/Frontend/ASTUnit.h" #include "clang/Frontend/PCHReader.h" #include "clang/Frontend/TextDiagnosticBuffer.h" #include "clang/AST/ASTContext.h" #include "clang/AST/DeclVisitor.h" #include "clang/AST/StmtVisitor.h" #include "clang/Lex/HeaderSearch.h" #include "clang/Lex/Preprocessor.h" #include "clang/Basic/TargetInfo.h" #include "clang/Basic/Diagnostic.h" #include "llvm/Support/Compiler.h" using namespace clang; ASTUnit::ASTUnit() { } ASTUnit::~ASTUnit() { } namespace { /// \brief Gathers information from PCHReader that will be used to initialize /// a Preprocessor. class VISIBILITY_HIDDEN PCHInfoCollector : public PCHReaderListener { LangOptions &LangOpt; HeaderSearch &HSI; std::string &TargetTriple; std::string &Predefines; unsigned &Counter; unsigned NumHeaderInfos; public: PCHInfoCollector(LangOptions &LangOpt, HeaderSearch &HSI, std::string &TargetTriple, std::string &Predefines, unsigned &Counter) : LangOpt(LangOpt), HSI(HSI), TargetTriple(TargetTriple), Predefines(Predefines), Counter(Counter), NumHeaderInfos(0) {} virtual bool ReadLanguageOptions(const LangOptions &LangOpts) { LangOpt = LangOpts; return false; } virtual bool ReadTargetTriple(const std::string &Triple) { TargetTriple = Triple; return false; } virtual bool ReadPredefinesBuffer(const char *PCHPredef, unsigned PCHPredefLen, FileID PCHBufferID, std::string &SuggestedPredefines) { Predefines = PCHPredef; return false; } virtual void ReadHeaderFileInfo(const HeaderFileInfo &HFI) { HSI.setHeaderFileInfoForUID(HFI, NumHeaderInfos++); } virtual void ReadCounter(unsigned Value) { Counter = Value; } }; } // anonymous namespace const std::string &ASTUnit::getOriginalSourceFileName() { return Reader->getOriginalSourceFile(); } ASTUnit *ASTUnit::LoadFromPCHFile(const std::string &Filename, FileManager &FileMgr, std::string *ErrMsg) { llvm::OwningPtr<ASTUnit> AST(new ASTUnit()); AST->DiagClient.reset(new TextDiagnosticBuffer()); AST->Diags.reset(new Diagnostic(AST->DiagClient.get())); AST->HeaderInfo.reset(new HeaderSearch(FileMgr)); AST->SourceMgr.reset(new SourceManager()); Diagnostic &Diags = *AST->Diags.get(); SourceManager &SourceMgr = *AST->SourceMgr.get(); // Gather Info for preprocessor construction later on. LangOptions LangInfo; HeaderSearch &HeaderInfo = *AST->HeaderInfo.get(); std::string TargetTriple; std::string Predefines; unsigned Counter; llvm::OwningPtr<ExternalASTSource> Source; AST->Reader.reset(new PCHReader(SourceMgr, FileMgr, Diags)); AST->Reader->setListener(new PCHInfoCollector(LangInfo, HeaderInfo, TargetTriple, Predefines, Counter)); switch (AST->Reader->ReadPCH(Filename)) { case PCHReader::Success: break; case PCHReader::Failure: case PCHReader::IgnorePCH: if (ErrMsg) *ErrMsg = "Could not load PCH file"; return NULL; } // PCH loaded successfully. Now create the preprocessor. // Get information about the target being compiled for. AST->Target.reset(TargetInfo::CreateTargetInfo(TargetTriple)); AST->PP.reset(new Preprocessor(Diags, LangInfo, *AST->Target.get(), SourceMgr, HeaderInfo)); Preprocessor &PP = *AST->PP.get(); PP.setPredefines(Predefines); PP.setCounterValue(Counter); AST->Reader->setPreprocessor(PP); // Create and initialize the ASTContext. AST->Ctx.reset(new ASTContext(LangInfo, SourceMgr, *AST->Target.get(), PP.getIdentifierTable(), PP.getSelectorTable(), PP.getBuiltinInfo(), /* FreeMemory = */ true, /* size_reserve = */0)); ASTContext &Context = *AST->Ctx.get(); AST->Reader->InitializeContext(Context); // Attach the PCH reader to the AST context as an external AST // source, so that declarations will be deserialized from the // PCH file as needed. Source.reset(AST->Reader.get()); Context.setExternalSource(Source); return AST.take(); } <commit_msg>Revert "Remove redundant local variable (use newly created instance data).", the previous commit this depends on is breaking x86_64-apple-darwin10 and Linux tests.<commit_after>//===--- ASTUnit.cpp - ASTUnit utility ------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // ASTUnit Implementation. // //===----------------------------------------------------------------------===// #include "clang/Frontend/ASTUnit.h" #include "clang/Frontend/PCHReader.h" #include "clang/Frontend/TextDiagnosticBuffer.h" #include "clang/AST/ASTContext.h" #include "clang/AST/DeclVisitor.h" #include "clang/AST/StmtVisitor.h" #include "clang/Lex/HeaderSearch.h" #include "clang/Lex/Preprocessor.h" #include "clang/Basic/TargetInfo.h" #include "clang/Basic/Diagnostic.h" #include "llvm/Support/Compiler.h" using namespace clang; ASTUnit::ASTUnit() { } ASTUnit::~ASTUnit() { } namespace { /// \brief Gathers information from PCHReader that will be used to initialize /// a Preprocessor. class VISIBILITY_HIDDEN PCHInfoCollector : public PCHReaderListener { LangOptions &LangOpt; HeaderSearch &HSI; std::string &TargetTriple; std::string &Predefines; unsigned &Counter; unsigned NumHeaderInfos; public: PCHInfoCollector(LangOptions &LangOpt, HeaderSearch &HSI, std::string &TargetTriple, std::string &Predefines, unsigned &Counter) : LangOpt(LangOpt), HSI(HSI), TargetTriple(TargetTriple), Predefines(Predefines), Counter(Counter), NumHeaderInfos(0) {} virtual bool ReadLanguageOptions(const LangOptions &LangOpts) { LangOpt = LangOpts; return false; } virtual bool ReadTargetTriple(const std::string &Triple) { TargetTriple = Triple; return false; } virtual bool ReadPredefinesBuffer(const char *PCHPredef, unsigned PCHPredefLen, FileID PCHBufferID, std::string &SuggestedPredefines) { Predefines = PCHPredef; return false; } virtual void ReadHeaderFileInfo(const HeaderFileInfo &HFI) { HSI.setHeaderFileInfoForUID(HFI, NumHeaderInfos++); } virtual void ReadCounter(unsigned Value) { Counter = Value; } }; } // anonymous namespace const std::string &ASTUnit::getOriginalSourceFileName() { return Reader->getOriginalSourceFile(); } ASTUnit *ASTUnit::LoadFromPCHFile(const std::string &Filename, FileManager &FileMgr, std::string *ErrMsg) { llvm::OwningPtr<ASTUnit> AST(new ASTUnit()); AST->DiagClient.reset(new TextDiagnosticBuffer()); AST->Diags.reset(new Diagnostic(AST->DiagClient.get())); AST->HeaderInfo.reset(new HeaderSearch(FileMgr)); AST->SourceMgr.reset(new SourceManager()); Diagnostic &Diags = *AST->Diags.get(); SourceManager &SourceMgr = *AST->SourceMgr.get(); // Gather Info for preprocessor construction later on. LangOptions LangInfo; HeaderSearch &HeaderInfo = *AST->HeaderInfo.get(); std::string TargetTriple; std::string Predefines; unsigned Counter; llvm::OwningPtr<PCHReader> Reader; llvm::OwningPtr<ExternalASTSource> Source; Reader.reset(new PCHReader(SourceMgr, FileMgr, Diags)); AST->Reader.reset(Reader.get()); Reader->setListener(new PCHInfoCollector(LangInfo, HeaderInfo, TargetTriple, Predefines, Counter)); switch (Reader->ReadPCH(Filename)) { case PCHReader::Success: break; case PCHReader::Failure: case PCHReader::IgnorePCH: if (ErrMsg) *ErrMsg = "Could not load PCH file"; return NULL; } // PCH loaded successfully. Now create the preprocessor. // Get information about the target being compiled for. AST->Target.reset(TargetInfo::CreateTargetInfo(TargetTriple)); AST->PP.reset(new Preprocessor(Diags, LangInfo, *AST->Target.get(), SourceMgr, HeaderInfo)); Preprocessor &PP = *AST->PP.get(); PP.setPredefines(Predefines); PP.setCounterValue(Counter); Reader->setPreprocessor(PP); // Create and initialize the ASTContext. AST->Ctx.reset(new ASTContext(LangInfo, SourceMgr, *AST->Target.get(), PP.getIdentifierTable(), PP.getSelectorTable(), PP.getBuiltinInfo(), /* FreeMemory = */ true, /* size_reserve = */0)); ASTContext &Context = *AST->Ctx.get(); Reader->InitializeContext(Context); // Attach the PCH reader to the AST context as an external AST // source, so that declarations will be deserialized from the // PCH file as needed. Source.reset(Reader.take()); Context.setExternalSource(Source); return AST.take(); } <|endoftext|>
<commit_before>/** Copyright (C) 2016, 2017 European Spallation Source ERIC */ #include <algorithm> #include <arpa/inet.h> #include <cassert> #include <cinttypes> #include <cstring> #include <tools/ReaderPcap.h> #include <netinet/ip.h> #include <netinet/udp.h> #include <fmt/format.h> // GCOVR_EXCL_START // Protocol identifiers const int ETHERTYPE_ARP = 0x0806; const int ETHERTYPE_IPV4 = 0x0800; const int IPPROTO_UDP = 17; // Header and data location specifications const int ETHERTYPE_OFFSET = 12; const int ETHERNET_HEADER_SIZE = 14; #define IP_HEADR_OFFSET 14 #define IP_HEADER_SIZE 20 #define UDP_HEADER_OFFSET 34 #define UDP_HEADER_SIZE 8 #define UDP_DATA_OFFSET 42 ReaderPcap::ReaderPcap(std::string filename) : FileName(filename) { memset(&Stats, 0, sizeof(struct stats_t)); } ReaderPcap::~ReaderPcap() { if (PcapHandle != NULL ) { pcap_close(PcapHandle); } } int ReaderPcap::open() { char errbuff[PCAP_ERRBUF_SIZE]; PcapHandle = pcap_open_offline(FileName.c_str(), errbuff); if (PcapHandle == NULL) { return -1; } return 0; } int ReaderPcap::validatePacket(struct pcap_pkthdr *header, const unsigned char *data) { Stats.PacketsTotal++; /**< total packets in pcap file */ Stats.BytesTotal += header->len; if (header->len != header->caplen) { Stats.PacketsTruncated++; return 0; } uint16_t type = ntohs(*(uint16_t *)&data[ETHERTYPE_OFFSET]); // printf("packet header len %d, type %x\n", header->len, type); if (type == ETHERTYPE_ARP) { Stats.EtherTypeArp++; } else if (type == ETHERTYPE_IPV4) { Stats.EtherTypeIpv4++; } else { Stats.EtherTypeUnknown++; } if (type != ETHERTYPE_IPV4) { // must be ipv4 return 0; } ip *ip = (ip *)&data[IP_HEADR_OFFSET]; // IPv4 header length must be 20, ip version 4, ipproto must be UDP if ((ip->ip_hl != 5) or (ip->ip_v != 4) or (ip->ip_p != IPPROTO_UDP)) { Stats.IpProtoUnknown++; return 0; } Stats.IpProtoUDP++; assert(header->len > ETHERNET_HEADER_SIZE + IP_HEADER_SIZE + UDP_HEADER_SIZE); assert(Stats.PacketsTotal == Stats.EtherTypeIpv4 + Stats.EtherTypeArp + Stats.EtherTypeUnknown); assert(Stats.EtherTypeIpv4 == Stats.IpProtoUDP + Stats.IpProtoUnknown); udphdr *udp = (udphdr *)&data[UDP_HEADER_OFFSET]; #ifndef __FAVOR_BSD // Why is __FAVOR_BSD not defined here? uint16_t UdpLen = htons(udp->len); #else uint16_t UdpLen = htons(udp->uh_ulen); #endif assert(UdpLen >= UDP_HEADER_SIZE); #if 0 printf("UDP Payload, Packet %" PRIu64 ", time: %d:%d seconds, size: %d bytes\n", Stats.PacketsTotal, (int)header->ts.tv_sec, (int)header->ts.tv_usec, (int)header->len); printf("ip src->dest: 0x%08x:%d ->0x%08x:%d\n", ntohl(*(uint32_t*)&ip->ip_src), ntohs(udp->uh_sport), ntohl(*(uint32_t*)&ip->ip_dst), ntohs(udp->uh_dport)); #endif return UdpLen; } int ReaderPcap::read(char *buffer, size_t bufferlen) { if (PcapHandle == nullptr) { return -1; } struct pcap_pkthdr *Header; const unsigned char *Data; int ret = pcap_next_ex(PcapHandle, &Header, &Data); if (ret < 0) { return -1; } int UdpDataLength; if ((UdpDataLength = validatePacket(Header, Data)) <= 0) { return UdpDataLength; } auto DataLength = std::min((size_t)(UdpDataLength - UDP_HEADER_SIZE), bufferlen); std::memcpy(buffer, &Data[UDP_DATA_OFFSET], DataLength); return DataLength; } int ReaderPcap::getStats() { if (PcapHandle == NULL) { return -1; } while (true) { int RetVal; struct pcap_pkthdr *Header; const unsigned char *Data; if ((RetVal = pcap_next_ex(PcapHandle, &Header, &Data)) < 0) { break; } validatePacket(Header, Data); } return 0; } void ReaderPcap::printPacket(unsigned char *data, size_t len) { for (unsigned int i = 0; i < len; i++) { if ((i % 16) == 0 && i != 0) { printf("\n"); } printf("%.2x ", data[i]); } printf("\n"); } void ReaderPcap::printStats() { printf("Total packets %" PRIu64 "\n", Stats.PacketsTotal); printf("Truncated packets %" PRIu64 "\n", Stats.PacketsTruncated); printf("Ethertype IPv4 %" PRIu64 "\n", Stats.EtherTypeIpv4); printf(" ipproto UDP %" PRIu64 "\n", Stats.IpProtoUDP); printf(" ipproto other %" PRIu64 "\n", Stats.IpProtoUnknown); printf("Ethertype unknown %" PRIu64 "\n", Stats.EtherTypeUnknown); printf("Ethertype ARP %" PRIu64 "\n", Stats.EtherTypeArp); printf("Total bytes %" PRIu64 "\n", Stats.BytesTotal); } // GCOVR_EXCL_STOP <commit_msg>Update prototype2/tools/ReaderPcap.cpp<commit_after>/** Copyright (C) 2016, 2017 European Spallation Source ERIC */ #include <algorithm> #include <arpa/inet.h> #include <cassert> #include <cinttypes> #include <cstring> #include <tools/ReaderPcap.h> #include <netinet/ip.h> #include <netinet/udp.h> #include <fmt/format.h> // GCOVR_EXCL_START // Protocol identifiers const int ETHERTYPE_ARP = 0x0806; const int ETHERTYPE_IPV4 = 0x0800; const int IPPROTO_UDP = 17; // Header and data location specifications const int ETHERTYPE_OFFSET = 12; const int ETHERNET_HEADER_SIZE = 14; #define IP_HEADR_OFFSET 14 #define IP_HEADER_SIZE 20 #define UDP_HEADER_OFFSET 34 #define UDP_HEADER_SIZE 8 #define UDP_DATA_OFFSET 42 ReaderPcap::ReaderPcap(std::string filename) : FileName(filename) { memset(&Stats, 0, sizeof(struct stats_t)); } ReaderPcap::~ReaderPcap() { if (PcapHandle != NULL ) { pcap_close(PcapHandle); } } int ReaderPcap::open() { char errbuff[PCAP_ERRBUF_SIZE]; PcapHandle = pcap_open_offline(FileName.c_str(), errbuff); if (PcapHandle == NULL) { return -1; } return 0; } int ReaderPcap::validatePacket(pcap_pkthdr *header, const unsigned char *data) { Stats.PacketsTotal++; /**< total packets in pcap file */ Stats.BytesTotal += header->len; if (header->len != header->caplen) { Stats.PacketsTruncated++; return 0; } uint16_t type = ntohs(*(uint16_t *)&data[ETHERTYPE_OFFSET]); // printf("packet header len %d, type %x\n", header->len, type); if (type == ETHERTYPE_ARP) { Stats.EtherTypeArp++; } else if (type == ETHERTYPE_IPV4) { Stats.EtherTypeIpv4++; } else { Stats.EtherTypeUnknown++; } if (type != ETHERTYPE_IPV4) { // must be ipv4 return 0; } ip *ip = (ip *)&data[IP_HEADR_OFFSET]; // IPv4 header length must be 20, ip version 4, ipproto must be UDP if ((ip->ip_hl != 5) or (ip->ip_v != 4) or (ip->ip_p != IPPROTO_UDP)) { Stats.IpProtoUnknown++; return 0; } Stats.IpProtoUDP++; assert(header->len > ETHERNET_HEADER_SIZE + IP_HEADER_SIZE + UDP_HEADER_SIZE); assert(Stats.PacketsTotal == Stats.EtherTypeIpv4 + Stats.EtherTypeArp + Stats.EtherTypeUnknown); assert(Stats.EtherTypeIpv4 == Stats.IpProtoUDP + Stats.IpProtoUnknown); udphdr *udp = (udphdr *)&data[UDP_HEADER_OFFSET]; #ifndef __FAVOR_BSD // Why is __FAVOR_BSD not defined here? uint16_t UdpLen = htons(udp->len); #else uint16_t UdpLen = htons(udp->uh_ulen); #endif assert(UdpLen >= UDP_HEADER_SIZE); #if 0 printf("UDP Payload, Packet %" PRIu64 ", time: %d:%d seconds, size: %d bytes\n", Stats.PacketsTotal, (int)header->ts.tv_sec, (int)header->ts.tv_usec, (int)header->len); printf("ip src->dest: 0x%08x:%d ->0x%08x:%d\n", ntohl(*(uint32_t*)&ip->ip_src), ntohs(udp->uh_sport), ntohl(*(uint32_t*)&ip->ip_dst), ntohs(udp->uh_dport)); #endif return UdpLen; } int ReaderPcap::read(char *buffer, size_t bufferlen) { if (PcapHandle == nullptr) { return -1; } struct pcap_pkthdr *Header; const unsigned char *Data; int ret = pcap_next_ex(PcapHandle, &Header, &Data); if (ret < 0) { return -1; } int UdpDataLength; if ((UdpDataLength = validatePacket(Header, Data)) <= 0) { return UdpDataLength; } auto DataLength = std::min((size_t)(UdpDataLength - UDP_HEADER_SIZE), bufferlen); std::memcpy(buffer, &Data[UDP_DATA_OFFSET], DataLength); return DataLength; } int ReaderPcap::getStats() { if (PcapHandle == NULL) { return -1; } while (true) { int RetVal; struct pcap_pkthdr *Header; const unsigned char *Data; if ((RetVal = pcap_next_ex(PcapHandle, &Header, &Data)) < 0) { break; } validatePacket(Header, Data); } return 0; } void ReaderPcap::printPacket(unsigned char *data, size_t len) { for (unsigned int i = 0; i < len; i++) { if ((i % 16) == 0 && i != 0) { printf("\n"); } printf("%.2x ", data[i]); } printf("\n"); } void ReaderPcap::printStats() { printf("Total packets %" PRIu64 "\n", Stats.PacketsTotal); printf("Truncated packets %" PRIu64 "\n", Stats.PacketsTruncated); printf("Ethertype IPv4 %" PRIu64 "\n", Stats.EtherTypeIpv4); printf(" ipproto UDP %" PRIu64 "\n", Stats.IpProtoUDP); printf(" ipproto other %" PRIu64 "\n", Stats.IpProtoUnknown); printf("Ethertype unknown %" PRIu64 "\n", Stats.EtherTypeUnknown); printf("Ethertype ARP %" PRIu64 "\n", Stats.EtherTypeArp); printf("Total bytes %" PRIu64 "\n", Stats.BytesTotal); } // GCOVR_EXCL_STOP <|endoftext|>
<commit_before>/* libClunk - cross-platform 3D audio API built on top SDL library * Copyright (C) 2007-2008 Netive Media Group * * 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 <clunk/distance_model.h> float clunk::DistanceModel::gain(float distance) const { float gain = 0; distance /= distance_divisor; switch(type) { case Inverse: if (clamped) { if (distance < reference_distance) distance = reference_distance; if (distance > max_distance) distance = max_distance; } gain = reference_distance / (reference_distance + rolloff_factor * (distance - reference_distance)); break; case Linear: if (clamped && distance < reference_distance) { distance = reference_distance; } if (distance > max_distance) distance = max_distance; gain = 1 - rolloff_factor * (distance - reference_distance) / (max_distance - reference_distance); break; case Exponent: if (clamped) { if (distance < reference_distance) distance = reference_distance; if (distance > max_distance) distance = max_distance; } gain = powf(distance / reference_distance, - rolloff_factor); break; } if (gain < 0) gain = 0; else if (gain > 1) gain = 1; return gain; } float clunk::DistanceModel::doppler_pitch(const v3<float> &sl, const v3<float> &s_vel, const v3<float> &l_vel) const { if (doppler_factor <= 0) return 1.0f; float len = sl.length(); if (len <= 0) return 1.0f; float max_speed = speed_of_sound / doppler_factor; float vls = sl.dot_product(l_vel) / len; if (vls > max_speed) vls = max_speed; float vss = sl.dot_product(s_vel) / len; if (vss > max_speed) vss = max_speed; return (speed_of_sound - doppler_factor * vls) / (speed_of_sound - doppler_factor * vss); } <commit_msg>fixed linear distance model attenuation<commit_after>/* libClunk - cross-platform 3D audio API built on top SDL library * Copyright (C) 2007-2008 Netive Media Group * * 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 <clunk/distance_model.h> float clunk::DistanceModel::gain(float distance) const { float gain = 0; distance /= distance_divisor; switch(type) { case Inverse: if (clamped) { if (distance < reference_distance) distance = reference_distance; if (distance > max_distance) distance = max_distance; } gain = reference_distance / (reference_distance + rolloff_factor * (distance - reference_distance)); break; case Linear: if (clamped) { if (distance < reference_distance) distance = reference_distance; if (distance > max_distance) distance = max_distance; } gain = 1 - rolloff_factor * (distance - reference_distance) / (max_distance - reference_distance); break; case Exponent: if (clamped) { if (distance < reference_distance) distance = reference_distance; if (distance > max_distance) distance = max_distance; } gain = powf(distance / reference_distance, - rolloff_factor); break; } if (gain < 0) gain = 0; else if (gain > 1) gain = 1; return gain; } float clunk::DistanceModel::doppler_pitch(const v3<float> &sl, const v3<float> &s_vel, const v3<float> &l_vel) const { if (doppler_factor <= 0) return 1.0f; float len = sl.length(); if (len <= 0) return 1.0f; float max_speed = speed_of_sound / doppler_factor; float vls = sl.dot_product(l_vel) / len; if (vls > max_speed) vls = max_speed; float vss = sl.dot_product(s_vel) / len; if (vss > max_speed) vss = max_speed; return (speed_of_sound - doppler_factor * vls) / (speed_of_sound - doppler_factor * vss); } <|endoftext|>
<commit_before>/* Copyright (c) 2011 Yahoo! Inc. All rights reserved. The copyrights embodied in the content of this file are licensed under the BSD (revised) open source license This creates a binary tree topology over a set of n nodes that connect. */ #ifdef _WIN32 #include <WinSock2.h> #include <Windows.h> #include <WS2tcpip.h> #include <io.h> #define SHUT_RDWR SD_BOTH typedef unsigned int uint32_t; typedef unsigned short uint16_t; typedef int socklen_t; typedef SOCKET socket_t; int daemon(int a, int b) { return 0; } int getpid() { return (int) ::GetCurrentProcessId(); } #else #include <unistd.h> #include <sys/socket.h> #include <netinet/in.h> #include <netinet/tcp.h> #include <netdb.h> #include <strings.h> typedef int socket_t; #endif #include <errno.h> #include <stdlib.h> #include <stdio.h> #include <string> #include <iostream> #include <fstream> #include <cmath> #include <map> using namespace std; struct client { uint32_t client_ip; socket_t socket; }; struct partial { client* nodes; size_t filled; }; static int socket_sort(const void* s1, const void* s2) { client* socket1 = (client*)s1; client* socket2 = (client*)s2; return socket1->client_ip - socket2->client_ip; } int build_tree(int* parent, uint16_t* kid_count, size_t source_count, int offset) { if(source_count == 1) { kid_count[offset] = 0; return offset; } int height = (int)floor(log((double)source_count)/log(2.0)); int root = (1 << height) - 1; int left_count = root; int left_offset = offset; int left_child = build_tree(parent, kid_count, left_count, left_offset); int oroot = root+offset; parent[left_child] = oroot; size_t right_count = source_count - left_count - 1; if (right_count > 0) { int right_offset = oroot+1; int right_child = build_tree(parent, kid_count, right_count, right_offset); parent[right_child] = oroot; kid_count[oroot] = 2; } else kid_count[oroot] = 1; return oroot; } void fail_send(const socket_t fd, const void* buf, const int count) { if (send(fd,(char*)buf,count,0)==-1) { cerr << "send failed!" << endl; exit(1); } } int main(int argc, char* argv[]) { if (argc > 2) { cout << "usage: spanning_tree [pid_file]" << endl; exit(0); } #ifdef _WIN32 WSAData wsaData; WSAStartup(MAKEWORD(2,2), &wsaData); int lastError = WSAGetLastError(); #endif socket_t sock = socket(PF_INET, SOCK_STREAM, 0); if (sock < 0) { #ifdef _WIN32 lastError = WSAGetLastError(); cerr << "can't open socket! (" << lastError << ")" << endl; #else cerr << "can't open socket! " << errno << endl; #endif exit(1); } int on = 1; if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char*)&on, sizeof(on)) < 0) perror("setsockopt SO_REUSEADDR"); sockaddr_in address; address.sin_family = AF_INET; address.sin_addr.s_addr = htonl(INADDR_ANY); short unsigned int port = 26543; address.sin_port = htons(port); if (bind(sock,(sockaddr*)&address, sizeof(address)) < 0) { cerr << "failure to bind!" << endl; exit(1); } if (daemon(1,1)) { cerr << "failure to background!" << endl; exit(1); } if (argc == 2) { ofstream pid_file; pid_file.open(argv[1]); if (!pid_file.is_open()) { cerr << "error writing pid file" << endl; exit(1); } pid_file << getpid() << endl; pid_file.close(); } map<size_t, partial> partial_nodesets; while(true) { listen(sock, 1024); sockaddr_in client_address; socklen_t size = sizeof(client_address); socket_t f = accept(sock,(sockaddr*)&client_address,&size); { char hostname[NI_MAXHOST]; char servInfo[NI_MAXSERV]; getnameinfo((sockaddr *) &client_address, sizeof(sockaddr), hostname, NI_MAXHOST, servInfo, NI_MAXSERV, 0); cerr << "inbound connection from " << hostname << endl; } if (f < 0) { cerr << "bad client socket!" << endl; exit (1); } size_t nonce = 0; if (recv(f, (char*)&nonce, sizeof(nonce), 0) != sizeof(nonce)) { cerr << "nonce read failed, exiting" << endl; exit(1); } size_t total = 0; if (recv(f, (char*)&total, sizeof(total), 0) != sizeof(total)) { cerr << "total node count read failed, exiting" << endl; exit(1); } size_t id = 0; if (recv(f, (char*)&id, sizeof(id), 0) != sizeof(id)) { cerr << "node id read failed, exiting" << endl; exit(1); } int ok = true; if ( id >= total ) { cout << "invalid id! " << endl; ok = false; } partial partial_nodeset; if (partial_nodesets.find(nonce) == partial_nodesets.end() ) { partial_nodeset.nodes = (client*) calloc(total, sizeof(client)); for (size_t i = 0; i < total; i++) partial_nodeset.nodes[i].client_ip = (uint32_t)-1; partial_nodeset.filled = 0; } else { partial_nodeset = partial_nodesets[nonce]; partial_nodesets.erase(nonce); } if (ok && partial_nodeset.nodes[id].client_ip != (uint32_t)-1) ok = false; fail_send(f,&ok, sizeof(ok)); if (ok) { partial_nodeset.nodes[id].client_ip = client_address.sin_addr.s_addr; partial_nodeset.nodes[id].socket = f; partial_nodeset.filled++; } if (partial_nodeset.filled != total) //Need to wait for more connections { partial_nodesets[nonce] = partial_nodeset; } else {//Time to make the spanning tree qsort(partial_nodeset.nodes, total, sizeof(client), socket_sort); int* parent = (int*)calloc(total,sizeof(int)); uint16_t* kid_count = (uint16_t*)calloc(total,sizeof(uint16_t)); int root = build_tree(parent, kid_count, total, 0); parent[root] = -1; for (size_t i = 0; i < total; i++) { fail_send(partial_nodeset.nodes[i].socket, &kid_count[i], sizeof(kid_count[i])); } uint16_t* client_ports=(uint16_t*)calloc(total,sizeof(uint16_t)); for(size_t i = 0;i < total;i++) { int done = 0; if(recv(partial_nodeset.nodes[i].socket, (char*)&(client_ports[i]), sizeof(client_ports[i]), 0) < (int) sizeof(client_ports[i])) cerr<<" Port read failed for node "<<i<<" read "<<done<<endl; }// all clients have bound to their ports. for (size_t i = 0; i < total; i++) { if (parent[i] >= 0) { fail_send(partial_nodeset.nodes[i].socket, &partial_nodeset.nodes[parent[i]].client_ip, sizeof(partial_nodeset.nodes[parent[i]].client_ip)); fail_send(partial_nodeset.nodes[i].socket, &client_ports[parent[i]], sizeof(client_ports[parent[i]])); } else { int bogus = -1; uint32_t bogus2 = -1; fail_send(partial_nodeset.nodes[i].socket, &bogus2, sizeof(bogus2)); fail_send(partial_nodeset.nodes[i].socket, &bogus, sizeof(bogus)); } shutdown(partial_nodeset.nodes[i].socket, SHUT_RDWR); } free (partial_nodeset.nodes); } } #ifdef _WIN32 WSACleanup(); #endif }<commit_msg>Newline at the end of cluster/spanning_tree.cc (clang++ warning)<commit_after>/* Copyright (c) 2011 Yahoo! Inc. All rights reserved. The copyrights embodied in the content of this file are licensed under the BSD (revised) open source license This creates a binary tree topology over a set of n nodes that connect. */ #ifdef _WIN32 #include <WinSock2.h> #include <Windows.h> #include <WS2tcpip.h> #include <io.h> #define SHUT_RDWR SD_BOTH typedef unsigned int uint32_t; typedef unsigned short uint16_t; typedef int socklen_t; typedef SOCKET socket_t; int daemon(int a, int b) { return 0; } int getpid() { return (int) ::GetCurrentProcessId(); } #else #include <unistd.h> #include <sys/socket.h> #include <netinet/in.h> #include <netinet/tcp.h> #include <netdb.h> #include <strings.h> typedef int socket_t; #endif #include <errno.h> #include <stdlib.h> #include <stdio.h> #include <string> #include <iostream> #include <fstream> #include <cmath> #include <map> using namespace std; struct client { uint32_t client_ip; socket_t socket; }; struct partial { client* nodes; size_t filled; }; static int socket_sort(const void* s1, const void* s2) { client* socket1 = (client*)s1; client* socket2 = (client*)s2; return socket1->client_ip - socket2->client_ip; } int build_tree(int* parent, uint16_t* kid_count, size_t source_count, int offset) { if(source_count == 1) { kid_count[offset] = 0; return offset; } int height = (int)floor(log((double)source_count)/log(2.0)); int root = (1 << height) - 1; int left_count = root; int left_offset = offset; int left_child = build_tree(parent, kid_count, left_count, left_offset); int oroot = root+offset; parent[left_child] = oroot; size_t right_count = source_count - left_count - 1; if (right_count > 0) { int right_offset = oroot+1; int right_child = build_tree(parent, kid_count, right_count, right_offset); parent[right_child] = oroot; kid_count[oroot] = 2; } else kid_count[oroot] = 1; return oroot; } void fail_send(const socket_t fd, const void* buf, const int count) { if (send(fd,(char*)buf,count,0)==-1) { cerr << "send failed!" << endl; exit(1); } } int main(int argc, char* argv[]) { if (argc > 2) { cout << "usage: spanning_tree [pid_file]" << endl; exit(0); } #ifdef _WIN32 WSAData wsaData; WSAStartup(MAKEWORD(2,2), &wsaData); int lastError = WSAGetLastError(); #endif socket_t sock = socket(PF_INET, SOCK_STREAM, 0); if (sock < 0) { #ifdef _WIN32 lastError = WSAGetLastError(); cerr << "can't open socket! (" << lastError << ")" << endl; #else cerr << "can't open socket! " << errno << endl; #endif exit(1); } int on = 1; if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char*)&on, sizeof(on)) < 0) perror("setsockopt SO_REUSEADDR"); sockaddr_in address; address.sin_family = AF_INET; address.sin_addr.s_addr = htonl(INADDR_ANY); short unsigned int port = 26543; address.sin_port = htons(port); if (bind(sock,(sockaddr*)&address, sizeof(address)) < 0) { cerr << "failure to bind!" << endl; exit(1); } if (daemon(1,1)) { cerr << "failure to background!" << endl; exit(1); } if (argc == 2) { ofstream pid_file; pid_file.open(argv[1]); if (!pid_file.is_open()) { cerr << "error writing pid file" << endl; exit(1); } pid_file << getpid() << endl; pid_file.close(); } map<size_t, partial> partial_nodesets; while(true) { listen(sock, 1024); sockaddr_in client_address; socklen_t size = sizeof(client_address); socket_t f = accept(sock,(sockaddr*)&client_address,&size); { char hostname[NI_MAXHOST]; char servInfo[NI_MAXSERV]; getnameinfo((sockaddr *) &client_address, sizeof(sockaddr), hostname, NI_MAXHOST, servInfo, NI_MAXSERV, 0); cerr << "inbound connection from " << hostname << endl; } if (f < 0) { cerr << "bad client socket!" << endl; exit (1); } size_t nonce = 0; if (recv(f, (char*)&nonce, sizeof(nonce), 0) != sizeof(nonce)) { cerr << "nonce read failed, exiting" << endl; exit(1); } size_t total = 0; if (recv(f, (char*)&total, sizeof(total), 0) != sizeof(total)) { cerr << "total node count read failed, exiting" << endl; exit(1); } size_t id = 0; if (recv(f, (char*)&id, sizeof(id), 0) != sizeof(id)) { cerr << "node id read failed, exiting" << endl; exit(1); } int ok = true; if ( id >= total ) { cout << "invalid id! " << endl; ok = false; } partial partial_nodeset; if (partial_nodesets.find(nonce) == partial_nodesets.end() ) { partial_nodeset.nodes = (client*) calloc(total, sizeof(client)); for (size_t i = 0; i < total; i++) partial_nodeset.nodes[i].client_ip = (uint32_t)-1; partial_nodeset.filled = 0; } else { partial_nodeset = partial_nodesets[nonce]; partial_nodesets.erase(nonce); } if (ok && partial_nodeset.nodes[id].client_ip != (uint32_t)-1) ok = false; fail_send(f,&ok, sizeof(ok)); if (ok) { partial_nodeset.nodes[id].client_ip = client_address.sin_addr.s_addr; partial_nodeset.nodes[id].socket = f; partial_nodeset.filled++; } if (partial_nodeset.filled != total) //Need to wait for more connections { partial_nodesets[nonce] = partial_nodeset; } else {//Time to make the spanning tree qsort(partial_nodeset.nodes, total, sizeof(client), socket_sort); int* parent = (int*)calloc(total,sizeof(int)); uint16_t* kid_count = (uint16_t*)calloc(total,sizeof(uint16_t)); int root = build_tree(parent, kid_count, total, 0); parent[root] = -1; for (size_t i = 0; i < total; i++) { fail_send(partial_nodeset.nodes[i].socket, &kid_count[i], sizeof(kid_count[i])); } uint16_t* client_ports=(uint16_t*)calloc(total,sizeof(uint16_t)); for(size_t i = 0;i < total;i++) { int done = 0; if(recv(partial_nodeset.nodes[i].socket, (char*)&(client_ports[i]), sizeof(client_ports[i]), 0) < (int) sizeof(client_ports[i])) cerr<<" Port read failed for node "<<i<<" read "<<done<<endl; }// all clients have bound to their ports. for (size_t i = 0; i < total; i++) { if (parent[i] >= 0) { fail_send(partial_nodeset.nodes[i].socket, &partial_nodeset.nodes[parent[i]].client_ip, sizeof(partial_nodeset.nodes[parent[i]].client_ip)); fail_send(partial_nodeset.nodes[i].socket, &client_ports[parent[i]], sizeof(client_ports[parent[i]])); } else { int bogus = -1; uint32_t bogus2 = -1; fail_send(partial_nodeset.nodes[i].socket, &bogus2, sizeof(bogus2)); fail_send(partial_nodeset.nodes[i].socket, &bogus, sizeof(bogus)); } shutdown(partial_nodeset.nodes[i].socket, SHUT_RDWR); } free (partial_nodeset.nodes); } } #ifdef _WIN32 WSACleanup(); #endif } <|endoftext|>
<commit_before>// The MIT License (MIT) // Copyright (c) 2016, Microsoft // 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 <cstring> #include "BitFunnel/Index/ITermTable.h" #include "BitFunnel/Index/Row.h" #include "BitFunnel/Index/RowIdSequence.h" #include "LoggerInterfaces/Check.h" #include "LoggerInterfaces/Logging.h" #include "RowTableDescriptor.h" namespace BitFunnel { RowTableDescriptor::RowTableDescriptor(DocIndex capacity, RowIndex rowCount, Rank rank, Rank maxRank, ptrdiff_t rowTableBufferOffset) : m_capacity(capacity), m_rowCount(rowCount), m_rank(rank), m_maxRank(maxRank), m_bufferOffset(rowTableBufferOffset), m_bytesPerRow(Row::BytesInRow(capacity, rank, maxRank)) { // Make sure capacity is properly rounded already. // TODO: fix. // LogAssertB(capacity == Row::DocumentsInRank0Row(capacity), // "capacity not evenly rounded."); // // Make sure offset of this RowTable is properly aligned. // LogAssertB((rowTableBufferOffset % c_rowTableByteAlignment) == 0); } RowTableDescriptor::RowTableDescriptor(RowTableDescriptor const & other) : m_capacity(other.m_capacity), m_rowCount(other.m_rowCount), m_rank(other.m_rank), m_maxRank(other.m_maxRank), m_bufferOffset(other.m_bufferOffset), m_bytesPerRow(other.m_bytesPerRow) { } void RowTableDescriptor::Initialize(void* sliceBuffer, ITermTable const & termTable) const { char* const rowTableBuffer = reinterpret_cast<char*>(sliceBuffer) + m_bufferOffset; memset(rowTableBuffer, 0, GetBufferSize(m_capacity, m_rowCount, m_rank, m_maxRank)); // The "match-all" row needs to be initialized differently. RowIdSequence rows(termTable.GetMatchAllTerm(), termTable); auto it = rows.begin(); if (it == rows.end()) { RecoverableError error("RowTableDescriptor::Initialize: expected at least one row."); throw error; } const RowId row = *it; ++it; if (it != rows.end()) { RecoverableError error("RowTableDescriptor::Initialize: expected no more than one row."); throw error; } if (row.GetRank() == m_rank) { // Fill up the match-all row with all ones. uint64_t * rowData = GetRowData(sliceBuffer, row.GetIndex()); memset(rowData, 0xFF, m_bytesPerRow); } } uint64_t RowTableDescriptor::GetBit(void* sliceBuffer, RowIndex rowIndex, DocIndex docIndex) const { uint64_t* const row = GetRowData(sliceBuffer, rowIndex); const size_t offset = QwordPositionFromDocIndex(docIndex); // Note that the offset here is shifted left by 6. // return _bittest64(row + (offset >> 6), offset & 0x3F); uint64_t bitPos = docIndex & 0x3F; uint64_t bitMask = 1ull << bitPos; uint64_t maskedVal = *(row + offset) & bitMask; // TODO: we probably don't need to shift the bit back down. return maskedVal >> bitPos; } void RowTableDescriptor::SetBit(void* sliceBuffer, RowIndex rowIndex, DocIndex docIndex) const { CHECK_LT(rowIndex, m_rowCount) << "rowIndex out of range."; uint64_t* const row = GetRowData(sliceBuffer, rowIndex); const size_t offset = QwordPositionFromDocIndex(docIndex); // Note that the offset here is shifted left by 6. // _interlockedbittestandset64(row + (offset >> 6), offset & 0x3F); uint64_t bitPos = docIndex & 0x3F; uint64_t bitMask = 1ull << bitPos; uint64_t newVal = *(row + offset) | bitMask; *(row + offset) = newVal; } void RowTableDescriptor::ClearBit(void* sliceBuffer, RowIndex rowIndex, DocIndex docIndex) const { uint64_t* const row = GetRowData(sliceBuffer, rowIndex); const size_t offset = QwordPositionFromDocIndex(docIndex); // Note that the offset here is shifted left by 6. // _interlockedbittestandreset64(row + (offset >> 6), offset & 0x3F); uint64_t bitPos = docIndex & 0x3F; uint64_t bitMask = ~(1ull << bitPos); uint64_t newVal = *(row + offset) & bitMask; *(row + offset) = newVal; } ptrdiff_t RowTableDescriptor::GetRowOffset(RowIndex rowIndex) const { // TODO: consider checking for overflow. return m_bufferOffset + static_cast<ptrdiff_t>(rowIndex * m_bytesPerRow); } /* static */ size_t RowTableDescriptor::GetBufferSize(DocIndex capacity, RowIndex rowCount, Rank rank, Rank maxRank) { // Make sure capacity is properly rounded already. // TODO: fix. // LogAssertB(capacity == Row::DocumentsInRank0Row(capacity), // "capacity not evenly rounded."); return static_cast<unsigned>( Row::BytesInRow(capacity, rank, maxRank) * rowCount); } uint64_t* RowTableDescriptor::GetRowData(void* sliceBuffer, RowIndex rowIndex) const { char* rowData = reinterpret_cast<char*>(sliceBuffer) + GetRowOffset(rowIndex); return reinterpret_cast<uint64_t*>(rowData); } size_t RowTableDescriptor::QwordPositionFromDocIndex(DocIndex docIndex) const { LogAssertB(docIndex < m_capacity, "docIndex out of range"); // Shifting by 6 gives the rank0Word. // Shifting by an additional m_rank gives the rankRWord. return docIndex >> (6 + m_rank); } size_t RowTableDescriptor::BitPositionFromDocIndex(DocIndex docIndex) const { LogAssertB(docIndex < m_capacity, "docIndex out of range"); size_t rank0Word = docIndex >> 6; size_t rankRWord = rank0Word >> m_rank; // TODO: check if compiler is smart enough to avoid doing a % here. size_t bitInWord = docIndex % 64; return (rankRWord << 6) + bitInWord; } } <commit_msg>Use MS intrinsics to set/get/clear bit. See #63.<commit_after>// The MIT License (MIT) // Copyright (c) 2016, Microsoft // 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 <cstring> #include "BitFunnel/Index/ITermTable.h" #include "BitFunnel/Index/Row.h" #include "BitFunnel/Index/RowIdSequence.h" #include "LoggerInterfaces/Check.h" #include "LoggerInterfaces/Logging.h" #include "RowTableDescriptor.h" #ifdef _MSC_VER #include <intrin.h> // For _interlockedbittestandreset64, etc. #endif namespace BitFunnel { RowTableDescriptor::RowTableDescriptor(DocIndex capacity, RowIndex rowCount, Rank rank, Rank maxRank, ptrdiff_t rowTableBufferOffset) : m_capacity(capacity), m_rowCount(rowCount), m_rank(rank), m_maxRank(maxRank), m_bufferOffset(rowTableBufferOffset), m_bytesPerRow(Row::BytesInRow(capacity, rank, maxRank)) { // Make sure capacity is properly rounded already. // TODO: fix. // LogAssertB(capacity == Row::DocumentsInRank0Row(capacity), // "capacity not evenly rounded."); // // Make sure offset of this RowTable is properly aligned. // LogAssertB((rowTableBufferOffset % c_rowTableByteAlignment) == 0); } RowTableDescriptor::RowTableDescriptor(RowTableDescriptor const & other) : m_capacity(other.m_capacity), m_rowCount(other.m_rowCount), m_rank(other.m_rank), m_maxRank(other.m_maxRank), m_bufferOffset(other.m_bufferOffset), m_bytesPerRow(other.m_bytesPerRow) { } void RowTableDescriptor::Initialize(void* sliceBuffer, ITermTable const & termTable) const { char* const rowTableBuffer = reinterpret_cast<char*>(sliceBuffer) + m_bufferOffset; memset(rowTableBuffer, 0, GetBufferSize(m_capacity, m_rowCount, m_rank, m_maxRank)); // The "match-all" row needs to be initialized differently. RowIdSequence rows(termTable.GetMatchAllTerm(), termTable); auto it = rows.begin(); if (it == rows.end()) { RecoverableError error("RowTableDescriptor::Initialize: expected at least one row."); throw error; } const RowId row = *it; ++it; if (it != rows.end()) { RecoverableError error("RowTableDescriptor::Initialize: expected no more than one row."); throw error; } if (row.GetRank() == m_rank) { // Fill up the match-all row with all ones. uint64_t * rowData = GetRowData(sliceBuffer, row.GetIndex()); memset(rowData, 0xFF, m_bytesPerRow); } } uint64_t RowTableDescriptor::GetBit(void* sliceBuffer, RowIndex rowIndex, DocIndex docIndex) const { uint64_t* const row = GetRowData(sliceBuffer, rowIndex); const size_t offset = QwordPositionFromDocIndex(docIndex); uint64_t bitPos = docIndex & 0x3F; #ifdef _MSC_VER return _bittest64(row + offset, bitPos); #else uint64_t bitMask = 1ull << bitPos; uint64_t maskedVal = *(row + offset) & bitMask; return maskedVal; #endif } void RowTableDescriptor::SetBit(void* sliceBuffer, RowIndex rowIndex, DocIndex docIndex) const { CHECK_LT(rowIndex, m_rowCount) << "rowIndex out of range."; uint64_t* const row = GetRowData(sliceBuffer, rowIndex); const size_t offset = QwordPositionFromDocIndex(docIndex); uint64_t bitPos = docIndex & 0x3F; #ifdef _MSC_VER _interlockedbittestandset64(row + offset, bitPos); #else uint64_t bitMask = 1ull << bitPos; uint64_t newVal = *(row + offset) | bitMask; *(row + offset) = newVal; #endif } void RowTableDescriptor::ClearBit(void* sliceBuffer, RowIndex rowIndex, DocIndex docIndex) const { uint64_t* const row = GetRowData(sliceBuffer, rowIndex); const size_t offset = QwordPositionFromDocIndex(docIndex); uint64_t bitPos = docIndex & 0x3F; #ifdef _MSC_VER _interlockedbittestandreset64(row + offset, bitPos); #else uint64_t bitMask = ~(1ull << bitPos); uint64_t newVal = *(row + offset) & bitMask; *(row + offset) = newVal; #endif } ptrdiff_t RowTableDescriptor::GetRowOffset(RowIndex rowIndex) const { // TODO: consider checking for overflow. return m_bufferOffset + static_cast<ptrdiff_t>(rowIndex * m_bytesPerRow); } /* static */ size_t RowTableDescriptor::GetBufferSize(DocIndex capacity, RowIndex rowCount, Rank rank, Rank maxRank) { // Make sure capacity is properly rounded already. // TODO: fix. // LogAssertB(capacity == Row::DocumentsInRank0Row(capacity), // "capacity not evenly rounded."); return static_cast<unsigned>( Row::BytesInRow(capacity, rank, maxRank) * rowCount); } uint64_t* RowTableDescriptor::GetRowData(void* sliceBuffer, RowIndex rowIndex) const { char* rowData = reinterpret_cast<char*>(sliceBuffer) + GetRowOffset(rowIndex); return reinterpret_cast<uint64_t*>(rowData); } size_t RowTableDescriptor::QwordPositionFromDocIndex(DocIndex docIndex) const { LogAssertB(docIndex < m_capacity, "docIndex out of range"); // Shifting by 6 gives the rank0Word. // Shifting by an additional m_rank gives the rankRWord. return docIndex >> (6 + m_rank); } size_t RowTableDescriptor::BitPositionFromDocIndex(DocIndex docIndex) const { LogAssertB(docIndex < m_capacity, "docIndex out of range"); size_t rank0Word = docIndex >> 6; size_t rankRWord = rank0Word >> m_rank; // TODO: check if compiler is smart enough to avoid doing a % here. size_t bitInWord = docIndex % 64; return (rankRWord << 6) + bitInWord; } } <|endoftext|>
<commit_before>// - Which Standard C++ library are we using? // NB: Can probably replace this with Boost's Predef system, though // requires Boost or a bcp import. // // For cross-compiling, *might* be able to use pragma/message to // generate output from the preprocessor, but this can be awkward. // Note the need to use stringization to expand other preprocessor // symbols: // // #define PPSTRINGIZE(x) PPSTRINGIZE2(x) // #define PPSTRINGIZE2(x) #x // // and that messaging facilities in the preprocessor change, e.g. // "warning", "pragma message" etc. Some, like "warning" in GCC, // don't expand their macro arguments either! // // // Copyright (c) 2014, Ben Morgan <bmorgan.warwick@gmail.com> // // Distributed under the OSI-approved BSD 3-Clause License (the "License"); // see accompanying file License.txt for details. // // This software is distributed WITHOUT ANY WARRANTY; without even the // implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. // See the License for more information. #include <iostream> int main() { #if defined(_LIBCPP_VERSION) std::cout << "libc++;" << _LIBCPP_VERSION; #elif defined(__GLIBCXX__) std::cout << "libstdc++;" << __GLIBCXX__; // - And so on for any others... #else return 1; #endif return 0; } <commit_msg>Report _MSC_VER as proxy for Microsoft Runtime (#11)<commit_after>// - Which Standard C++ library are we using? // NB: Can probably replace this with Boost's Predef system, though // requires Boost or a bcp import. // // For cross-compiling, *might* be able to use pragma/message to // generate output from the preprocessor, but this can be awkward. // Note the need to use stringization to expand other preprocessor // symbols: // // #define PPSTRINGIZE(x) PPSTRINGIZE2(x) // #define PPSTRINGIZE2(x) #x // // and that messaging facilities in the preprocessor change, e.g. // "warning", "pragma message" etc. Some, like "warning" in GCC, // don't expand their macro arguments either! // // // Copyright (c) 2014, Ben Morgan <bmorgan.warwick@gmail.com> // // Distributed under the OSI-approved BSD 3-Clause License (the "License"); // see accompanying file License.txt for details. // // This software is distributed WITHOUT ANY WARRANTY; without even the // implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. // See the License for more information. #include <iostream> int main() { #if defined(_LIBCPP_VERSION) std::cout << "libc++;" << _LIBCPP_VERSION; #elif defined(__GLIBCXX__) std::cout << "libstdc++;" << __GLIBCXX__; #elif defined(_MSC_VER) // Not *totally* clear yet this is the true runtime // lib version(s), but clear enough proxy for now // See also _MSVC_STL_VERSION and _MSVC_STL_UPDATE std::cout << "msvc;" << _MSC_VER; // - And so on for any others... #else return 1; #endif return 0; } <|endoftext|>
<commit_before>/* $Id$Revision: */ /* vim:set shiftwidth=4 ts=8: */ /************************************************************************* * Copyright (c) 2011 AT&T Intellectual Property * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: See CVS logs. Details at http://www.graphviz.org/ *************************************************************************/ #ifdef WIN32 #include "windows.h" #endif #include "csettings.h" #include "qmessagebox.h" #include "qfiledialog.h" #include <QtGui> #include <qfile.h> #include "mdichild.h" #include "string.h" #include "mainwindow.h" #include <QTemporaryFile> #define WIDGET(t,f) ((t*)findChild<t *>(#f)) typedef struct { const char *data; int len; int cur; } rdr_t; bool loadAttrs(const QString fileName, QComboBox * cbNameG, QComboBox * cbNameN, QComboBox * cbNameE) { QStringList lines; QFile file(fileName); if (file.open(QIODevice::ReadOnly)) { QTextStream stream(&file); QString line; while (!stream.atEnd()) { line = stream.readLine(); // line of text excluding '\n' if (line.left(1) == ":") { QString attrName; QStringList sl = line.split(":"); for (int id = 0; id < sl.count(); id++) { if (id == 1) attrName = sl[id]; if (id == 2) { if (sl[id].contains("G")) cbNameG->addItem(attrName); if (sl[id].contains("N")) cbNameN->addItem(attrName); if (sl[id].contains("E")) cbNameE->addItem(attrName); } }; } } file.close(); } else { errout << "Could not open attribute name file \"" << fileName << "\" for reading\n" << flush; } return false; } QString stripFileExtension(QString fileName) { int idx; for (idx = fileName.length(); idx >= 0; idx--) { if (fileName.mid(idx, 1) == ".") break; } return fileName.left(idx); } char *graph_reader(char *str, int num, FILE * stream) //helper function to load / parse graphs from tstring { if (num == 0) return str; const char *ptr; char *optr; char c; int l; rdr_t *s = (rdr_t *) stream; if (s->cur >= s->len) return NULL; l = 0; ptr = s->data + s->cur; optr = str; do { *optr++ = c = *ptr++; l++; } while (c && (c != '\n') && (l < num - 1)); *optr = '\0'; s->cur += l; return str; } CFrmSettings::CFrmSettings() { this->gvc = gvContext(); Ui_Dialog tempDia; tempDia.setupUi(this); graph = NULL; activeWindow = NULL; QString path; #ifndef WIN32 char *s = getenv("GVEDIT_PATH"); if (s) path = s; else path = GVEDIT_DATADIR; #endif connect(WIDGET(QPushButton, pbAdd), SIGNAL(clicked()), this, SLOT(addSlot())); connect(WIDGET(QPushButton, pbNew), SIGNAL(clicked()), this, SLOT(newSlot())); connect(WIDGET(QPushButton, pbOpen), SIGNAL(clicked()), this, SLOT(openSlot())); connect(WIDGET(QPushButton, pbSave), SIGNAL(clicked()), this, SLOT(saveSlot())); connect(WIDGET(QPushButton, btnOK), SIGNAL(clicked()), this, SLOT(okSlot())); connect(WIDGET(QPushButton, btnCancel), SIGNAL(clicked()), this, SLOT(cancelSlot())); connect(WIDGET(QPushButton, pbOut), SIGNAL(clicked()), this, SLOT(outputSlot())); connect(WIDGET(QPushButton, pbHelp), SIGNAL(clicked()), this, SLOT(helpSlot())); connect(WIDGET(QComboBox, cbScope), SIGNAL(currentIndexChanged(int)), this, SLOT(scopeChangedSlot(int))); scopeChangedSlot(0); #ifndef WIN32 loadAttrs(path + "/attrs.txt", WIDGET(QComboBox, cbNameG), WIDGET(QComboBox, cbNameN), WIDGET(QComboBox, cbNameE)); #else loadAttrs("../share/graphviz/gvedit/attributes.txt", WIDGET(QComboBox, cbNameG), WIDGET(QComboBox, cbNameN), WIDGET(QComboBox, cbNameE)); #endif setWindowIcon(QIcon(":/images/icon.png")); } void CFrmSettings::outputSlot() { QString _filter = "Output File(*." + WIDGET(QComboBox, cbExtension)->currentText() + ")"; QString fileName = QFileDialog::getSaveFileName(this, tr("Save Graph As.."), "/", _filter); if (!fileName.isEmpty()) WIDGET(QLineEdit, leOutput)->setText(fileName); } void CFrmSettings::scopeChangedSlot(int id) { WIDGET(QComboBox, cbNameG)->setVisible(id == 0); WIDGET(QComboBox, cbNameN)->setVisible(id == 1); WIDGET(QComboBox, cbNameE)->setVisible(id == 2); } void CFrmSettings::addSlot() { QString _scope = WIDGET(QComboBox, cbScope)->currentText(); QString _name; switch (WIDGET(QComboBox, cbScope)->currentIndex()) { case 0: _name = WIDGET(QComboBox, cbNameG)->currentText(); break; case 1: _name = WIDGET(QComboBox, cbNameN)->currentText(); break; case 2: _name = WIDGET(QComboBox, cbNameE)->currentText(); break; } QString _value = WIDGET(QLineEdit, leValue)->text(); if (_value.trimmed().length() == 0) QMessageBox::warning(this, tr("GvEdit"), tr ("Please enter a value for selected attribute!"), QMessageBox::Ok, QMessageBox::Ok); else { QString str = _scope + "[" + _name + "=\""; if (WIDGET(QTextEdit, teAttributes)->toPlainText().contains(str)) { QMessageBox::warning(this, tr("GvEdit"), tr("Attribute is already defined!"), QMessageBox::Ok, QMessageBox::Ok); return; } else { str = str + _value + "\"]"; WIDGET(QTextEdit, teAttributes)->setPlainText(WIDGET(QTextEdit, teAttributes)-> toPlainText() + str + "\n"); } } } void CFrmSettings::helpSlot() { QDesktopServices:: openUrl(QUrl("http://www.graphviz.org/doc/info/attrs.html")); } void CFrmSettings::cancelSlot() { this->reject(); } void CFrmSettings::okSlot() { saveContent(); this->done(drawGraph()); } void CFrmSettings::newSlot() { WIDGET(QTextEdit, teAttributes)->setPlainText(tr("")); } void CFrmSettings::openSlot() { QString fileName = QFileDialog::getOpenFileName(this, tr("Open File"), "/", tr("Text file (*.*)")); if (!fileName.isEmpty()) { QFile file(fileName); if (!file.open(QFile::ReadOnly | QFile::Text)) { QMessageBox::warning(this, tr("MDI"), tr("Cannot read file %1:\n%2.") .arg(fileName) .arg(file.errorString())); return; } QTextStream in(&file); WIDGET(QTextEdit, teAttributes)->setPlainText(in.readAll()); } } void CFrmSettings::saveSlot() { if (WIDGET(QTextEdit, teAttributes)->toPlainText().trimmed(). length() == 0) { QMessageBox::warning(this, tr("GvEdit"), tr("Nothing to save!"), QMessageBox::Ok, QMessageBox::Ok); return; } QString fileName = QFileDialog::getSaveFileName(this, tr("Open File"), "/", tr("Text File(*.*)")); if (!fileName.isEmpty()) { QFile file(fileName); if (!file.open(QFile::WriteOnly | QFile::Text)) { QMessageBox::warning(this, tr("MDI"), tr("Cannot write file %1:\n%2.") .arg(fileName) .arg(file.errorString())); return; } QTextStream out(&file); out << WIDGET(QTextEdit, teAttributes)->toPlainText(); return; } } bool CFrmSettings::loadGraph(MdiChild * m) { if (graph) agclose(graph); graphData.clear(); graphData.append(m->toPlainText()); setActiveWindow(m); return true; } bool CFrmSettings::createLayout() { rdr_t rdr; //first attach attributes to graph int _pos = graphData.indexOf(tr("{")); graphData.replace(_pos, 1, "{" + WIDGET(QTextEdit, teAttributes)->toPlainText()); /* Reset line number and file name; * If known, might want to use real name */ agsetfile("<gvedit>"); QByteArray bytes = graphData.toUtf8(); rdr.data = bytes.constData(); rdr.len = strlen(rdr.data); rdr.cur = 0; graph = agread_usergets((FILE *) & rdr, (gets_f) graph_reader); /* graph=agread_usergets(reinterpret_cast<FILE*>(this),(gets_f)graph_reader); */ if (!graph) return false; if (agerrors()) { agclose(graph); graph = NULL; return false; } Agraph_t *G = this->graph; QString layout; if(agfindattr(agprotonode(G), "pos")) layout="nop2"; else layout=WIDGET(QComboBox, cbLayout)->currentText(); gvLayout(gvc, G, (char *)layout.toUtf8().constData()); /* library function */ return true; } static QString buildTempFile() { QTemporaryFile tempFile; tempFile.setAutoRemove(false); tempFile.open(); QString a = tempFile.fileName(); tempFile.close(); return a; } void CFrmSettings::doPreview(QString fileName) { if (getActiveWindow()->previewFrm) { getActiveWindow()->parentFrm->mdiArea-> removeSubWindow(getActiveWindow()->previewFrm->subWindowRef); delete getActiveWindow()->previewFrm; getActiveWindow()->previewFrm = NULL; } if ((fileName.isNull()) || !(getActiveWindow()->loadPreview(fileName))) { //create preview QString prevFile(buildTempFile()); gvRenderFilename(gvc, graph, "png", (char *) prevFile.toUtf8().constData()); getActiveWindow()->loadPreview(prevFile); #if 0 if (!this->getActiveWindow()->loadPreview(prevFile)) QMessageBox::information(this, tr("GVEdit"), tr ("Preview file can not be opened.")); #endif } } bool CFrmSettings::renderLayout() { if (!graph) return false; QString sfx = WIDGET(QComboBox, cbExtension)->currentText(); if (sfx == QString("NONE")) doPreview(QString()); else { QString fileName(WIDGET(QLineEdit, leOutput)->text()); fileName = stripFileExtension(fileName); fileName = fileName + "." + sfx; if (fileName != activeWindow->outputFile) activeWindow->outputFile = fileName; if (gvRenderFilename (gvc, graph, (char *) sfx.toUtf8().constData(), (char *) fileName.toUtf8().constData())) return false; doPreview(fileName); } return true; } bool CFrmSettings::loadLayouts() { return false; } bool CFrmSettings::loadRenderers() { return false; } void CFrmSettings::refreshContent() { WIDGET(QComboBox, cbLayout)->setCurrentIndex(activeWindow->layoutIdx); WIDGET(QComboBox, cbExtension)->setCurrentIndex(activeWindow->renderIdx); if (!activeWindow->outputFile.isEmpty()) WIDGET(QLineEdit, leOutput)->setText(activeWindow->outputFile); else WIDGET(QLineEdit, leOutput)->setText(stripFileExtension(activeWindow-> currentFile()) + "." + WIDGET(QComboBox, cbExtension)->currentText()); WIDGET(QTextEdit, teAttributes)->setText(activeWindow->attributes); WIDGET(QLineEdit, leValue)->setText(""); } void CFrmSettings::saveContent() { activeWindow->layoutIdx = WIDGET(QComboBox, cbLayout)->currentIndex(); activeWindow->renderIdx = WIDGET(QComboBox, cbExtension)->currentIndex(); activeWindow->outputFile = WIDGET(QLineEdit, leOutput)->text(); activeWindow->attributes = WIDGET(QTextEdit, teAttributes)->toPlainText(); } int CFrmSettings::drawGraph() { int rc; if (createLayout() && renderLayout()) { getActiveWindow()->settingsSet = false; rc = QDialog::Accepted; } else rc = QDialog::Accepted; agreseterrors(); return rc; /* return QDialog::Rejected; */ } int CFrmSettings::runSettings(MdiChild * m) { if (this->loadGraph(m)) return drawGraph(); if ((m) && (m == getActiveWindow())) { if (this->loadGraph(m)) return drawGraph(); else return QDialog::Rejected; } else return showSettings(m); } int CFrmSettings::showSettings(MdiChild * m) { if (this->loadGraph(m)) { refreshContent(); return this->exec(); } else return QDialog::Rejected; } void CFrmSettings::setActiveWindow(MdiChild * m) { this->activeWindow = m; } MdiChild *CFrmSettings::getActiveWindow() { return activeWindow; } <commit_msg>Fix bug 2120<commit_after>/* $Id$Revision: */ /* vim:set shiftwidth=4 ts=8: */ /************************************************************************* * Copyright (c) 2011 AT&T Intellectual Property * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: See CVS logs. Details at http://www.graphviz.org/ *************************************************************************/ #ifdef WIN32 #include "windows.h" #endif #include "csettings.h" #include "qmessagebox.h" #include "qfiledialog.h" #include <QtGui> #include <qfile.h> #include "mdichild.h" #include "string.h" #include "mainwindow.h" #include <QTemporaryFile> #define WIDGET(t,f) ((t*)findChild<t *>(#f)) typedef struct { const char *data; int len; int cur; } rdr_t; bool loadAttrs(const QString fileName, QComboBox * cbNameG, QComboBox * cbNameN, QComboBox * cbNameE) { QStringList lines; QFile file(fileName); if (file.open(QIODevice::ReadOnly)) { QTextStream stream(&file); QString line; while (!stream.atEnd()) { line = stream.readLine(); // line of text excluding '\n' if (line.left(1) == ":") { QString attrName; QStringList sl = line.split(":"); for (int id = 0; id < sl.count(); id++) { if (id == 1) attrName = sl[id]; if (id == 2) { if (sl[id].contains("G")) cbNameG->addItem(attrName); if (sl[id].contains("N")) cbNameN->addItem(attrName); if (sl[id].contains("E")) cbNameE->addItem(attrName); } }; } } file.close(); } else { errout << "Could not open attribute name file \"" << fileName << "\" for reading\n" << flush; } return false; } QString stripFileExtension(QString fileName) { int idx; for (idx = fileName.length(); idx >= 0; idx--) { if (fileName.mid(idx, 1) == ".") break; } return fileName.left(idx); } char *graph_reader(char *str, int num, FILE * stream) //helper function to load / parse graphs from tstring { if (num == 0) return str; const char *ptr; char *optr; char c; int l; rdr_t *s = (rdr_t *) stream; if (s->cur >= s->len) return NULL; l = 0; ptr = s->data + s->cur; optr = str; do { *optr++ = c = *ptr++; l++; } while (c && (c != '\n') && (l < num - 1)); *optr = '\0'; s->cur += l; return str; } CFrmSettings::CFrmSettings() { this->gvc = gvContext(); Ui_Dialog tempDia; tempDia.setupUi(this); graph = NULL; activeWindow = NULL; QString path; #ifndef WIN32 char *s = getenv("GVEDIT_PATH"); if (s) path = s; else path = GVEDIT_DATADIR; #endif connect(WIDGET(QPushButton, pbAdd), SIGNAL(clicked()), this, SLOT(addSlot())); connect(WIDGET(QPushButton, pbNew), SIGNAL(clicked()), this, SLOT(newSlot())); connect(WIDGET(QPushButton, pbOpen), SIGNAL(clicked()), this, SLOT(openSlot())); connect(WIDGET(QPushButton, pbSave), SIGNAL(clicked()), this, SLOT(saveSlot())); connect(WIDGET(QPushButton, btnOK), SIGNAL(clicked()), this, SLOT(okSlot())); connect(WIDGET(QPushButton, btnCancel), SIGNAL(clicked()), this, SLOT(cancelSlot())); connect(WIDGET(QPushButton, pbOut), SIGNAL(clicked()), this, SLOT(outputSlot())); connect(WIDGET(QPushButton, pbHelp), SIGNAL(clicked()), this, SLOT(helpSlot())); connect(WIDGET(QComboBox, cbScope), SIGNAL(currentIndexChanged(int)), this, SLOT(scopeChangedSlot(int))); scopeChangedSlot(0); #ifndef WIN32 loadAttrs(path + "/attrs.txt", WIDGET(QComboBox, cbNameG), WIDGET(QComboBox, cbNameN), WIDGET(QComboBox, cbNameE)); #else loadAttrs("../share/graphviz/gvedit/attributes.txt", WIDGET(QComboBox, cbNameG), WIDGET(QComboBox, cbNameN), WIDGET(QComboBox, cbNameE)); #endif setWindowIcon(QIcon(":/images/icon.png")); } void CFrmSettings::outputSlot() { QString _filter = "Output File(*." + WIDGET(QComboBox, cbExtension)->currentText() + ")"; QString fileName = QFileDialog::getSaveFileName(this, tr("Save Graph As.."), "/", _filter); if (!fileName.isEmpty()) WIDGET(QLineEdit, leOutput)->setText(fileName); } void CFrmSettings::scopeChangedSlot(int id) { WIDGET(QComboBox, cbNameG)->setVisible(id == 0); WIDGET(QComboBox, cbNameN)->setVisible(id == 1); WIDGET(QComboBox, cbNameE)->setVisible(id == 2); } void CFrmSettings::addSlot() { QString _scope = WIDGET(QComboBox, cbScope)->currentText(); QString _name; switch (WIDGET(QComboBox, cbScope)->currentIndex()) { case 0: _name = WIDGET(QComboBox, cbNameG)->currentText(); break; case 1: _name = WIDGET(QComboBox, cbNameN)->currentText(); break; case 2: _name = WIDGET(QComboBox, cbNameE)->currentText(); break; } QString _value = WIDGET(QLineEdit, leValue)->text(); if (_value.trimmed().length() == 0) QMessageBox::warning(this, tr("GvEdit"), tr ("Please enter a value for selected attribute!"), QMessageBox::Ok, QMessageBox::Ok); else { QString str = _scope + "[" + _name + "=\""; if (WIDGET(QTextEdit, teAttributes)->toPlainText().contains(str)) { QMessageBox::warning(this, tr("GvEdit"), tr("Attribute is already defined!"), QMessageBox::Ok, QMessageBox::Ok); return; } else { str = str + _value + "\"]"; WIDGET(QTextEdit, teAttributes)->setPlainText(WIDGET(QTextEdit, teAttributes)-> toPlainText() + str + "\n"); } } } void CFrmSettings::helpSlot() { QDesktopServices:: openUrl(QUrl("http://www.graphviz.org/doc/info/attrs.html")); } void CFrmSettings::cancelSlot() { this->reject(); } void CFrmSettings::okSlot() { saveContent(); this->done(drawGraph()); } void CFrmSettings::newSlot() { WIDGET(QTextEdit, teAttributes)->setPlainText(tr("")); } void CFrmSettings::openSlot() { QString fileName = QFileDialog::getOpenFileName(this, tr("Open File"), "/", tr("Text file (*.*)")); if (!fileName.isEmpty()) { QFile file(fileName); if (!file.open(QFile::ReadOnly | QFile::Text)) { QMessageBox::warning(this, tr("MDI"), tr("Cannot read file %1:\n%2.") .arg(fileName) .arg(file.errorString())); return; } QTextStream in(&file); WIDGET(QTextEdit, teAttributes)->setPlainText(in.readAll()); } } void CFrmSettings::saveSlot() { if (WIDGET(QTextEdit, teAttributes)->toPlainText().trimmed(). length() == 0) { QMessageBox::warning(this, tr("GvEdit"), tr("Nothing to save!"), QMessageBox::Ok, QMessageBox::Ok); return; } QString fileName = QFileDialog::getSaveFileName(this, tr("Open File"), "/", tr("Text File(*.*)")); if (!fileName.isEmpty()) { QFile file(fileName); if (!file.open(QFile::WriteOnly | QFile::Text)) { QMessageBox::warning(this, tr("MDI"), tr("Cannot write file %1:\n%2.") .arg(fileName) .arg(file.errorString())); return; } QTextStream out(&file); out << WIDGET(QTextEdit, teAttributes)->toPlainText(); return; } } bool CFrmSettings::loadGraph(MdiChild * m) { if (graph) agclose(graph); graphData.clear(); graphData.append(m->toPlainText()); setActiveWindow(m); return true; } bool CFrmSettings::createLayout() { rdr_t rdr; //first attach attributes to graph int _pos = graphData.indexOf(tr("{")); graphData.replace(_pos, 1, "{" + WIDGET(QTextEdit, teAttributes)->toPlainText()); /* Reset line number and file name; * If known, might want to use real name */ agsetfile("<gvedit>"); QByteArray bytes = graphData.toUtf8(); rdr.data = bytes.constData(); rdr.len = strlen(rdr.data); rdr.cur = 0; graph = agread_usergets((FILE *) & rdr, (gets_f) graph_reader); /* graph=agread_usergets(reinterpret_cast<FILE*>(this),(gets_f)graph_reader); */ if (!graph) return false; if (agerrors()) { agclose(graph); graph = NULL; return false; } Agraph_t *G = this->graph; QString layout; if(agfindattr(agprotonode(G), "pos")) layout="nop2"; else layout=WIDGET(QComboBox, cbLayout)->currentText(); gvLayout(gvc, G, (char *)layout.toUtf8().constData()); /* library function */ return true; } static QString buildTempFile() { QTemporaryFile tempFile; tempFile.setAutoRemove(false); tempFile.open(); QString a = tempFile.fileName(); tempFile.close(); return a; } void CFrmSettings::doPreview(QString fileName) { if (getActiveWindow()->previewFrm) { getActiveWindow()->parentFrm->mdiArea-> removeSubWindow(getActiveWindow()->previewFrm->subWindowRef); delete getActiveWindow()->previewFrm; getActiveWindow()->previewFrm = NULL; } if ((fileName.isNull()) || !(getActiveWindow()->loadPreview(fileName))) { //create preview QString prevFile(buildTempFile()); gvRenderFilename(gvc, graph, "png", (char *) prevFile.toUtf8().constData()); getActiveWindow()->loadPreview(prevFile); #if 0 if (!this->getActiveWindow()->loadPreview(prevFile)) QMessageBox::information(this, tr("GVEdit"), tr ("Preview file can not be opened.")); #endif } } bool CFrmSettings::renderLayout() { if (!graph) return false; QString sfx = WIDGET(QComboBox, cbExtension)->currentText(); QString fileName(WIDGET(QLineEdit, leOutput)->text()); if ((fileName == QString("")) || (sfx == QString("NONE"))) doPreview(QString()); else { fileName = stripFileExtension(fileName); fileName = fileName + "." + sfx; if (fileName != activeWindow->outputFile) activeWindow->outputFile = fileName; if (gvRenderFilename (gvc, graph, (char *) sfx.toUtf8().constData(), (char *) fileName.toUtf8().constData())) return false; doPreview(fileName); } return true; } bool CFrmSettings::loadLayouts() { return false; } bool CFrmSettings::loadRenderers() { return false; } void CFrmSettings::refreshContent() { WIDGET(QComboBox, cbLayout)->setCurrentIndex(activeWindow->layoutIdx); WIDGET(QComboBox, cbExtension)->setCurrentIndex(activeWindow->renderIdx); if (!activeWindow->outputFile.isEmpty()) WIDGET(QLineEdit, leOutput)->setText(activeWindow->outputFile); else WIDGET(QLineEdit, leOutput)->setText(stripFileExtension(activeWindow-> currentFile()) + "." + WIDGET(QComboBox, cbExtension)->currentText()); WIDGET(QTextEdit, teAttributes)->setText(activeWindow->attributes); WIDGET(QLineEdit, leValue)->setText(""); } void CFrmSettings::saveContent() { activeWindow->layoutIdx = WIDGET(QComboBox, cbLayout)->currentIndex(); activeWindow->renderIdx = WIDGET(QComboBox, cbExtension)->currentIndex(); activeWindow->outputFile = WIDGET(QLineEdit, leOutput)->text(); activeWindow->attributes = WIDGET(QTextEdit, teAttributes)->toPlainText(); } int CFrmSettings::drawGraph() { int rc; if (createLayout() && renderLayout()) { getActiveWindow()->settingsSet = false; rc = QDialog::Accepted; } else rc = QDialog::Accepted; agreseterrors(); return rc; /* return QDialog::Rejected; */ } int CFrmSettings::runSettings(MdiChild * m) { if (this->loadGraph(m)) return drawGraph(); if ((m) && (m == getActiveWindow())) { if (this->loadGraph(m)) return drawGraph(); else return QDialog::Rejected; } else return showSettings(m); } int CFrmSettings::showSettings(MdiChild * m) { if (this->loadGraph(m)) { refreshContent(); return this->exec(); } else return QDialog::Rejected; } void CFrmSettings::setActiveWindow(MdiChild * m) { this->activeWindow = m; } MdiChild *CFrmSettings::getActiveWindow() { return activeWindow; } <|endoftext|>
<commit_before>//===--- RawSyntax.cpp - Swift Raw Syntax Implementation ------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// #include "swift/Basic/ColorUtils.h" #include "swift/Syntax/RawSyntax.h" #include "swift/Syntax/SyntaxArena.h" #include "llvm/Support/Casting.h" #include "llvm/Support/raw_ostream.h" #include <algorithm> using llvm::dyn_cast; using namespace swift; using namespace swift::syntax; namespace { static bool isTrivialSyntaxKind(SyntaxKind Kind) { if (isUnknownKind(Kind)) return true; if (isCollectionKind(Kind)) return true; switch(Kind) { case SyntaxKind::SourceFile: case SyntaxKind::CodeBlockItem: case SyntaxKind::ExpressionStmt: case SyntaxKind::DeclarationStmt: return true; default: return false; } } static void printSyntaxKind(SyntaxKind Kind, llvm::raw_ostream &OS, SyntaxPrintOptions Opts, bool Open) { std::unique_ptr<swift::OSColor> Color; if (Opts.Visual) { Color.reset(new swift::OSColor(OS, llvm::raw_ostream::GREEN)); } OS << "<"; if (!Open) OS << "/"; dumpSyntaxKind(OS, Kind); OS << ">"; } static void dumpTokenKind(llvm::raw_ostream &OS, tok Kind) { switch (Kind) { #define TOKEN(X) \ case tok::X: \ OS << #X; \ break; #include "swift/Syntax/TokenKinds.def" case tok::NUM_TOKENS: OS << "NUM_TOKENS (unset)"; break; } } } // end of anonymous namespace RawSyntax::RawSyntax(SyntaxKind Kind, ArrayRef<RC<RawSyntax>> Layout, SourcePresence Presence, bool ManualMemory) { assert(Kind != SyntaxKind::Token && "'token' syntax node must be constructed with dedicated constructor"); Bits.Kind = unsigned(Kind); Bits.Presence = unsigned(Presence); Bits.ManualMemory = unsigned(ManualMemory); Bits.NumChildren = Layout.size(); // Compute the text length Bits.TextLength = 0; for (const auto ChildNode : Layout) { if (ChildNode) { Bits.TextLength += ChildNode->getTextLength(); } } // Initialize layout data. std::uninitialized_copy(Layout.begin(), Layout.end(), getTrailingObjects<RC<RawSyntax>>()); } RawSyntax::RawSyntax(tok TokKind, OwnedString Text, ArrayRef<TriviaPiece> LeadingTrivia, ArrayRef<TriviaPiece> TrailingTrivia, SourcePresence Presence, bool ManualMemory) { Bits.Kind = unsigned(SyntaxKind::Token); Bits.Presence = unsigned(Presence); Bits.ManualMemory = unsigned(ManualMemory); Bits.TokenKind = unsigned(TokKind); Bits.NumLeadingTrivia = LeadingTrivia.size(); Bits.NumTrailingTrivia = TrailingTrivia.size(); // Initialize token text. ::new (static_cast<void *>(getTrailingObjects<OwnedString>())) OwnedString(Text); // Initialize leading trivia. std::uninitialized_copy(LeadingTrivia.begin(), LeadingTrivia.end(), getTrailingObjects<TriviaPiece>()); // Initialize trailing trivia. std::uninitialized_copy(TrailingTrivia.begin(), TrailingTrivia.end(), getTrailingObjects<TriviaPiece>() + Bits.NumLeadingTrivia); } RawSyntax::~RawSyntax() { if (isToken()) { getTrailingObjects<OwnedString>()->~OwnedString(); for (auto &trivia : getLeadingTrivia()) trivia.~TriviaPiece(); for (auto &trivia : getTrailingTrivia()) trivia.~TriviaPiece(); } else { for (auto &child : getLayout()) child.~RC<RawSyntax>(); } } RC<RawSyntax> RawSyntax::make(SyntaxKind Kind, ArrayRef<RC<RawSyntax>> Layout, SourcePresence Presence, SyntaxArena *Arena) { auto size = totalSizeToAlloc<RC<RawSyntax>, OwnedString, TriviaPiece>( Layout.size(), 0, 0); void *data = Arena ? Arena->AllocateRawSyntax(size, alignof(RawSyntax)) : ::operator new(size); return RC<RawSyntax>(new (data) RawSyntax(Kind, Layout, Presence, bool(Arena))); } RC<RawSyntax> RawSyntax::make(tok TokKind, OwnedString Text, ArrayRef<TriviaPiece> LeadingTrivia, ArrayRef<TriviaPiece> TrailingTrivia, SourcePresence Presence, SyntaxArena *Arena) { auto size = totalSizeToAlloc<RC<RawSyntax>, OwnedString, TriviaPiece>( 0, 1, LeadingTrivia.size() + TrailingTrivia.size()); void *data = Arena ? Arena->AllocateRawSyntax(size, alignof(RawSyntax)) : ::operator new(size); return RC<RawSyntax>(new (data) RawSyntax( TokKind, Text, LeadingTrivia, TrailingTrivia, Presence, bool(Arena))); } RC<RawSyntax> RawSyntax::append(RC<RawSyntax> NewLayoutElement) const { auto Layout = getLayout(); std::vector<RC<RawSyntax>> NewLayout; NewLayout.reserve(Layout.size() + 1); std::copy(Layout.begin(), Layout.end(), std::back_inserter(NewLayout)); NewLayout.push_back(NewLayoutElement); return RawSyntax::make(getKind(), NewLayout, SourcePresence::Present); } RC<RawSyntax> RawSyntax::replaceChild(CursorIndex Index, RC<RawSyntax> NewLayoutElement) const { auto Layout = getLayout(); std::vector<RC<RawSyntax>> NewLayout; NewLayout.reserve(Layout.size()); std::copy(Layout.begin(), Layout.begin() + Index, std::back_inserter(NewLayout)); NewLayout.push_back(NewLayoutElement); std::copy(Layout.begin() + Index + 1, Layout.end(), std::back_inserter(NewLayout)); return RawSyntax::make(getKind(), NewLayout, getPresence()); } llvm::Optional<AbsolutePosition> RawSyntax::accumulateAbsolutePosition(AbsolutePosition &Pos) const { llvm::Optional<AbsolutePosition> Ret; if (isToken()) { if (isMissing()) return None; for (auto &Leader : getLeadingTrivia()) Leader.accumulateAbsolutePosition(Pos); Ret = Pos; Pos.addText(getTokenText()); for (auto &Trailer : getTrailingTrivia()) Trailer.accumulateAbsolutePosition(Pos); } else { for (auto &Child : getLayout()) { if (!Child) continue; auto Result = Child->accumulateAbsolutePosition(Pos); if (!Ret && Result) Ret = Result; } } return Ret; } bool RawSyntax::accumulateLeadingTrivia(AbsolutePosition &Pos) const { if (isToken()) { if (!isMissing()) { for (auto &Leader: getLeadingTrivia()) Leader.accumulateAbsolutePosition(Pos); return true; } } else { for (auto &Child: getLayout()) { if (!Child) continue; if (Child->accumulateLeadingTrivia(Pos)) return true; } } return false; } void RawSyntax::print(llvm::raw_ostream &OS, SyntaxPrintOptions Opts) const { if (isMissing()) return; if (isToken()) { for (const auto &Leader : getLeadingTrivia()) Leader.print(OS); OS << getTokenText(); for (const auto &Trailer : getTrailingTrivia()) Trailer.print(OS); } else { auto Kind = getKind(); const bool PrintKind = Opts.PrintSyntaxKind && (Opts.PrintTrivialNodeKind || !isTrivialSyntaxKind(Kind)); if (PrintKind) printSyntaxKind(Kind, OS, Opts, true); for (const auto &LE : getLayout()) if (LE) LE->print(OS, Opts); if (PrintKind) printSyntaxKind(Kind, OS, Opts, false); } } void RawSyntax::dump() const { dump(llvm::errs(), /*Indent*/ 0); } void RawSyntax::dump(llvm::raw_ostream &OS, unsigned Indent) const { auto indent = [&](unsigned Amount) { for (decltype(Amount) i = 0; i < Amount; ++i) { OS << ' '; } }; indent(Indent); OS << '('; dumpSyntaxKind(OS, getKind()); if (isMissing()) OS << " [missing] "; if (isToken()) { OS << " "; dumpTokenKind(OS, getTokenKind()); for (auto &Leader : getLeadingTrivia()) { OS << "\n"; Leader.dump(OS, Indent + 1); } OS << "\n"; indent(Indent + 1); OS << "(text=\""; OS.write_escaped(getTokenText(), /*UseHexEscapes=*/true); OS << "\")"; for (auto &Trailer : getTrailingTrivia()) { OS << "\n"; Trailer.dump(OS, Indent + 1); } } else { for (auto &Child : getLayout()) { if (!Child) continue; OS << "\n"; Child->dump(OS, Indent + 1); } } OS << ')'; } void AbsolutePosition::printLineAndColumn(llvm::raw_ostream &OS) const { OS << getLine() << ':' << getColumn(); } void AbsolutePosition::dump(llvm::raw_ostream &OS) const { OS << "(absolute_position "; OS << "offset=" << getOffset() << " "; OS << "line=" << getLine() << " "; OS << "column=" << getColumn(); OS << ')'; } void RawSyntax::Profile(llvm::FoldingSetNodeID &ID, tok TokKind, OwnedString Text, ArrayRef<TriviaPiece> LeadingTrivia, ArrayRef<TriviaPiece> TrailingTrivia) { ID.AddInteger(unsigned(TokKind)); switch (TokKind) { #define TOKEN_DEFAULT(NAME) case tok::NAME: #define PUNCTUATOR(NAME, X) TOKEN_DEFAULT(NAME) #define KEYWORD(KW) TOKEN_DEFAULT(kw_##KW) #define POUND_KEYWORD(KW) TOKEN_DEFAULT(pound_##KW) #include "swift/Syntax/TokenKinds.def" break; default: ID.AddString(Text.str()); break; } for (auto &Piece : LeadingTrivia) Piece.Profile(ID); for (auto &Piece : TrailingTrivia) Piece.Profile(ID); } <commit_msg>[incrParse] Fix lexer offset issue when missing tokens get synthesized<commit_after>//===--- RawSyntax.cpp - Swift Raw Syntax Implementation ------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// #include "swift/Basic/ColorUtils.h" #include "swift/Syntax/RawSyntax.h" #include "swift/Syntax/SyntaxArena.h" #include "llvm/Support/Casting.h" #include "llvm/Support/raw_ostream.h" #include <algorithm> using llvm::dyn_cast; using namespace swift; using namespace swift::syntax; namespace { static bool isTrivialSyntaxKind(SyntaxKind Kind) { if (isUnknownKind(Kind)) return true; if (isCollectionKind(Kind)) return true; switch(Kind) { case SyntaxKind::SourceFile: case SyntaxKind::CodeBlockItem: case SyntaxKind::ExpressionStmt: case SyntaxKind::DeclarationStmt: return true; default: return false; } } static void printSyntaxKind(SyntaxKind Kind, llvm::raw_ostream &OS, SyntaxPrintOptions Opts, bool Open) { std::unique_ptr<swift::OSColor> Color; if (Opts.Visual) { Color.reset(new swift::OSColor(OS, llvm::raw_ostream::GREEN)); } OS << "<"; if (!Open) OS << "/"; dumpSyntaxKind(OS, Kind); OS << ">"; } static void dumpTokenKind(llvm::raw_ostream &OS, tok Kind) { switch (Kind) { #define TOKEN(X) \ case tok::X: \ OS << #X; \ break; #include "swift/Syntax/TokenKinds.def" case tok::NUM_TOKENS: OS << "NUM_TOKENS (unset)"; break; } } } // end of anonymous namespace RawSyntax::RawSyntax(SyntaxKind Kind, ArrayRef<RC<RawSyntax>> Layout, SourcePresence Presence, bool ManualMemory) { assert(Kind != SyntaxKind::Token && "'token' syntax node must be constructed with dedicated constructor"); Bits.Kind = unsigned(Kind); Bits.Presence = unsigned(Presence); Bits.ManualMemory = unsigned(ManualMemory); Bits.NumChildren = Layout.size(); // Compute the text length Bits.TextLength = 0; for (const auto ChildNode : Layout) { if (ChildNode && !ChildNode->isMissing()) { Bits.TextLength += ChildNode->getTextLength(); } } // Initialize layout data. std::uninitialized_copy(Layout.begin(), Layout.end(), getTrailingObjects<RC<RawSyntax>>()); } RawSyntax::RawSyntax(tok TokKind, OwnedString Text, ArrayRef<TriviaPiece> LeadingTrivia, ArrayRef<TriviaPiece> TrailingTrivia, SourcePresence Presence, bool ManualMemory) { Bits.Kind = unsigned(SyntaxKind::Token); Bits.Presence = unsigned(Presence); Bits.ManualMemory = unsigned(ManualMemory); Bits.TokenKind = unsigned(TokKind); Bits.NumLeadingTrivia = LeadingTrivia.size(); Bits.NumTrailingTrivia = TrailingTrivia.size(); // Initialize token text. ::new (static_cast<void *>(getTrailingObjects<OwnedString>())) OwnedString(Text); // Initialize leading trivia. std::uninitialized_copy(LeadingTrivia.begin(), LeadingTrivia.end(), getTrailingObjects<TriviaPiece>()); // Initialize trailing trivia. std::uninitialized_copy(TrailingTrivia.begin(), TrailingTrivia.end(), getTrailingObjects<TriviaPiece>() + Bits.NumLeadingTrivia); } RawSyntax::~RawSyntax() { if (isToken()) { getTrailingObjects<OwnedString>()->~OwnedString(); for (auto &trivia : getLeadingTrivia()) trivia.~TriviaPiece(); for (auto &trivia : getTrailingTrivia()) trivia.~TriviaPiece(); } else { for (auto &child : getLayout()) child.~RC<RawSyntax>(); } } RC<RawSyntax> RawSyntax::make(SyntaxKind Kind, ArrayRef<RC<RawSyntax>> Layout, SourcePresence Presence, SyntaxArena *Arena) { auto size = totalSizeToAlloc<RC<RawSyntax>, OwnedString, TriviaPiece>( Layout.size(), 0, 0); void *data = Arena ? Arena->AllocateRawSyntax(size, alignof(RawSyntax)) : ::operator new(size); return RC<RawSyntax>(new (data) RawSyntax(Kind, Layout, Presence, bool(Arena))); } RC<RawSyntax> RawSyntax::make(tok TokKind, OwnedString Text, ArrayRef<TriviaPiece> LeadingTrivia, ArrayRef<TriviaPiece> TrailingTrivia, SourcePresence Presence, SyntaxArena *Arena) { auto size = totalSizeToAlloc<RC<RawSyntax>, OwnedString, TriviaPiece>( 0, 1, LeadingTrivia.size() + TrailingTrivia.size()); void *data = Arena ? Arena->AllocateRawSyntax(size, alignof(RawSyntax)) : ::operator new(size); return RC<RawSyntax>(new (data) RawSyntax( TokKind, Text, LeadingTrivia, TrailingTrivia, Presence, bool(Arena))); } RC<RawSyntax> RawSyntax::append(RC<RawSyntax> NewLayoutElement) const { auto Layout = getLayout(); std::vector<RC<RawSyntax>> NewLayout; NewLayout.reserve(Layout.size() + 1); std::copy(Layout.begin(), Layout.end(), std::back_inserter(NewLayout)); NewLayout.push_back(NewLayoutElement); return RawSyntax::make(getKind(), NewLayout, SourcePresence::Present); } RC<RawSyntax> RawSyntax::replaceChild(CursorIndex Index, RC<RawSyntax> NewLayoutElement) const { auto Layout = getLayout(); std::vector<RC<RawSyntax>> NewLayout; NewLayout.reserve(Layout.size()); std::copy(Layout.begin(), Layout.begin() + Index, std::back_inserter(NewLayout)); NewLayout.push_back(NewLayoutElement); std::copy(Layout.begin() + Index + 1, Layout.end(), std::back_inserter(NewLayout)); return RawSyntax::make(getKind(), NewLayout, getPresence()); } llvm::Optional<AbsolutePosition> RawSyntax::accumulateAbsolutePosition(AbsolutePosition &Pos) const { llvm::Optional<AbsolutePosition> Ret; if (isToken()) { if (isMissing()) return None; for (auto &Leader : getLeadingTrivia()) Leader.accumulateAbsolutePosition(Pos); Ret = Pos; Pos.addText(getTokenText()); for (auto &Trailer : getTrailingTrivia()) Trailer.accumulateAbsolutePosition(Pos); } else { for (auto &Child : getLayout()) { if (!Child) continue; auto Result = Child->accumulateAbsolutePosition(Pos); if (!Ret && Result) Ret = Result; } } return Ret; } bool RawSyntax::accumulateLeadingTrivia(AbsolutePosition &Pos) const { if (isToken()) { if (!isMissing()) { for (auto &Leader: getLeadingTrivia()) Leader.accumulateAbsolutePosition(Pos); return true; } } else { for (auto &Child: getLayout()) { if (!Child) continue; if (Child->accumulateLeadingTrivia(Pos)) return true; } } return false; } void RawSyntax::print(llvm::raw_ostream &OS, SyntaxPrintOptions Opts) const { if (isMissing()) return; if (isToken()) { for (const auto &Leader : getLeadingTrivia()) Leader.print(OS); OS << getTokenText(); for (const auto &Trailer : getTrailingTrivia()) Trailer.print(OS); } else { auto Kind = getKind(); const bool PrintKind = Opts.PrintSyntaxKind && (Opts.PrintTrivialNodeKind || !isTrivialSyntaxKind(Kind)); if (PrintKind) printSyntaxKind(Kind, OS, Opts, true); for (const auto &LE : getLayout()) if (LE) LE->print(OS, Opts); if (PrintKind) printSyntaxKind(Kind, OS, Opts, false); } } void RawSyntax::dump() const { dump(llvm::errs(), /*Indent*/ 0); } void RawSyntax::dump(llvm::raw_ostream &OS, unsigned Indent) const { auto indent = [&](unsigned Amount) { for (decltype(Amount) i = 0; i < Amount; ++i) { OS << ' '; } }; indent(Indent); OS << '('; dumpSyntaxKind(OS, getKind()); if (isMissing()) OS << " [missing] "; if (isToken()) { OS << " "; dumpTokenKind(OS, getTokenKind()); for (auto &Leader : getLeadingTrivia()) { OS << "\n"; Leader.dump(OS, Indent + 1); } OS << "\n"; indent(Indent + 1); OS << "(text=\""; OS.write_escaped(getTokenText(), /*UseHexEscapes=*/true); OS << "\")"; for (auto &Trailer : getTrailingTrivia()) { OS << "\n"; Trailer.dump(OS, Indent + 1); } } else { for (auto &Child : getLayout()) { if (!Child) continue; OS << "\n"; Child->dump(OS, Indent + 1); } } OS << ')'; } void AbsolutePosition::printLineAndColumn(llvm::raw_ostream &OS) const { OS << getLine() << ':' << getColumn(); } void AbsolutePosition::dump(llvm::raw_ostream &OS) const { OS << "(absolute_position "; OS << "offset=" << getOffset() << " "; OS << "line=" << getLine() << " "; OS << "column=" << getColumn(); OS << ')'; } void RawSyntax::Profile(llvm::FoldingSetNodeID &ID, tok TokKind, OwnedString Text, ArrayRef<TriviaPiece> LeadingTrivia, ArrayRef<TriviaPiece> TrailingTrivia) { ID.AddInteger(unsigned(TokKind)); switch (TokKind) { #define TOKEN_DEFAULT(NAME) case tok::NAME: #define PUNCTUATOR(NAME, X) TOKEN_DEFAULT(NAME) #define KEYWORD(KW) TOKEN_DEFAULT(kw_##KW) #define POUND_KEYWORD(KW) TOKEN_DEFAULT(pound_##KW) #include "swift/Syntax/TokenKinds.def" break; default: ID.AddString(Text.str()); break; } for (auto &Piece : LeadingTrivia) Piece.Profile(ID); for (auto &Piece : TrailingTrivia) Piece.Profile(ID); } <|endoftext|>
<commit_before>/** * Copyright 2016 by LRR-TUM * Jens Breitbart <j.breitbart@tum.de> * Josef Weidendorfer <weidendo@in.tum.de> * * Licensed under GNU Lesser General Public License 2.1 or later. * Some rights reserved. See LICENSE */ #include "distgen/distgen.h" #include "distgen/distgen_internal.h" #define _GNU_SOURCE //#define __USE_GNU #include <cassert> #include <cstdio> #include <cstdlib> #include <sched.h> #include <sys/syscall.h> #include <sys/types.h> #include <unistd.h> #include <omp.h> #include "ponci/ponci.hpp" // TODO We currently allocate the buffers once, should we change this? // GByte/s measured for i cores is stored in [i-1] static double distgen_mem_bw_results[DISTGEN_MAXTHREADS]; // the configuration of the system static distgend_initT system_config; // Prototypes static void set_affinity(distgend_initT init); static double bench(distgend_configT config); void distgend_init(distgend_initT init) { assert(init.number_of_threads < DISTGEN_MAXTHREADS); assert(init.NUMA_domains < init.number_of_threads); assert((init.number_of_threads % init.NUMA_domains) == 0); assert(init.number_of_threads % (init.NUMA_domains * init.SMT_factor) == 0); system_config = init; // we currently measure maximum read bandwidth pseudoRandom = 0; depChain = 0; doWrite = 0; // number of iterations. currently a magic number iter = 1000; // set a size of 50 MB // TODO we should compute this based on L3 size addDist(50000000); // set the number of threads to the maximum available in the system tcount = init.number_of_threads; omp_set_num_threads(tcount); set_affinity(init); initBufs(); // fill distgen_mem_bw_results distgend_configT config; for (unsigned char i = 0; i < init.number_of_threads / init.NUMA_domains; ++i) { config.number_of_threads = i + 1; config.threads_to_use[i] = i; distgen_mem_bw_results[i] = bench(config); } } double distgend_get_max_bandwidth(distgend_configT config) { assert(config.number_of_threads > 0); const size_t phys_cores_per_numa = system_config.number_of_threads / (system_config.NUMA_domains * system_config.SMT_factor); double res = 0.0; size_t cores_per_numa_domain[DISTGEN_MAXTHREADS]; for (size_t i = 0; i < system_config.NUMA_domains; ++i) cores_per_numa_domain[i] = 0; // for every NUMA domain we use // -> count the cores used // TODO how to handle multiple HTs for one core? for (size_t i = 0; i < config.number_of_threads; ++i) { size_t t = config.threads_to_use[i]; size_t n = (t / phys_cores_per_numa) % system_config.NUMA_domains; ++cores_per_numa_domain[n]; } for (size_t i = 0; i < system_config.NUMA_domains; ++i) { size_t temp = cores_per_numa_domain[i]; if (temp > 0) res += distgen_mem_bw_results[temp - 1]; } return res; } double distgend_is_membound(distgend_configT config) { // run benchmark on given cores // compare the result with distgend_get_max_bandwidth(); const double m = bench(config); const double c = distgend_get_max_bandwidth(config); const double res = m / c; return (res > 1.0) ? 1.0 : res; } ////////////////////////////////////////////////////////////////////////////////////////////////// // INTERNAL FUNCTIONS ////////////////////////////////////////////////////////////////////////////////////////////////// static double bench(distgend_configT config) { double ret = 0.0; #pragma omp parallel reduction(+ : ret) { size_t tid = (size_t)omp_get_thread_num(); for (size_t i = 0; i < config.number_of_threads; ++i) { if (tid == config.threads_to_use[i]) { double tsum = 0.0; u64 taCount = 0; const double t1 = wtime(); runBench(buffer[omp_get_thread_num()], iter, depChain, doWrite, &tsum, &taCount); const double t2 = wtime(); const double temp = taCount * 64.0 / 1024.0 / 1024.0 / 1024.0; ret += temp / (t2 - t1); } } } return ret; } static void set_affinity(distgend_initT init) { cgroup_create(DISTGEN_CGROUP_NAME); size_t *arr = (size_t *)malloc(sizeof(size_t) * init.number_of_threads); const size_t phys_cores_per_numa = init.number_of_threads / (init.NUMA_domains * init.SMT_factor); size_t i = 0; for (size_t n = 0; n < init.NUMA_domains; ++n) { size_t next_core = n * phys_cores_per_numa; for (size_t s = 0; s < init.SMT_factor; ++s) { for (size_t c = 0; c < phys_cores_per_numa; ++c) { arr[i] = next_core; ++next_core; ++i; } next_core += phys_cores_per_numa * (init.NUMA_domains - 1); } } assert(i == init.number_of_threads); cgroup_set_cpus(DISTGEN_CGROUP_NAME, arr, init.number_of_threads); for (size_t n = 0; n < init.NUMA_domains; ++n) arr[n] = n; cgroup_set_mems(DISTGEN_CGROUP_NAME, arr, init.NUMA_domains); cgroup_add_me(DISTGEN_CGROUP_NAME); } <commit_msg>Fixed an issue when calling distgend_init and distgend_is_membound from different threads.<commit_after>/** * Copyright 2016 by LRR-TUM * Jens Breitbart <j.breitbart@tum.de> * Josef Weidendorfer <weidendo@in.tum.de> * * Licensed under GNU Lesser General Public License 2.1 or later. * Some rights reserved. See LICENSE */ #include "distgen/distgen.h" #include "distgen/distgen_internal.h" #define _GNU_SOURCE //#define __USE_GNU #include <cassert> #include <cstdio> #include <cstdlib> #include <sched.h> #include <sys/syscall.h> #include <sys/types.h> #include <unistd.h> #include <omp.h> #include "ponci/ponci.hpp" // TODO We currently allocate the buffers once, should we change this? // GByte/s measured for i cores is stored in [i-1] static double distgen_mem_bw_results[DISTGEN_MAXTHREADS]; // the configuration of the system static distgend_initT system_config; // Prototypes static void set_affinity(distgend_initT init); static double bench(distgend_configT config); void distgend_init(distgend_initT init) { assert(init.number_of_threads < DISTGEN_MAXTHREADS); assert(init.NUMA_domains < init.number_of_threads); assert((init.number_of_threads % init.NUMA_domains) == 0); assert(init.number_of_threads % (init.NUMA_domains * init.SMT_factor) == 0); system_config = init; // we currently measure maximum read bandwidth pseudoRandom = 0; depChain = 0; doWrite = 0; // number of iterations. currently a magic number iter = 1000; // set a size of 50 MB // TODO we should compute this based on L3 size addDist(50000000); // set the number of threads to the maximum available in the system tcount = init.number_of_threads; omp_set_num_threads(tcount); set_affinity(init); initBufs(); // fill distgen_mem_bw_results distgend_configT config; for (unsigned char i = 0; i < init.number_of_threads / init.NUMA_domains; ++i) { config.number_of_threads = i + 1; config.threads_to_use[i] = i; distgen_mem_bw_results[i] = bench(config); } } double distgend_get_max_bandwidth(distgend_configT config) { assert(config.number_of_threads > 0); const size_t phys_cores_per_numa = system_config.number_of_threads / (system_config.NUMA_domains * system_config.SMT_factor); double res = 0.0; size_t cores_per_numa_domain[DISTGEN_MAXTHREADS]; for (size_t i = 0; i < system_config.NUMA_domains; ++i) cores_per_numa_domain[i] = 0; // for every NUMA domain we use // -> count the cores used // TODO how to handle multiple HTs for one core? for (size_t i = 0; i < config.number_of_threads; ++i) { size_t t = config.threads_to_use[i]; size_t n = (t / phys_cores_per_numa) % system_config.NUMA_domains; ++cores_per_numa_domain[n]; } for (size_t i = 0; i < system_config.NUMA_domains; ++i) { size_t temp = cores_per_numa_domain[i]; if (temp > 0) res += distgen_mem_bw_results[temp - 1]; } return res; } double distgend_is_membound(distgend_configT config) { // run benchmark on given cores // compare the result with distgend_get_max_bandwidth(); const double m = bench(config); const double c = distgend_get_max_bandwidth(config); const double res = m / c; return (res > 1.0) ? 1.0 : res; } ////////////////////////////////////////////////////////////////////////////////////////////////// // INTERNAL FUNCTIONS ////////////////////////////////////////////////////////////////////////////////////////////////// static double bench(distgend_configT config) { double ret = 0.0; omp_set_num_threads(system_config.number_of_threads); #pragma omp parallel reduction(+ : ret) { size_t tid = (size_t)omp_get_thread_num(); for (size_t i = 0; i < config.number_of_threads; ++i) { if (tid == config.threads_to_use[i]) { double tsum = 0.0; u64 taCount = 0; const double t1 = wtime(); runBench(buffer[omp_get_thread_num()], iter, depChain, doWrite, &tsum, &taCount); const double t2 = wtime(); const double temp = taCount * 64.0 / 1024.0 / 1024.0 / 1024.0; ret += temp / (t2 - t1); } } } return ret; } static void set_affinity(distgend_initT init) { cgroup_create(DISTGEN_CGROUP_NAME); size_t *arr = (size_t *)malloc(sizeof(size_t) * init.number_of_threads); const size_t phys_cores_per_numa = init.number_of_threads / (init.NUMA_domains * init.SMT_factor); size_t i = 0; for (size_t n = 0; n < init.NUMA_domains; ++n) { size_t next_core = n * phys_cores_per_numa; for (size_t s = 0; s < init.SMT_factor; ++s) { for (size_t c = 0; c < phys_cores_per_numa; ++c) { arr[i] = next_core; ++next_core; ++i; } next_core += phys_cores_per_numa * (init.NUMA_domains - 1); } } assert(i == init.number_of_threads); cgroup_set_cpus(DISTGEN_CGROUP_NAME, arr, init.number_of_threads); for (size_t n = 0; n < init.NUMA_domains; ++n) arr[n] = n; cgroup_set_mems(DISTGEN_CGROUP_NAME, arr, init.NUMA_domains); cgroup_add_me(DISTGEN_CGROUP_NAME); free(arr); } <|endoftext|>
<commit_before>// Copyright (c) 2016 ASMlover. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright // notice, this list ofconditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in // the documentation and/or other materialsprovided with the // distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. #include <memory> #include <vector> #include <Chaos/Unittest/TestHarness.h> namespace Chaos { struct HarnessContext { const char* base; const char* name; void (*closure)(void); HarnessContext(const char* b, const char* n, void (*fn)(void)) : base(b) , name(n) , closure(fn) { } }; typedef std::vector<HarnessContext> HarnessContextVector; HarnessContextVector* g_tests; // must be raw pointer for darwin (unique_ptr is invalid) bool register_testharness(const char* base, const char* name, void (*closure)(void)) { if (nullptr == g_tests) g_tests = new HarnessContextVector; g_tests->push_back(HarnessContext(base, name, closure)); return true; } int run_all_testharness(void) { int total_tests = 0; int passed_tests = 0; if (nullptr != g_tests && !g_tests->empty()) { total_tests = static_cast<int>(g_tests->size()); for (auto& hc : *g_tests) { hc.closure(); ++passed_tests; } delete g_tests; } ColorIO::fprintf(stdout, ColorIO::ColorType::COLORTYPE_GREEN, "========== PASSED (%d/%d) test harness\n", passed_tests, total_tests); return 0; } } <commit_msg>:art: chore(testharness): updated the test harness passed output prompt<commit_after>// Copyright (c) 2016 ASMlover. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright // notice, this list ofconditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in // the documentation and/or other materialsprovided with the // distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. #include <memory> #include <vector> #include <Chaos/Unittest/TestHarness.h> namespace Chaos { struct HarnessContext { const char* base; const char* name; void (*closure)(void); HarnessContext(const char* b, const char* n, void (*fn)(void)) : base(b) , name(n) , closure(fn) { } }; typedef std::vector<HarnessContext> HarnessContextVector; HarnessContextVector* g_tests; // must be raw pointer for darwin (unique_ptr is invalid) bool register_testharness(const char* base, const char* name, void (*closure)(void)) { if (nullptr == g_tests) g_tests = new HarnessContextVector; g_tests->push_back(HarnessContext(base, name, closure)); return true; } int run_all_testharness(void) { int total_tests = 0; int passed_tests = 0; if (nullptr != g_tests && !g_tests->empty()) { total_tests = static_cast<int>(g_tests->size()); for (auto& hc : *g_tests) { hc.closure(); ++passed_tests; ColorIO::fprintf(stdout, ColorIO::ColorType::COLORTYPE_GREEN, "********** [%s] test harness PASSED (%d/%d) **********\n", hc.name, passed_tests, total_tests); } delete g_tests; } ColorIO::fprintf(stdout, ColorIO::ColorType::COLORTYPE_GREEN, "========== PASSED (%d/%d) test harness ==========\n", passed_tests, total_tests); return 0; } } <|endoftext|>