text
stringlengths
54
60.6k
<commit_before>/** * @file support.hh * @author Miroslav Cibulka * @created 12/5/15 * @copyright Copyright (c) 2015 XXX * @detail * */ #pragma once #include "../src/state.hh" #include "../src/cell.hh" #include "../src/cellular_automata.hh" #include <iostream> #include <ctime> /** * @brief this example state recalculates each tick average from * surrounding states */ struct ExampleState : public State<unsigned> { typedef State<unsigned> _BaseC; virtual _BaseC &operator<<(const State &another_state) { new_value += another_state.getValue(); ++count; return *this; } virtual _BaseC::value_type getValue() const { return value; } virtual void setValue(_BaseC::value_type _value) { value = _value; } virtual void renew() { if (count != 0) value = new_value / count; } private: _BaseC::value_type new_value = 0; _BaseC::value_type count = 0; _BaseC::value_type value = 0; }; typedef Cell <4, ExampleState> cellT; typedef AliveCell <4, ExampleState> alive_cellT; #define MAP_SIZE 100 class VanNeumannCAutomata : public CellularAutomata2D<MAP_SIZE, MAP_SIZE, ExampleState, alive_cellT> { public: typedef CellularAutomata2D<MAP_SIZE, MAP_SIZE, ExampleState, alive_cellT> _BaseT; /** * if chance is out of bounds then exception is called */ VanNeumannCAutomata(float p) : _BaseT(), chance(p) { if (p < 0 || p > 1) throw ::std::runtime_error( std::string("{class VanNeumannCAutomata} parameter 'p' means ") + "chance <=> <0, 1>!\nbut I've got '" + ::std::to_string(p) + "'"); // init randomizer ::std::srand((unsigned)::std::time(0)); for (_BaseT::cell_type *&ptr : this->map) ptr->getState().setValue((unsigned)(rand() * p)); for (size_t x = 0; x < height; ++x) for (size_t y = 0; y < width; ++y) { auto _cell = map[x * width + y]; if (x < height - 1) _cell->setNeighbour(0, map[(x + 1) * width + y]); if (x > 0) _cell->setNeighbour(1, map[(x - 1) * width + y]); if (y < width - 1) _cell->setNeighbour(2, map[x * width + y + 1]); if (y > 0) _cell->setNeighbour(3, map[x * width + y - 1]); } } private: float chance; }; <commit_msg>missing include in support.h<commit_after>/** * @file support.hh * @author Miroslav Cibulka * @created 12/5/15 * @copyright Copyright (c) 2015 XXX * @detail * */ #pragma once #include "../src/state.hh" #include "../src/cell.hh" #include "../src/cellular_automata.hh" #include <iostream> #include <ctime> #include <stdexcept> /** * @brief this example state recalculates each tick average from * surrounding states */ struct ExampleState : public State<unsigned> { typedef State<unsigned> _BaseC; virtual _BaseC &operator<<(const State &another_state) { new_value += another_state.getValue(); ++count; return *this; } virtual _BaseC::value_type getValue() const { return value; } virtual void setValue(_BaseC::value_type _value) { value = _value; } virtual void renew() { if (count != 0) value = new_value / count; } private: _BaseC::value_type new_value = 0; _BaseC::value_type count = 0; _BaseC::value_type value = 0; }; typedef Cell <4, ExampleState> cellT; typedef AliveCell <4, ExampleState> alive_cellT; #define MAP_SIZE 100 class VanNeumannCAutomata : public CellularAutomata2D<MAP_SIZE, MAP_SIZE, ExampleState, alive_cellT> { public: typedef CellularAutomata2D<MAP_SIZE, MAP_SIZE, ExampleState, alive_cellT> _BaseT; /** * if chance is out of bounds then exception is called */ VanNeumannCAutomata(float p) : _BaseT(), chance(p) { if (p < 0 || p > 1) throw ::std::runtime_error( std::string("{class VanNeumannCAutomata} parameter 'p' means ") + "chance <=> <0, 1>!\nbut I've got '" + ::std::to_string(p) + "'"); // init randomizer ::std::srand((unsigned)::std::time(0)); for (_BaseT::cell_type *&ptr : this->map) ptr->getState().setValue((unsigned)(rand() * p)); for (size_t x = 0; x < height; ++x) for (size_t y = 0; y < width; ++y) { auto _cell = map[x * width + y]; if (x < height - 1) _cell->setNeighbour(0, map[(x + 1) * width + y]); if (x > 0) _cell->setNeighbour(1, map[(x - 1) * width + y]); if (y < width - 1) _cell->setNeighbour(2, map[x * width + y + 1]); if (y > 0) _cell->setNeighbour(3, map[x * width + y - 1]); } } private: float chance; }; <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: uiborder.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: rt $ $Date: 2004-08-23 08:56:07 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifdef SW_DLLIMPLEMENTATION #undef SW_DLLIMPLEMENTATION #endif #pragma hdrstop //CHINA001 #ifndef _SVX_BORDER_HXX //autogen //CHINA001 #include <svx/border.hxx> //CHINA001 #endif #include <svx/svxdlg.hxx> //CHINA001 #include <svx/svxids.hrc> //CHINA001 #include <svx/dialogs.hrc> //CHINA001 #include <svtools/itemset.hxx> //CHINA001 #include <svx/flagsdef.hxx> //CHINA001 #include <sfx2/tabdlg.hxx> //CHINA001 #ifndef _SFXINTITEM_HXX //CHINA001 #include <svtools/intitem.hxx> //CHINA001 #endif //CHINA001 #include "swtypes.hxx" #include "uiborder.hxx" #include "frmui.hrc" SwBorderDlg::SwBorderDlg(Window* pParent, SfxItemSet& rSet, USHORT nType) : SfxSingleTabDialog(pParent, rSet, 0) { SetText(SW_RESSTR(STR_FRMUI_BORDER)); // TabPage erzeugen //CHINA001 SvxBorderTabPage* pPage = (SvxBorderTabPage*) SvxBorderTabPage::Create(this, rSet); //CHINA001 pPage->SetSWMode(nType); //CHINA001 if(SW_BORDER_MODE_TABLE == nType) //CHINA001 pPage->HideShadowControls(); //CHINA001 SetTabPage(pPage); SfxAbstractDialogFactory* pFact = SfxAbstractDialogFactory::Create(); DBG_ASSERT(pFact, "Dialogdiet fail!");//CHINA001 ::CreateTabPage fnCreatePage = pFact->GetTabPageCreatorFunc( RID_SVXPAGE_BORDER ); if ( fnCreatePage ) { SfxTabPage* pPage = (*fnCreatePage)( this, rSet ); SfxAllItemSet aSet(*(rSet.GetPool())); aSet.Put (SfxUInt16Item(SID_SWMODE_TYPE,nType)); if(SW_BORDER_MODE_TABLE == nType) aSet.Put (SfxUInt32Item(SID_FLAG_TYPE,SVX_HIDESHADOWCTL)); pPage->PageCreated(aSet); SetTabPage(pPage); } } SwBorderDlg::~SwBorderDlg() { } <commit_msg>INTEGRATION: CWS ooo19126 (1.5.596); FILE MERGED 2005/09/05 13:44:51 rt 1.5.596.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: uiborder.cxx,v $ * * $Revision: 1.6 $ * * last change: $Author: rt $ $Date: 2005-09-09 07:54:29 $ * * 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 * ************************************************************************/ #ifdef SW_DLLIMPLEMENTATION #undef SW_DLLIMPLEMENTATION #endif #pragma hdrstop //CHINA001 #ifndef _SVX_BORDER_HXX //autogen //CHINA001 #include <svx/border.hxx> //CHINA001 #endif #include <svx/svxdlg.hxx> //CHINA001 #include <svx/svxids.hrc> //CHINA001 #include <svx/dialogs.hrc> //CHINA001 #include <svtools/itemset.hxx> //CHINA001 #include <svx/flagsdef.hxx> //CHINA001 #include <sfx2/tabdlg.hxx> //CHINA001 #ifndef _SFXINTITEM_HXX //CHINA001 #include <svtools/intitem.hxx> //CHINA001 #endif //CHINA001 #include "swtypes.hxx" #include "uiborder.hxx" #include "frmui.hrc" SwBorderDlg::SwBorderDlg(Window* pParent, SfxItemSet& rSet, USHORT nType) : SfxSingleTabDialog(pParent, rSet, 0) { SetText(SW_RESSTR(STR_FRMUI_BORDER)); // TabPage erzeugen //CHINA001 SvxBorderTabPage* pPage = (SvxBorderTabPage*) SvxBorderTabPage::Create(this, rSet); //CHINA001 pPage->SetSWMode(nType); //CHINA001 if(SW_BORDER_MODE_TABLE == nType) //CHINA001 pPage->HideShadowControls(); //CHINA001 SetTabPage(pPage); SfxAbstractDialogFactory* pFact = SfxAbstractDialogFactory::Create(); DBG_ASSERT(pFact, "Dialogdiet fail!");//CHINA001 ::CreateTabPage fnCreatePage = pFact->GetTabPageCreatorFunc( RID_SVXPAGE_BORDER ); if ( fnCreatePage ) { SfxTabPage* pPage = (*fnCreatePage)( this, rSet ); SfxAllItemSet aSet(*(rSet.GetPool())); aSet.Put (SfxUInt16Item(SID_SWMODE_TYPE,nType)); if(SW_BORDER_MODE_TABLE == nType) aSet.Put (SfxUInt32Item(SID_FLAG_TYPE,SVX_HIDESHADOWCTL)); pPage->PageCreated(aSet); SetTabPage(pPage); } } SwBorderDlg::~SwBorderDlg() { } <|endoftext|>
<commit_before>#include <iostream> #include <pthread.h> #include <Python.h> #include "character.h" using namespace std; static int error(const std::string & message){ std::cout << message << std::endl; return -1; } pthread_mutex_t quitMutex = PTHREAD_MUTEX_INITIALIZER; bool globalQuit = false; pthread_mutex_t stateChangedMutex = PTHREAD_MUTEX_INITIALIZER; bool stateChanged = false; pthread_mutex_t stateMutex = PTHREAD_MUTEX_INITIALIZER; int stateNumber = 0; pthread_mutex_t listMutex = PTHREAD_MUTEX_INITIALIZER; bool listStates = false; void * handleCharacter (void * arg){ const char * module = (const char *)arg; try { Character * character = new Character(module); bool quit = false; while(!quit){ character->act(); pthread_mutex_lock(&quitMutex); if (globalQuit){ quit = true; } pthread_mutex_unlock(&quitMutex); pthread_mutex_lock(&stateChangedMutex); if (stateChanged){ pthread_mutex_lock(&stateMutex); character->changeState(stateNumber); pthread_mutex_unlock(&stateMutex); stateChanged = false; } pthread_mutex_unlock(&stateChangedMutex); pthread_mutex_lock(&listMutex); if (listStates){ character->listStates(); listStates = false; } pthread_mutex_unlock(&listMutex); } delete character; } catch (const PyException & ex){ error("Problem with module! Reason: " + ex.getReason()); } pthread_mutex_lock(&quitMutex); globalQuit = true; pthread_mutex_unlock(&quitMutex); } int main(int argc, char ** argv){ if (argc > 1){ Py_Initialize(); /* NOTE need to make sure we are trying to load in the same directory (is there a work around?) */ PyRun_SimpleString("import sys"); PyRun_SimpleString("sys.path.append('./')"); std::cout << "Type 'quit' or 'exit' to quit." << std::endl; std::cout << "To change to state zero type 'zero'." << std::endl; std::cout << "To list all states type 'list'." << std::endl; pthread_t characterThread; int ret = pthread_create(&characterThread, NULL, handleCharacter, (void *)argv[1]); bool quit = false; while (!quit){ std::string keys; std::cout << "Enter state number: "; std::cin >> keys; if (ret == -1){ quit = true; } pthread_mutex_lock(&quitMutex); if (globalQuit){ std::cout << "Killed!" << std::endl; quit = true; } pthread_mutex_unlock(&quitMutex); if (keys == "quit" || keys == "exit" || keys == "q"){ quit = true; pthread_mutex_lock(&quitMutex); globalQuit = true; pthread_mutex_unlock(&quitMutex); std::cout << "Shutting Down." << std::endl; } else if (keys == "zero"){ pthread_mutex_lock(&stateChangedMutex); stateChanged = true; pthread_mutex_lock(&stateMutex); stateNumber = 0; pthread_mutex_unlock(&stateMutex); pthread_mutex_unlock(&stateChangedMutex); } else if (keys == "list"){ pthread_mutex_lock(&listMutex); listStates = true; pthread_mutex_unlock(&listMutex); } else { int number = atoi(keys.c_str()); if (number != 0){ pthread_mutex_lock(&stateChangedMutex); stateChanged = true; pthread_mutex_lock(&stateMutex); stateNumber = number; pthread_mutex_unlock(&stateMutex); pthread_mutex_unlock(&stateChangedMutex); } } std::cin.clear(); } pthread_join(characterThread, NULL); Py_Finalize(); return 0; } std::cout << "Usage: ./test character_module_name" << std::endl; return 0; } <commit_msg>Restart character if it crashes instead of quitting.<commit_after>#include <iostream> #include <pthread.h> #include <Python.h> #include "character.h" using namespace std; static int error(const std::string & message){ std::cout << message << std::endl; return -1; } static void lock(pthread_mutex_t & mutex){ pthread_mutex_lock(&mutex); } static void unlock(pthread_mutex_t & mutex){ pthread_mutex_unlock(&mutex); } pthread_mutex_t quitMutex = PTHREAD_MUTEX_INITIALIZER; bool globalQuit = false; pthread_mutex_t stateChangedMutex = PTHREAD_MUTEX_INITIALIZER; bool stateChanged = false; pthread_mutex_t stateMutex = PTHREAD_MUTEX_INITIALIZER; int stateNumber = 0; pthread_mutex_t listMutex = PTHREAD_MUTEX_INITIALIZER; bool listStates = false; void * handleCharacter (void * arg){ const char * module = (const char *)arg; Py_Initialize(); /* NOTE need to make sure we are trying to load in the same directory (is there a work around?) */ PyRun_SimpleString("import sys"); PyRun_SimpleString("sys.path.append('./')"); try { Character * character = new Character(module); bool quit = false; while(!quit){ character->act(); lock(quitMutex); if (globalQuit){ quit = true; } unlock(quitMutex); lock(stateChangedMutex); if (stateChanged){ lock(stateMutex); character->changeState(stateNumber); unlock(stateMutex); stateChanged = false; } unlock(stateChangedMutex); lock(listMutex); if (listStates){ character->listStates(); listStates = false; } unlock(listMutex); } delete character; } catch (const PyException & ex){ error("Problem with module! Reason: " + ex.getReason()); unlock(stateMutex); unlock(stateChangedMutex); } Py_Finalize(); lock(quitMutex); globalQuit = true; unlock(quitMutex); } int main(int argc, char ** argv){ if (argc > 1){ std::cout << "Type 'quit' or 'exit' to quit." << std::endl; std::cout << "To change to state zero type 'zero'." << std::endl; std::cout << "To list all states type 'list'." << std::endl; pthread_t characterThread; int ret = pthread_create(&characterThread, NULL, handleCharacter, (void *)argv[1]); bool quit = false; while (!quit){ std::string keys; std::cout << "Enter state number: "; std::cin >> keys; lock(quitMutex); if (globalQuit){ globalQuit = false; lock(stateChangedMutex); stateChanged = false; unlock(stateChangedMutex); lock(listMutex); listStates = false; unlock(listMutex); std::cout << "Character crashed or had a problem! Restarting..." << std::endl; ret = pthread_create(&characterThread, NULL, handleCharacter, (void *)argv[1]); keys.clear(); std::cin.clear(); } unlock(quitMutex); if (ret == -1){ quit = true; } if (keys == "quit" || keys == "exit" || keys == "q"){ quit = true; lock(quitMutex); globalQuit = true; unlock(quitMutex); std::cout << "Shutting Down." << std::endl; } else if (keys == "help" || keys == "?"){ std::cout << "'quit', 'exit', 'q' to exit" << std::endl; std::cout << "'list', to print available states" << std::endl; std::cout << "'zero', to change to state zero" << std::endl; } else if (keys == "zero"){ lock(stateChangedMutex); stateChanged = true; lock(stateMutex); stateNumber = 0; unlock(stateMutex); unlock(stateChangedMutex); } else if (keys == "list"){ lock(listMutex); listStates = true; unlock(listMutex); } else { int number = atoi(keys.c_str()); if (number != 0){ lock(stateChangedMutex); stateChanged = true; lock(stateMutex); stateNumber = number; unlock(stateMutex); unlock(stateChangedMutex); } } std::cin.clear(); } pthread_join(characterThread, NULL); return 0; } std::cout << "Usage: ./test character_module_name" << std::endl; return 0; } <|endoftext|>
<commit_before>// // MFM.cpp // Clock Signal // // Created by Thomas Harte on 18/09/2016. // Copyright © 2016 Thomas Harte. All rights reserved. // #include "MFM.hpp" #import "../PCMTrack.hpp" #import "../../../NumberTheory/CRC.hpp" using namespace Storage::Encodings::MFM; template <class T> class Shifter { public: virtual void add_byte(uint8_t input) = 0; virtual void add_index_address_mark() = 0; virtual void add_ID_address_mark() = 0; virtual void add_data_address_mark() = 0; virtual void add_deleted_data_address_mark() = 0; protected: // override me! void output_short(uint16_t value); }; template <class T> class MFMShifter: public Shifter<T> { public: void add_byte(uint8_t input) { uint16_t spread_value = (uint16_t)( ((input & 0x01) << 0) | ((input & 0x02) << 1) | ((input & 0x04) << 2) | ((input & 0x08) << 3) | ((input & 0x10) << 4) | ((input & 0x20) << 5) | ((input & 0x40) << 6) | ((input & 0x80) << 7) ); uint16_t or_bits = (uint16_t)((spread_value << 1) | (spread_value >> 1) | (output_ << 15)); output_ = spread_value | ((~or_bits) & 0xaaaa); static_cast<T *>(this)->output_short(output_); } void add_index_address_mark() { static_cast<T *>(this)->output_short(output_ = 0x5224); add_byte(0xfc); } void add_ID_address_mark() { static_cast<T *>(this)->output_short(output_ = 0x4489); add_byte(0xfe); } void add_data_address_mark() { static_cast<T *>(this)->output_short(output_ = 0x4489); add_byte(0xfb); } void add_deleted_data_address_mark() { static_cast<T *>(this)->output_short(output_ = 0x4489); add_byte(0xf8); } private: uint16_t output_; }; template <class T> class FMShifter: public Shifter<T> { public: void add_byte(uint8_t input) { static_cast<T *>(this)->output_short( (uint16_t)( ((input & 0x01) << 1) | ((input & 0x02) << 2) | ((input & 0x04) << 3) | ((input & 0x08) << 4) | ((input & 0x10) << 5) | ((input & 0x20) << 6) | ((input & 0x40) << 7) | ((input & 0x80) << 8) | 0x5555 )); } void add_index_address_mark() { // data 0xfc, with clock 0xd7 => 1111 1100 with clock 1101 0111 => 1111 1011 1011 0101 static_cast<T *>(this)->output_short(0xfbb5); } void add_ID_address_mark() { // data 0xfe, with clock 0xc7 => 1111 1110 with clock 1100 0111 => 1111 1010 1011 1101 static_cast<T *>(this)->output_short(0xfabd); } void add_data_address_mark() { // data 0xfb, with clock 0xc7 => 1111 1011 with clock 1100 0111 => 1111 1010 1001 1111 static_cast<T *>(this)->output_short(0xfa9f); } void add_deleted_data_address_mark() { // data 0xf8, with clock 0xc7 => 1111 1000 with clock 1100 0111 => 1111 1010 1001 0101 static_cast<T *>(this)->output_short(0xfa95); } }; static uint8_t logarithmic_size_for_size(size_t size) { switch(size) { default: return 0; case 256: return 1; case 512: return 2; case 1024: return 3; case 2048: return 4; case 4196: return 5; } } template<class T> std::shared_ptr<Storage::Disk::Track> GetTrackWithSectors( const std::vector<Sector> &sectors, size_t post_index_address_mark_bytes, uint8_t post_index_address_mark_value, size_t pre_address_mark_bytes, size_t post_address_mark_bytes, size_t pre_data_mark_bytes, size_t post_data_bytes, size_t inter_sector_gap) { T shifter; NumberTheory::CRC16 crc_generator(0x1021, 0xffff); // output the index mark shifter.add_index_address_mark(); // add the post-index mark for(int c = 0; c < post_index_address_mark_bytes; c++) shifter.add_byte(post_index_address_mark_value); // add sectors for(const Sector &sector : sectors) { // gap for(int c = 0; c < pre_address_mark_bytes; c++) shifter.add_byte(0x00); // sector header shifter.add_ID_address_mark(); shifter.add_byte(sector.track); shifter.add_byte(sector.side); shifter.add_byte(sector.sector); uint8_t size = logarithmic_size_for_size(sector.data.size()); shifter.add_byte(size); // header CRC crc_generator.reset(); crc_generator.add(sector.track); crc_generator.add(sector.side); crc_generator.add(sector.sector); crc_generator.add(size); uint16_t crc_value = crc_generator.get_value(); shifter.add_byte(crc_value & 0xff); shifter.add_byte(crc_value >> 8); // gap for(int c = 0; c < post_address_mark_bytes; c++) shifter.add_byte(0x4e); for(int c = 0; c < pre_data_mark_bytes; c++) shifter.add_byte(0x00); // data shifter.add_data_address_mark(); crc_generator.reset(); for(size_t c = 0; c < sector.data.size(); c++) { shifter.add_byte(sector.data[c]); crc_generator.add(sector.data[c]); } // data CRC crc_value = crc_generator.get_value(); shifter.add_byte(crc_value & 0xff); shifter.add_byte(crc_value >> 8); // gap for(int c = 0; c < post_data_bytes; c++) shifter.add_byte(0x00); for(int c = 0; c < inter_sector_gap; c++) shifter.add_byte(0x4e); } // TODO: total size check Storage::Disk::PCMSegment segment; return std::shared_ptr<Storage::Disk::Track>(new Storage::Disk::PCMTrack(std::move(segment))); } struct VectorReceiver { void output_short(uint16_t value) { data.push_back(value & 0xff); data.push_back(value >> 8); } std::vector<uint8_t> data; }; std::shared_ptr<Storage::Disk::Track> Storage::Encodings::MFM::GetFMTrackWithSectors(const std::vector<Sector> &sectors) { struct VectorShifter: public FMShifter<VectorShifter>, VectorReceiver { using VectorReceiver::output_short; }; return GetTrackWithSectors<VectorShifter>( sectors, 16, 0x00, 6, 0, 17, 14, 0); } std::shared_ptr<Storage::Disk::Track> Storage::Encodings::MFM::GetMFMTrackWithSectors(const std::vector<Sector> &sectors) { struct VectorShifter: public MFMShifter<VectorShifter>, VectorReceiver { using VectorReceiver::output_short; }; return GetTrackWithSectors<VectorShifter>( sectors, 50, 0x4e, 12, 22, 12, 18, 32); } <commit_msg>Adapted pervasively to MSB-first output. Which seems to be correct.<commit_after>// // MFM.cpp // Clock Signal // // Created by Thomas Harte on 18/09/2016. // Copyright © 2016 Thomas Harte. All rights reserved. // #include "MFM.hpp" #import "../PCMTrack.hpp" #import "../../../NumberTheory/CRC.hpp" using namespace Storage::Encodings::MFM; template <class T> class Shifter { public: virtual void add_byte(uint8_t input) = 0; virtual void add_index_address_mark() = 0; virtual void add_ID_address_mark() = 0; virtual void add_data_address_mark() = 0; virtual void add_deleted_data_address_mark() = 0; protected: /*! Intended to be overridden by subclasses; should write value out as PCM data, MSB first. */ void output_short(uint16_t value); }; template <class T> class MFMShifter: public Shifter<T> { public: void add_byte(uint8_t input) { uint16_t spread_value = (uint16_t)( ((input & 0x01) << 0) | ((input & 0x02) << 1) | ((input & 0x04) << 2) | ((input & 0x08) << 3) | ((input & 0x10) << 4) | ((input & 0x20) << 5) | ((input & 0x40) << 6) | ((input & 0x80) << 7) ); uint16_t or_bits = (uint16_t)((spread_value << 1) | (spread_value >> 1) | (output_ << 15)); output_ = spread_value | ((~or_bits) & 0xaaaa); static_cast<T *>(this)->output_short(output_); } void add_index_address_mark() { static_cast<T *>(this)->output_short(output_ = 0x5224); add_byte(0xfc); } void add_ID_address_mark() { static_cast<T *>(this)->output_short(output_ = 0x4489); add_byte(0xfe); } void add_data_address_mark() { static_cast<T *>(this)->output_short(output_ = 0x4489); add_byte(0xfb); } void add_deleted_data_address_mark() { static_cast<T *>(this)->output_short(output_ = 0x4489); add_byte(0xf8); } private: uint16_t output_; }; template <class T> class FMShifter: public Shifter<T> { // encodes each 16-bit part as clock, data, clock, data [...] public: void add_byte(uint8_t input) { static_cast<T *>(this)->output_short( (uint16_t)( ((input & 0x01) << 0) | ((input & 0x02) << 1) | ((input & 0x04) << 2) | ((input & 0x08) << 3) | ((input & 0x10) << 4) | ((input & 0x20) << 5) | ((input & 0x40) << 6) | ((input & 0x80) << 7) | 0xaaaa )); } void add_index_address_mark() { // data 0xfc, with clock 0xd7 => 1111 1100 with clock 1101 0111 => 1111 0111 0111 1010 static_cast<T *>(this)->output_short(0xf77a); } void add_ID_address_mark() { // data 0xfe, with clock 0xc7 => 1111 1110 with clock 1100 0111 => 1111 0101 0111 1110 static_cast<T *>(this)->output_short(0xf57e); } void add_data_address_mark() { // data 0xfb, with clock 0xc7 => 1111 1011 with clock 1100 0111 => 1111 0101 0110 1111 static_cast<T *>(this)->output_short(0xf56f); } void add_deleted_data_address_mark() { // data 0xf8, with clock 0xc7 => 1111 1000 with clock 1100 0111 => 1111 0101 0110 1010 static_cast<T *>(this)->output_short(0xf56a); } }; static uint8_t logarithmic_size_for_size(size_t size) { switch(size) { default: return 0; case 256: return 1; case 512: return 2; case 1024: return 3; case 2048: return 4; case 4196: return 5; } } template<class T> std::shared_ptr<Storage::Disk::Track> GetTrackWithSectors( const std::vector<Sector> &sectors, size_t post_index_address_mark_bytes, uint8_t post_index_address_mark_value, size_t pre_address_mark_bytes, size_t post_address_mark_bytes, size_t pre_data_mark_bytes, size_t post_data_bytes, size_t inter_sector_gap) { T shifter; NumberTheory::CRC16 crc_generator(0x1021, 0xffff); // output the index mark shifter.add_index_address_mark(); // add the post-index mark for(int c = 0; c < post_index_address_mark_bytes; c++) shifter.add_byte(post_index_address_mark_value); // add sectors for(const Sector &sector : sectors) { // gap for(int c = 0; c < pre_address_mark_bytes; c++) shifter.add_byte(0x00); // sector header shifter.add_ID_address_mark(); shifter.add_byte(sector.track); shifter.add_byte(sector.side); shifter.add_byte(sector.sector); uint8_t size = logarithmic_size_for_size(sector.data.size()); shifter.add_byte(size); // header CRC crc_generator.reset(); crc_generator.add(sector.track); crc_generator.add(sector.side); crc_generator.add(sector.sector); crc_generator.add(size); uint16_t crc_value = crc_generator.get_value(); shifter.add_byte(crc_value >> 8); shifter.add_byte(crc_value & 0xff); // gap for(int c = 0; c < post_address_mark_bytes; c++) shifter.add_byte(0x4e); for(int c = 0; c < pre_data_mark_bytes; c++) shifter.add_byte(0x00); // data shifter.add_data_address_mark(); crc_generator.reset(); for(size_t c = 0; c < sector.data.size(); c++) { shifter.add_byte(sector.data[c]); crc_generator.add(sector.data[c]); } // data CRC crc_value = crc_generator.get_value(); shifter.add_byte(crc_value >> 8); shifter.add_byte(crc_value & 0xff); // gap for(int c = 0; c < post_data_bytes; c++) shifter.add_byte(0x00); for(int c = 0; c < inter_sector_gap; c++) shifter.add_byte(0x4e); } // TODO: total size check Storage::Disk::PCMSegment segment; return std::shared_ptr<Storage::Disk::Track>(new Storage::Disk::PCMTrack(std::move(segment))); } struct VectorReceiver { void output_short(uint16_t value) { data.push_back(value >> 8); data.push_back(value & 0xff); } std::vector<uint8_t> data; }; std::shared_ptr<Storage::Disk::Track> Storage::Encodings::MFM::GetFMTrackWithSectors(const std::vector<Sector> &sectors) { struct VectorShifter: public FMShifter<VectorShifter>, VectorReceiver { using VectorReceiver::output_short; }; return GetTrackWithSectors<VectorShifter>( sectors, 16, 0x00, 6, 0, 17, 14, 0); } std::shared_ptr<Storage::Disk::Track> Storage::Encodings::MFM::GetMFMTrackWithSectors(const std::vector<Sector> &sectors) { struct VectorShifter: public MFMShifter<VectorShifter>, VectorReceiver { using VectorReceiver::output_short; }; return GetTrackWithSectors<VectorShifter>( sectors, 50, 0x4e, 12, 22, 12, 18, 32); } <|endoftext|>
<commit_before>#pragma once #include "../utility/iterator_traits.hpp" #include "sxml_parse_core.hpp" namespace SXML { namespace Internal { template <typename T, typename... L, template <typename...> class ContainerT> void xml_parse_generic_container( ContainerT <T, L...>& value, std::string const& name, PropertyTree const& object, XmlParseOptions options = {}, typename std::enable_if < has_random_access_iterator <ContainerT, L...>::value || has_bidirectional_iterator <ContainerT, L...>::value || has_forward_iterator <ContainerT, L...>::value >::type* = nullptr) { try { GET_VALUE(T, name, value, {}); } DEFAULT_CATCH({}, {}) /* try { GET_CHILD(name, pt, {}); for (auto const& i : pt) { T temp; xml_parse(temp, "", i.second, options); value.emplace_back(std::move(temp)); } } DEFAULT_CATCH({}, {}) */ } } } <commit_msg>Fixed parsing of containers.<commit_after>#pragma once #include "../utility/sxml_iterator_traits.hpp" #include "sxml_parse_core.hpp" #include <iostream> namespace SXML { namespace Internal { template <typename T, typename... L, template <typename...> class ContainerT> void xml_parse_generic_container( ContainerT <T, L...>& value, NodeName const& name, PropertyTree const& object, XmlParseOptions options = {}, typename std::enable_if < has_random_access_iterator <ContainerT, L...>::value || has_bidirectional_iterator <ContainerT, L...>::value || has_forward_iterator <ContainerT, L...>::value >::type* = nullptr) { try { if (!options.stateMixing) value.clear(); auto parent = name.parent(); GET_CHILD(parent, pt, {}); auto range = pt.equal_range(name.getName()); for (auto i = range.first; i != range.second; ++i) { T temp; xml_parse(temp, "", i->second, options); value.emplace_back(std::move(temp)); } } DEFAULT_CATCH({}, {}) /* try { GET_CHILD(name, pt, {}); for (auto const& i : pt) { T temp; xml_parse(temp, "", i.second, options); value.emplace_back(std::move(temp)); } } DEFAULT_CATCH({}, {}) */ } } } <|endoftext|>
<commit_before>// This file may contain portions of the code derived/adopted from the Go // standard library, which is covered by a BSD-style license. You can find more // details in 3rdparty/go_license.txt file. #include "stf.hh" #include "zbs/vector.hh" #include "zbs/string.hh" #include "zbs/unicode/utf8.hh" STF_SUITE_NAME("zbs/unicode/utf8"); using namespace zbs; namespace utf8 = unicode::utf8; struct utf8map_t { rune r; string str; }; utf8map_t utf8map[] = { {0x0000, slice<const char>{"\0", 1}}, {0x0001, "\x01"}, {0x007e, "\x7e"}, {0x007f, "\x7f"}, {0x0080, "\xc2\x80"}, {0x0081, "\xc2\x81"}, {0x00bf, "\xc2\xbf"}, {0x00c0, "\xc3\x80"}, {0x00c1, "\xc3\x81"}, {0x00c8, "\xc3\x88"}, {0x00d0, "\xc3\x90"}, {0x00e0, "\xc3\xa0"}, {0x00f0, "\xc3\xb0"}, {0x00f8, "\xc3\xb8"}, {0x00ff, "\xc3\xbf"}, {0x0100, "\xc4\x80"}, {0x07ff, "\xdf\xbf"}, {0x0800, "\xe0\xa0\x80"}, {0x0801, "\xe0\xa0\x81"}, {0xd7ff, "\xed\x9f\xbf"}, // last code point before surrogate half. {0xe000, "\xee\x80\x80"}, // first code point after surrogate half. {0xfffe, "\xef\xbf\xbe"}, {0xffff, "\xef\xbf\xbf"}, {0x10000, "\xf0\x90\x80\x80"}, {0x10001, "\xf0\x90\x80\x81"}, {0x10fffe, "\xf4\x8f\xbf\xbe"}, {0x10ffff, "\xf4\x8f\xbf\xbf"}, {0xFFFD, "\xef\xbf\xbd"}, }; utf8map_t surrogate_map[] = { {0xd800, "\xed\xa0\x80"}, // surrogate min decodes to (RuneError, 1) {0xdfff, "\xed\xbf\xbf"}, // surrogate max decodes to (RuneError, 1) }; string test_strings[] = { // TODO }; struct rune_count_test { string in; int out; }; rune_count_test rune_count_tests[] = { {"abcd", 4}, {"☺☻☹", 3}, {"1,2,3,4", 7}, {slice<const char>("\xe2\x00", 2), 2}, }; struct rune_len_test { rune r; int size; }; rune_len_test rune_len_tests[] = { {0, 1}, {U'e', 1}, {U'é', 2}, {U'☺', 3}, {utf8::rune_error, 3}, {utf8::max_rune, 4}, {0xD800, -1}, {0xDFFF, -1}, {utf8::max_rune + 1, -1}, {-1, -1}, }; struct valid_test { string in; bool out; }; valid_test valid_tests[] = { {"", true}, {"a", true}, {"abc", true}, {"Ж", true}, {"ЖЖ", true}, {"брэд-ЛГТМ", true}, {"☺☻☹", true}, {string({66, char(250)}), false}, {string({66, char(250), 67}), false}, {"a\uFFFDb", true}, {"\xF4\x8F\xBF\xBF", true}, // U+10FFFF {"\xF4\x90\x80\x80", false}, // U+10FFFF+1; out of range {"\xF7\xBF\xBF\xBF", false}, // 0x1FFFFF; out of range {"\xFB\xBF\xBF\xBF\xBF", false}, // 0x3FFFFFF; out of range {"\xc0\x80", false}, // U+0000 encoded in two bytes: incorrect {"\xed\xa0\x80", false}, // U+D800 high surrogate (sic) {"\xed\xbf\xbf", false}, // U+DFFF low surrogate (sic) }; struct valid_rune_test { rune in; bool out; }; valid_rune_test valid_rune_tests[] = { {0, true}, {'e', true}, {U'é', true}, {U'☺', true}, {utf8::rune_error, true}, {utf8::max_rune, true}, {0xD7FF, true}, {0xD800, false}, {0xDFFF, false}, {0xE000, true}, {utf8::max_rune + 1, false}, {-1, false}, }; STF_TEST("utf8::full_rune(slice<const char>)") { for (const auto &m : utf8map) { STF_ASSERT(utf8::full_rune(m.str)); auto s = m.str.sub(0, m.str.len()-1); STF_ASSERT(!utf8::full_rune(s)); } } STF_TEST("utf8::encode_rune(slice<char>, rune)") { for (const auto &m : utf8map) { char buf[10]; int n = utf8::encode_rune(buf, m.r); STF_ASSERT(slice<const char>(buf, n) == m.str.sub()); } // check that negative runes encode as rune_error vector<char> errbuf(utf8::utf_max); errbuf.resize(utf8::encode_rune(errbuf, utf8::rune_error)); vector<char> buf(utf8::utf_max); buf.resize(utf8::encode_rune(buf, -1)); STF_ASSERT(errbuf == buf); } STF_TEST("utf8::decode_rune(slice<const char>, int*)") { for (const auto &m : utf8map) { int size; string str = m.str; rune r = utf8::decode_rune(str, &size); STF_ASSERT(r == m.r && size == str.len()); // make sure trailing byte works str.append({"\0", 1}); r = utf8::decode_rune(str, &size); STF_ASSERT(r == m.r && size == str.len()-1); // remove trailing \0 str.remove(str.len()-1); // make sure missing bytes fail int wantsize = 1; if (wantsize >= str.len()) { wantsize = 0; } r = utf8::decode_rune(str.sub(0, str.len()-1), &size); STF_ASSERT(r == utf8::rune_error && size == wantsize); // make sure bad sequences fail if (str.len() == 1) { str[0] = 0x80; } else { str[str.len()-1] = 0x7F; } r = utf8::decode_rune(str, &size); STF_ASSERT(r == utf8::rune_error && size == 1); } // surrogate runes for (const auto &m : surrogate_map) { int size; rune r = utf8::decode_rune(m.str, &size); STF_ASSERT(r == utf8::rune_error && size == 1); } } bool test_sequence(slice<const char> s) { struct info { int index; rune r; }; vector<info> index(s.len()); int j = 0, i = 0; while (i < s.len()) { int size; rune r = utf8::decode_rune(s.sub(i), &size); index[j++] = {i, r}; i += size; } j--; i = s.len(); while (i > 0) { int size; rune r = utf8::decode_last_rune(s.sub(0, i), &size); if (index[j].r != r) { return false; } i -= size; if (index[j].index != i) { return false; } j--; } return true; } STF_TEST("utf8::decode_last_rune(slice<const char>, int*)") { // We actually test here that `decode_last_rune` corresponds to // `decode_rune`, because `decode_rune` works according to test above. for (const auto &ts : test_strings) { for (const auto &m : utf8map) { for (const auto &s : {ts + m.str, m.str + ts, ts + m.str + ts}) { STF_ASSERT(test_sequence(s)); } } } } STF_TEST("utf8::rune_count(slice<const char>)") { for (const auto &t : rune_count_tests) { STF_ASSERT(utf8::rune_count(t.in) == t.out); } } STF_TEST("utf8::rune_len(rune)") { for (const auto &t : rune_len_tests) { STF_ASSERT(utf8::rune_len(t.r) == t.size); } } STF_TEST("utf8::valid(slice<const char>)") { for (const auto &t : valid_tests) { STF_ASSERT(utf8::valid(t.in) == t.out); } } STF_TEST("utf8::valid_rune(rune)") { for (const auto &t : valid_rune_tests) { STF_ASSERT(utf8::valid_rune(t.in) == t.out); } } STF_TEST("utf8::rune_start(char)") { for (const auto &m : utf8map) { char first = m.str[0]; STF_ASSERT(utf8::rune_start(first)); if (m.str.len() > 1) { char second = m.str[1]; STF_ASSERT(!utf8::rune_start(second)); } } } <commit_msg>Add missing unicode::utf8 tests.<commit_after>// This file may contain portions of the code derived/adopted from the Go // standard library, which is covered by a BSD-style license. You can find more // details in 3rdparty/go_license.txt file. #include "stf.hh" #include "zbs/vector.hh" #include "zbs/string.hh" #include "zbs/unicode/utf8.hh" STF_SUITE_NAME("zbs/unicode/utf8"); using namespace zbs; namespace utf8 = unicode::utf8; struct utf8map_t { rune r; string str; }; utf8map_t utf8map[] = { {0x0000, slice<const char>{"\0", 1}}, {0x0001, "\x01"}, {0x007e, "\x7e"}, {0x007f, "\x7f"}, {0x0080, "\xc2\x80"}, {0x0081, "\xc2\x81"}, {0x00bf, "\xc2\xbf"}, {0x00c0, "\xc3\x80"}, {0x00c1, "\xc3\x81"}, {0x00c8, "\xc3\x88"}, {0x00d0, "\xc3\x90"}, {0x00e0, "\xc3\xa0"}, {0x00f0, "\xc3\xb0"}, {0x00f8, "\xc3\xb8"}, {0x00ff, "\xc3\xbf"}, {0x0100, "\xc4\x80"}, {0x07ff, "\xdf\xbf"}, {0x0800, "\xe0\xa0\x80"}, {0x0801, "\xe0\xa0\x81"}, {0xd7ff, "\xed\x9f\xbf"}, // last code point before surrogate half. {0xe000, "\xee\x80\x80"}, // first code point after surrogate half. {0xfffe, "\xef\xbf\xbe"}, {0xffff, "\xef\xbf\xbf"}, {0x10000, "\xf0\x90\x80\x80"}, {0x10001, "\xf0\x90\x80\x81"}, {0x10fffe, "\xf4\x8f\xbf\xbe"}, {0x10ffff, "\xf4\x8f\xbf\xbf"}, {0xFFFD, "\xef\xbf\xbd"}, }; utf8map_t surrogate_map[] = { {0xd800, "\xed\xa0\x80"}, // surrogate min decodes to (RuneError, 1) {0xdfff, "\xed\xbf\xbf"}, // surrogate max decodes to (RuneError, 1) }; string test_strings[] = { "", "abcd", "☺☻☹", "日a本b語ç日ð本Ê語þ日¥本¼語i日©", "日a本b語ç日ð本Ê語þ日¥本¼語i日©日a本b語ç日ð本Ê語þ日¥本¼語i日©日a本b語ç日ð本Ê語þ日¥本¼語i日©", "\x80\x80\x80\x80", }; struct rune_count_test { string in; int out; }; rune_count_test rune_count_tests[] = { {"abcd", 4}, {"☺☻☹", 3}, {"1,2,3,4", 7}, {slice<const char>("\xe2\x00", 2), 2}, }; struct rune_len_test { rune r; int size; }; rune_len_test rune_len_tests[] = { {0, 1}, {U'e', 1}, {U'é', 2}, {U'☺', 3}, {utf8::rune_error, 3}, {utf8::max_rune, 4}, {0xD800, -1}, {0xDFFF, -1}, {utf8::max_rune + 1, -1}, {-1, -1}, }; struct valid_test { string in; bool out; }; valid_test valid_tests[] = { {"", true}, {"a", true}, {"abc", true}, {"Ж", true}, {"ЖЖ", true}, {"брэд-ЛГТМ", true}, {"☺☻☹", true}, {string({66, char(250)}), false}, {string({66, char(250), 67}), false}, {"a\uFFFDb", true}, {"\xF4\x8F\xBF\xBF", true}, // U+10FFFF {"\xF4\x90\x80\x80", false}, // U+10FFFF+1; out of range {"\xF7\xBF\xBF\xBF", false}, // 0x1FFFFF; out of range {"\xFB\xBF\xBF\xBF\xBF", false}, // 0x3FFFFFF; out of range {"\xc0\x80", false}, // U+0000 encoded in two bytes: incorrect {"\xed\xa0\x80", false}, // U+D800 high surrogate (sic) {"\xed\xbf\xbf", false}, // U+DFFF low surrogate (sic) }; struct valid_rune_test { rune in; bool out; }; valid_rune_test valid_rune_tests[] = { {0, true}, {'e', true}, {U'é', true}, {U'☺', true}, {utf8::rune_error, true}, {utf8::max_rune, true}, {0xD7FF, true}, {0xD800, false}, {0xDFFF, false}, {0xE000, true}, {utf8::max_rune + 1, false}, {-1, false}, }; STF_TEST("utf8::full_rune(slice<const char>)") { for (const auto &m : utf8map) { STF_ASSERT(utf8::full_rune(m.str)); auto s = m.str.sub(0, m.str.len()-1); STF_ASSERT(!utf8::full_rune(s)); } } STF_TEST("utf8::encode_rune(slice<char>, rune)") { for (const auto &m : utf8map) { char buf[10]; int n = utf8::encode_rune(buf, m.r); STF_ASSERT(slice<const char>(buf, n) == m.str.sub()); } // check that negative runes encode as rune_error vector<char> errbuf(utf8::utf_max); errbuf.resize(utf8::encode_rune(errbuf, utf8::rune_error)); vector<char> buf(utf8::utf_max); buf.resize(utf8::encode_rune(buf, -1)); STF_ASSERT(errbuf == buf); } STF_TEST("utf8::decode_rune(slice<const char>, int*)") { for (const auto &m : utf8map) { int size; string str = m.str; rune r = utf8::decode_rune(str, &size); STF_ASSERT(r == m.r && size == str.len()); // make sure trailing byte works str.append({"\0", 1}); r = utf8::decode_rune(str, &size); STF_ASSERT(r == m.r && size == str.len()-1); // remove trailing \0 str.remove(str.len()-1); // make sure missing bytes fail int wantsize = 1; if (wantsize >= str.len()) { wantsize = 0; } r = utf8::decode_rune(str.sub(0, str.len()-1), &size); STF_ASSERT(r == utf8::rune_error && size == wantsize); // make sure bad sequences fail if (str.len() == 1) { str[0] = 0x80; } else { str[str.len()-1] = 0x7F; } r = utf8::decode_rune(str, &size); STF_ASSERT(r == utf8::rune_error && size == 1); } // surrogate runes for (const auto &m : surrogate_map) { int size; rune r = utf8::decode_rune(m.str, &size); STF_ASSERT(r == utf8::rune_error && size == 1); } } bool test_sequence(slice<const char> s) { struct info { int index; rune r; }; vector<info> index(s.len()); int j = 0, i = 0; while (i < s.len()) { int size; rune r = utf8::decode_rune(s.sub(i), &size); index[j++] = {i, r}; i += size; } j--; i = s.len(); while (i > 0) { int size; rune r = utf8::decode_last_rune(s.sub(0, i), &size); if (index[j].r != r) { return false; } i -= size; if (index[j].index != i) { return false; } j--; } return true; } STF_TEST("utf8::decode_last_rune(slice<const char>, int*)") { // We actually test here that `decode_last_rune` corresponds to // `decode_rune`, because `decode_rune` works according to test above. for (const auto &ts : test_strings) { for (const auto &m : utf8map) { for (const auto &s : {ts + m.str, m.str + ts, ts + m.str + ts}) { STF_ASSERT(test_sequence(s)); } } } } STF_TEST("utf8::rune_count(slice<const char>)") { for (const auto &t : rune_count_tests) { STF_ASSERT(utf8::rune_count(t.in) == t.out); } } STF_TEST("utf8::rune_len(rune)") { for (const auto &t : rune_len_tests) { STF_ASSERT(utf8::rune_len(t.r) == t.size); } } STF_TEST("utf8::valid(slice<const char>)") { for (const auto &t : valid_tests) { STF_ASSERT(utf8::valid(t.in) == t.out); } } STF_TEST("utf8::valid_rune(rune)") { for (const auto &t : valid_rune_tests) { STF_ASSERT(utf8::valid_rune(t.in) == t.out); } } STF_TEST("utf8::rune_start(char)") { for (const auto &m : utf8map) { char first = m.str[0]; STF_ASSERT(utf8::rune_start(first)); if (m.str.len() > 1) { char second = m.str[1]; STF_ASSERT(!utf8::rune_start(second)); } } } <|endoftext|>
<commit_before>/** \brief Utility for augmenting MARC records with links to a local full-text database. * \author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de) * * \copyright 2015 Universitätsbiblothek Tübingen. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <iostream> #include <memory> #include <vector> #include <cassert> #include <cstdio> #include <cstdlib> #include <ctime> #include <kchashdb.h> #include "Compiler.h" #include "DbConnection.h" #include "DirectoryEntry.h" #include "ExecUtil.h" #include "FileLocker.h" #include "FileUtil.h" #include "MarcUtil.h" #include "MediaTypeUtil.h" #include "PdfUtil.h" #include "SmartDownloader.h" #include "SqlUtil.h" #include "StringUtil.h" #include "Subfields.h" #include "util.h" #include "VuFind.h" #include "XmlWriter.h" static void Usage() __attribute__((noreturn)); static void Usage() { std::cerr << "Usage: " << ::progname << " file_offset counter marc_input marc_output full_text_db\n\n" << " file_offset Where to start reading a MARC data set from in marc_input.\n\n"; std::exit(EXIT_FAILURE); } bool GetDocumentAndMediaType(const std::string &url, const unsigned timeout, std::string * const document, std::string * const media_type) { if (not SmartDownload(url, timeout, document)) { std::cerr << "Failed to download the document for " << url << " (timeout: " << timeout << " sec)\n"; return false; } *media_type = MediaTypeUtil::GetMediaType(*document, /* auto_simplify = */ false); if (media_type->empty()) return false; return true; } static std::map<std::string, std::string> marc_to_tesseract_language_codes_map { { "fre", "fra" }, { "eng", "eng" }, { "ger", "deu" }, { "ita", "ita" }, { "dut", "nld" }, { "swe", "swe" }, { "dan", "dan" }, { "nor", "nor" }, { "rus", "rus" }, { "fin", "fin" }, { "por", "por" }, { "pol", "pol" }, { "slv", "slv" }, { "hun", "hun" }, { "cze", "ces" }, { "bul", "bul" }, }; std::string GetTesseractLanguageCode(const MarcUtil::Record &record) { const auto map_iter(marc_to_tesseract_language_codes_map.find( record.getLanguageCode())); return (map_iter == marc_to_tesseract_language_codes_map.cend()) ? "" : map_iter->second; } bool GetTextFromImagePDF(const std::string &document, const std::string &media_type, const std::string &original_url, const MarcUtil::Record &record, const std::string &pdf_images_script, std::string * const extracted_text) { extracted_text->clear(); if (not StringUtil::StartsWith(media_type, "application/pdf") or not PdfDocContainsNoText(document)) return false; std::cerr << "Found a PDF w/ no text.\n"; const FileUtil::AutoTempFile auto_temp_file; const std::string &input_filename(auto_temp_file.getFilePath()); if (not FileUtil::WriteString(input_filename, document)) Error("failed to write the PDF to a temp file!"); const FileUtil::AutoTempFile auto_temp_file2; const std::string &output_filename(auto_temp_file2.getFilePath()); const std::string language_code(GetTesseractLanguageCode(record)); static constexpr unsigned TIMEOUT(60); // in seconds if (ExecUtil::Exec(pdf_images_script, { input_filename, output_filename, language_code }, "", "", "", TIMEOUT) != 0) { Warning("failed to execute conversion script \"" + pdf_images_script + "\" w/in " + std::to_string(TIMEOUT) + " seconds ! (original Url: " + original_url + ")"); return false; } std::string plain_text; if (not ReadFile(output_filename, extracted_text)) Error("failed to read OCR output!"); if (extracted_text->empty()) std::cerr << "Warning: OCR output is empty!\n"; else std::cerr << "Whoohoo, got OCR'ed text.\n"; return true; } // Checks subfields "3" and "z" to see if they start w/ "Rezension". bool IsProbablyAReview(const Subfields &subfields) { const auto _3_begin_end(subfields.getIterators('3')); if (_3_begin_end.first != _3_begin_end.second) { if (StringUtil::StartsWith(_3_begin_end.first->second, "Rezension")) return true; } else { const auto z_begin_end(subfields.getIterators('z')); if (z_begin_end.first != z_begin_end.second and StringUtil::StartsWith(z_begin_end.first->second, "Rezension")) return true; } return false; } /** Writes "media_type" and "document" to "db" and returns the unique key that was generated for the write. */ std::string DbLockedWriteDocumentWithMediaType(const std::string &media_type, const std::string &document, const std::string &db_filename) { FileLocker file_locker(db_filename, FileLocker::WRITE_ONLY); kyotocabinet::HashDB db; if (not db.open(db_filename, kyotocabinet::HashDB::OWRITER)) Error("Failed to open database \"" + db_filename + "\" for writing (" + std::string(db.error().message()) + ")!"); const std::string key(std::to_string(db.count() + 1)); if (not db.add(key, "Content-type: " + media_type + "\r\n\r\n" + document)) Error("Failed to add key/value pair to database \"" + db_filename + "\" (" + std::string(db.error().message()) + ")!"); return key; } bool GetExtractedTextFromDatabase(DbConnection * const db_connection, const std::string &url, const std::string &document, std::string * const extracted_text) { const std::string QUERY("SELECT hash,full_text FROM full_text_cache WHERE url=\"" + url + "\""); if (not db_connection->query(QUERY)) throw std::runtime_error("Query \"" + QUERY + "\" failed because: " + db_connection->getLastErrorMessage()); DbResultSet result_set(db_connection->getLastResultSet()); if (result_set.empty()) return false; assert(result_set.size() == 1); DbRow row(result_set.getNextRow()); const std::string hash(StringUtil::ToHexString(StringUtil::Sha1(document))); if (unlikely(hash != row["hash"])) return false; // The document must have changed! *extracted_text = row["full_text"]; // Update the timestap: const time_t now(std::time(nullptr)); const std::string current_datetime(SqlUtil::TimeTToDatetime(now)); const std::string UPDATE_STMT("UPDATE full_text_cache SET last_used=\"" + current_datetime + "\" WHERE url=\"" + url + "\""); if (not db_connection->query(UPDATE_STMT)) throw std::runtime_error("Query \"" + UPDATE_STMT + "\" failed because: " + db_connection->getLastErrorMessage()); return true; } // Returns true if text has been successfully extracted, else false. bool ProcessRecord(File * const input, const std::string &marc_output_filename, const std::string &pdf_images_script, const std::string &db_filename) { MarcUtil::Record record(MarcUtil::Record::XmlFactory(input)); record.setRecordWillBeWrittenAsXml(true); ssize_t _856_index(record.getFieldIndex("856")); if (_856_index == -1) Error("no 856 tag found!"); constexpr unsigned PER_DOC_TIMEOUT(40); bool succeeded(false); const std::vector<DirectoryEntry> &dir_entries(record.getDirEntries()); const std::vector<std::string> &fields(record.getFields()); const ssize_t dir_entry_count(static_cast<ssize_t>(dir_entries.size())); for (/* Empty! */; _856_index < dir_entry_count and dir_entries[_856_index].getTag() == "856"; ++_856_index) { Subfields subfields(fields[_856_index]); if (subfields.getIndicator1() == '7' or not subfields.hasSubfield('u')) continue; if (IsProbablyAReview(subfields)) continue; std::string document, media_type; const std::string url(subfields.getFirstSubfieldValue('u')); if (not GetDocumentAndMediaType(url, PER_DOC_TIMEOUT, &document, &media_type)) continue; std::string mysql_url; VuFind::GetMysqlURL(&mysql_url); DbConnection db_connection(mysql_url); std::string extracted_text, key; if (GetExtractedTextFromDatabase(&db_connection, url, document, &extracted_text)) key = DbLockedWriteDocumentWithMediaType("text/plain", extracted_text, db_filename); else if (GetTextFromImagePDF(document, media_type, url, record, pdf_images_script, &extracted_text)) { key = DbLockedWriteDocumentWithMediaType("text/plain", extracted_text, db_filename); const std::string hash(StringUtil::ToHexString(StringUtil::Sha1(document))); const time_t now(std::time(nullptr)); const std::string current_datetime(SqlUtil::TimeTToDatetime(now)); const std::string INSERT_STMT("REPLACE INTO full_text_cache SET url=\"" + url + "\", hash=\"" + hash + "\", full_text=\"" + SqlUtil::EscapeBlob(&extracted_text) + "\", last_used=\"" + current_datetime + "\""); if (not db_connection.query(INSERT_STMT)) throw std::runtime_error("Query \"" + INSERT_STMT + "\" failed because: " + db_connection.getLastErrorMessage()); } else key = DbLockedWriteDocumentWithMediaType(media_type, document, db_filename); subfields.addSubfield('e', "http://localhost/cgi-bin/full_text_lookup?id=" + key); const std::string new_856_field(subfields.toString()); record.updateField(_856_index, new_856_field); succeeded = true; } // Safely append the modified MARC data to the MARC output file: FileLocker file_locker(marc_output_filename, FileLocker::WRITE_ONLY); File marc_output(marc_output_filename, "ab"); if (not marc_output) Error("can't open \"" + marc_output_filename + "\" for appending!"); XmlWriter xml_writer(&marc_output, XmlWriter::WriteTheXmlDeclaration); record.write(&xml_writer); return succeeded; } const std::string BASH_HELPER("pdf_images_to_text.sh"); std::string GetPathToPdfImagesScript(const char * const argv0) { #pragma GCC diagnostic ignored "-Wvla" char path[std::strlen(argv0) + 1]; #pragma GCC diagnostic warning "-Wvla" std::strcpy(path, argv0); const std::string pdf_images_script_path(ExecUtil::Which(BASH_HELPER)); if (::access(pdf_images_script_path.c_str(), X_OK) != 0) Error("can't execute \"" + pdf_images_script_path + "\"!"); return pdf_images_script_path; } int main(int argc, char *argv[]) { ::progname = argv[0]; if (argc != 5) Usage(); long offset; if (not StringUtil::ToNumber(argv[1], &offset)) Error("file offset must be a number!"); const std::string marc_input_filename(argv[2]); File marc_input(marc_input_filename, "r"); if (not marc_input) Error("can't open \"" + marc_input_filename + "\" for reading!"); const std::string marc_output_filename(argv[3]); if (not marc_input.seek(offset, SEEK_SET)) Error("failed to position " + marc_input_filename + " at offset " + std::to_string(offset) + "! (" + std::to_string(errno) + ")"); try { return ProcessRecord(&marc_input, marc_output_filename, GetPathToPdfImagesScript(argv[0]), argv[4]) ? EXIT_SUCCESS : EXIT_FAILURE; } catch (const std::exception &e) { Error("While reading \"" + marc_input_filename + "\" starting at offset \"" + std::string(argv[1]) + "\", caught exception: " + std::string(e.what())); } } <commit_msg>Fixed an incorrect enum value which indicated the opposite of the behaviour that we actually wanted.<commit_after>/** \brief Utility for augmenting MARC records with links to a local full-text database. * \author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de) * * \copyright 2015 Universitätsbiblothek Tübingen. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <iostream> #include <memory> #include <vector> #include <cassert> #include <cstdio> #include <cstdlib> #include <ctime> #include <kchashdb.h> #include "Compiler.h" #include "DbConnection.h" #include "DirectoryEntry.h" #include "ExecUtil.h" #include "FileLocker.h" #include "FileUtil.h" #include "MarcUtil.h" #include "MediaTypeUtil.h" #include "PdfUtil.h" #include "SmartDownloader.h" #include "SqlUtil.h" #include "StringUtil.h" #include "Subfields.h" #include "util.h" #include "VuFind.h" #include "XmlWriter.h" static void Usage() __attribute__((noreturn)); static void Usage() { std::cerr << "Usage: " << ::progname << " file_offset counter marc_input marc_output full_text_db\n\n" << " file_offset Where to start reading a MARC data set from in marc_input.\n\n"; std::exit(EXIT_FAILURE); } bool GetDocumentAndMediaType(const std::string &url, const unsigned timeout, std::string * const document, std::string * const media_type) { if (not SmartDownload(url, timeout, document)) { std::cerr << "Failed to download the document for " << url << " (timeout: " << timeout << " sec)\n"; return false; } *media_type = MediaTypeUtil::GetMediaType(*document, /* auto_simplify = */ false); if (media_type->empty()) return false; return true; } static std::map<std::string, std::string> marc_to_tesseract_language_codes_map { { "fre", "fra" }, { "eng", "eng" }, { "ger", "deu" }, { "ita", "ita" }, { "dut", "nld" }, { "swe", "swe" }, { "dan", "dan" }, { "nor", "nor" }, { "rus", "rus" }, { "fin", "fin" }, { "por", "por" }, { "pol", "pol" }, { "slv", "slv" }, { "hun", "hun" }, { "cze", "ces" }, { "bul", "bul" }, }; std::string GetTesseractLanguageCode(const MarcUtil::Record &record) { const auto map_iter(marc_to_tesseract_language_codes_map.find( record.getLanguageCode())); return (map_iter == marc_to_tesseract_language_codes_map.cend()) ? "" : map_iter->second; } bool GetTextFromImagePDF(const std::string &document, const std::string &media_type, const std::string &original_url, const MarcUtil::Record &record, const std::string &pdf_images_script, std::string * const extracted_text) { extracted_text->clear(); if (not StringUtil::StartsWith(media_type, "application/pdf") or not PdfDocContainsNoText(document)) return false; std::cerr << "Found a PDF w/ no text.\n"; const FileUtil::AutoTempFile auto_temp_file; const std::string &input_filename(auto_temp_file.getFilePath()); if (not FileUtil::WriteString(input_filename, document)) Error("failed to write the PDF to a temp file!"); const FileUtil::AutoTempFile auto_temp_file2; const std::string &output_filename(auto_temp_file2.getFilePath()); const std::string language_code(GetTesseractLanguageCode(record)); static constexpr unsigned TIMEOUT(60); // in seconds if (ExecUtil::Exec(pdf_images_script, { input_filename, output_filename, language_code }, "", "", "", TIMEOUT) != 0) { Warning("failed to execute conversion script \"" + pdf_images_script + "\" w/in " + std::to_string(TIMEOUT) + " seconds ! (original Url: " + original_url + ")"); return false; } std::string plain_text; if (not ReadFile(output_filename, extracted_text)) Error("failed to read OCR output!"); if (extracted_text->empty()) std::cerr << "Warning: OCR output is empty!\n"; else std::cerr << "Whoohoo, got OCR'ed text.\n"; return true; } // Checks subfields "3" and "z" to see if they start w/ "Rezension". bool IsProbablyAReview(const Subfields &subfields) { const auto _3_begin_end(subfields.getIterators('3')); if (_3_begin_end.first != _3_begin_end.second) { if (StringUtil::StartsWith(_3_begin_end.first->second, "Rezension")) return true; } else { const auto z_begin_end(subfields.getIterators('z')); if (z_begin_end.first != z_begin_end.second and StringUtil::StartsWith(z_begin_end.first->second, "Rezension")) return true; } return false; } /** Writes "media_type" and "document" to "db" and returns the unique key that was generated for the write. */ std::string DbLockedWriteDocumentWithMediaType(const std::string &media_type, const std::string &document, const std::string &db_filename) { FileLocker file_locker(db_filename, FileLocker::WRITE_ONLY); kyotocabinet::HashDB db; if (not db.open(db_filename, kyotocabinet::HashDB::OWRITER)) Error("Failed to open database \"" + db_filename + "\" for writing (" + std::string(db.error().message()) + ")!"); const std::string key(std::to_string(db.count() + 1)); if (not db.add(key, "Content-type: " + media_type + "\r\n\r\n" + document)) Error("Failed to add key/value pair to database \"" + db_filename + "\" (" + std::string(db.error().message()) + ")!"); return key; } bool GetExtractedTextFromDatabase(DbConnection * const db_connection, const std::string &url, const std::string &document, std::string * const extracted_text) { const std::string QUERY("SELECT hash,full_text FROM full_text_cache WHERE url=\"" + url + "\""); if (not db_connection->query(QUERY)) throw std::runtime_error("Query \"" + QUERY + "\" failed because: " + db_connection->getLastErrorMessage()); DbResultSet result_set(db_connection->getLastResultSet()); if (result_set.empty()) return false; assert(result_set.size() == 1); DbRow row(result_set.getNextRow()); const std::string hash(StringUtil::ToHexString(StringUtil::Sha1(document))); if (unlikely(hash != row["hash"])) return false; // The document must have changed! *extracted_text = row["full_text"]; // Update the timestap: const time_t now(std::time(nullptr)); const std::string current_datetime(SqlUtil::TimeTToDatetime(now)); const std::string UPDATE_STMT("UPDATE full_text_cache SET last_used=\"" + current_datetime + "\" WHERE url=\"" + url + "\""); if (not db_connection->query(UPDATE_STMT)) throw std::runtime_error("Query \"" + UPDATE_STMT + "\" failed because: " + db_connection->getLastErrorMessage()); return true; } // Returns true if text has been successfully extracted, else false. bool ProcessRecord(File * const input, const std::string &marc_output_filename, const std::string &pdf_images_script, const std::string &db_filename) { MarcUtil::Record record(MarcUtil::Record::XmlFactory(input)); record.setRecordWillBeWrittenAsXml(true); ssize_t _856_index(record.getFieldIndex("856")); if (_856_index == -1) Error("no 856 tag found!"); constexpr unsigned PER_DOC_TIMEOUT(40); bool succeeded(false); const std::vector<DirectoryEntry> &dir_entries(record.getDirEntries()); const std::vector<std::string> &fields(record.getFields()); const ssize_t dir_entry_count(static_cast<ssize_t>(dir_entries.size())); for (/* Empty! */; _856_index < dir_entry_count and dir_entries[_856_index].getTag() == "856"; ++_856_index) { Subfields subfields(fields[_856_index]); if (subfields.getIndicator1() == '7' or not subfields.hasSubfield('u')) continue; if (IsProbablyAReview(subfields)) continue; std::string document, media_type; const std::string url(subfields.getFirstSubfieldValue('u')); if (not GetDocumentAndMediaType(url, PER_DOC_TIMEOUT, &document, &media_type)) continue; std::string mysql_url; VuFind::GetMysqlURL(&mysql_url); DbConnection db_connection(mysql_url); std::string extracted_text, key; if (GetExtractedTextFromDatabase(&db_connection, url, document, &extracted_text)) key = DbLockedWriteDocumentWithMediaType("text/plain", extracted_text, db_filename); else if (GetTextFromImagePDF(document, media_type, url, record, pdf_images_script, &extracted_text)) { key = DbLockedWriteDocumentWithMediaType("text/plain", extracted_text, db_filename); const std::string hash(StringUtil::ToHexString(StringUtil::Sha1(document))); const time_t now(std::time(nullptr)); const std::string current_datetime(SqlUtil::TimeTToDatetime(now)); const std::string INSERT_STMT("REPLACE INTO full_text_cache SET url=\"" + url + "\", hash=\"" + hash + "\", full_text=\"" + SqlUtil::EscapeBlob(&extracted_text) + "\", last_used=\"" + current_datetime + "\""); if (not db_connection.query(INSERT_STMT)) throw std::runtime_error("Query \"" + INSERT_STMT + "\" failed because: " + db_connection.getLastErrorMessage()); } else key = DbLockedWriteDocumentWithMediaType(media_type, document, db_filename); subfields.addSubfield('e', "http://localhost/cgi-bin/full_text_lookup?id=" + key); const std::string new_856_field(subfields.toString()); record.updateField(_856_index, new_856_field); succeeded = true; } // Safely append the modified MARC data to the MARC output file: FileLocker file_locker(marc_output_filename, FileLocker::WRITE_ONLY); File marc_output(marc_output_filename, "ab"); if (not marc_output) Error("can't open \"" + marc_output_filename + "\" for appending!"); XmlWriter xml_writer(&marc_output, XmlWriter::DoNotWriteTheXmlDeclaration); record.write(&xml_writer); return succeeded; } const std::string BASH_HELPER("pdf_images_to_text.sh"); std::string GetPathToPdfImagesScript(const char * const argv0) { #pragma GCC diagnostic ignored "-Wvla" char path[std::strlen(argv0) + 1]; #pragma GCC diagnostic warning "-Wvla" std::strcpy(path, argv0); const std::string pdf_images_script_path(ExecUtil::Which(BASH_HELPER)); if (::access(pdf_images_script_path.c_str(), X_OK) != 0) Error("can't execute \"" + pdf_images_script_path + "\"!"); return pdf_images_script_path; } int main(int argc, char *argv[]) { ::progname = argv[0]; if (argc != 5) Usage(); long offset; if (not StringUtil::ToNumber(argv[1], &offset)) Error("file offset must be a number!"); const std::string marc_input_filename(argv[2]); File marc_input(marc_input_filename, "r"); if (not marc_input) Error("can't open \"" + marc_input_filename + "\" for reading!"); const std::string marc_output_filename(argv[3]); if (not marc_input.seek(offset, SEEK_SET)) Error("failed to position " + marc_input_filename + " at offset " + std::to_string(offset) + "! (" + std::to_string(errno) + ")"); try { return ProcessRecord(&marc_input, marc_output_filename, GetPathToPdfImagesScript(argv[0]), argv[4]) ? EXIT_SUCCESS : EXIT_FAILURE; } catch (const std::exception &e) { Error("While reading \"" + marc_input_filename + "\" starting at offset \"" + std::string(argv[1]) + "\", caught exception: " + std::string(e.what())); } } <|endoftext|>
<commit_before>/* * Caching HTTP responses in heap memory. * * author: Max Kellermann <mk@cm4all.com> */ #include "http_cache_heap.hxx" #include "http_cache_rfc.hxx" #include "http_cache_document.hxx" #include "http_cache_age.hxx" #include "cache.hxx" #include "istream.h" #include "rubber.hxx" #include "istream_rubber.hxx" #include "slice.hxx" #include "pool.hxx" #include "util/Cast.hxx" #include <time.h> #include <string.h> #include <errno.h> #include <stdio.h> #include <unistd.h> struct http_cache_item { struct cache_item item; struct pool *pool; struct http_cache_document document; size_t size; Rubber *rubber; unsigned rubber_id; http_cache_item(struct pool &_pool, const struct http_cache_info &info, const struct strmap *request_headers, http_status_t status, const struct strmap *response_headers, size_t _size, Rubber &_rubber, unsigned _rubber_id) :pool(&_pool), document(_pool, info, request_headers, status, response_headers), size(_size), rubber(&_rubber), rubber_id(_rubber_id) { cache_item_init_absolute(&item, http_cache_calc_expires(&info, request_headers), pool_netto_size(pool) + size); } http_cache_item(const http_cache_item &) = delete; static http_cache_item *FromDocument(http_cache_document *document) { return &ContainerCast2(*document, &http_cache_item::document); } }; static bool http_cache_item_match(const struct cache_item *_item, void *ctx) { const struct http_cache_item *item = (const struct http_cache_item *)_item; const struct strmap *headers = (const struct strmap *)ctx; return item->document.VaryFits(headers); } struct http_cache_document * http_cache_heap_get(struct http_cache_heap *cache, const char *uri, struct strmap *request_headers) { struct http_cache_item *item = (struct http_cache_item *)cache_get_match(cache->cache, uri, http_cache_item_match, request_headers); if (item == nullptr) return nullptr; return &item->document; } void http_cache_heap_put(struct http_cache_heap *cache, const char *url, const struct http_cache_info *info, struct strmap *request_headers, http_status_t status, const struct strmap *response_headers, Rubber *rubber, unsigned rubber_id, size_t size) { struct pool *pool = pool_new_slice(cache->pool, "http_cache_item", cache->slice_pool); auto item = NewFromPool<http_cache_item>(*pool, *pool, *info, request_headers, status, response_headers, size, *rubber, rubber_id); cache_put_match(cache->cache, p_strdup(pool, url), &item->item, http_cache_item_match, request_headers); } void http_cache_heap_remove(struct http_cache_heap *cache, const char *url, struct http_cache_document *document) { struct cache *cache2 = cache->cache; auto item = http_cache_item::FromDocument(document); cache_remove_item(cache2, url, &item->item); cache_item_unlock(cache2, &item->item); } void http_cache_heap_remove_url(struct http_cache_heap *cache, const char *url, struct strmap *headers) { cache_remove_match(cache->cache, url, http_cache_item_match, headers); } void http_cache_heap_flush(struct http_cache_heap *cache) { cache_flush(cache->cache); slice_pool_compress(cache->slice_pool); } void http_cache_heap_lock(struct http_cache_document *document) { auto item = http_cache_item::FromDocument(document); cache_item_lock(&item->item); } void http_cache_heap_unlock(struct http_cache_heap *cache, struct http_cache_document *document) { auto item = http_cache_item::FromDocument(document); cache_item_unlock(cache->cache, &item->item); } struct istream * http_cache_heap_istream(struct pool *pool, struct http_cache_heap *cache, struct http_cache_document *document) { auto item = http_cache_item::FromDocument(document); if (item->rubber_id == 0) /* don't lock the item */ return istream_null_new(pool); struct istream *istream = istream_rubber_new(pool, item->rubber, item->rubber_id, 0, item->size, false); return istream_unlock_new(pool, istream, cache->cache, &item->item); } /* * cache_class * */ static bool http_cache_item_validate(struct cache_item *_item) { struct http_cache_item *item = (struct http_cache_item *)_item; (void)item; return true; } static void http_cache_item_destroy(struct cache_item *_item) { struct http_cache_item *item = (struct http_cache_item *)_item; if (item->rubber_id != 0) rubber_remove(item->rubber, item->rubber_id); pool_unref(item->pool); } static const struct cache_class http_cache_class = { .validate = http_cache_item_validate, .destroy = http_cache_item_destroy, }; /* * cache_class * */ void http_cache_heap_init(struct http_cache_heap *cache, struct pool &pool, size_t max_size) { cache->pool = &pool; cache->cache = cache_new(pool, &http_cache_class, 65521, max_size); cache->slice_pool = slice_pool_new(1024, 65536); } void http_cache_heap_deinit(struct http_cache_heap *cache) { cache_close(cache->cache); slice_pool_free(cache->slice_pool); } void http_cache_heap_get_stats(const struct http_cache_heap *cache, const Rubber *rubber, struct cache_stats *data) { cache_get_stats(cache->cache, data); data->netto_size += rubber_get_netto_size(rubber); data->brutto_size += rubber_get_brutto_size(rubber); } <commit_msg>http_cache_heap: move code to http_cache_item::OpenStream()<commit_after>/* * Caching HTTP responses in heap memory. * * author: Max Kellermann <mk@cm4all.com> */ #include "http_cache_heap.hxx" #include "http_cache_rfc.hxx" #include "http_cache_document.hxx" #include "http_cache_age.hxx" #include "cache.hxx" #include "istream.h" #include "rubber.hxx" #include "istream_rubber.hxx" #include "slice.hxx" #include "pool.hxx" #include "util/Cast.hxx" #include <time.h> #include <string.h> #include <errno.h> #include <stdio.h> #include <unistd.h> struct http_cache_item { struct cache_item item; struct pool *pool; struct http_cache_document document; size_t size; Rubber *rubber; unsigned rubber_id; http_cache_item(struct pool &_pool, const struct http_cache_info &info, const struct strmap *request_headers, http_status_t status, const struct strmap *response_headers, size_t _size, Rubber &_rubber, unsigned _rubber_id) :pool(&_pool), document(_pool, info, request_headers, status, response_headers), size(_size), rubber(&_rubber), rubber_id(_rubber_id) { cache_item_init_absolute(&item, http_cache_calc_expires(&info, request_headers), pool_netto_size(pool) + size); } http_cache_item(const http_cache_item &) = delete; static http_cache_item *FromDocument(http_cache_document *document) { return &ContainerCast2(*document, &http_cache_item::document); } struct istream *OpenStream(struct pool *_pool) { return istream_rubber_new(_pool, rubber, rubber_id, 0, size, false); } }; static bool http_cache_item_match(const struct cache_item *_item, void *ctx) { const struct http_cache_item *item = (const struct http_cache_item *)_item; const struct strmap *headers = (const struct strmap *)ctx; return item->document.VaryFits(headers); } struct http_cache_document * http_cache_heap_get(struct http_cache_heap *cache, const char *uri, struct strmap *request_headers) { struct http_cache_item *item = (struct http_cache_item *)cache_get_match(cache->cache, uri, http_cache_item_match, request_headers); if (item == nullptr) return nullptr; return &item->document; } void http_cache_heap_put(struct http_cache_heap *cache, const char *url, const struct http_cache_info *info, struct strmap *request_headers, http_status_t status, const struct strmap *response_headers, Rubber *rubber, unsigned rubber_id, size_t size) { struct pool *pool = pool_new_slice(cache->pool, "http_cache_item", cache->slice_pool); auto item = NewFromPool<http_cache_item>(*pool, *pool, *info, request_headers, status, response_headers, size, *rubber, rubber_id); cache_put_match(cache->cache, p_strdup(pool, url), &item->item, http_cache_item_match, request_headers); } void http_cache_heap_remove(struct http_cache_heap *cache, const char *url, struct http_cache_document *document) { struct cache *cache2 = cache->cache; auto item = http_cache_item::FromDocument(document); cache_remove_item(cache2, url, &item->item); cache_item_unlock(cache2, &item->item); } void http_cache_heap_remove_url(struct http_cache_heap *cache, const char *url, struct strmap *headers) { cache_remove_match(cache->cache, url, http_cache_item_match, headers); } void http_cache_heap_flush(struct http_cache_heap *cache) { cache_flush(cache->cache); slice_pool_compress(cache->slice_pool); } void http_cache_heap_lock(struct http_cache_document *document) { auto item = http_cache_item::FromDocument(document); cache_item_lock(&item->item); } void http_cache_heap_unlock(struct http_cache_heap *cache, struct http_cache_document *document) { auto item = http_cache_item::FromDocument(document); cache_item_unlock(cache->cache, &item->item); } struct istream * http_cache_heap_istream(struct pool *pool, struct http_cache_heap *cache, struct http_cache_document *document) { auto item = http_cache_item::FromDocument(document); if (item->rubber_id == 0) /* don't lock the item */ return istream_null_new(pool); struct istream *istream = item->OpenStream(pool); return istream_unlock_new(pool, istream, cache->cache, &item->item); } /* * cache_class * */ static bool http_cache_item_validate(struct cache_item *_item) { struct http_cache_item *item = (struct http_cache_item *)_item; (void)item; return true; } static void http_cache_item_destroy(struct cache_item *_item) { struct http_cache_item *item = (struct http_cache_item *)_item; if (item->rubber_id != 0) rubber_remove(item->rubber, item->rubber_id); pool_unref(item->pool); } static const struct cache_class http_cache_class = { .validate = http_cache_item_validate, .destroy = http_cache_item_destroy, }; /* * cache_class * */ void http_cache_heap_init(struct http_cache_heap *cache, struct pool &pool, size_t max_size) { cache->pool = &pool; cache->cache = cache_new(pool, &http_cache_class, 65521, max_size); cache->slice_pool = slice_pool_new(1024, 65536); } void http_cache_heap_deinit(struct http_cache_heap *cache) { cache_close(cache->cache); slice_pool_free(cache->slice_pool); } void http_cache_heap_get_stats(const struct http_cache_heap *cache, const Rubber *rubber, struct cache_stats *data) { cache_get_stats(cache->cache, data); data->netto_size += rubber_get_netto_size(rubber); data->brutto_size += rubber_get_brutto_size(rubber); } <|endoftext|>
<commit_before>/* Copyright (c) 2003, Arvid Norberg 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. */ #include "libtorrent/pch.hpp" #include <cctype> #include <algorithm> #ifdef _MSC_VER #pragma warning(push, 1) #endif #include <boost/optional.hpp> #ifdef _MSC_VER #pragma warning(pop) #endif #include "libtorrent/identify_client.hpp" #include "libtorrent/fingerprint.hpp" namespace { using namespace libtorrent; int decode_digit(char c) { if (std::isdigit(c)) return c - '0'; return unsigned(c) - 'A' + 10; } // takes a peer id and returns a valid boost::optional // object if the peer id matched the azureus style encoding // the returned fingerprint contains information about the // client's id boost::optional<fingerprint> parse_az_style(const peer_id& id) { fingerprint ret("..", 0, 0, 0, 0); if (id[0] != '-' || !std::isprint(id[1]) || (id[2] < '0') || (id[3] < '0') || (id[4] < '0') || (id[5] < '0') || (id[6] < '0') || id[7] != '-') return boost::optional<fingerprint>(); ret.name[0] = id[1]; ret.name[1] = id[2]; ret.major_version = decode_digit(id[3]); ret.minor_version = decode_digit(id[4]); ret.revision_version = decode_digit(id[5]); ret.tag_version = decode_digit(id[6]); return boost::optional<fingerprint>(ret); } // checks if a peer id can possibly contain a shadow-style // identification boost::optional<fingerprint> parse_shadow_style(const peer_id& id) { fingerprint ret("..", 0, 0, 0, 0); if (!std::isalnum(id[0])) return boost::optional<fingerprint>(); if (std::equal(id.begin()+4, id.begin()+6, "--")) { if ((id[1] < '0') || (id[2] < '0') || (id[3] < '0')) return boost::optional<fingerprint>(); ret.major_version = decode_digit(id[1]); ret.minor_version = decode_digit(id[2]); ret.revision_version = decode_digit(id[3]); } else { if (id[8] != 0 || id[1] > 127 || id[2] > 127 || id[3] > 127) return boost::optional<fingerprint>(); ret.major_version = id[1]; ret.minor_version = id[2]; ret.revision_version = id[3]; } ret.name[0] = id[0]; ret.name[1] = 0; ret.tag_version = 0; return boost::optional<fingerprint>(ret); } // checks if a peer id can possibly contain a mainline-style // identification boost::optional<fingerprint> parse_mainline_style(const peer_id& id) { char ids[21]; std::copy(id.begin(), id.end(), ids); ids[20] = 0; fingerprint ret("..", 0, 0, 0, 0); ret.name[1] = 0; ret.tag_version = 0; if (sscanf(ids, "%c%d-%d-%d--", &ret.name[0], &ret.major_version, &ret.minor_version , &ret.revision_version) != 4 || !std::isprint(ret.name[0])) return boost::optional<fingerprint>(); return boost::optional<fingerprint>(ret); } struct map_entry { char const* id; char const* name; }; // only support BitTorrentSpecification // must be ordered alphabetically map_entry name_map[] = { {"A", "ABC"} , {"AG", "Ares"} , {"AR", "Arctic Torrent"} , {"AV", "Avicora"} , {"AX", "BitPump"} , {"AZ", "Azureus"} , {"A~", "Ares"} , {"BB", "BitBuddy"} , {"BC", "BitComet"} , {"BF", "Bitflu"} , {"BG", "BTG"} , {"BR", "BitRocket"} , {"BS", "BTSlave"} , {"BX", "BittorrentX"} , {"CD", "Enhanced CTorrent"} , {"CT", "CTorrent"} , {"DE", "Deluge Torrent"} , {"EB", "EBit"} , {"ES", "electric sheep"} , {"HL", "Halite"} , {"HN", "Hydranode"} , {"KT", "KTorrent"} , {"LK", "Linkage"} , {"LP", "lphant"} , {"LT", "libtorrent"} , {"M", "Mainline"} , {"ML", "MLDonkey"} , {"MO", "Mono Torrent"} , {"MP", "MooPolice"} , {"MT", "Moonlight Torrent"} , {"O", "Osprey Permaseed"} , {"PD", "Pando"} , {"Q", "BTQueue"} , {"QT", "Qt 4"} , {"R", "Tribler"} , {"S", "Shadow"} , {"SB", "Swiftbit"} , {"SN", "ShareNet"} , {"SS", "SwarmScope"} , {"SZ", "Shareaza"} , {"S~", "Shareaza (beta)"} , {"T", "BitTornado"} , {"TN", "Torrent.NET"} , {"TR", "Transmission"} , {"TS", "TorrentStorm"} , {"TT", "TuoTu"} , {"U", "UPnP"} , {"UL", "uLeecher"} , {"UT", "uTorrent"} , {"XT", "XanTorrent"} , {"XX", "Xtorrent"} , {"ZT", "ZipTorrent"} , {"lt", "rTorrent"} , {"pX", "pHoeniX"} , {"qB", "qBittorrent"} }; bool compare_id(map_entry const& lhs, map_entry const& rhs) { return lhs.id[0] < rhs.id[0] || ((lhs.id[0] == rhs.id[0]) && (lhs.id[1] < rhs.id[1])); } std::string lookup(fingerprint const& f) { std::stringstream identity; const int size = sizeof(name_map)/sizeof(name_map[0]); map_entry tmp = {f.name, ""}; map_entry* i = std::lower_bound(name_map, name_map + size , tmp, &compare_id); #ifndef NDEBUG for (int i = 1; i < size; ++i) { assert(compare_id(name_map[i-1] , name_map[i])); } #endif if (i < name_map + size && std::equal(f.name, f.name + 2, i->id)) identity << i->name; else { identity << f.name[0]; if (f.name[1] != 0) identity << f.name[1]; } identity << " " << (int)f.major_version << "." << (int)f.minor_version << "." << (int)f.revision_version; if (f.name[1] != 0) identity << "." << (int)f.tag_version; return identity.str(); } bool find_string(unsigned char const* id, char const* search) { return std::equal(search, search + std::strlen(search), id); } } namespace libtorrent { boost::optional<fingerprint> client_fingerprint(peer_id const& p) { // look for azureus style id boost::optional<fingerprint> f; f = parse_az_style(p); if (f) return f; // look for shadow style id f = parse_shadow_style(p); if (f) return f; // look for mainline style id f = parse_mainline_style(p); if (f) return f; return f; } std::string identify_client(peer_id const& p) { peer_id::const_iterator PID = p.begin(); boost::optional<fingerprint> f; if (p.is_all_zeros()) return "Unknown"; // ---------------------- // non standard encodings // ---------------------- if (find_string(PID, "Deadman Walking-")) return "Deadman"; if (find_string(PID + 5, "Azureus")) return "Azureus 2.0.3.2"; if (find_string(PID, "DansClient")) return "XanTorrent"; if (find_string(PID + 4, "btfans")) return "SimpleBT"; if (find_string(PID, "PRC.P---")) return "Bittorrent Plus! II"; if (find_string(PID, "P87.P---")) return "Bittorrent Plus!"; if (find_string(PID, "S587Plus")) return "Bittorrent Plus!"; if (find_string(PID, "martini")) return "Martini Man"; if (find_string(PID, "Plus---")) return "Bittorrent Plus"; if (find_string(PID, "turbobt")) return "TurboBT"; if (find_string(PID, "a00---0")) return "Swarmy"; if (find_string(PID, "a02---0")) return "Swarmy"; if (find_string(PID, "T00---0")) return "Teeweety"; if (find_string(PID, "BTDWV-")) return "Deadman Walking"; if (find_string(PID + 2, "BS")) return "BitSpirit"; if (find_string(PID, "Pando-")) return "Pando"; if (find_string(PID, "LIME")) return "LimeWire"; if (find_string(PID, "btuga")) return "BTugaXP"; if (find_string(PID, "oernu")) return "BTugaXP"; if (find_string(PID, "Mbrst")) return "Burst!"; if (find_string(PID, "Plus")) return "Plus!"; if (find_string(PID, "-Qt-")) return "Qt"; if (find_string(PID, "exbc")) return "BitComet"; if (find_string(PID, "DNA")) return "BitTorrent DNA"; if (find_string(PID, "-G3")) return "G3 Torrent"; if (find_string(PID, "XBT")) return "XBT"; if (find_string(PID, "OP")) return "Opera"; if (find_string(PID, "-BOW") && PID[7] == '-') return "Bits on Wheels " + std::string(PID + 4, PID + 7); if (find_string(PID, "eX")) { std::string user(PID + 2, PID + 14); return std::string("eXeem ('") + user.c_str() + "')"; } if (std::equal(PID, PID + 13, "\0\0\0\0\0\0\0\0\0\0\0\0\x97")) return "Experimental 3.2.1b2"; if (std::equal(PID, PID + 13, "\0\0\0\0\0\0\0\0\0\0\0\0\0")) return "Experimental 3.1"; // look for azureus style id f = parse_az_style(p); if (f) return lookup(*f); // look for shadow style id f = parse_shadow_style(p); if (f) return lookup(*f); // look for mainline style id f = parse_mainline_style(p); if (f) return lookup(*f); if (std::equal(PID, PID + 12, "\0\0\0\0\0\0\0\0\0\0\0\0")) return "Generic"; std::string unknown("Unknown ["); for (peer_id::const_iterator i = p.begin(); i != p.end(); ++i) { unknown += std::isprint(*i)?*i:'.'; } unknown += "]"; return unknown; } } <commit_msg>refactored identify_client<commit_after>/* Copyright (c) 2003, Arvid Norberg 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. */ #include "libtorrent/pch.hpp" #include <cctype> #include <algorithm> #ifdef _MSC_VER #pragma warning(push, 1) #endif #include <boost/optional.hpp> #ifdef _MSC_VER #pragma warning(pop) #endif #include "libtorrent/identify_client.hpp" #include "libtorrent/fingerprint.hpp" namespace { using namespace libtorrent; int decode_digit(char c) { if (std::isdigit(c)) return c - '0'; return unsigned(c) - 'A' + 10; } // takes a peer id and returns a valid boost::optional // object if the peer id matched the azureus style encoding // the returned fingerprint contains information about the // client's id boost::optional<fingerprint> parse_az_style(const peer_id& id) { fingerprint ret("..", 0, 0, 0, 0); if (id[0] != '-' || !std::isprint(id[1]) || (id[2] < '0') || (id[3] < '0') || (id[4] < '0') || (id[5] < '0') || (id[6] < '0') || id[7] != '-') return boost::optional<fingerprint>(); ret.name[0] = id[1]; ret.name[1] = id[2]; ret.major_version = decode_digit(id[3]); ret.minor_version = decode_digit(id[4]); ret.revision_version = decode_digit(id[5]); ret.tag_version = decode_digit(id[6]); return boost::optional<fingerprint>(ret); } // checks if a peer id can possibly contain a shadow-style // identification boost::optional<fingerprint> parse_shadow_style(const peer_id& id) { fingerprint ret("..", 0, 0, 0, 0); if (!std::isalnum(id[0])) return boost::optional<fingerprint>(); if (std::equal(id.begin()+4, id.begin()+6, "--")) { if ((id[1] < '0') || (id[2] < '0') || (id[3] < '0')) return boost::optional<fingerprint>(); ret.major_version = decode_digit(id[1]); ret.minor_version = decode_digit(id[2]); ret.revision_version = decode_digit(id[3]); } else { if (id[8] != 0 || id[1] > 127 || id[2] > 127 || id[3] > 127) return boost::optional<fingerprint>(); ret.major_version = id[1]; ret.minor_version = id[2]; ret.revision_version = id[3]; } ret.name[0] = id[0]; ret.name[1] = 0; ret.tag_version = 0; return boost::optional<fingerprint>(ret); } // checks if a peer id can possibly contain a mainline-style // identification boost::optional<fingerprint> parse_mainline_style(const peer_id& id) { char ids[21]; std::copy(id.begin(), id.end(), ids); ids[20] = 0; fingerprint ret("..", 0, 0, 0, 0); ret.name[1] = 0; ret.tag_version = 0; if (sscanf(ids, "%c%d-%d-%d--", &ret.name[0], &ret.major_version, &ret.minor_version , &ret.revision_version) != 4 || !std::isprint(ret.name[0])) return boost::optional<fingerprint>(); return boost::optional<fingerprint>(ret); } struct map_entry { char const* id; char const* name; }; // only support BitTorrentSpecification // must be ordered alphabetically map_entry name_map[] = { {"A", "ABC"} , {"AG", "Ares"} , {"AR", "Arctic Torrent"} , {"AV", "Avicora"} , {"AX", "BitPump"} , {"AZ", "Azureus"} , {"A~", "Ares"} , {"BB", "BitBuddy"} , {"BC", "BitComet"} , {"BF", "Bitflu"} , {"BG", "BTG"} , {"BR", "BitRocket"} , {"BS", "BTSlave"} , {"BX", "BittorrentX"} , {"CD", "Enhanced CTorrent"} , {"CT", "CTorrent"} , {"DE", "Deluge Torrent"} , {"EB", "EBit"} , {"ES", "electric sheep"} , {"HL", "Halite"} , {"HN", "Hydranode"} , {"KT", "KTorrent"} , {"LK", "Linkage"} , {"LP", "lphant"} , {"LT", "libtorrent"} , {"M", "Mainline"} , {"ML", "MLDonkey"} , {"MO", "Mono Torrent"} , {"MP", "MooPolice"} , {"MT", "Moonlight Torrent"} , {"O", "Osprey Permaseed"} , {"PD", "Pando"} , {"Q", "BTQueue"} , {"QT", "Qt 4"} , {"R", "Tribler"} , {"S", "Shadow"} , {"SB", "Swiftbit"} , {"SN", "ShareNet"} , {"SS", "SwarmScope"} , {"ST", "SymTorrent"} , {"SZ", "Shareaza"} , {"S~", "Shareaza (beta)"} , {"T", "BitTornado"} , {"TN", "Torrent.NET"} , {"TR", "Transmission"} , {"TS", "TorrentStorm"} , {"TT", "TuoTu"} , {"U", "UPnP"} , {"UL", "uLeecher"} , {"UT", "uTorrent"} , {"XL", "Xunlei"} , {"XT", "XanTorrent"} , {"XX", "Xtorrent"} , {"ZT", "ZipTorrent"} , {"lt", "rTorrent"} , {"pX", "pHoeniX"} , {"qB", "qBittorrent"} , {"st", "SharkTorrent"} }; struct generic_map_entry { int offset; char const* id; char const* name; }; // non-standard names generic_map_entry generic_mappings[] = { {0, "Deadman Walking-", "Deadman"} , {5, "Azureus", "Azureus 2.0.3.2"} , {0, "DansClient", "XanTorrent"} , {4, "btfans", "SimpleBT"} , {0, "PRC.P---", "Bittorrent Plus! II"} , {0, "P87.P---", "Bittorrent Plus!"} , {0, "S587Plus", "Bittorrent Plus!"} , {0, "martini", "Martini Man"} , {0, "Plus---", "Bittorrent Plus"} , {0, "turbobt", "TurboBT"} , {0, "a00---0", "Swarmy"} , {0, "a02---0", "Swarmy"} , {0, "T00---0", "Teeweety"} , {0, "BTDWV-", "Deadman Walking"} , {2, "BS", "BitSpirit"} , {0, "Pando-", "Pando"} , {0, "LIME", "LimeWire"} , {0, "btuga", "BTugaXP"} , {0, "oernu", "BTugaXP"} , {0, "Mbrst", "Burst!"} , {0, "PEERAPP", "PeerApp"} , {0, "Plus", "Plus!"} , {0, "-Qt-", "Qt"} , {0, "exbc", "BitComet"} , {0, "DNA", "BitTorrent DNA"} , {0, "-G3", "G3 Torrent"} , {0, "-FG", "FlashGet"} , {0, "-ML", "MLdonkey"} , {0, "XBT", "XBT"} , {0, "OP", "Opera"} , {2, "RS", "Rufus"} , {0, "AZ2500BT", "BitTyrant"} }; bool compare_id(map_entry const& lhs, map_entry const& rhs) { return lhs.id[0] < rhs.id[0] || ((lhs.id[0] == rhs.id[0]) && (lhs.id[1] < rhs.id[1])); } std::string lookup(fingerprint const& f) { std::stringstream identity; const int size = sizeof(name_map)/sizeof(name_map[0]); map_entry tmp = {f.name, ""}; map_entry* i = std::lower_bound(name_map, name_map + size , tmp, &compare_id); #ifndef NDEBUG for (int i = 1; i < size; ++i) { assert(compare_id(name_map[i-1] , name_map[i])); } #endif if (i < name_map + size && std::equal(f.name, f.name + 2, i->id)) identity << i->name; else { identity << f.name[0]; if (f.name[1] != 0) identity << f.name[1]; } identity << " " << (int)f.major_version << "." << (int)f.minor_version << "." << (int)f.revision_version; if (f.name[1] != 0) identity << "." << (int)f.tag_version; return identity.str(); } bool find_string(unsigned char const* id, char const* search) { return std::equal(search, search + std::strlen(search), id); } } namespace libtorrent { boost::optional<fingerprint> client_fingerprint(peer_id const& p) { // look for azureus style id boost::optional<fingerprint> f; f = parse_az_style(p); if (f) return f; // look for shadow style id f = parse_shadow_style(p); if (f) return f; // look for mainline style id f = parse_mainline_style(p); if (f) return f; return f; } std::string identify_client(peer_id const& p) { peer_id::const_iterator PID = p.begin(); boost::optional<fingerprint> f; if (p.is_all_zeros()) return "Unknown"; // ---------------------- // non standard encodings // ---------------------- int num_generic_mappings = sizeof(generic_mappings) / sizeof(generic_mappings[0]); for (int i = 0; i < num_generic_mappings; ++i) { generic_map_entry const& e = generic_mappings[i]; if (find_string(PID + e.offset, e.id)) return e.name; } if (find_string(PID, "-BOW") && PID[7] == '-') return "Bits on Wheels " + std::string(PID + 4, PID + 7); if (find_string(PID, "eX")) { std::string user(PID + 2, PID + 14); return std::string("eXeem ('") + user.c_str() + "')"; } if (std::equal(PID, PID + 13, "\0\0\0\0\0\0\0\0\0\0\0\0\x97")) return "Experimental 3.2.1b2"; if (std::equal(PID, PID + 13, "\0\0\0\0\0\0\0\0\0\0\0\0\0")) return "Experimental 3.1"; // look for azureus style id f = parse_az_style(p); if (f) return lookup(*f); // look for shadow style id f = parse_shadow_style(p); if (f) return lookup(*f); // look for mainline style id f = parse_mainline_style(p); if (f) return lookup(*f); if (std::equal(PID, PID + 12, "\0\0\0\0\0\0\0\0\0\0\0\0")) return "Generic"; std::string unknown("Unknown ["); for (peer_id::const_iterator i = p.begin(); i != p.end(); ++i) { unknown += std::isprint(*i)?*i:'.'; } unknown += "]"; return unknown; } } <|endoftext|>
<commit_before>/* Copyright (c) 2003, Arvid Norberg 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. */ #include <cctype> #include <algorithm> #ifdef _MSC_VER #pragma warning(push, 1) #endif #include <boost/optional.hpp> #ifdef _MSC_VER #pragma warning(pop) #endif #include "libtorrent/identify_client.hpp" #include "libtorrent/fingerprint.hpp" namespace { using namespace libtorrent; int decode_digit(char c) { if (std::isdigit(c)) return c - '0'; return unsigned(c) - 'A' + 10; } // takes a peer id and returns a valid boost::optional // object if the peer id matched the azureus style encoding // the returned fingerprint contains information about the // client's id boost::optional<fingerprint> parse_az_style(const peer_id& id) { fingerprint ret("..", 0, 0, 0, 0); if (id[0] != '-' || !std::isprint(id[1]) || (id[2] < '0') || (id[3] < '0') || (id[4] < '0') || (id[5] < '0') || (id[6] < '0') || id[7] != '-') return boost::optional<fingerprint>(); ret.name[0] = id[1]; ret.name[1] = id[2]; ret.major_version = decode_digit(id[3]); ret.minor_version = decode_digit(id[4]); ret.revision_version = decode_digit(id[5]); ret.tag_version = decode_digit(id[6]); return boost::optional<fingerprint>(ret); } // checks if a peer id can possibly contain a shadow-style // identification boost::optional<fingerprint> parse_shadow_style(const peer_id& id) { fingerprint ret("..", 0, 0, 0, 0); if (!std::isalnum(id[0])) return boost::optional<fingerprint>(); if (std::equal(id.begin()+4, id.begin()+6, "--")) { if ((id[1] < '0') || (id[2] < '0') || (id[3] < '0')) return boost::optional<fingerprint>(); ret.major_version = decode_digit(id[1]); ret.minor_version = decode_digit(id[2]); ret.revision_version = decode_digit(id[3]); } else { if (id[8] != 0 || id[1] > 127 || id[2] > 127 || id[3] > 127) return boost::optional<fingerprint>(); ret.major_version = id[1]; ret.minor_version = id[2]; ret.revision_version = id[3]; } ret.name[0] = id[0]; ret.name[1] = 0; ret.tag_version = 0; return boost::optional<fingerprint>(ret); } // checks if a peer id can possibly contain a mainline-style // identification boost::optional<fingerprint> parse_mainline_style(const peer_id& id) { char ids[21]; std::copy(id.begin(), id.end(), ids); ids[20] = 0; fingerprint ret("..", 0, 0, 0, 0); ret.name[1] = 0; ret.tag_version = 0; if (sscanf(ids, "%c%d-%d-%d--", &ret.id[0], &ret.major_version, &ret.minor_version , &ret.revision_version) != 4 || !std::isprint(ret.id[0])) return boost::optional<fingerprint>(); return boost::optional<fingerprint>(ret); } typedef std::pair<char const*, char const*> map_entry; // only support BitTorrentSpecification // must be ordered alphabetically map_entry name_map[] = { map_entry("A", "ABC") , map_entry("AR", "Arctic Torrent") , map_entry("AX", "BitPump") , map_entry("AZ", "Azureus") , map_entry("BB", "BitBuddy") , map_entry("BC", "BitComet") , map_entry("BS", "BTSlave") , map_entry("BX", "BittorrentX") , map_entry("CD", "Enhanced CTorrent") , map_entry("CT", "CTorrent") , map_entry("KT", "KTorrent") , map_entry("LP", "lphant") , map_entry("LT", "libtorrent") , map_entry("M", "Mainline") , map_entry("MP", "MooPolice") , map_entry("MT", "Moonlight Torrent") , map_entry("O", "Osprey Permaseed") , map_entry("R", "Tribler") , map_entry("S", "Shadow") , map_entry("SB", "Swiftbit") , map_entry("SN", "ShareNet") , map_entry("SS", "SwarmScope") , map_entry("SZ", "Shareaza") , map_entry("T", "BitTornado") , map_entry("TN", "Torrent.NET") , map_entry("TR", "Transmission") , map_entry("TS", "TorrentStorm") , map_entry("U", "UPnP") , map_entry("UT", "MicroTorrent") , map_entry("XT", "XanTorrent") , map_entry("ZT", "ZipTorrent") , map_entry("lt", "libTorrent (libtorrent.rakshasa.no/)") , map_entry("pX", "pHoeniX") }; bool compare_first_string(map_entry const& lhs, map_entry const& rhs) { return lhs.first[0] < rhs.first[0] || ((lhs.first[0] == rhs.first[0]) && (lhs.first[1] < rhs.first[1])); } std::string lookup(fingerprint const& f) { std::stringstream identity; const int size = sizeof(name_map)/sizeof(name_map[0]); map_entry* i = std::lower_bound(name_map, name_map + size , map_entry(f.name, ""), &compare_first_string); #ifndef NDEBUG for (int i = 1; i < size; ++i) { assert(compare_first_string(name_map[i-1] , name_map[i])); } #endif if (i < name_map + size && std::equal(f.name, f.name + 2, i->first)) identity << i->second; else { identity << f.name[0]; if (f.name[1] != 0) identity << f.name[1]; } identity << " " << (int)f.major_version << "." << (int)f.minor_version << "." << (int)f.revision_version; if (f.name[1] != 0) identity << "." << (int)f.tag_version; return identity.str(); } bool find_string(unsigned char const* id, char const* search) { return std::equal(search, search + std::strlen(search), id); } } namespace libtorrent { boost::optional<fingerprint> client_fingerprint(peer_id const& p) { // look for azureus style id boost::optional<fingerprint> f; f = parse_az_style(p); if (f) return f; // look for shadow style id f = parse_shadow_style(p); if (f) return f; // look for mainline style id f = parse_mainline_style(p); if (f) return f; return f; } std::string identify_client(peer_id const& p) { peer_id::const_iterator PID = p.begin(); boost::optional<fingerprint> f; if (p.is_all_zeros()) return "Unknown"; // ---------------------- // non standard encodings // ---------------------- if (find_string(PID, "Deadman Walking-")) return "Deadman"; if (find_string(PID + 5, "Azureus")) return "Azureus 2.0.3.2"; if (find_string(PID, "DansClient")) return "XanTorrent"; if (find_string(PID + 4, "btfans")) return "SimpleBT"; if (find_string(PID, "PRC.P---")) return "Bittorrent Plus! II"; if (find_string(PID, "P87.P---")) return "Bittorrent Plus!"; if (find_string(PID, "S587Plus")) return "Bittorrent Plus!"; if (find_string(PID, "martini")) return "Martini Man"; if (find_string(PID, "Plus---")) return "Bittorrent Plus"; if (find_string(PID, "turbobt")) return "TurboBT"; if (find_string(PID, "a00---0")) return "Swarmy"; if (find_string(PID, "a02---0")) return "Swarmy"; if (find_string(PID, "T00---0")) return "Teeweety"; if (find_string(PID, "BTDWV-")) return "Deadman Walking"; if (find_string(PID + 2, "BS")) return "BitSpirit"; if (find_string(PID, "btuga")) return "BTugaXP"; if (find_string(PID, "oernu")) return "BTugaXP"; if (find_string(PID, "Mbrst")) return "Burst!"; if (find_string(PID, "Plus")) return "Plus!"; if (find_string(PID, "-Qt-")) return "Qt"; if (find_string(PID, "exbc")) return "BitComet"; if (find_string(PID, "-G3")) return "G3 Torrent"; if (find_string(PID, "XBT")) return "XBT"; if (find_string(PID, "OP")) return "Opera"; if (find_string(PID, "-BOW") && PID[7] == '-') return "Bits on Wheels " + std::string(PID + 4, PID + 7); if (find_string(PID, "eX")) { std::string user(PID + 2, PID + 14); return std::string("eXeem ('") + user.c_str() + "')"; } if (std::equal(PID, PID + 13, "\0\0\0\0\0\0\0\0\0\0\0\0\x97")) return "Experimental 3.2.1b2"; if (std::equal(PID, PID + 13, "\0\0\0\0\0\0\0\0\0\0\0\0\0")) return "Experimental 3.1"; // look for azureus style id f = parse_az_style(p); if (f) return lookup(*f); // look for shadow style id f = parse_shadow_style(p); if (f) return lookup(*f); // look for mainline style id f = parse_mainline_style(p); if (f) return lookup(*f); if (std::equal(PID, PID + 12, "\0\0\0\0\0\0\0\0\0\0\0\0")) return "Generic"; std::string unknown("Unknown ["); for (peer_id::const_iterator i = p.begin(); i != p.end(); ++i) { unknown += std::isprint(*i)?*i:'.'; } unknown += "]"; return unknown; } } <commit_msg>fixed compilation error in previous checkin<commit_after>/* Copyright (c) 2003, Arvid Norberg 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. */ #include <cctype> #include <algorithm> #ifdef _MSC_VER #pragma warning(push, 1) #endif #include <boost/optional.hpp> #ifdef _MSC_VER #pragma warning(pop) #endif #include "libtorrent/identify_client.hpp" #include "libtorrent/fingerprint.hpp" namespace { using namespace libtorrent; int decode_digit(char c) { if (std::isdigit(c)) return c - '0'; return unsigned(c) - 'A' + 10; } // takes a peer id and returns a valid boost::optional // object if the peer id matched the azureus style encoding // the returned fingerprint contains information about the // client's id boost::optional<fingerprint> parse_az_style(const peer_id& id) { fingerprint ret("..", 0, 0, 0, 0); if (id[0] != '-' || !std::isprint(id[1]) || (id[2] < '0') || (id[3] < '0') || (id[4] < '0') || (id[5] < '0') || (id[6] < '0') || id[7] != '-') return boost::optional<fingerprint>(); ret.name[0] = id[1]; ret.name[1] = id[2]; ret.major_version = decode_digit(id[3]); ret.minor_version = decode_digit(id[4]); ret.revision_version = decode_digit(id[5]); ret.tag_version = decode_digit(id[6]); return boost::optional<fingerprint>(ret); } // checks if a peer id can possibly contain a shadow-style // identification boost::optional<fingerprint> parse_shadow_style(const peer_id& id) { fingerprint ret("..", 0, 0, 0, 0); if (!std::isalnum(id[0])) return boost::optional<fingerprint>(); if (std::equal(id.begin()+4, id.begin()+6, "--")) { if ((id[1] < '0') || (id[2] < '0') || (id[3] < '0')) return boost::optional<fingerprint>(); ret.major_version = decode_digit(id[1]); ret.minor_version = decode_digit(id[2]); ret.revision_version = decode_digit(id[3]); } else { if (id[8] != 0 || id[1] > 127 || id[2] > 127 || id[3] > 127) return boost::optional<fingerprint>(); ret.major_version = id[1]; ret.minor_version = id[2]; ret.revision_version = id[3]; } ret.name[0] = id[0]; ret.name[1] = 0; ret.tag_version = 0; return boost::optional<fingerprint>(ret); } // checks if a peer id can possibly contain a mainline-style // identification boost::optional<fingerprint> parse_mainline_style(const peer_id& id) { char ids[21]; std::copy(id.begin(), id.end(), ids); ids[20] = 0; fingerprint ret("..", 0, 0, 0, 0); ret.name[1] = 0; ret.tag_version = 0; if (sscanf(ids, "%c%d-%d-%d--", &ret.name[0], &ret.major_version, &ret.minor_version , &ret.revision_version) != 4 || !std::isprint(ret.name[0])) return boost::optional<fingerprint>(); return boost::optional<fingerprint>(ret); } typedef std::pair<char const*, char const*> map_entry; // only support BitTorrentSpecification // must be ordered alphabetically map_entry name_map[] = { map_entry("A", "ABC") , map_entry("AR", "Arctic Torrent") , map_entry("AX", "BitPump") , map_entry("AZ", "Azureus") , map_entry("BB", "BitBuddy") , map_entry("BC", "BitComet") , map_entry("BS", "BTSlave") , map_entry("BX", "BittorrentX") , map_entry("CD", "Enhanced CTorrent") , map_entry("CT", "CTorrent") , map_entry("KT", "KTorrent") , map_entry("LP", "lphant") , map_entry("LT", "libtorrent") , map_entry("M", "Mainline") , map_entry("MP", "MooPolice") , map_entry("MT", "Moonlight Torrent") , map_entry("O", "Osprey Permaseed") , map_entry("R", "Tribler") , map_entry("S", "Shadow") , map_entry("SB", "Swiftbit") , map_entry("SN", "ShareNet") , map_entry("SS", "SwarmScope") , map_entry("SZ", "Shareaza") , map_entry("T", "BitTornado") , map_entry("TN", "Torrent.NET") , map_entry("TR", "Transmission") , map_entry("TS", "TorrentStorm") , map_entry("U", "UPnP") , map_entry("UT", "MicroTorrent") , map_entry("XT", "XanTorrent") , map_entry("ZT", "ZipTorrent") , map_entry("lt", "libTorrent (libtorrent.rakshasa.no/)") , map_entry("pX", "pHoeniX") }; bool compare_first_string(map_entry const& lhs, map_entry const& rhs) { return lhs.first[0] < rhs.first[0] || ((lhs.first[0] == rhs.first[0]) && (lhs.first[1] < rhs.first[1])); } std::string lookup(fingerprint const& f) { std::stringstream identity; const int size = sizeof(name_map)/sizeof(name_map[0]); map_entry* i = std::lower_bound(name_map, name_map + size , map_entry(f.name, ""), &compare_first_string); #ifndef NDEBUG for (int i = 1; i < size; ++i) { assert(compare_first_string(name_map[i-1] , name_map[i])); } #endif if (i < name_map + size && std::equal(f.name, f.name + 2, i->first)) identity << i->second; else { identity << f.name[0]; if (f.name[1] != 0) identity << f.name[1]; } identity << " " << (int)f.major_version << "." << (int)f.minor_version << "." << (int)f.revision_version; if (f.name[1] != 0) identity << "." << (int)f.tag_version; return identity.str(); } bool find_string(unsigned char const* id, char const* search) { return std::equal(search, search + std::strlen(search), id); } } namespace libtorrent { boost::optional<fingerprint> client_fingerprint(peer_id const& p) { // look for azureus style id boost::optional<fingerprint> f; f = parse_az_style(p); if (f) return f; // look for shadow style id f = parse_shadow_style(p); if (f) return f; // look for mainline style id f = parse_mainline_style(p); if (f) return f; return f; } std::string identify_client(peer_id const& p) { peer_id::const_iterator PID = p.begin(); boost::optional<fingerprint> f; if (p.is_all_zeros()) return "Unknown"; // ---------------------- // non standard encodings // ---------------------- if (find_string(PID, "Deadman Walking-")) return "Deadman"; if (find_string(PID + 5, "Azureus")) return "Azureus 2.0.3.2"; if (find_string(PID, "DansClient")) return "XanTorrent"; if (find_string(PID + 4, "btfans")) return "SimpleBT"; if (find_string(PID, "PRC.P---")) return "Bittorrent Plus! II"; if (find_string(PID, "P87.P---")) return "Bittorrent Plus!"; if (find_string(PID, "S587Plus")) return "Bittorrent Plus!"; if (find_string(PID, "martini")) return "Martini Man"; if (find_string(PID, "Plus---")) return "Bittorrent Plus"; if (find_string(PID, "turbobt")) return "TurboBT"; if (find_string(PID, "a00---0")) return "Swarmy"; if (find_string(PID, "a02---0")) return "Swarmy"; if (find_string(PID, "T00---0")) return "Teeweety"; if (find_string(PID, "BTDWV-")) return "Deadman Walking"; if (find_string(PID + 2, "BS")) return "BitSpirit"; if (find_string(PID, "btuga")) return "BTugaXP"; if (find_string(PID, "oernu")) return "BTugaXP"; if (find_string(PID, "Mbrst")) return "Burst!"; if (find_string(PID, "Plus")) return "Plus!"; if (find_string(PID, "-Qt-")) return "Qt"; if (find_string(PID, "exbc")) return "BitComet"; if (find_string(PID, "-G3")) return "G3 Torrent"; if (find_string(PID, "XBT")) return "XBT"; if (find_string(PID, "OP")) return "Opera"; if (find_string(PID, "-BOW") && PID[7] == '-') return "Bits on Wheels " + std::string(PID + 4, PID + 7); if (find_string(PID, "eX")) { std::string user(PID + 2, PID + 14); return std::string("eXeem ('") + user.c_str() + "')"; } if (std::equal(PID, PID + 13, "\0\0\0\0\0\0\0\0\0\0\0\0\x97")) return "Experimental 3.2.1b2"; if (std::equal(PID, PID + 13, "\0\0\0\0\0\0\0\0\0\0\0\0\0")) return "Experimental 3.1"; // look for azureus style id f = parse_az_style(p); if (f) return lookup(*f); // look for shadow style id f = parse_shadow_style(p); if (f) return lookup(*f); // look for mainline style id f = parse_mainline_style(p); if (f) return lookup(*f); if (std::equal(PID, PID + 12, "\0\0\0\0\0\0\0\0\0\0\0\0")) return "Generic"; std::string unknown("Unknown ["); for (peer_id::const_iterator i = p.begin(); i != p.end(); ++i) { unknown += std::isprint(*i)?*i:'.'; } unknown += "]"; return unknown; } } <|endoftext|>
<commit_before>/* Copyright (c) 2003, Arvid Norberg 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. */ #include <cctype> #ifdef _MSC_VER #pragma warning(push, 1) #endif #include <boost/optional.hpp> #ifdef _MSC_VER #pragma warning(pop) #endif #include "libtorrent/identify_client.hpp" #include "libtorrent/fingerprint.hpp" #if defined(_MSC_VER) && _MSC_VER < 1300 namespace std { using ::isprint; using ::isdigit; } #endif namespace { using namespace libtorrent; // takes a peer id and returns a valid boost::optional // object if the peer id matched the azureus style encoding // the returned fingerprint contains information about the // client's id boost::optional<fingerprint> parse_az_style(const peer_id& id) { fingerprint ret("..", 0, 0, 0, 0); peer_id::const_iterator i = id.begin(); if (*i != '-') return boost::optional<fingerprint>(); ++i; for (int j = 0; j < 2; ++j) { if (!std::isprint(*i)) return boost::optional<fingerprint>(); ret.id[j] = *i; ++i; } if (!std::isdigit(*i)) return boost::optional<fingerprint>(); ret.major_version = *i - '0'; ++i; if (!std::isdigit(*i)) return boost::optional<fingerprint>(); ret.minor_version = *i - '0'; ++i; if (!std::isdigit(*i)) return boost::optional<fingerprint>(); ret.revision_version = *i - '0'; ++i; if (!std::isdigit(*i)) return boost::optional<fingerprint>(); ret.tag_version = *i - '0'; ++i; if (*i != '-') return boost::optional<fingerprint>(); return boost::optional<fingerprint>(ret); } // checks if a peer id can possibly contain a shadow-style // identification boost::optional<fingerprint> parse_shadow_style(const peer_id& id) { fingerprint ret("..", 0, 0, 0, 0); peer_id::const_iterator i = id.begin(); if (!std::isprint(*i)) return boost::optional<fingerprint>(); ret.id[0] = *i; ret.id[1] = 0; ++i; if (std::equal(id.begin()+4, id.begin()+8, "----")) { if (!std::isdigit(*i)) return boost::optional<fingerprint>(); ret.major_version = *i - '0'; ++i; if (!std::isdigit(*i)) return boost::optional<fingerprint>(); ret.minor_version = *i - '0'; ++i; if (!std::isdigit(*i)) return boost::optional<fingerprint>(); ret.revision_version = *i - '0'; } else if (id[8] == 0) { if (*i > 127) return boost::optional<fingerprint>(); ret.major_version = *i; ++i; if (*i > 127) return boost::optional<fingerprint>(); ret.minor_version = *i; ++i; if (*i > 127) return boost::optional<fingerprint>(); ret.revision_version = *i; } else return boost::optional<fingerprint>(); ret.tag_version = 0; return boost::optional<fingerprint>(ret); } // checks if a peer id can possibly contain a mainline-style // identification boost::optional<fingerprint> parse_mainline_style(const peer_id& id) { fingerprint ret("..", 0, 0, 0, 0); peer_id::const_iterator i = id.begin(); if (!std::isprint(*i)) return boost::optional<fingerprint>(); ret.id[0] = *i; ret.id[1] = 0; ++i; if (!std::isdigit(*i)) return boost::optional<fingerprint>(); ret.major_version = *i - '0'; ++i; if (*i != '-') return boost::optional<fingerprint>(); ++i; if (!std::isdigit(*i)) return boost::optional<fingerprint>(); ret.minor_version = *i - '0'; ++i; if (*i != '-') return boost::optional<fingerprint>(); ++i; if (!std::isdigit(*i)) return boost::optional<fingerprint>(); ret.revision_version = *i - '0'; ++i; if (!std::equal(i, i+1, "--")) return boost::optional<fingerprint>(); ret.tag_version = 0; return boost::optional<fingerprint>(ret); } } // namespace unnamed namespace libtorrent { std::string identify_client(const peer_id& p) { peer_id::const_iterator PID = p.begin(); boost::optional<fingerprint> f; if (p.is_all_zeros()) return "Unkown"; // look for azureus style id f = parse_az_style(p); if (f) { std::stringstream identity; // azureus if (std::equal(f->id, f->id+2, "AZ")) identity << "Azureus "; // BittorrentX else if (std::equal(f->id, f->id+2, "BX")) identity << "BittorrentX "; // libtorrent else if (std::equal(f->id, f->id+2, "LT")) identity << "libtorrent "; // Moonlight Torrent else if (std::equal(f->id, f->id+2, "MT")) identity << "Moonlight Torrent "; // Torrent Storm else if (std::equal(f->id, f->id+2, "TS")) identity << "TorrentStorm "; // SwarmScope else if (std::equal(f->id, f->id+2, "SS")) identity << "SwarmScope "; // XanTorrent else if (std::equal(f->id, f->id+2, "XT")) identity << "XanTorrent "; // unknown client else identity << std::string(f->id, f->id+2) << " "; identity << (int)f->major_version << "." << (int)f->minor_version << "." << (int)f->revision_version << "." << (int)f->tag_version; return identity.str(); } // look for shadow style id f = parse_shadow_style(p); if (f) { std::stringstream identity; // Shadow if (std::equal(f->id, f->id+1, "S")) identity << "Shadow "; // ABC else if (std::equal(f->id, f->id+1, "A")) identity << "ABC "; // UPnP else if (std::equal(f->id, f->id+1, "U")) identity << "UPnP "; // BitTornado else if (std::equal(f->id, f->id+1, "T")) identity << "BitTornado "; // unknown client else identity << std::string(f->id, f->id+1) << " "; identity << (int)f->major_version << "." << (int)f->minor_version << "." << (int)f->revision_version; return identity.str(); } f = parse_mainline_style(p); if (f) { std::stringstream identity; // Mainline if (std::equal(f->id, f->id+1, "M")) identity << "Mainline "; // unknown client else identity << std::string(f->id, f->id+1) << " "; identity << (int)f->major_version << "." << (int)f->minor_version << "." << (int)f->revision_version; return identity.str(); } // ---------------------- // non standard encodings // ---------------------- if (std::equal(PID, PID + 12, "-G3g3rmz ")) { return "G3 Torrent"; } if (std::equal(PID, PID + 4, "exbc")) { std::stringstream s; s << "BitComet " << (int)PID[4] << "." << (int)PID[5]/10 << (int)PID[5]%10; return s.str(); } if (std::equal(PID + 5, PID + 5 + 8, "Azureus")) { return "Azureus 2.0.3.2"; } if (std::equal(PID, PID + 11, "DansClient")) { return "XanTorrent"; } if (std::equal(PID, PID + 7, "Plus---")) { return "Bittorrent Plus"; } if (std::equal(PID, PID + 16, "Deadman Walking-")) { return "Deadman"; } if (std::equal(PID, PID + 7, "btuga")) { return "BTugaXP"; } if (std::equal(PID, PID + 7, "btfans")) { return "SimpleBT"; } if (std::equal(PID, PID + 7, "turbobt")) { std::stringstream s; s << "TurboBT " << PID[8] << "." << PID[10] << "." << PID[12]; return s.str(); } if (std::equal(PID, PID + 13, "\0\0\0\0\0\0\0\0\0\0\0\0\x97")) { return "Experimental 3.2.1b2"; } if (std::equal(PID, PID + 13, "\0\0\0\0\0\0\0\0\0\0\0\0\0")) { return "Experimental 3.1"; } if (std::equal(PID, PID + 12, "\0\0\0\0\0\0\0\0\0\0\0\0")) { return "Generic"; } std::string unknown("Unknown ["); for (peer_id::const_iterator i = p.begin(); i != p.end(); ++i) { unknown += std::isprint(*i)?*i:'.'; } unknown += "]"; return unknown; } } <commit_msg>*** empty log message ***<commit_after>/* Copyright (c) 2003, Arvid Norberg 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. */ #include <cctype> #ifdef _MSC_VER #pragma warning(push, 1) #endif #include <boost/optional.hpp> #ifdef _MSC_VER #pragma warning(pop) #endif #include "libtorrent/identify_client.hpp" #include "libtorrent/fingerprint.hpp" #if defined(_MSC_VER) && _MSC_VER < 1300 namespace std { using ::isprint; using ::isdigit; } #endif namespace { using namespace libtorrent; // takes a peer id and returns a valid boost::optional // object if the peer id matched the azureus style encoding // the returned fingerprint contains information about the // client's id boost::optional<fingerprint> parse_az_style(const peer_id& id) { fingerprint ret("..", 0, 0, 0, 0); peer_id::const_iterator i = id.begin(); if (*i != '-') return boost::optional<fingerprint>(); ++i; for (int j = 0; j < 2; ++j) { if (!std::isprint(*i)) return boost::optional<fingerprint>(); ret.id[j] = *i; ++i; } if (*i < '0') return boost::optional<fingerprint>(); ret.major_version = *i - '0'; ++i; if (*i < '0') return boost::optional<fingerprint>(); ret.minor_version = *i - '0'; ++i; if (*i < '0') return boost::optional<fingerprint>(); ret.revision_version = *i - '0'; ++i; if (*i < '0') return boost::optional<fingerprint>(); ret.tag_version = *i - '0'; ++i; if (*i != '-') return boost::optional<fingerprint>(); return boost::optional<fingerprint>(ret); } // checks if a peer id can possibly contain a shadow-style // identification boost::optional<fingerprint> parse_shadow_style(const peer_id& id) { fingerprint ret("..", 0, 0, 0, 0); peer_id::const_iterator i = id.begin(); if (*i < '0') return boost::optional<fingerprint>(); ret.id[0] = *i; ret.id[1] = 0; ++i; if (std::equal(id.begin()+4, id.begin()+8, "----")) { if (*i < '0') return boost::optional<fingerprint>(); ret.major_version = *i - '0'; ++i; if (*i < '0') return boost::optional<fingerprint>(); ret.minor_version = *i - '0'; ++i; if (*i < '0') return boost::optional<fingerprint>(); ret.revision_version = *i - '0'; } else if (id[8] == 0) { if (*i > 127) return boost::optional<fingerprint>(); ret.major_version = *i; ++i; if (*i > 127) return boost::optional<fingerprint>(); ret.minor_version = *i; ++i; if (*i > 127) return boost::optional<fingerprint>(); ret.revision_version = *i; } else return boost::optional<fingerprint>(); ret.tag_version = 0; return boost::optional<fingerprint>(ret); } // checks if a peer id can possibly contain a mainline-style // identification boost::optional<fingerprint> parse_mainline_style(const peer_id& id) { fingerprint ret("..", 0, 0, 0, 0); peer_id::const_iterator i = id.begin(); if (!std::isprint(*i)) return boost::optional<fingerprint>(); ret.id[0] = *i; ret.id[1] = 0; ++i; if (*i < '0') return boost::optional<fingerprint>(); ret.major_version = *i - '0'; ++i; if (*i != '-') return boost::optional<fingerprint>(); ++i; if (*i < '0') return boost::optional<fingerprint>(); ret.minor_version = *i - '0'; ++i; if (*i != '-') return boost::optional<fingerprint>(); ++i; if (*i < '0') return boost::optional<fingerprint>(); ret.revision_version = *i - '0'; ++i; if (!std::equal(i, i+1, "--")) return boost::optional<fingerprint>(); ret.tag_version = 0; return boost::optional<fingerprint>(ret); } } // namespace unnamed namespace libtorrent { std::string identify_client(const peer_id& p) { peer_id::const_iterator PID = p.begin(); boost::optional<fingerprint> f; if (p.is_all_zeros()) return "Unkown"; // look for azureus style id f = parse_az_style(p); if (f) { std::stringstream identity; // azureus if (std::equal(f->id, f->id+2, "AZ")) identity << "Azureus "; // BittorrentX else if (std::equal(f->id, f->id+2, "BX")) identity << "BittorrentX "; // libtorrent else if (std::equal(f->id, f->id+2, "LT")) identity << "libtorrent "; // Moonlight Torrent else if (std::equal(f->id, f->id+2, "MT")) identity << "Moonlight Torrent "; // Torrent Storm else if (std::equal(f->id, f->id+2, "TS")) identity << "TorrentStorm "; // SwarmScope else if (std::equal(f->id, f->id+2, "SS")) identity << "SwarmScope "; // XanTorrent else if (std::equal(f->id, f->id+2, "XT")) identity << "XanTorrent "; // unknown client else identity << std::string(f->id, f->id+2) << " "; identity << (int)f->major_version << "." << (int)f->minor_version << "." << (int)f->revision_version << "." << (int)f->tag_version; return identity.str(); } // look for shadow style id f = parse_shadow_style(p); if (f) { std::stringstream identity; // Shadow if (std::equal(f->id, f->id+1, "S")) identity << "Shadow "; // ABC else if (std::equal(f->id, f->id+1, "A")) identity << "ABC "; // UPnP else if (std::equal(f->id, f->id+1, "U")) identity << "UPnP "; // BitTornado else if (std::equal(f->id, f->id+1, "T")) identity << "BitTornado "; // unknown client else identity << std::string(f->id, f->id+1) << " "; identity << (int)f->major_version << "." << (int)f->minor_version << "." << (int)f->revision_version; return identity.str(); } f = parse_mainline_style(p); if (f) { std::stringstream identity; // Mainline if (std::equal(f->id, f->id+1, "M")) identity << "Mainline "; // unknown client else identity << std::string(f->id, f->id+1) << " "; identity << (int)f->major_version << "." << (int)f->minor_version << "." << (int)f->revision_version; return identity.str(); } // ---------------------- // non standard encodings // ---------------------- if (std::equal(PID, PID + 12, "-G3g3rmz ")) { return "G3 Torrent"; } if (std::equal(PID, PID + 4, "exbc")) { std::stringstream s; s << "BitComet " << (int)PID[4] << "." << (int)PID[5]/10 << (int)PID[5]%10; return s.str(); } if (std::equal(PID + 5, PID + 5 + 8, "Azureus")) { return "Azureus 2.0.3.2"; } if (std::equal(PID, PID + 11, "DansClient")) { return "XanTorrent"; } if (std::equal(PID, PID + 7, "Plus---")) { return "Bittorrent Plus"; } if (std::equal(PID, PID + 16, "Deadman Walking-")) { return "Deadman"; } if (std::equal(PID, PID + 7, "btuga")) { return "BTugaXP"; } if (std::equal(PID, PID + 7, "btfans")) { return "SimpleBT"; } if (std::equal(PID, PID + 7, "turbobt")) { std::stringstream s; s << "TurboBT " << PID[8] << "." << PID[10] << "." << PID[12]; return s.str(); } if (std::equal(PID, PID + 13, "\0\0\0\0\0\0\0\0\0\0\0\0\x97")) { return "Experimental 3.2.1b2"; } if (std::equal(PID, PID + 13, "\0\0\0\0\0\0\0\0\0\0\0\0\0")) { return "Experimental 3.1"; } if (std::equal(PID, PID + 12, "\0\0\0\0\0\0\0\0\0\0\0\0")) { return "Generic"; } std::string unknown("Unknown ["); for (peer_id::const_iterator i = p.begin(); i != p.end(); ++i) { unknown += std::isprint(*i)?*i:'.'; } unknown += "]"; return unknown; } } <|endoftext|>
<commit_before>// // Copyright (c) 2002-2013 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // #include "compiler/translator/OutputGLSL.h" TOutputGLSL::TOutputGLSL(TInfoSinkBase& objSink, ShArrayIndexClampingStrategy clampingStrategy, ShHashFunction64 hashFunction, NameMap& nameMap, TSymbolTable& symbolTable, int shaderVersion, ShShaderOutput output) : TOutputGLSLBase(objSink, clampingStrategy, hashFunction, nameMap, symbolTable, shaderVersion, output) { } bool TOutputGLSL::writeVariablePrecision(TPrecision) { return false; } void TOutputGLSL::visitSymbol(TIntermSymbol *node) { TInfoSinkBase& out = objSink(); const TString &symbol = node->getSymbol(); if (symbol == "gl_FragDepthEXT") { out << "gl_FragDepth"; } else if (symbol == "gl_FragColor" && IsGLSL130OrNewer(getShaderOutput())) { out << "webgl_FragColor"; } else if (symbol == "gl_FragData" && IsGLSL130OrNewer(getShaderOutput())) { out << "webgl_FragData"; } else if (symbol == "gl_SecondaryFragColorEXT") { out << "angle_SecondaryFragColor"; } else if (symbol == "gl_SecondaryFragDataEXT") { out << "angle_SecondaryFragData"; } else { TOutputGLSLBase::visitSymbol(node); } } TString TOutputGLSL::translateTextureFunction(TString &name) { static const char *simpleRename[] = { "texture2DLodEXT", "texture2DLod", "texture2DProjLodEXT", "texture2DProjLod", "textureCubeLodEXT", "textureCubeLod", "texture2DGradEXT", "texture2DGradARB", "texture2DProjGradEXT", "texture2DProjGradARB", "textureCubeGradEXT", "textureCubeGradARB", NULL, NULL }; static const char *legacyToCoreRename[] = { "texture2D", "texture", "texture2DProj", "textureProj", "texture2DLod", "textureLod", "texture2DProjLod", "textureProjLod", "textureCube", "texture", "textureCubeLod", "textureLod", // Extensions "texture2DLodEXT", "textureLod", "texture2DProjLodEXT", "textureProjLod", "textureCubeLodEXT", "textureLod", "texture2DGradEXT", "textureGrad", "texture2DProjGradEXT", "textureProjGrad", "textureCubeGradEXT", "textureGrad", NULL, NULL }; const char **mapping = (IsGLSL130OrNewer(getShaderOutput())) ? legacyToCoreRename : simpleRename; for (int i = 0; mapping[i] != NULL; i += 2) { if (name == mapping[i]) { return mapping[i+1]; } } return name; } <commit_msg>Add texture2DRect -> texture conversion for OpenGL core profile<commit_after>// // Copyright (c) 2002-2013 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // #include "compiler/translator/OutputGLSL.h" TOutputGLSL::TOutputGLSL(TInfoSinkBase& objSink, ShArrayIndexClampingStrategy clampingStrategy, ShHashFunction64 hashFunction, NameMap& nameMap, TSymbolTable& symbolTable, int shaderVersion, ShShaderOutput output) : TOutputGLSLBase(objSink, clampingStrategy, hashFunction, nameMap, symbolTable, shaderVersion, output) { } bool TOutputGLSL::writeVariablePrecision(TPrecision) { return false; } void TOutputGLSL::visitSymbol(TIntermSymbol *node) { TInfoSinkBase& out = objSink(); const TString &symbol = node->getSymbol(); if (symbol == "gl_FragDepthEXT") { out << "gl_FragDepth"; } else if (symbol == "gl_FragColor" && IsGLSL130OrNewer(getShaderOutput())) { out << "webgl_FragColor"; } else if (symbol == "gl_FragData" && IsGLSL130OrNewer(getShaderOutput())) { out << "webgl_FragData"; } else if (symbol == "gl_SecondaryFragColorEXT") { out << "angle_SecondaryFragColor"; } else if (symbol == "gl_SecondaryFragDataEXT") { out << "angle_SecondaryFragData"; } else { TOutputGLSLBase::visitSymbol(node); } } TString TOutputGLSL::translateTextureFunction(TString &name) { static const char *simpleRename[] = { "texture2DLodEXT", "texture2DLod", "texture2DProjLodEXT", "texture2DProjLod", "textureCubeLodEXT", "textureCubeLod", "texture2DGradEXT", "texture2DGradARB", "texture2DProjGradEXT", "texture2DProjGradARB", "textureCubeGradEXT", "textureCubeGradARB", NULL, NULL }; static const char *legacyToCoreRename[] = { "texture2D", "texture", "texture2DProj", "textureProj", "texture2DLod", "textureLod", "texture2DProjLod", "textureProjLod", "texture2DRect", "texture", "textureCube", "texture", "textureCubeLod", "textureLod", // Extensions "texture2DLodEXT", "textureLod", "texture2DProjLodEXT", "textureProjLod", "textureCubeLodEXT", "textureLod", "texture2DGradEXT", "textureGrad", "texture2DProjGradEXT", "textureProjGrad", "textureCubeGradEXT", "textureGrad", NULL, NULL }; const char **mapping = (IsGLSL130OrNewer(getShaderOutput())) ? legacyToCoreRename : simpleRename; for (int i = 0; mapping[i] != NULL; i += 2) { if (name == mapping[i]) { return mapping[i+1]; } } return name; } <|endoftext|>
<commit_before> #ifndef __FRAMEWORK_RECORDING_DISPATCHRECORDER_HXX_ #include <recording/dispatchrecorder.hxx> #endif #ifndef __FRAMEWORK_THREADHELP_WRITEGUARD_HXX_ #include <threadhelp/writeguard.hxx> #endif #ifndef __FRAMEWORK_THREADHELP_READGUARD_HXX_ #include <threadhelp/readguard.hxx> #endif #ifndef __FRAMEWORK_SERVICES_H_ #include <services.h> #endif #ifndef _SV_SVAPP_HXX #include <vcl/svapp.hxx> #endif namespace framework{ //***************************************************************************************************************** // XInterface, XTypeProvider, XServiceInfo //***************************************************************************************************************** DEFINE_XINTERFACE_3( DispatchRecorder, OWeakObject, DIRECT_INTERFACE(css::lang::XTypeProvider), DIRECT_INTERFACE(css::lang::XServiceInfo), DIRECT_INTERFACE(css::frame::XDispatchRecorder)) DEFINE_XTYPEPROVIDER_3( DispatchRecorder, css::lang::XTypeProvider, css::lang::XServiceInfo, css::frame::XDispatchRecorder) DEFINE_XSERVICEINFO_MULTISERVICE( DispatchRecorder, ::cppu::OWeakObject, SERVICENAME_DISPATCHRECORDER, IMPLEMENTATIONNAME_DISPATCHRECORDER) DEFINE_INIT_SERVICE( DispatchRecorder, { } ) //*********************************************************************** DispatchRecorder::DispatchRecorder( const css::uno::Reference< css::lang::XMultiServiceFactory >& xSMGR ) : ThreadHelpBase ( &Application::GetSolarMutex() ) , ::cppu::OWeakObject( ) , m_xSMGR ( xSMGR ) { } //************************************************************************ DispatchRecorder::~DispatchRecorder() { } //************************************************************************* // generate header void SAL_CALL DispatchRecorder::startRecording( const css::uno::Reference< css::frame::XFrame >& xFrame ) throw( css::uno::RuntimeException ) { /* SAFE{ */ WriteGuard aWriteLock(m_aLock); LOG_ASSERT2(m_aScriptBuffer.getLength()>0, "DispatchRecorder::startRecording()", "start without end called ... append new macro to old one!") m_aScriptBuffer.ensureCapacity(10000); m_aScriptBuffer.appendAscii("rem ----------------------------------------------------------------------\n"); m_aScriptBuffer.appendAscii("rem define variables\n"); m_aScriptBuffer.appendAscii("dim document as object\n"); m_aScriptBuffer.appendAscii("dim dispatcher as object\n"); m_aScriptBuffer.appendAscii("dim parser as object\n"); m_aScriptBuffer.appendAscii("dim url as new com.sun.star.util.URL\n"); m_aScriptBuffer.appendAscii("rem ----------------------------------------------------------------------\n"); m_aScriptBuffer.appendAscii("rem get access to the document\n"); m_aScriptBuffer.appendAscii("document = ThisComponent.CurrentController.Frame\n"); m_aScriptBuffer.appendAscii("parser = createUnoService(\"com.sun.star.util.URLTransformer\")\n\n"); m_nRecordingID = 1; /* } */ } //************************************************************************* void SAL_CALL DispatchRecorder::recordDispatch( const css::util::URL& aURL, const css::uno::Sequence< css::beans::PropertyValue >& lArguments ) throw( css::uno::RuntimeException ) { implts_recordMacro(aURL,lArguments,sal_False); } //************************************************************************* void SAL_CALL DispatchRecorder::recordDispatchAsComment( const css::util::URL& aURL, const css::uno::Sequence< css::beans::PropertyValue >& lArguments ) throw( css::uno::RuntimeException ) { implts_recordMacro(aURL,lArguments,sal_True); } //************************************************************************* void SAL_CALL DispatchRecorder::endRecording() throw( css::uno::RuntimeException ) { /* SAFE{ */ WriteGuard aWriteLock(m_aLock); m_sScript = m_aScriptBuffer.makeStringAndClear(); /* } */ } //************************************************************************* ::rtl::OUString SAL_CALL DispatchRecorder::getRecordedMacro() throw( css::uno::RuntimeException ) { /* SAFE{ */ ReadGuard aReadLock(m_aLock); return m_sScript; /* } */ } //************************************************************************* void SAL_CALL DispatchRecorder::implts_recordMacro( const css::util::URL& aURL, const css::uno::Sequence< css::beans::PropertyValue >& lArguments, sal_Bool bAsComment ) { ::rtl::OUStringBuffer aArgumentBuffer(1000); ::rtl::OUStringBuffer aScriptBuffer(1000); ::rtl::OUString sArrayName; aScriptBuffer.appendAscii("rem ----------------------------------------------------------------------\n"); aScriptBuffer.appendAscii("rem dispatch\n"); sal_Int32 nLength = lArguments.getLength(); sal_Int32 nValidArgs = 0; for( sal_Int32 i=0; i<nLength; ++i ) { if(lArguments[i].Value.hasValue()) { // this value is used to name the arrays of aArgumentBuffer if(sArrayName.getLength()<1) { sArrayName = ::rtl::OUString::createFromAscii("args"); sArrayName += ::rtl::OUString::valueOf((sal_Int32)m_nRecordingID); } ++nValidArgs; // add arg().Name if(bAsComment) aArgumentBuffer.appendAscii("rem "); aArgumentBuffer.append (sArrayName); aArgumentBuffer.appendAscii("("); aArgumentBuffer.append (i); aArgumentBuffer.appendAscii(").Name = \""); aArgumentBuffer.append (lArguments[i].Name); aArgumentBuffer.appendAscii("\"\n"); // add arg().Value if(bAsComment) aArgumentBuffer.appendAscii("rem "); aArgumentBuffer.append (sArrayName); aArgumentBuffer.appendAscii("("); aArgumentBuffer.append (i); aArgumentBuffer.appendAscii(").Value = "); // if value == bool if (lArguments[i].Value.getValueType() == getBooleanCppuType()) { sal_Bool bVal; lArguments[i].Value >>= bVal; if (bVal) aArgumentBuffer.appendAscii("true"); else aArgumentBuffer.appendAscii("false"); } else // if value == sal_Int8 if (lArguments[i].Value.getValueType() == getCppuType((sal_Int8*)0)) { sal_Int8 nVal; lArguments[i].Value >>= nVal; aArgumentBuffer.append((sal_Int32)nVal); } else // if value == sal_Int16 if (lArguments[i].Value.getValueType() == getCppuType((sal_Int16*)0)) { sal_Int16 nVal; lArguments[i].Value >>= nVal; aArgumentBuffer.append((sal_Int32)nVal); } else // if value == sal_Int32 if (lArguments[i].Value.getValueType() == getCppuType((sal_Int32*)0)) { sal_Int32 nVal; lArguments[i].Value >>= nVal; aArgumentBuffer.append((sal_Int32)nVal); } else // if value == float if (lArguments[i].Value.getValueType() == getCppuType((float*)0)) { float fVal; lArguments[i].Value >>= fVal; aArgumentBuffer.append(fVal); } else // if value == double if (lArguments[i].Value.getValueType() == getCppuType((double*)0)) { double fVal; lArguments[i].Value >>= fVal; aArgumentBuffer.append(fVal); } else // if value == string if (lArguments[i].Value.getValueType() == getCppuType((::rtl::OUString*)0)) { ::rtl::OUString sVal; lArguments[i].Value >>= sVal; aArgumentBuffer.appendAscii("\""); aArgumentBuffer.append (sVal); aArgumentBuffer.appendAscii("\""); } else LOG_ASSERT2(0, "Type not scriptable!") aArgumentBuffer.appendAscii("\n"); } } // if aArgumentBuffer exist - pack it into the aScriptBuffer if(nValidArgs>0) { if(bAsComment) aArgumentBuffer.appendAscii("rem "); aScriptBuffer.appendAscii("dim "); aScriptBuffer.append (sArrayName); aScriptBuffer.appendAscii("("); aScriptBuffer.append ((sal_Int32)(nValidArgs-1)); // 0 based! aScriptBuffer.appendAscii(") as new com.sun.star.beans.PropertyValue\n"); aScriptBuffer.append (aArgumentBuffer.makeStringAndClear()); aScriptBuffer.appendAscii("\n"); } // add code for parsing urls if(bAsComment) aArgumentBuffer.appendAscii("rem "); aScriptBuffer.appendAscii("url.Complete = \""); aScriptBuffer.append (aURL.Complete); aScriptBuffer.appendAscii("\"\n"); if(bAsComment) aArgumentBuffer.appendAscii("rem "); aScriptBuffer.appendAscii("parser.parseStrict(url)\n"); // add code for dispatches if(bAsComment) aArgumentBuffer.appendAscii("rem "); aScriptBuffer.appendAscii("disp = document.queryDispatch(url,\"\",0)\n"); if(bAsComment) aArgumentBuffer.appendAscii("rem "); if(nValidArgs<1) aScriptBuffer.appendAscii("disp.dispatch(url,noargs())\n"); else { aScriptBuffer.appendAscii("disp.dispatch(url,"); aScriptBuffer.append( sArrayName.getStr() ); aScriptBuffer.appendAscii("())\n"); } aScriptBuffer.appendAscii("\n"); /* SAFE { */ m_aScriptBuffer.append(aScriptBuffer.makeStringAndClear()); m_nRecordingID++; /* } */ } } // namespace framework <commit_msg>#98405#: support for structs as arrays<commit_after> #ifndef __FRAMEWORK_RECORDING_DISPATCHRECORDER_HXX_ #include <recording/dispatchrecorder.hxx> #endif #ifndef __FRAMEWORK_THREADHELP_WRITEGUARD_HXX_ #include <threadhelp/writeguard.hxx> #endif #ifndef __FRAMEWORK_THREADHELP_READGUARD_HXX_ #include <threadhelp/readguard.hxx> #endif #ifndef __FRAMEWORK_SERVICES_H_ #include <services.h> #endif #ifndef _SV_SVAPP_HXX #include <vcl/svapp.hxx> #endif namespace framework{ //***************************************************************************************************************** // XInterface, XTypeProvider, XServiceInfo //***************************************************************************************************************** DEFINE_XINTERFACE_3( DispatchRecorder, OWeakObject, DIRECT_INTERFACE(css::lang::XTypeProvider), DIRECT_INTERFACE(css::lang::XServiceInfo), DIRECT_INTERFACE(css::frame::XDispatchRecorder)) DEFINE_XTYPEPROVIDER_3( DispatchRecorder, css::lang::XTypeProvider, css::lang::XServiceInfo, css::frame::XDispatchRecorder) DEFINE_XSERVICEINFO_MULTISERVICE( DispatchRecorder, ::cppu::OWeakObject, SERVICENAME_DISPATCHRECORDER, IMPLEMENTATIONNAME_DISPATCHRECORDER) DEFINE_INIT_SERVICE( DispatchRecorder, { } ) //*********************************************************************** DispatchRecorder::DispatchRecorder( const css::uno::Reference< css::lang::XMultiServiceFactory >& xSMGR ) : ThreadHelpBase ( &Application::GetSolarMutex() ) , ::cppu::OWeakObject( ) , m_xSMGR ( xSMGR ) { } //************************************************************************ DispatchRecorder::~DispatchRecorder() { } //************************************************************************* // generate header void SAL_CALL DispatchRecorder::startRecording( const css::uno::Reference< css::frame::XFrame >& xFrame ) throw( css::uno::RuntimeException ) { /* SAFE{ */ WriteGuard aWriteLock(m_aLock); LOG_ASSERT2(m_aScriptBuffer.getLength()>0, "DispatchRecorder::startRecording()", "start without end called ... append new macro to old one!") m_aScriptBuffer.ensureCapacity(10000); m_aScriptBuffer.appendAscii("rem ----------------------------------------------------------------------\n"); m_aScriptBuffer.appendAscii("rem define variables\n"); m_aScriptBuffer.appendAscii("dim document as object\n"); m_aScriptBuffer.appendAscii("dim dispatcher as object\n"); m_aScriptBuffer.appendAscii("dim parser as object\n"); m_aScriptBuffer.appendAscii("dim url as new com.sun.star.util.URL\n"); m_aScriptBuffer.appendAscii("rem ----------------------------------------------------------------------\n"); m_aScriptBuffer.appendAscii("rem get access to the document\n"); m_aScriptBuffer.appendAscii("document = ThisComponent.CurrentController.Frame\n"); m_aScriptBuffer.appendAscii("parser = createUnoService(\"com.sun.star.util.URLTransformer\")\n\n"); m_nRecordingID = 1; /* } */ } //************************************************************************* void SAL_CALL DispatchRecorder::recordDispatch( const css::util::URL& aURL, const css::uno::Sequence< css::beans::PropertyValue >& lArguments ) throw( css::uno::RuntimeException ) { implts_recordMacro(aURL,lArguments,sal_False); } //************************************************************************* void SAL_CALL DispatchRecorder::recordDispatchAsComment( const css::util::URL& aURL, const css::uno::Sequence< css::beans::PropertyValue >& lArguments ) throw( css::uno::RuntimeException ) { implts_recordMacro(aURL,lArguments,sal_True); } //************************************************************************* void SAL_CALL DispatchRecorder::endRecording() throw( css::uno::RuntimeException ) { /* SAFE{ */ WriteGuard aWriteLock(m_aLock); m_sScript = m_aScriptBuffer.makeStringAndClear(); /* } */ } //************************************************************************* ::rtl::OUString SAL_CALL DispatchRecorder::getRecordedMacro() throw( css::uno::RuntimeException ) { /* SAFE{ */ ReadGuard aReadLock(m_aLock); return m_sScript; /* } */ } //************************************************************************* static void AppendToBuffer( css::uno::Any aValue, ::rtl::OUStringBuffer& aArgumentBuffer ) { // if value == bool if (aValue.getValueType() == getBooleanCppuType()) { sal_Bool bVal; aValue >>= bVal; if (bVal) aArgumentBuffer.appendAscii("true"); else aArgumentBuffer.appendAscii("false"); } else // if value == sal_Int8 if (aValue.getValueType() == getCppuType((sal_Int8*)0)) { sal_Int8 nVal; aValue >>= nVal; aArgumentBuffer.append((sal_Int32)nVal); } else // if value == sal_Int16 if (aValue.getValueType() == getCppuType((sal_Int16*)0)) { sal_Int16 nVal; aValue >>= nVal; aArgumentBuffer.append((sal_Int32)nVal); } else // if value == sal_Int32 if (aValue.getValueType() == getCppuType((sal_Int32*)0)) { sal_Int32 nVal; aValue >>= nVal; aArgumentBuffer.append((sal_Int32)nVal); } else // if value == float if (aValue.getValueType() == getCppuType((float*)0)) { float fVal; aValue >>= fVal; aArgumentBuffer.append(fVal); } else // if value == double if (aValue.getValueType() == getCppuType((double*)0)) { double fVal; aValue >>= fVal; aArgumentBuffer.append(fVal); } else // if value == string if (aValue.getValueType() == getCppuType((::rtl::OUString*)0)) { ::rtl::OUString sVal; aValue >>= sVal; aArgumentBuffer.appendAscii("\""); aArgumentBuffer.append (sVal); aArgumentBuffer.appendAscii("\""); } else if (aValue.getValueType() == ::getCppuType((const css::uno::Sequence < css::uno::Any >*)0) ) { css::uno::Sequence < css::uno::Any > aSeq; aValue >>= aSeq; aArgumentBuffer.appendAscii("Array("); for ( sal_Int32 nAny=0; nAny<aSeq.getLength(); nAny++ ) { AppendToBuffer( aSeq[nAny], aArgumentBuffer ); if ( nAny+1 < aSeq.getLength() ) // not last argument aArgumentBuffer.appendAscii(","); } aArgumentBuffer.appendAscii(")"); } else LOG_WARNING("","Type not scriptable!") } void SAL_CALL DispatchRecorder::implts_recordMacro( const css::util::URL& aURL, const css::uno::Sequence< css::beans::PropertyValue >& lArguments, sal_Bool bAsComment ) { ::rtl::OUStringBuffer aArgumentBuffer(1000); ::rtl::OUStringBuffer aScriptBuffer(1000); ::rtl::OUString sArrayName; aScriptBuffer.appendAscii("rem ----------------------------------------------------------------------\n"); aScriptBuffer.appendAscii("rem dispatch\n"); sal_Int32 nLength = lArguments.getLength(); sal_Int32 nValidArgs = 0; for( sal_Int32 i=0; i<nLength; ++i ) { if(lArguments[i].Value.hasValue()) { // this value is used to name the arrays of aArgumentBuffer if(sArrayName.getLength()<1) { sArrayName = ::rtl::OUString::createFromAscii("args"); sArrayName += ::rtl::OUString::valueOf((sal_Int32)m_nRecordingID); } ++nValidArgs; // add arg().Name if(bAsComment) aArgumentBuffer.appendAscii("rem "); aArgumentBuffer.append (sArrayName); aArgumentBuffer.appendAscii("("); aArgumentBuffer.append (i); aArgumentBuffer.appendAscii(").Name = \""); aArgumentBuffer.append (lArguments[i].Name); aArgumentBuffer.appendAscii("\"\n"); // add arg().Value if(bAsComment) aArgumentBuffer.appendAscii("rem "); aArgumentBuffer.append (sArrayName); aArgumentBuffer.appendAscii("("); aArgumentBuffer.append (i); aArgumentBuffer.appendAscii(").Value = "); AppendToBuffer( lArguments[i].Value, aArgumentBuffer); aArgumentBuffer.appendAscii("\n"); } } // if aArgumentBuffer exist - pack it into the aScriptBuffer if(nValidArgs>0) { if(bAsComment) aArgumentBuffer.appendAscii("rem "); aScriptBuffer.appendAscii("dim "); aScriptBuffer.append (sArrayName); aScriptBuffer.appendAscii("("); aScriptBuffer.append ((sal_Int32)(nValidArgs-1)); // 0 based! aScriptBuffer.appendAscii(") as new com.sun.star.beans.PropertyValue\n"); aScriptBuffer.append (aArgumentBuffer.makeStringAndClear()); aScriptBuffer.appendAscii("\n"); } // add code for parsing urls if(bAsComment) aArgumentBuffer.appendAscii("rem "); aScriptBuffer.appendAscii("url.Complete = \""); aScriptBuffer.append (aURL.Complete); aScriptBuffer.appendAscii("\"\n"); if(bAsComment) aArgumentBuffer.appendAscii("rem "); aScriptBuffer.appendAscii("parser.parseStrict(url)\n"); // add code for dispatches if(bAsComment) aArgumentBuffer.appendAscii("rem "); aScriptBuffer.appendAscii("disp = document.queryDispatch(url,\"\",0)\n"); if(bAsComment) aArgumentBuffer.appendAscii("rem "); if(nValidArgs<1) aScriptBuffer.appendAscii("disp.dispatch(url,noargs())\n"); else { aScriptBuffer.appendAscii("disp.dispatch(url,"); aScriptBuffer.append( sArrayName.getStr() ); aScriptBuffer.appendAscii("())\n"); } aScriptBuffer.appendAscii("\n"); /* SAFE { */ m_aScriptBuffer.append(aScriptBuffer.makeStringAndClear()); m_nRecordingID++; /* } */ } } // namespace framework <|endoftext|>
<commit_before> #include <nstd/Console.h> #include <nstd/Error.h> #include <nstd/Time.h> #include <lz4.h> #include "Tools/Sha256.h" #include "Client.h" bool_t Client::connect(const String& user, const String& password, const String& address) { disconnect(); // establish connection uint16_t port; uint32_t ipAddr = Socket::resolveAddr(address, port); if(ipAddr == Socket::noneAddr) { error = Error::getErrorString(); return false; } if(!socket.open() || !socket.connect(ipAddr, port)) { error = Error::getErrorString(); return false; } // send login request Buffer buffer(sizeof(DataProtocol::LoginRequest) + user.length()); DataProtocol::LoginRequest* loginRequest = (DataProtocol::LoginRequest*)(byte_t*)buffer; loginRequest->messageType = DataProtocol::loginRequest; loginRequest->size = sizeof(DataProtocol::LoginRequest) + user.length(); loginRequest->requestId = nextRequestId++; loginRequest->userNameSize = user.length(); Memory::copy(loginRequest + 1, user, user.length()); if(!sendRequest(*loginRequest)) return false; // receive login response if(!receiveResponse(loginRequest->requestId , buffer)) return false; const DataProtocol::LoginResponse* loginResponse = (const DataProtocol::LoginResponse*)(const byte_t*)buffer; if(loginResponse->messageType != DataProtocol::loginResponse || loginResponse->size < sizeof(*loginResponse)) { error = "Received invalid login response."; return false; } // send auth request DataProtocol::AuthRequest authRequest; authRequest.messageType = DataProtocol::authRequest; authRequest.size = sizeof(authRequest); authRequest.requestId = nextRequestId++; byte_t pwHash[32]; Sha256::hmac(loginResponse->pwSalt, sizeof(loginResponse->pwSalt), (const byte_t*)(const char_t*)password, password.length(), pwHash); Sha256::hmac(loginResponse->authSalt, sizeof(loginResponse->authSalt), pwHash, sizeof(pwHash), authRequest.signature); if(!sendRequest(authRequest)) return false; // receive auth response if(!receiveResponse(authRequest.requestId, buffer)) return false; const DataProtocol::Header* authResponse = (const DataProtocol::Header*)(const byte_t*)buffer; if(authResponse->messageType != DataProtocol::authResponse) { error = "Received invalid auth response."; return false; } // create event socket pair if(!eventPipeRead.pair(eventPipeWrite)) return false; // start receive thread if(!thread.start(threadProc, this)) { error = Error::getErrorString(); return false; } return true; } void_t Client::disconnect() { eventPipeWrite.close(); // terminate worker thread thread.join(); socket.close(); eventPipeRead.close(); actions.clear(); nextRequestId = 1; selectedTable = 0; } void_t Client::listTables() { actionMutex.lock(); Action& action = actions.append(Action()); action.type = listTablesAction; actionMutex.unlock(); interrupt(); } void_t Client::createTable(const String& name) { actionMutex.lock(); Action& action = actions.append(Action()); action.type = createTableAction; action.paramStr = name; actionMutex.unlock(); interrupt(); } void_t Client::selectTable(uint32_t tableId) { actionMutex.lock(); Action& action = actions.append(Action()); action.type = selectTableAction; action.param = tableId; actionMutex.unlock(); interrupt(); } void_t Client::query() { actionMutex.lock(); Action& action = actions.append(Action()); action.type = queryAction; actionMutex.unlock(); interrupt(); } void_t Client::add(const String& value) { actionMutex.lock(); Action& action = actions.append(Action()); action.type = addAction; action.paramStr = value; actionMutex.unlock(); interrupt(); } uint_t Client::threadProc(void_t* param) { Client* client = (Client*)param; return client->process();; } uint8_t Client::process() { Socket::Selector selector; selector.set(socket, Socket::Selector::readEvent); selector.set(eventPipeRead, Socket::Selector::readEvent); Buffer buffer; Socket* selectedSocket; uint_t events; while(socket.isOpen()) { if(!selector.select(selectedSocket, events, 100 * 1000)) continue; if(selectedSocket == &socket) { if(!receiveData(buffer)) { // connection lost or error Console::errorf("error: Could not receive data: %s\n", (const char_t*)error); return 1; } handleData(*(const DataProtocol::Header*)(const byte_t*)buffer); } else { uint32_t event; switch(eventPipeRead.recv((byte_t*)&event, sizeof(event), sizeof(event))) { case 0: return 0; case sizeof(event): { Action action; actionMutex.lock(); action = actions.front(); actions.removeFront(); actionMutex.unlock(); handleAction(action); } break; default: // unexpected result return 1; } } } return false; } void_t Client::handleData(const DataProtocol::Header& header) { //switch(header.messageType) //{ //case DataProtocol::queryResponse: // handleQueryResponse(header); // break; //} } void_t Client::handleAction(const Action& action) { switch(action.type) { case listTablesAction: { DataProtocol::QueryRequest queryRequest; queryRequest.messageType = DataProtocol::queryRequest; queryRequest.size = sizeof(queryRequest); queryRequest.tableId = DataProtocol::tablesTable; queryRequest.type = DataProtocol::QueryRequest::all; queryRequest.requestId = nextRequestId++; if(!sendRequest(queryRequest)) { Console::errorf("error: Could not send query: %s\n", (const char_t*)error); return; } Buffer buffer; for(;;) { if(!receiveResponse(queryRequest.requestId, buffer)) { Console::errorf("error: Could not receive query response: %s\n", (const char_t*)error); return; } const DataProtocol::Header* header = (const DataProtocol::Header*)(const byte_t*)buffer; if(header->messageType != DataProtocol::queryResponse) { error = "Receive invalid query response."; Console::errorf("error: Could not receive query response: %s\n", (const char_t*)error); return; } for(const DataProtocol::Table* table = (const DataProtocol::Table*)(header + 1), * end = (const DataProtocol::Table*)((const byte_t*)header + header->size); table < end; table = (const DataProtocol::Table*)((const byte_t*)table + table->size)) { String tableName; DataProtocol::getString(*header, *table, sizeof(DataProtocol::Table), table->nameSize, tableName); tableName.resize(tableName.length()); Console::printf("%6llu: %s\n", table->id, (const char_t*)tableName); } if(!(header->flags & DataProtocol::Header::fragmented)) break; } } break; case selectTableAction: selectedTable = action.param; //Console::printf("selected table %u\n", action.param); break; case createTableAction: { const String& tableName = action.paramStr; Buffer buffer; buffer.resize(sizeof(DataProtocol::AddRequest) + sizeof(DataProtocol::Table) + tableName.length()); DataProtocol::AddRequest* addRequest = (DataProtocol::AddRequest*)(byte_t*)buffer; DataProtocol::setHeader(*addRequest, DataProtocol::addRequest, buffer.size(), nextRequestId++); addRequest->tableId = DataProtocol::tablesTable; DataProtocol::Table* table = (DataProtocol::Table*)(addRequest + 1); DataProtocol::setEntityHeader(*table, 0, 0, sizeof(*table) + tableName.length()); table->flags = 0; DataProtocol::setString(*table, table->nameSize, sizeof(*table), tableName); if(!sendRequest(*addRequest)) { Console::errorf("error: Could not send add request: %s\n", (const char_t*)error); return; } if(!receiveResponse(addRequest->requestId, buffer)) { Console::errorf("error: Could not receive add response: %s\n", (const char_t*)error); return; } } break; case queryAction: { DataProtocol::QueryRequest queryRequest; queryRequest.messageType = DataProtocol::queryRequest; queryRequest.size = sizeof(queryRequest); queryRequest.requestId = nextRequestId++; queryRequest.tableId = selectedTable; queryRequest.type = DataProtocol::QueryRequest::all; queryRequest.param = 0; if(!sendRequest(queryRequest)) { Console::errorf("error: Could not send query: %s\n", (const char_t*)error); return; } Buffer buffer; for(;;) { if(!receiveResponse(queryRequest.requestId, buffer)) { Console::errorf("error: Could not receive query response: %s\n", (const char_t*)error); return; } const DataProtocol::Header* header = (const DataProtocol::Header*)(const byte_t*)buffer; if(header->messageType != DataProtocol::queryResponse || header->size < sizeof(*header) + sizeof(uint16_t)) { error = "Received invalid query response."; Console::errorf("error: Could not receive query response: %s\n", (const char_t*)error); return; } const byte_t* data; size_t dataSize; Buffer buffer; if(header->flags & DataProtocol::Header::compressed) { dataSize = *(const uint16_t*)(header + 1); uint16_t compressedSize = header->size - (sizeof(*header) + sizeof(uint16_t)); buffer.resize(dataSize); if(LZ4_decompress_safe((const char*)(header + 1) + sizeof(uint16_t), (char*)(byte_t*)buffer, compressedSize, dataSize) != dataSize) { error = "Decompression failed."; Console::errorf("error: Could not receive query response: %s\n", (const char_t*)error); return; } data = buffer; } else { data = (const byte_t*)(header + 1); dataSize = header->size - sizeof(*header); } for(const DataProtocol::Entity* entity = (const DataProtocol::Entity*)data, * end = (const DataProtocol::Entity*)((const byte_t*)data + dataSize); entity < end; entity = (const DataProtocol::Entity*)((const byte_t*)entity + entity->size)) { Console::printf("id=%llu, size=%u, time=%llu\n", entity->id, (uint_t)entity->size, entity->time); } if(!(header->flags & DataProtocol::Header::fragmented)) break; } } break; case addAction: { const String& value = action.paramStr; Buffer buffer; buffer.resize(sizeof(DataProtocol::AddRequest) + sizeof(DataProtocol::Table) + value.length()); DataProtocol::AddRequest* addRequest = (DataProtocol::AddRequest*)(byte_t*)buffer; DataProtocol::setHeader(*addRequest, DataProtocol::addRequest, buffer.size(), nextRequestId++); addRequest->tableId = selectedTable; DataProtocol::Table* entity = (DataProtocol::Table*)(addRequest + 1); DataProtocol::setEntityHeader(*entity, 0, Time::time(), sizeof(DataProtocol::Table) + value.length()); DataProtocol::setString(*entity, entity->nameSize, sizeof(*entity), value); if(!sendRequest(*addRequest)) { Console::errorf("error: Could not send add request: %s\n", (const char_t*)error); return; } if(!receiveResponse(addRequest->requestId, buffer)) { Console::errorf("error: Could not receive add response: %s\n", (const char_t*)error); return; } } break; } } void_t Client::interrupt() { uint32_t event = 1; eventPipeWrite.send((byte_t*)&event, sizeof(event)); } bool_t Client::sendRequest(DataProtocol::Header& header) { header.flags = 0; header.requestId = 0; if(socket.send((const byte_t*)&header, header.size) != header.size) { error = Error::getErrorString(); return false; } return true; } bool_t Client::receiveData(Buffer& buffer) { buffer.resize(sizeof(DataProtocol::Header)); ssize_t x = socket.recv((byte_t*)buffer, sizeof(DataProtocol::Header), sizeof(DataProtocol::Header)); if(x != sizeof(DataProtocol::Header)) { if(Error::getLastError()) error = Error::getErrorString(); else error = "Connection closed by peer."; socket.close(); return false; } const DataProtocol::Header* header = (const DataProtocol::Header*)(const byte_t*)buffer; if(header->size < sizeof(DataProtocol::Header)) { error = "Received invalid data."; return false; } size_t dataSize = header->size - sizeof(DataProtocol::Header); if(dataSize > 0) { buffer.resize(header->size); if(socket.recv((byte_t*)buffer + sizeof(DataProtocol::Header), dataSize, dataSize) != dataSize) { if(Error::getLastError()) error = Error::getErrorString(); else error = "Connection closed by peer."; socket.close(); return false; } } return true; } bool_t Client::receiveResponse(uint32_t requestId, Buffer& buffer) { while(socket.isOpen()) { if(!receiveData(buffer)) return false; const DataProtocol::Header* header = (const DataProtocol::Header*)(const byte_t*)buffer; if(header->requestId == requestId) { if(header->messageType == DataProtocol::errorResponse && header->size >= sizeof(DataProtocol::ErrorResponse)) { error = DataProtocol::getErrorString((DataProtocol::Error)((const DataProtocol::ErrorResponse*)header)->error); return false; } return true; } else handleData(*header); } return false; } <commit_msg>Fix empty compressed blocks not being handled correctly<commit_after> #include <nstd/Console.h> #include <nstd/Error.h> #include <nstd/Time.h> #include <lz4.h> #include "Tools/Sha256.h" #include "Client.h" bool_t Client::connect(const String& user, const String& password, const String& address) { disconnect(); // establish connection uint16_t port; uint32_t ipAddr = Socket::resolveAddr(address, port); if(ipAddr == Socket::noneAddr) { error = Error::getErrorString(); return false; } if(!socket.open() || !socket.connect(ipAddr, port)) { error = Error::getErrorString(); return false; } // send login request Buffer buffer(sizeof(DataProtocol::LoginRequest) + user.length()); DataProtocol::LoginRequest* loginRequest = (DataProtocol::LoginRequest*)(byte_t*)buffer; loginRequest->messageType = DataProtocol::loginRequest; loginRequest->size = sizeof(DataProtocol::LoginRequest) + user.length(); loginRequest->requestId = nextRequestId++; loginRequest->userNameSize = user.length(); Memory::copy(loginRequest + 1, user, user.length()); if(!sendRequest(*loginRequest)) return false; // receive login response if(!receiveResponse(loginRequest->requestId , buffer)) return false; const DataProtocol::LoginResponse* loginResponse = (const DataProtocol::LoginResponse*)(const byte_t*)buffer; if(loginResponse->messageType != DataProtocol::loginResponse || loginResponse->size < sizeof(*loginResponse)) { error = "Received invalid login response."; return false; } // send auth request DataProtocol::AuthRequest authRequest; authRequest.messageType = DataProtocol::authRequest; authRequest.size = sizeof(authRequest); authRequest.requestId = nextRequestId++; byte_t pwHash[32]; Sha256::hmac(loginResponse->pwSalt, sizeof(loginResponse->pwSalt), (const byte_t*)(const char_t*)password, password.length(), pwHash); Sha256::hmac(loginResponse->authSalt, sizeof(loginResponse->authSalt), pwHash, sizeof(pwHash), authRequest.signature); if(!sendRequest(authRequest)) return false; // receive auth response if(!receiveResponse(authRequest.requestId, buffer)) return false; const DataProtocol::Header* authResponse = (const DataProtocol::Header*)(const byte_t*)buffer; if(authResponse->messageType != DataProtocol::authResponse) { error = "Received invalid auth response."; return false; } // create event socket pair if(!eventPipeRead.pair(eventPipeWrite)) return false; // start receive thread if(!thread.start(threadProc, this)) { error = Error::getErrorString(); return false; } return true; } void_t Client::disconnect() { eventPipeWrite.close(); // terminate worker thread thread.join(); socket.close(); eventPipeRead.close(); actions.clear(); nextRequestId = 1; selectedTable = 0; } void_t Client::listTables() { actionMutex.lock(); Action& action = actions.append(Action()); action.type = listTablesAction; actionMutex.unlock(); interrupt(); } void_t Client::createTable(const String& name) { actionMutex.lock(); Action& action = actions.append(Action()); action.type = createTableAction; action.paramStr = name; actionMutex.unlock(); interrupt(); } void_t Client::selectTable(uint32_t tableId) { actionMutex.lock(); Action& action = actions.append(Action()); action.type = selectTableAction; action.param = tableId; actionMutex.unlock(); interrupt(); } void_t Client::query() { actionMutex.lock(); Action& action = actions.append(Action()); action.type = queryAction; actionMutex.unlock(); interrupt(); } void_t Client::add(const String& value) { actionMutex.lock(); Action& action = actions.append(Action()); action.type = addAction; action.paramStr = value; actionMutex.unlock(); interrupt(); } uint_t Client::threadProc(void_t* param) { Client* client = (Client*)param; return client->process();; } uint8_t Client::process() { Socket::Selector selector; selector.set(socket, Socket::Selector::readEvent); selector.set(eventPipeRead, Socket::Selector::readEvent); Buffer buffer; Socket* selectedSocket; uint_t events; while(socket.isOpen()) { if(!selector.select(selectedSocket, events, 100 * 1000)) continue; if(selectedSocket == &socket) { if(!receiveData(buffer)) { // connection lost or error Console::errorf("error: Could not receive data: %s\n", (const char_t*)error); return 1; } handleData(*(const DataProtocol::Header*)(const byte_t*)buffer); } else { uint32_t event; switch(eventPipeRead.recv((byte_t*)&event, sizeof(event), sizeof(event))) { case 0: return 0; case sizeof(event): { Action action; actionMutex.lock(); action = actions.front(); actions.removeFront(); actionMutex.unlock(); handleAction(action); } break; default: // unexpected result return 1; } } } return false; } void_t Client::handleData(const DataProtocol::Header& header) { //switch(header.messageType) //{ //case DataProtocol::queryResponse: // handleQueryResponse(header); // break; //} } void_t Client::handleAction(const Action& action) { switch(action.type) { case listTablesAction: { DataProtocol::QueryRequest queryRequest; queryRequest.messageType = DataProtocol::queryRequest; queryRequest.size = sizeof(queryRequest); queryRequest.tableId = DataProtocol::tablesTable; queryRequest.type = DataProtocol::QueryRequest::all; queryRequest.requestId = nextRequestId++; if(!sendRequest(queryRequest)) { Console::errorf("error: Could not send query: %s\n", (const char_t*)error); return; } Buffer buffer; for(;;) { if(!receiveResponse(queryRequest.requestId, buffer)) { Console::errorf("error: Could not receive query response: %s\n", (const char_t*)error); return; } const DataProtocol::Header* header = (const DataProtocol::Header*)(const byte_t*)buffer; if(header->messageType != DataProtocol::queryResponse) { error = "Receive invalid query response."; Console::errorf("error: Could not receive query response: %s\n", (const char_t*)error); return; } for(const DataProtocol::Table* table = (const DataProtocol::Table*)(header + 1), * end = (const DataProtocol::Table*)((const byte_t*)header + header->size); table < end; table = (const DataProtocol::Table*)((const byte_t*)table + table->size)) { String tableName; DataProtocol::getString(*header, *table, sizeof(DataProtocol::Table), table->nameSize, tableName); tableName.resize(tableName.length()); Console::printf("%6llu: %s\n", table->id, (const char_t*)tableName); } if(!(header->flags & DataProtocol::Header::fragmented)) break; } } break; case selectTableAction: selectedTable = action.param; //Console::printf("selected table %u\n", action.param); break; case createTableAction: { const String& tableName = action.paramStr; Buffer buffer; buffer.resize(sizeof(DataProtocol::AddRequest) + sizeof(DataProtocol::Table) + tableName.length()); DataProtocol::AddRequest* addRequest = (DataProtocol::AddRequest*)(byte_t*)buffer; DataProtocol::setHeader(*addRequest, DataProtocol::addRequest, buffer.size(), nextRequestId++); addRequest->tableId = DataProtocol::tablesTable; DataProtocol::Table* table = (DataProtocol::Table*)(addRequest + 1); DataProtocol::setEntityHeader(*table, 0, 0, sizeof(*table) + tableName.length()); table->flags = 0; DataProtocol::setString(*table, table->nameSize, sizeof(*table), tableName); if(!sendRequest(*addRequest)) { Console::errorf("error: Could not send add request: %s\n", (const char_t*)error); return; } if(!receiveResponse(addRequest->requestId, buffer)) { Console::errorf("error: Could not receive add response: %s\n", (const char_t*)error); return; } } break; case queryAction: { DataProtocol::QueryRequest queryRequest; queryRequest.messageType = DataProtocol::queryRequest; queryRequest.size = sizeof(queryRequest); queryRequest.requestId = nextRequestId++; queryRequest.tableId = selectedTable; queryRequest.type = DataProtocol::QueryRequest::all; queryRequest.param = 0; if(!sendRequest(queryRequest)) { Console::errorf("error: Could not send query: %s\n", (const char_t*)error); return; } Buffer buffer; for(;;) { if(!receiveResponse(queryRequest.requestId, buffer)) { Console::errorf("error: Could not receive query response: %s\n", (const char_t*)error); return; } const DataProtocol::Header* header = (const DataProtocol::Header*)(const byte_t*)buffer; if(header->messageType != DataProtocol::queryResponse || header->size < sizeof(*header) + sizeof(uint16_t)) { error = "Received invalid query response."; Console::errorf("error: Could not receive query response: %s\n", (const char_t*)error); return; } const byte_t* data; size_t dataSize; Buffer buffer; if(header->flags & DataProtocol::Header::compressed) { dataSize = *(const uint16_t*)(header + 1); uint16_t compressedSize = header->size - (sizeof(*header) + sizeof(uint16_t)); buffer.resize(dataSize); if(dataSize > 0 && LZ4_decompress_safe((const char*)(header + 1) + sizeof(uint16_t), (char*)(byte_t*)buffer, compressedSize, dataSize) != dataSize) { error = "Decompression failed."; Console::errorf("error: Could not receive query response: %s\n", (const char_t*)error); return; } data = buffer; } else { data = (const byte_t*)(header + 1); dataSize = header->size - sizeof(*header); } for(const DataProtocol::Entity* entity = (const DataProtocol::Entity*)data, * end = (const DataProtocol::Entity*)((const byte_t*)data + dataSize); entity < end; entity = (const DataProtocol::Entity*)((const byte_t*)entity + entity->size)) { Console::printf("id=%llu, size=%u, time=%llu\n", entity->id, (uint_t)entity->size, entity->time); } if(!(header->flags & DataProtocol::Header::fragmented)) break; } } break; case addAction: { const String& value = action.paramStr; Buffer buffer; buffer.resize(sizeof(DataProtocol::AddRequest) + sizeof(DataProtocol::Table) + value.length()); DataProtocol::AddRequest* addRequest = (DataProtocol::AddRequest*)(byte_t*)buffer; DataProtocol::setHeader(*addRequest, DataProtocol::addRequest, buffer.size(), nextRequestId++); addRequest->tableId = selectedTable; DataProtocol::Table* entity = (DataProtocol::Table*)(addRequest + 1); DataProtocol::setEntityHeader(*entity, 0, Time::time(), sizeof(DataProtocol::Table) + value.length()); DataProtocol::setString(*entity, entity->nameSize, sizeof(*entity), value); if(!sendRequest(*addRequest)) { Console::errorf("error: Could not send add request: %s\n", (const char_t*)error); return; } if(!receiveResponse(addRequest->requestId, buffer)) { Console::errorf("error: Could not receive add response: %s\n", (const char_t*)error); return; } } break; } } void_t Client::interrupt() { uint32_t event = 1; eventPipeWrite.send((byte_t*)&event, sizeof(event)); } bool_t Client::sendRequest(DataProtocol::Header& header) { header.flags = 0; header.requestId = 0; if(socket.send((const byte_t*)&header, header.size) != header.size) { error = Error::getErrorString(); return false; } return true; } bool_t Client::receiveData(Buffer& buffer) { buffer.resize(sizeof(DataProtocol::Header)); ssize_t x = socket.recv((byte_t*)buffer, sizeof(DataProtocol::Header), sizeof(DataProtocol::Header)); if(x != sizeof(DataProtocol::Header)) { if(Error::getLastError()) error = Error::getErrorString(); else error = "Connection closed by peer."; socket.close(); return false; } const DataProtocol::Header* header = (const DataProtocol::Header*)(const byte_t*)buffer; if(header->size < sizeof(DataProtocol::Header)) { error = "Received invalid data."; return false; } size_t dataSize = header->size - sizeof(DataProtocol::Header); if(dataSize > 0) { buffer.resize(header->size); if(socket.recv((byte_t*)buffer + sizeof(DataProtocol::Header), dataSize, dataSize) != dataSize) { if(Error::getLastError()) error = Error::getErrorString(); else error = "Connection closed by peer."; socket.close(); return false; } } return true; } bool_t Client::receiveResponse(uint32_t requestId, Buffer& buffer) { while(socket.isOpen()) { if(!receiveData(buffer)) return false; const DataProtocol::Header* header = (const DataProtocol::Header*)(const byte_t*)buffer; if(header->requestId == requestId) { if(header->messageType == DataProtocol::errorResponse && header->size >= sizeof(DataProtocol::ErrorResponse)) { error = DataProtocol::getErrorString((DataProtocol::Error)((const DataProtocol::ErrorResponse*)header)->error); return false; } return true; } else handleData(*header); } return false; } <|endoftext|>
<commit_before>#include <gtest/gtest.h> #include <type_traits> #include <utils.h> template<typename I> class TestPowInt : public ::testing::Test { protected: const I zero; const I one; const I two; const I three; const I five; const I max; const I digits; TestPowInt() { zero = 0; one = 1; two = 2; three = 3; five = 5; max = std::numeric_limits<I>::max(); digits = static_cast<I>(std::numeric_limits<I>::digits); }; }; typedef ::testing::Types< char, short, int, long, long long, unsigned char, unsigned short, unsigned int, unsigned long, unsigned long long> IntTypes; TYPED_TEST_CASE(TestPowInt, IntTypes); TYPED_TEST(TestPowInt, TestPowInt00) { EXPECT_EQ(this->one, ipow(this->zero, this->zero)); } TYPED_TEST(TestPowInt, TestPowIntX0) { EXPECT_EQ(this->one, ipow(this->one, this->zero)); EXPECT_EQ(this->one, ipow(this->two, this->zero)); EXPECT_EQ(this->one, ipow(this->three, this->zero)); EXPECT_EQ(this->one, ipow(this->five, this->zero)); EXPECT_EQ(this->one, ipow(this->digits, this->zero)); EXPECT_EQ(this->one, ipow(this->max, this->zero)); } TYPED_TEST(TestPowInt, TestPowInt0X) { EXPECT_EQ(this->zero, ipow(this->zero, this->one)); EXPECT_EQ(this->zero, ipow(this->zero, this->two)); EXPECT_EQ(this->zero, ipow(this->zero, this->three)); EXPECT_EQ(this->zero, ipow(this->zero, this->five)); EXPECT_EQ(this->zero, ipow(this->zero, this->digits)); EXPECT_EQ(this->zero, ipow(this->zero, this->max)); } TYPED_TEST(TestPowInt, TestPowIntX1) { EXPECT_EQ(this->one, ipow(this->one, this->one)); EXPECT_EQ(this->two, ipow(this->two, this->one)); EXPECT_EQ(this->three, ipow(this->three, this->one)); EXPECT_EQ(this->max, ipow(max, this->one)); } TYPED_TEST(TestPowInt, TestPowInt1X) { EXPECT_EQ(this->one, ipow(this->one, this->one)); EXPECT_EQ(this->one, ipow(this->one, this->two)); EXPECT_EQ(this->one, ipow(this->one, this->digits)); EXPECT_EQ(this->one, ipow(this->one, this->max)); } TYPED_TEST(TestPowInt, TestPowIntExamples) { EXPECT_EQ(4, ipow(this->two, this->two)); EXPECT_EQ(9, ipow(this->three, this->two)); EXPECT_EQ(25, ipow(this->five, this->two)); EXPECT_EQ(this->one << (this->digits - 1), ipow(this->two, TypeParam(this->digits - 1))); EXPECT_EQ(8, ipow(this->two, this->three)); EXPECT_EQ(27, ipow(this->three, this->three)); EXPECT_EQ(125, ipow(this->five, this->three)); EXPECT_EQ(32, ipow(this->two, this->five)); } TYPED_TEST(TestPowInt, TestPowIntTooLarge) { EXPECT_ANY_THROW(ipow(this->two, this->digits)); EXPECT_ANY_THROW(ipow(this->two, this->max)); EXPECT_ANY_THROW(ipow(this->three, this->digits)); EXPECT_ANY_THROW(ipow(this->three, this->max)); EXPECT_ANY_THROW(ipow(this->max, this->digits)); EXPECT_ANY_THROW(ipow(this->max, this->max)); } <commit_msg>Correctly initiate const data members of TestPowInt<commit_after>#include <gtest/gtest.h> #include <type_traits> #include <utils.h> template<typename I> class TestPowInt : public ::testing::Test { protected: const I zero = 0; const I one = 1; const I two = 2; const I three = 3; const I five = 5; const I max = std::numeric_limits<I>::max(); const I digits = static_cast<I>(std::numeric_limits<I>::digits); }; typedef ::testing::Types< char, short, int, long, long long, unsigned char, unsigned short, unsigned int, unsigned long, unsigned long long> IntTypes; TYPED_TEST_CASE(TestPowInt, IntTypes); TYPED_TEST(TestPowInt, TestPowInt00) { EXPECT_EQ(this->one, ipow(this->zero, this->zero)); } TYPED_TEST(TestPowInt, TestPowIntX0) { EXPECT_EQ(this->one, ipow(this->one, this->zero)); EXPECT_EQ(this->one, ipow(this->two, this->zero)); EXPECT_EQ(this->one, ipow(this->three, this->zero)); EXPECT_EQ(this->one, ipow(this->five, this->zero)); EXPECT_EQ(this->one, ipow(this->digits, this->zero)); EXPECT_EQ(this->one, ipow(this->max, this->zero)); } TYPED_TEST(TestPowInt, TestPowInt0X) { EXPECT_EQ(this->zero, ipow(this->zero, this->one)); EXPECT_EQ(this->zero, ipow(this->zero, this->two)); EXPECT_EQ(this->zero, ipow(this->zero, this->three)); EXPECT_EQ(this->zero, ipow(this->zero, this->five)); EXPECT_EQ(this->zero, ipow(this->zero, this->digits)); EXPECT_EQ(this->zero, ipow(this->zero, this->max)); } TYPED_TEST(TestPowInt, TestPowIntX1) { EXPECT_EQ(this->one, ipow(this->one, this->one)); EXPECT_EQ(this->two, ipow(this->two, this->one)); EXPECT_EQ(this->three, ipow(this->three, this->one)); EXPECT_EQ(this->max, ipow(max, this->one)); } TYPED_TEST(TestPowInt, TestPowInt1X) { EXPECT_EQ(this->one, ipow(this->one, this->one)); EXPECT_EQ(this->one, ipow(this->one, this->two)); EXPECT_EQ(this->one, ipow(this->one, this->digits)); EXPECT_EQ(this->one, ipow(this->one, this->max)); } TYPED_TEST(TestPowInt, TestPowIntExamples) { EXPECT_EQ(4, ipow(this->two, this->two)); EXPECT_EQ(9, ipow(this->three, this->two)); EXPECT_EQ(25, ipow(this->five, this->two)); EXPECT_EQ(this->one << (this->digits - 1), ipow(this->two, TypeParam(this->digits - 1))); EXPECT_EQ(8, ipow(this->two, this->three)); EXPECT_EQ(27, ipow(this->three, this->three)); EXPECT_EQ(125, ipow(this->five, this->three)); EXPECT_EQ(32, ipow(this->two, this->five)); } TYPED_TEST(TestPowInt, TestPowIntTooLarge) { EXPECT_ANY_THROW(ipow(this->two, this->digits)); EXPECT_ANY_THROW(ipow(this->two, this->max)); EXPECT_ANY_THROW(ipow(this->three, this->digits)); EXPECT_ANY_THROW(ipow(this->three, this->max)); EXPECT_ANY_THROW(ipow(this->max, this->digits)); EXPECT_ANY_THROW(ipow(this->max, this->max)); } <|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 "util/u_math.h" #include "api/util.hpp" #include "core/memory.hpp" #include "core/format.hpp" using namespace clover; CLOVER_API cl_mem clCreateBuffer(cl_context d_ctx, cl_mem_flags flags, size_t size, void *host_ptr, cl_int *r_errcode) try { auto &ctx = obj(d_ctx); if (bool(host_ptr) != bool(flags & (CL_MEM_USE_HOST_PTR | CL_MEM_COPY_HOST_PTR))) throw error(CL_INVALID_HOST_PTR); if (!size || size > fold(maximum(), 0u, map(std::mem_fn(&device::max_mem_alloc_size), ctx.devs()) )) throw error(CL_INVALID_BUFFER_SIZE); if (flags & ~(CL_MEM_READ_WRITE | CL_MEM_WRITE_ONLY | CL_MEM_READ_ONLY | CL_MEM_USE_HOST_PTR | CL_MEM_ALLOC_HOST_PTR | CL_MEM_COPY_HOST_PTR)) throw error(CL_INVALID_VALUE); if (util_bitcount(flags & (CL_MEM_READ_ONLY | CL_MEM_WRITE_ONLY | CL_MEM_READ_WRITE)) > 1) throw error(CL_INVALID_VALUE); if ((flags & CL_MEM_USE_HOST_PTR) && (flags & (CL_MEM_COPY_HOST_PTR | CL_MEM_ALLOC_HOST_PTR))) throw error(CL_INVALID_VALUE); ret_error(r_errcode, CL_SUCCESS); return new root_buffer(ctx, flags, size, host_ptr); } catch (error &e) { ret_error(r_errcode, e); return NULL; } CLOVER_API cl_mem clCreateSubBuffer(cl_mem d_mem, cl_mem_flags flags, cl_buffer_create_type op, const void *op_info, cl_int *r_errcode) try { auto &parent = obj<root_buffer>(d_mem); if ((flags & (CL_MEM_USE_HOST_PTR | CL_MEM_ALLOC_HOST_PTR | CL_MEM_COPY_HOST_PTR)) || (~flags & parent.flags() & (CL_MEM_READ_ONLY | CL_MEM_WRITE_ONLY))) throw error(CL_INVALID_VALUE); if (op == CL_BUFFER_CREATE_TYPE_REGION) { auto reg = reinterpret_cast<const cl_buffer_region *>(op_info); if (!reg || reg->origin > parent.size() || reg->origin + reg->size > parent.size()) throw error(CL_INVALID_VALUE); if (!reg->size) throw error(CL_INVALID_BUFFER_SIZE); ret_error(r_errcode, CL_SUCCESS); return new sub_buffer(parent, flags, reg->origin, reg->size); } else { throw error(CL_INVALID_VALUE); } } catch (error &e) { ret_error(r_errcode, e); return NULL; } CLOVER_API cl_mem clCreateImage2D(cl_context d_ctx, cl_mem_flags flags, const cl_image_format *format, size_t width, size_t height, size_t row_pitch, void *host_ptr, cl_int *r_errcode) try { auto &ctx = obj(d_ctx); if (flags & ~(CL_MEM_READ_WRITE | CL_MEM_WRITE_ONLY | CL_MEM_READ_ONLY | CL_MEM_USE_HOST_PTR | CL_MEM_ALLOC_HOST_PTR | CL_MEM_COPY_HOST_PTR)) throw error(CL_INVALID_VALUE); if (!format) throw error(CL_INVALID_IMAGE_FORMAT_DESCRIPTOR); if (width < 1 || height < 1) throw error(CL_INVALID_IMAGE_SIZE); if (bool(host_ptr) != bool(flags & (CL_MEM_USE_HOST_PTR | CL_MEM_COPY_HOST_PTR))) throw error(CL_INVALID_HOST_PTR); if (!supported_formats(ctx, CL_MEM_OBJECT_IMAGE2D).count(*format)) throw error(CL_IMAGE_FORMAT_NOT_SUPPORTED); ret_error(r_errcode, CL_SUCCESS); return new image2d(ctx, flags, format, width, height, row_pitch, host_ptr); } catch (error &e) { ret_error(r_errcode, e); return NULL; } CLOVER_API cl_mem clCreateImage3D(cl_context d_ctx, cl_mem_flags flags, const cl_image_format *format, size_t width, size_t height, size_t depth, size_t row_pitch, size_t slice_pitch, void *host_ptr, cl_int *r_errcode) try { auto &ctx = obj(d_ctx); if (flags & ~(CL_MEM_READ_WRITE | CL_MEM_WRITE_ONLY | CL_MEM_READ_ONLY | CL_MEM_USE_HOST_PTR | CL_MEM_ALLOC_HOST_PTR | CL_MEM_COPY_HOST_PTR)) throw error(CL_INVALID_VALUE); if (!format) throw error(CL_INVALID_IMAGE_FORMAT_DESCRIPTOR); if (width < 1 || height < 1 || depth < 2) throw error(CL_INVALID_IMAGE_SIZE); if (bool(host_ptr) != bool(flags & (CL_MEM_USE_HOST_PTR | CL_MEM_COPY_HOST_PTR))) throw error(CL_INVALID_HOST_PTR); if (!supported_formats(ctx, CL_MEM_OBJECT_IMAGE3D).count(*format)) throw error(CL_IMAGE_FORMAT_NOT_SUPPORTED); ret_error(r_errcode, CL_SUCCESS); return new image3d(ctx, flags, format, width, height, depth, row_pitch, slice_pitch, host_ptr); } catch (error &e) { ret_error(r_errcode, e); return NULL; } CLOVER_API cl_int clGetSupportedImageFormats(cl_context d_ctx, cl_mem_flags flags, cl_mem_object_type type, cl_uint count, cl_image_format *r_buf, cl_uint *r_count) try { auto &ctx = obj(d_ctx); if (flags & ~(CL_MEM_READ_WRITE | CL_MEM_WRITE_ONLY | CL_MEM_READ_ONLY | CL_MEM_USE_HOST_PTR | CL_MEM_ALLOC_HOST_PTR | CL_MEM_COPY_HOST_PTR)) throw error(CL_INVALID_VALUE); if (r_buf && !r_count) throw error(CL_INVALID_VALUE); auto formats = supported_formats(ctx, type); if (r_buf) std::copy_n(formats.begin(), std::min((cl_uint)formats.size(), count), r_buf); if (r_count) *r_count = formats.size(); return CL_SUCCESS; } catch (error &e) { return e.get(); } CLOVER_API cl_int clGetMemObjectInfo(cl_mem d_mem, cl_mem_info param, size_t size, void *r_buf, size_t *r_size) try { property_buffer buf { r_buf, size, r_size }; auto &mem = obj(d_mem); switch (param) { case CL_MEM_TYPE: buf.as_scalar<cl_mem_object_type>() = mem.type(); break; case CL_MEM_FLAGS: buf.as_scalar<cl_mem_flags>() = mem.flags(); break; case CL_MEM_SIZE: buf.as_scalar<size_t>() = mem.size(); break; case CL_MEM_HOST_PTR: buf.as_scalar<void *>() = mem.host_ptr(); break; case CL_MEM_MAP_COUNT: buf.as_scalar<cl_uint>() = 0; break; case CL_MEM_REFERENCE_COUNT: buf.as_scalar<cl_uint>() = mem.ref_count(); break; case CL_MEM_CONTEXT: buf.as_scalar<cl_context>() = desc(mem.ctx); break; case CL_MEM_ASSOCIATED_MEMOBJECT: { sub_buffer *sub = dynamic_cast<sub_buffer *>(&mem); buf.as_scalar<cl_mem>() = (sub ? desc(sub->parent) : NULL); break; } case CL_MEM_OFFSET: { sub_buffer *sub = dynamic_cast<sub_buffer *>(&mem); buf.as_scalar<size_t>() = (sub ? sub->offset() : 0); break; } default: throw error(CL_INVALID_VALUE); } return CL_SUCCESS; } catch (error &e) { return e.get(); } CLOVER_API cl_int clGetImageInfo(cl_mem d_mem, cl_image_info param, size_t size, void *r_buf, size_t *r_size) try { property_buffer buf { r_buf, size, r_size }; auto &img = obj<image>(d_mem); switch (param) { case CL_IMAGE_FORMAT: buf.as_scalar<cl_image_format>() = img.format(); break; case CL_IMAGE_ELEMENT_SIZE: buf.as_scalar<size_t>() = 0; break; case CL_IMAGE_ROW_PITCH: buf.as_scalar<size_t>() = img.row_pitch(); break; case CL_IMAGE_SLICE_PITCH: buf.as_scalar<size_t>() = img.slice_pitch(); break; case CL_IMAGE_WIDTH: buf.as_scalar<size_t>() = img.width(); break; case CL_IMAGE_HEIGHT: buf.as_scalar<size_t>() = img.height(); break; case CL_IMAGE_DEPTH: buf.as_scalar<size_t>() = img.depth(); break; default: throw error(CL_INVALID_VALUE); } return CL_SUCCESS; } catch (error &e) { return e.get(); } CLOVER_API cl_int clRetainMemObject(cl_mem d_mem) try { obj(d_mem).retain(); return CL_SUCCESS; } catch (error &e) { return e.get(); } CLOVER_API cl_int clReleaseMemObject(cl_mem d_mem) try { if (obj(d_mem).release()) delete pobj(d_mem); return CL_SUCCESS; } catch (error &e) { return e.get(); } CLOVER_API cl_int clSetMemObjectDestructorCallback(cl_mem d_mem, void (CL_CALLBACK *pfn_notify)(cl_mem, void *), void *user_data) try { auto &mem = obj(d_mem); if (!pfn_notify) return CL_INVALID_VALUE; mem.destroy_notify([=]{ pfn_notify(d_mem, user_data); }); return CL_SUCCESS; } catch (error &e) { return e.get(); } <commit_msg>clover: Use cl_ulong in the maximum allocation size calculation to avoid overflow.<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 "util/u_math.h" #include "api/util.hpp" #include "core/memory.hpp" #include "core/format.hpp" using namespace clover; CLOVER_API cl_mem clCreateBuffer(cl_context d_ctx, cl_mem_flags flags, size_t size, void *host_ptr, cl_int *r_errcode) try { auto &ctx = obj(d_ctx); if (bool(host_ptr) != bool(flags & (CL_MEM_USE_HOST_PTR | CL_MEM_COPY_HOST_PTR))) throw error(CL_INVALID_HOST_PTR); if (!size || size > fold(maximum(), cl_ulong(0), map(std::mem_fn(&device::max_mem_alloc_size), ctx.devs()) )) throw error(CL_INVALID_BUFFER_SIZE); if (flags & ~(CL_MEM_READ_WRITE | CL_MEM_WRITE_ONLY | CL_MEM_READ_ONLY | CL_MEM_USE_HOST_PTR | CL_MEM_ALLOC_HOST_PTR | CL_MEM_COPY_HOST_PTR)) throw error(CL_INVALID_VALUE); if (util_bitcount(flags & (CL_MEM_READ_ONLY | CL_MEM_WRITE_ONLY | CL_MEM_READ_WRITE)) > 1) throw error(CL_INVALID_VALUE); if ((flags & CL_MEM_USE_HOST_PTR) && (flags & (CL_MEM_COPY_HOST_PTR | CL_MEM_ALLOC_HOST_PTR))) throw error(CL_INVALID_VALUE); ret_error(r_errcode, CL_SUCCESS); return new root_buffer(ctx, flags, size, host_ptr); } catch (error &e) { ret_error(r_errcode, e); return NULL; } CLOVER_API cl_mem clCreateSubBuffer(cl_mem d_mem, cl_mem_flags flags, cl_buffer_create_type op, const void *op_info, cl_int *r_errcode) try { auto &parent = obj<root_buffer>(d_mem); if ((flags & (CL_MEM_USE_HOST_PTR | CL_MEM_ALLOC_HOST_PTR | CL_MEM_COPY_HOST_PTR)) || (~flags & parent.flags() & (CL_MEM_READ_ONLY | CL_MEM_WRITE_ONLY))) throw error(CL_INVALID_VALUE); if (op == CL_BUFFER_CREATE_TYPE_REGION) { auto reg = reinterpret_cast<const cl_buffer_region *>(op_info); if (!reg || reg->origin > parent.size() || reg->origin + reg->size > parent.size()) throw error(CL_INVALID_VALUE); if (!reg->size) throw error(CL_INVALID_BUFFER_SIZE); ret_error(r_errcode, CL_SUCCESS); return new sub_buffer(parent, flags, reg->origin, reg->size); } else { throw error(CL_INVALID_VALUE); } } catch (error &e) { ret_error(r_errcode, e); return NULL; } CLOVER_API cl_mem clCreateImage2D(cl_context d_ctx, cl_mem_flags flags, const cl_image_format *format, size_t width, size_t height, size_t row_pitch, void *host_ptr, cl_int *r_errcode) try { auto &ctx = obj(d_ctx); if (flags & ~(CL_MEM_READ_WRITE | CL_MEM_WRITE_ONLY | CL_MEM_READ_ONLY | CL_MEM_USE_HOST_PTR | CL_MEM_ALLOC_HOST_PTR | CL_MEM_COPY_HOST_PTR)) throw error(CL_INVALID_VALUE); if (!format) throw error(CL_INVALID_IMAGE_FORMAT_DESCRIPTOR); if (width < 1 || height < 1) throw error(CL_INVALID_IMAGE_SIZE); if (bool(host_ptr) != bool(flags & (CL_MEM_USE_HOST_PTR | CL_MEM_COPY_HOST_PTR))) throw error(CL_INVALID_HOST_PTR); if (!supported_formats(ctx, CL_MEM_OBJECT_IMAGE2D).count(*format)) throw error(CL_IMAGE_FORMAT_NOT_SUPPORTED); ret_error(r_errcode, CL_SUCCESS); return new image2d(ctx, flags, format, width, height, row_pitch, host_ptr); } catch (error &e) { ret_error(r_errcode, e); return NULL; } CLOVER_API cl_mem clCreateImage3D(cl_context d_ctx, cl_mem_flags flags, const cl_image_format *format, size_t width, size_t height, size_t depth, size_t row_pitch, size_t slice_pitch, void *host_ptr, cl_int *r_errcode) try { auto &ctx = obj(d_ctx); if (flags & ~(CL_MEM_READ_WRITE | CL_MEM_WRITE_ONLY | CL_MEM_READ_ONLY | CL_MEM_USE_HOST_PTR | CL_MEM_ALLOC_HOST_PTR | CL_MEM_COPY_HOST_PTR)) throw error(CL_INVALID_VALUE); if (!format) throw error(CL_INVALID_IMAGE_FORMAT_DESCRIPTOR); if (width < 1 || height < 1 || depth < 2) throw error(CL_INVALID_IMAGE_SIZE); if (bool(host_ptr) != bool(flags & (CL_MEM_USE_HOST_PTR | CL_MEM_COPY_HOST_PTR))) throw error(CL_INVALID_HOST_PTR); if (!supported_formats(ctx, CL_MEM_OBJECT_IMAGE3D).count(*format)) throw error(CL_IMAGE_FORMAT_NOT_SUPPORTED); ret_error(r_errcode, CL_SUCCESS); return new image3d(ctx, flags, format, width, height, depth, row_pitch, slice_pitch, host_ptr); } catch (error &e) { ret_error(r_errcode, e); return NULL; } CLOVER_API cl_int clGetSupportedImageFormats(cl_context d_ctx, cl_mem_flags flags, cl_mem_object_type type, cl_uint count, cl_image_format *r_buf, cl_uint *r_count) try { auto &ctx = obj(d_ctx); if (flags & ~(CL_MEM_READ_WRITE | CL_MEM_WRITE_ONLY | CL_MEM_READ_ONLY | CL_MEM_USE_HOST_PTR | CL_MEM_ALLOC_HOST_PTR | CL_MEM_COPY_HOST_PTR)) throw error(CL_INVALID_VALUE); if (r_buf && !r_count) throw error(CL_INVALID_VALUE); auto formats = supported_formats(ctx, type); if (r_buf) std::copy_n(formats.begin(), std::min((cl_uint)formats.size(), count), r_buf); if (r_count) *r_count = formats.size(); return CL_SUCCESS; } catch (error &e) { return e.get(); } CLOVER_API cl_int clGetMemObjectInfo(cl_mem d_mem, cl_mem_info param, size_t size, void *r_buf, size_t *r_size) try { property_buffer buf { r_buf, size, r_size }; auto &mem = obj(d_mem); switch (param) { case CL_MEM_TYPE: buf.as_scalar<cl_mem_object_type>() = mem.type(); break; case CL_MEM_FLAGS: buf.as_scalar<cl_mem_flags>() = mem.flags(); break; case CL_MEM_SIZE: buf.as_scalar<size_t>() = mem.size(); break; case CL_MEM_HOST_PTR: buf.as_scalar<void *>() = mem.host_ptr(); break; case CL_MEM_MAP_COUNT: buf.as_scalar<cl_uint>() = 0; break; case CL_MEM_REFERENCE_COUNT: buf.as_scalar<cl_uint>() = mem.ref_count(); break; case CL_MEM_CONTEXT: buf.as_scalar<cl_context>() = desc(mem.ctx); break; case CL_MEM_ASSOCIATED_MEMOBJECT: { sub_buffer *sub = dynamic_cast<sub_buffer *>(&mem); buf.as_scalar<cl_mem>() = (sub ? desc(sub->parent) : NULL); break; } case CL_MEM_OFFSET: { sub_buffer *sub = dynamic_cast<sub_buffer *>(&mem); buf.as_scalar<size_t>() = (sub ? sub->offset() : 0); break; } default: throw error(CL_INVALID_VALUE); } return CL_SUCCESS; } catch (error &e) { return e.get(); } CLOVER_API cl_int clGetImageInfo(cl_mem d_mem, cl_image_info param, size_t size, void *r_buf, size_t *r_size) try { property_buffer buf { r_buf, size, r_size }; auto &img = obj<image>(d_mem); switch (param) { case CL_IMAGE_FORMAT: buf.as_scalar<cl_image_format>() = img.format(); break; case CL_IMAGE_ELEMENT_SIZE: buf.as_scalar<size_t>() = 0; break; case CL_IMAGE_ROW_PITCH: buf.as_scalar<size_t>() = img.row_pitch(); break; case CL_IMAGE_SLICE_PITCH: buf.as_scalar<size_t>() = img.slice_pitch(); break; case CL_IMAGE_WIDTH: buf.as_scalar<size_t>() = img.width(); break; case CL_IMAGE_HEIGHT: buf.as_scalar<size_t>() = img.height(); break; case CL_IMAGE_DEPTH: buf.as_scalar<size_t>() = img.depth(); break; default: throw error(CL_INVALID_VALUE); } return CL_SUCCESS; } catch (error &e) { return e.get(); } CLOVER_API cl_int clRetainMemObject(cl_mem d_mem) try { obj(d_mem).retain(); return CL_SUCCESS; } catch (error &e) { return e.get(); } CLOVER_API cl_int clReleaseMemObject(cl_mem d_mem) try { if (obj(d_mem).release()) delete pobj(d_mem); return CL_SUCCESS; } catch (error &e) { return e.get(); } CLOVER_API cl_int clSetMemObjectDestructorCallback(cl_mem d_mem, void (CL_CALLBACK *pfn_notify)(cl_mem, void *), void *user_data) try { auto &mem = obj(d_mem); if (!pfn_notify) return CL_INVALID_VALUE; mem.destroy_notify([=]{ pfn_notify(d_mem, user_data); }); return CL_SUCCESS; } catch (error &e) { return e.get(); } <|endoftext|>
<commit_before>/* This file is part of Magnum. Original authors — credit is appreciated but not required: 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 — Vladimír Vondruš <mosra@centrum.cz> 2018 — scturtle <scturtle@gmail.com> This is free and unencumbered software released into the public domain. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means. In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <Magnum/Image.h> #include <Magnum/GL/Buffer.h> #include <Magnum/GL/DefaultFramebuffer.h> #include <Magnum/GL/Mesh.h> #include <Magnum/GL/PixelFormat.h> #include <Magnum/GL/Renderer.h> #include <Magnum/MeshTools/Compile.h> #include <Magnum/Platform/Sdl2Application.h> #include <Magnum/Primitives/Grid.h> #include <Magnum/SceneGraph/Camera.h> #include <Magnum/SceneGraph/Drawable.h> #include <Magnum/SceneGraph/MatrixTransformation3D.h> #include <Magnum/SceneGraph/Object.h> #include <Magnum/SceneGraph/Scene.h> #include <Magnum/Shaders/Flat.h> #include <Magnum/Shaders/VertexColor.h> #include <Magnum/Trade/MeshData3D.h> namespace Magnum { namespace Examples { using Object3D = SceneGraph::Object<SceneGraph::MatrixTransformation3D>; using Scene3D = SceneGraph::Scene<SceneGraph::MatrixTransformation3D>; using namespace Math::Literals; class MouseInteractionExample: public Platform::Application { public: explicit MouseInteractionExample(const Arguments &arguments); private: Float depthAt(const Vector2i& position); Vector3 unproject(const Vector2i& position, Float depth); void mousePressEvent(MouseEvent &event) override; void mouseMoveEvent(MouseMoveEvent &event) override; void mouseScrollEvent(MouseScrollEvent &event) override; void drawEvent() override; Shaders::VertexColor3D _vertexColorShader{NoCreate}; Shaders::Flat3D _flatShader{NoCreate}; GL::Mesh _mesh{NoCreate}, _grid{NoCreate}; Scene3D _scene; SceneGraph::DrawableGroup3D _drawables; Object3D* _cameraObject; SceneGraph::Camera3D* _camera; Float _lastDepth{0.8f}; Vector2i _lastPosition{-1}; Vector3 _rotationPoint, _translationPoint; }; class VertexColorDrawable: public SceneGraph::Drawable3D { public: explicit VertexColorDrawable(Object3D& object, Shaders::VertexColor3D& shader, GL::Mesh& mesh, SceneGraph::DrawableGroup3D& drawables): SceneGraph::Drawable3D{object, &drawables}, _shader(shader), _mesh(mesh) {} void draw(const Matrix4& transformation, SceneGraph::Camera3D& camera) { _shader.setTransformationProjectionMatrix(camera.projectionMatrix()*transformation); _mesh.draw(_shader); } private: Shaders::VertexColor3D& _shader; GL::Mesh& _mesh; }; class FlatDrawable: public SceneGraph::Drawable3D { public: explicit FlatDrawable(Object3D& object, Shaders::Flat3D& shader, GL::Mesh& mesh, SceneGraph::DrawableGroup3D& drawables): SceneGraph::Drawable3D{object, &drawables}, _shader(shader), _mesh(mesh) {} void draw(const Matrix4& transformation, SceneGraph::Camera3D& camera) { _shader.setColor(0x747474_rgbf) .setTransformationProjectionMatrix(camera.projectionMatrix()*transformation); _mesh.draw(_shader); } private: Shaders::Flat3D& _shader; GL::Mesh& _mesh; }; MouseInteractionExample::MouseInteractionExample(const Arguments &arguments): Platform::Application{arguments, NoCreate} { /* Try 8x MSAA, fall back to zero samples if not possible. Enable only 2x MSAA if we have enough DPI. */ { const Vector2 dpiScaling = this->dpiScaling({}); Configuration conf; conf.setTitle("Magnum Mouse Interaction Example") .setSize(conf.size(), dpiScaling); GLConfiguration glConf; glConf.setSampleCount(dpiScaling.max() < 2.0f ? 8 : 2); if(!tryCreate(conf, glConf)) create(conf, glConf.setSampleCount(0)); } /* Shaders, renderer setup */ _vertexColorShader = Shaders::VertexColor3D{}; _flatShader = Shaders::Flat3D{}; GL::Renderer::enable(GL::Renderer::Feature::DepthTest); /* Triangle data */ const struct { Vector3 pos; Color3 color; } data[]{{{-1.0f, -1.0f, 0.0f}, 0xff0000_rgbf}, {{ 1.0f, -1.0f, 0.0f}, 0x00ff00_rgbf}, {{ 0.0f, 1.0f, 0.0f}, 0x0000ff_rgbf}}; /* Triangle mesh */ GL::Buffer buffer; buffer.setData(data); _mesh = GL::Mesh{}; _mesh.setCount(3) .addVertexBuffer(std::move(buffer), 0, Shaders::VertexColor3D::Position{}, Shaders::VertexColor3D::Color3{}); /* Triangle object */ auto triangle = new Object3D{&_scene}; new VertexColorDrawable{*triangle, _vertexColorShader, _mesh, _drawables}; /* Grid */ _grid = MeshTools::compile(Primitives::grid3DWireframe({15, 15})); auto grid = new Object3D{&_scene}; (*grid) .rotateX(90.0_degf) .scale(Vector3{8.0f}); new FlatDrawable{*grid, _flatShader, _grid, _drawables}; /* Set up the camera */ _cameraObject = new Object3D{&_scene}; (*_cameraObject) .translate(Vector3::zAxis(5.0f)) .rotateX(-15.0_degf) .rotateY(30.0_degf); _camera = new SceneGraph::Camera3D{*_cameraObject}; _camera->setProjectionMatrix(Matrix4::perspectiveProjection( 45.0_degf, Vector2{windowSize()}.aspectRatio(), 0.01f, 100.0f)); } Float MouseInteractionExample::depthAt(const Vector2i& position) { const Vector2i fbPosition{position.x(), GL::defaultFramebuffer.viewport().sizeY() - position.y() - 1}; GL::defaultFramebuffer.mapForRead(GL::DefaultFramebuffer::ReadAttachment::Front); Image2D data = GL::defaultFramebuffer.read( Range2Di::fromSize(fbPosition, Vector2i{1}).padded(Vector2i{2}), {GL::PixelFormat::DepthComponent, GL::PixelType::Float}); return Math::min(Containers::arrayCast<const Float>(data.data())); } Vector3 MouseInteractionExample::unproject(const Vector2i& position, Float depth) { const Range2Di view = GL::defaultFramebuffer.viewport(); const Vector2i fbPosition{position.x(), view.sizeY() - position.y() - 1}; const Vector3 in{2*Vector2{fbPosition - view.min()}/Vector2{view.size()} - Vector2{1.0f}, depth*2.0f - 1.0f}; /* Use the following to get global coordinates instead of camera-relative: (_cameraObject->absoluteTransformationMatrix()*_camera->projectionMatrix().inverted()).transformPoint(in) */ return _camera->projectionMatrix().inverted().transformPoint(in); } void MouseInteractionExample::mousePressEvent(MouseEvent& event) { const Float currentDepth = depthAt(event.position()); const Float depth = currentDepth == 1.0f ? _lastDepth : currentDepth; _translationPoint = unproject(event.position(), depth); if(currentDepth != 1.0f) { _rotationPoint = _translationPoint; _lastDepth = depth; } } void MouseInteractionExample::mouseMoveEvent(MouseMoveEvent& event) { if(_lastPosition == Vector2i{-1}) _lastPosition = event.position(); const Vector2i delta = event.position() - _lastPosition; _lastPosition = event.position(); if(!event.buttons()) return; /* Translate */ if(event.modifiers() & MouseMoveEvent::Modifier::Shift) { const Vector3 p = unproject(event.position(), _lastDepth); _cameraObject->translateLocal(_translationPoint - p); /* is Z always 0? */ _translationPoint = p; /* Rotate around rotation point */ } else _cameraObject->transformLocal( Matrix4::translation(_rotationPoint)* Matrix4::rotationX(-0.01_radf*delta.y())* Matrix4::rotationY(-0.01_radf*delta.x())* Matrix4::translation(-_rotationPoint)); redraw(); } void MouseInteractionExample::mouseScrollEvent(MouseScrollEvent &event) { const Float currentDepth = depthAt(event.position()); const Float depth = currentDepth == 1.0f ? _lastDepth : currentDepth; const Vector3 p = unproject(event.position(), depth); if(currentDepth != 1.0f) { _rotationPoint = p; _lastDepth = depth; } const Int direction = event.offset().y(); if(!direction) return; /* Move towards/backwards the rotation point in cam coords */ _cameraObject->translateLocal(_rotationPoint*(direction < 0 ? -1.0f : 1.0f)*0.1f); redraw(); } void MouseInteractionExample::drawEvent() { GL::defaultFramebuffer.clear(GL::FramebufferClear::Color|GL::FramebufferClear::Depth); _camera->draw(_drawables); swapBuffers(); } }} MAGNUM_APPLICATION_MAIN(Magnum::Examples::MouseInteractionExample) <commit_msg>mouseinteraction: minor cleanup.<commit_after>/* This file is part of Magnum. Original authors — credit is appreciated but not required: 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 — Vladimír Vondruš <mosra@centrum.cz> 2018 — scturtle <scturtle@gmail.com> This is free and unencumbered software released into the public domain. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means. In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <Magnum/Image.h> #include <Magnum/GL/Buffer.h> #include <Magnum/GL/DefaultFramebuffer.h> #include <Magnum/GL/Mesh.h> #include <Magnum/GL/PixelFormat.h> #include <Magnum/GL/Renderer.h> #include <Magnum/MeshTools/Compile.h> #include <Magnum/Platform/Sdl2Application.h> #include <Magnum/Primitives/Grid.h> #include <Magnum/SceneGraph/Camera.h> #include <Magnum/SceneGraph/Drawable.h> #include <Magnum/SceneGraph/MatrixTransformation3D.h> #include <Magnum/SceneGraph/Object.h> #include <Magnum/SceneGraph/Scene.h> #include <Magnum/Shaders/Flat.h> #include <Magnum/Shaders/VertexColor.h> #include <Magnum/Trade/MeshData3D.h> namespace Magnum { namespace Examples { using Object3D = SceneGraph::Object<SceneGraph::MatrixTransformation3D>; using Scene3D = SceneGraph::Scene<SceneGraph::MatrixTransformation3D>; using namespace Math::Literals; class MouseInteractionExample: public Platform::Application { public: explicit MouseInteractionExample(const Arguments& arguments); private: Float depthAt(const Vector2i& position); Vector3 unproject(const Vector2i& position, Float depth) const; void mousePressEvent(MouseEvent& event) override; void mouseMoveEvent(MouseMoveEvent& event) override; void mouseScrollEvent(MouseScrollEvent& event) override; void drawEvent() override; Shaders::VertexColor3D _vertexColorShader{NoCreate}; Shaders::Flat3D _flatShader{NoCreate}; GL::Mesh _mesh{NoCreate}, _grid{NoCreate}; Scene3D _scene; SceneGraph::DrawableGroup3D _drawables; Object3D* _cameraObject; SceneGraph::Camera3D* _camera; Float _lastDepth{0.8f}; Vector2i _lastPosition{-1}; Vector3 _rotationPoint, _translationPoint; }; class VertexColorDrawable: public SceneGraph::Drawable3D { public: explicit VertexColorDrawable(Object3D& object, Shaders::VertexColor3D& shader, GL::Mesh& mesh, SceneGraph::DrawableGroup3D& drawables): SceneGraph::Drawable3D{object, &drawables}, _shader(shader), _mesh(mesh) {} void draw(const Matrix4& transformation, SceneGraph::Camera3D& camera) { _shader.setTransformationProjectionMatrix(camera.projectionMatrix()*transformation); _mesh.draw(_shader); } private: Shaders::VertexColor3D& _shader; GL::Mesh& _mesh; }; class FlatDrawable: public SceneGraph::Drawable3D { public: explicit FlatDrawable(Object3D& object, Shaders::Flat3D& shader, GL::Mesh& mesh, SceneGraph::DrawableGroup3D& drawables): SceneGraph::Drawable3D{object, &drawables}, _shader(shader), _mesh(mesh) {} void draw(const Matrix4& transformation, SceneGraph::Camera3D& camera) { _shader.setColor(0x747474_rgbf) .setTransformationProjectionMatrix(camera.projectionMatrix()*transformation); _mesh.draw(_shader); } private: Shaders::Flat3D& _shader; GL::Mesh& _mesh; }; MouseInteractionExample::MouseInteractionExample(const Arguments& arguments): Platform::Application{arguments, NoCreate} { /* Try 8x MSAA, fall back to zero samples if not possible. Enable only 2x MSAA if we have enough DPI. */ { const Vector2 dpiScaling = this->dpiScaling({}); Configuration conf; conf.setTitle("Magnum Mouse Interaction Example") .setSize(conf.size(), dpiScaling); GLConfiguration glConf; glConf.setSampleCount(dpiScaling.max() < 2.0f ? 8 : 2); if(!tryCreate(conf, glConf)) create(conf, glConf.setSampleCount(0)); } /* Shaders, renderer setup */ _vertexColorShader = Shaders::VertexColor3D{}; _flatShader = Shaders::Flat3D{}; GL::Renderer::enable(GL::Renderer::Feature::DepthTest); /* Triangle data */ const struct { Vector3 pos; Color3 color; } data[]{{{-1.0f, -1.0f, 0.0f}, 0xff0000_rgbf}, {{ 1.0f, -1.0f, 0.0f}, 0x00ff00_rgbf}, {{ 0.0f, 1.0f, 0.0f}, 0x0000ff_rgbf}}; /* Triangle mesh */ GL::Buffer buffer; buffer.setData(data); _mesh = GL::Mesh{}; _mesh.setCount(3) .addVertexBuffer(std::move(buffer), 0, Shaders::VertexColor3D::Position{}, Shaders::VertexColor3D::Color3{}); /* Triangle object */ auto triangle = new Object3D{&_scene}; new VertexColorDrawable{*triangle, _vertexColorShader, _mesh, _drawables}; /* Grid */ _grid = MeshTools::compile(Primitives::grid3DWireframe({15, 15})); auto grid = new Object3D{&_scene}; (*grid) .rotateX(90.0_degf) .scale(Vector3{8.0f}); new FlatDrawable{*grid, _flatShader, _grid, _drawables}; /* Set up the camera */ _cameraObject = new Object3D{&_scene}; (*_cameraObject) .translate(Vector3::zAxis(5.0f)) .rotateX(-15.0_degf) .rotateY(30.0_degf); _camera = new SceneGraph::Camera3D{*_cameraObject}; _camera->setProjectionMatrix(Matrix4::perspectiveProjection( 45.0_degf, Vector2{windowSize()}.aspectRatio(), 0.01f, 100.0f)); } Float MouseInteractionExample::depthAt(const Vector2i& position) { const Vector2i fbPosition{position.x(), GL::defaultFramebuffer.viewport().sizeY() - position.y() - 1}; GL::defaultFramebuffer.mapForRead(GL::DefaultFramebuffer::ReadAttachment::Front); Image2D data = GL::defaultFramebuffer.read( Range2Di::fromSize(fbPosition, Vector2i{1}).padded(Vector2i{2}), {GL::PixelFormat::DepthComponent, GL::PixelType::Float}); return Math::min(Containers::arrayCast<const Float>(data.data())); } Vector3 MouseInteractionExample::unproject(const Vector2i& position, Float depth) const { const Range2Di view = GL::defaultFramebuffer.viewport(); const Vector2i fbPosition{position.x(), view.sizeY() - position.y() - 1}; const Vector3 in{2*Vector2{fbPosition - view.min()}/Vector2{view.size()} - Vector2{1.0f}, depth*2.0f - 1.0f}; /* Use the following to get global coordinates instead of camera-relative: (_cameraObject->absoluteTransformationMatrix()*_camera->projectionMatrix().inverted()).transformPoint(in) */ return _camera->projectionMatrix().inverted().transformPoint(in); } void MouseInteractionExample::mousePressEvent(MouseEvent& event) { const Float currentDepth = depthAt(event.position()); const Float depth = currentDepth == 1.0f ? _lastDepth : currentDepth; _translationPoint = unproject(event.position(), depth); if(currentDepth != 1.0f) { _rotationPoint = _translationPoint; _lastDepth = depth; } } void MouseInteractionExample::mouseMoveEvent(MouseMoveEvent& event) { if(_lastPosition == Vector2i{-1}) _lastPosition = event.position(); const Vector2i delta = event.position() - _lastPosition; _lastPosition = event.position(); if(!event.buttons()) return; /* Translate */ if(event.modifiers() & MouseMoveEvent::Modifier::Shift) { const Vector3 p = unproject(event.position(), _lastDepth); _cameraObject->translateLocal(_translationPoint - p); /* is Z always 0? */ _translationPoint = p; /* Rotate around rotation point */ } else _cameraObject->transformLocal( Matrix4::translation(_rotationPoint)* Matrix4::rotationX(-0.01_radf*delta.y())* Matrix4::rotationY(-0.01_radf*delta.x())* Matrix4::translation(-_rotationPoint)); redraw(); } void MouseInteractionExample::mouseScrollEvent(MouseScrollEvent& event) { const Float currentDepth = depthAt(event.position()); const Float depth = currentDepth == 1.0f ? _lastDepth : currentDepth; const Vector3 p = unproject(event.position(), depth); if(currentDepth != 1.0f) { _rotationPoint = p; _lastDepth = depth; } const Int direction = event.offset().y(); if(!direction) return; /* Move towards/backwards the rotation point in cam coords */ _cameraObject->translateLocal(_rotationPoint*(direction < 0 ? -1.0f : 1.0f)*0.1f); redraw(); } void MouseInteractionExample::drawEvent() { GL::defaultFramebuffer.clear(GL::FramebufferClear::Color|GL::FramebufferClear::Depth); _camera->draw(_drawables); swapBuffers(); } }} MAGNUM_APPLICATION_MAIN(Magnum::Examples::MouseInteractionExample) <|endoftext|>
<commit_before>#pragma once #include "signature-page.hh" #include "tree-draw.hh" #include "time-series-draw.hh" #include "clades-draw.hh" #include "mapped-antigens-draw.hh" #include "aa-at-pos-draw.hh" #include "antigenic-maps-draw.hh" #include "title-draw.hh" // ---------------------------------------------------------------------- class SettingsMod : public acmacs::settings::object { public: using acmacs::settings::object::object; acmacs::settings::field<std::string> name{this, "N"}; acmacs::settings::field<std::string> name_commented{this, "?N"}; acmacs::settings::field<acmacs::Offset> offset{this, "offset"}; acmacs::settings::field<double> size{this, "size"}; acmacs::settings::field<Color> color{this, "color"}; acmacs::settings::field<acmacs::TextStyle> style{this, "style"}; acmacs::settings::field<std::string> text{this, "text"}; }; // ---------------------------------------------------------------------- constexpr const char* SETTINGS_VERSION_4 = "signature-page-settings-v4"; class Settings : public acmacs::settings::toplevel { public: Settings(); acmacs::settings::field<std::string> version{this, " version", SETTINGS_VERSION_4}; acmacs::settings::field_array_of<SettingsMod> mods{this, "mods"}; acmacs::settings::field_object<SignaturePageDrawSettings> signature_page{this, "signature_page"}; acmacs::settings::field_object<TitleDrawSettings> title{this, "title"}; acmacs::settings::field_object<TreeDrawSettings> tree_draw{this, "tree_draw"}; acmacs::settings::field_object<TimeSeriesDrawSettings> time_series{this, "time_series"}; acmacs::settings::field_object<CladesDrawSettings> clades{this, "clades"}; acmacs::settings::field_object<HzSections> hz_sections{this, "hz_sections"}; acmacs::settings::field_object<MappedAntigensDrawSettings> mapped_antigens{this, "mapped_antigens"}; acmacs::settings::field_object<AAAtPosDrawSettings> aa_at_pos{this, "aa_at_pos"}; acmacs::settings::field_object<AntigenicMapsDrawSettings> antigenic_maps{this, "antigenic_maps"}; void upgrade(); // upgrade to the new version in case old version data provided }; // class Settings // ---------------------------------------------------------------------- void read_settings(Settings& aSettings, std::string aFilename); void write_settings(const Settings& aSettings, std::string aFilename); // ---------------------------------------------------------------------- /// Local Variables: /// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer)) /// End: <commit_msg>acmacs::settings::v1<commit_after>#pragma once #include "signature-page.hh" #include "tree-draw.hh" #include "time-series-draw.hh" #include "clades-draw.hh" #include "mapped-antigens-draw.hh" #include "aa-at-pos-draw.hh" #include "antigenic-maps-draw.hh" #include "title-draw.hh" // ---------------------------------------------------------------------- class SettingsMod : public acmacs::settings::object { public: using acmacs::settings::object::object; acmacs::settings::field<std::string> name{this, "N"}; acmacs::settings::field<std::string> name_commented{this, "?N"}; acmacs::settings::field<acmacs::Offset> offset{this, "offset"}; acmacs::settings::field<double> size{this, "size"}; acmacs::settings::field<Color> color{this, "color"}; acmacs::settings::field<acmacs::TextStyle> style{this, "style"}; acmacs::settings::field<std::string> text{this, "text"}; }; // ---------------------------------------------------------------------- constexpr const char* SETTINGS_VERSION_4 = "signature-page-settings-v4"; class Settings : public acmacs::settings::toplevel { public: Settings(); acmacs::settings::field<std::string> version{this, " version", SETTINGS_VERSION_4}; acmacs::settings::field_array_of<SettingsMod> mods{this, "mods"}; acmacs::settings::field_object<SignaturePageDrawSettings> signature_page{this, "signature_page"}; acmacs::settings::field_object<TitleDrawSettings> title{this, "title"}; acmacs::settings::field_object<TreeDrawSettings> tree_draw{this, "tree"}; acmacs::settings::field_object<TimeSeriesDrawSettings> time_series{this, "time_series"}; acmacs::settings::field_object<CladesDrawSettings> clades{this, "clades"}; acmacs::settings::field_object<HzSections> hz_sections{this, "hz_sections"}; acmacs::settings::field_object<MappedAntigensDrawSettings> mapped_antigens{this, "mapped_antigens"}; acmacs::settings::field_object<AAAtPosDrawSettings> aa_at_pos{this, "aa_at_pos"}; acmacs::settings::field_object<AntigenicMapsDrawSettings> antigenic_maps{this, "antigenic_maps"}; void upgrade(); // upgrade to the new version in case old version data provided }; // class Settings // ---------------------------------------------------------------------- void read_settings(Settings& aSettings, std::string aFilename); void write_settings(const Settings& aSettings, std::string aFilename); // ---------------------------------------------------------------------- /// Local Variables: /// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer)) /// End: <|endoftext|>
<commit_before>#include "stdlibs_for_debugging.h" #include "foobar.h" // TODO (unit test): // - reflection.h, REFLECTABLE(function), namespace::ClassTemplate, namespace::function(ClassTemplate), SmartRef // - also make sure that no invalid free functions are added (e.g. push_back on a vector) #include <smartref/smartref.h> #include <iostream> #include <vector> #include <typeinfo> using namespace std; using namespace foobar; using smartref::using_; template<typename T> class Property : public using_<T> { // TODO: Add proper reference-leaking control by allowing // the user-defined conversion functions to be private. public: operator T &() & { return data; } operator T &&() && { return move(data); } operator const T &() const & { return data; } operator const T &&() const && { return move(data); } private: T data; }; /* class JSONValue : public using_<JSONValue, double>, public using_<JSONValue, string>, public using_<JSONValue, vector<JSONValue>>, public using_<JSONValue, map<JSONValue, JSONValue>> { public: operator double &() { return get<double>(data); } operator double &() { return get<string>(data); } operator double &() { return get<vector<JSONValue>>(data); } operator double &() { return get<map<JSONValue, JSONValue>>(data); } private: variant< double, string, vector<JSONValue>, map<JSONValue, JSONValue> > data; }; */ namespace foobar { void asdf(Foo) { cout << "asdf(Foo)" << endl; } void asdf(Derived) { cout << "asdf(Derived)" << endl; } template<typename T> void asdf(ClassTemplate<T>) { cout << "asdf(ClassTemplate<T>)" << endl; } } // namespace foobar namespace foobar2 { struct A {}; struct B {}; template<typename> void qwerty(A) { cout << "foobar2::qwerty<T>(A)" << endl; } template<typename> void qwerty(foobar::ClassTemplate<A>) { cout << "foobar2::qwerty<T>(foobar::ClassTemplate<A>)" << endl; } template<typename, typename U> void qwerty(foobar::ClassTemplate<U>) { cout << "foobar2::qwerty<T>(foobar::ClassTemplate<U>)" << endl; } } // namespace foobar2 int main() { /* JSONValue json = {}; json["asdf"] = 1.0; json[123456] = nullptr; json.DOT(qwerty) = "the other (third) operator dot proposal"; json.qwerty = "__getattr__ for C++"; */ cout << "Hello, Wandbox!" << endl; Property<vector<int>> v; v.push_back(1); v.push_back(2); v.push_back(3); #if 0 //v.push_back(1, 2, 3); for (auto x : v) { cout << x << endl; } Property<int> x{}; Property<int> y{}; // TODO: Proper reference leaking control // i.e. {x + y} -> Property<decltype(delegate(x)+delegate(y))> auto z = x + y; cout << z << endl; cout << typeid(z).name() << endl; Property<Foo> foo; foo.foo(); Property<Bar> bar; bar.bar(); bar.bar2(); bar.bar3(); Property<Baz> baz; baz.baz(); baz.baz2(); Property<Bat> bat; bat.bat(); bat.bat2(); { Bar bar; bar.bar(); bar.bar2(); bar.bar3(); Baz baz; baz.baz(); baz.baz2(); Bat bat; bat.bat(); bat.bat2(); } { Property<Bla> bla; bla.foo(); bla.bar(); auto x = decltype(bla)::baz{1234}; cout << typeid(x).name() << " " << x << endl; auto y = decltype(bla)::bla{}; y.foo(); y.bar(); } { Property<Overloads> o; o.foo(); o.foo(0); o.bar<int>(); } { Property<GenericClassA> a; a.foobar(); a.foobar(1); a.foobar(1.0); static_assert(is_same<decltype(a)::some_type, GenericClassA::some_type>::value); Property<GenericClassB> b; b.foobar(); b.foobar(1); static_assert(is_same<decltype(b)::some_type, GenericClassB::some_type>::value); Property<ClassTemplate<int>> c; c.foobarbaz(); static_assert(is_same<decltype(c)::some_foo_type, ClassTemplate<int>::some_foo_type>::value); Property<ClassTemplate<float>> d; d.foobarbaz(); static_assert(is_same<decltype(d)::some_foo_type, ClassTemplate<float>::some_foo_type>::value); } { Property<ConstClass> non_const_obj; const Property<ConstClass> const_obj; non_const_obj.foo(); // Should compile non_const_obj.bar(); // Should compile const_obj.foo(); // Should compile // const_obj.bar(); // Should not compile } { Property<RefClass> obj; const Property<RefClass> cobj; obj.foo(); // "RefClass::foo() &" move(obj).foo(); // "RefClass::foo() &&" cobj.foo(); // "RefClass::foo() const &" move(cobj).foo(); // "RefClass::foo() const &&" } #endif { Property<Foo> foo; Property<Derived> derived; Property<MoreDerived> moreDerived; Property<ClassTemplate<int>> tmpl; asdf(foo); // "asdf(Foo)" asdf(derived); // "asdf(Derived)" asdf(moreDerived); // "asdf(Derived)" asdf(tmpl); // "asdf(ClassTemplate<T>)" } { foobar2::A tmpl1; ClassTemplate<foobar2::A > tmpl2; ClassTemplate<foobar2::B > tmpl3; Property< foobar2::A > tmpl4; Property<ClassTemplate<foobar2::A>> tmpl5; Property<ClassTemplate<foobar2::B>> tmpl6; using reflectable::qwerty; qwerty<int>(tmpl1); qwerty<int>(tmpl2); qwerty<int>(tmpl3); qwerty<int>(tmpl4); qwerty<int>(tmpl5); qwerty<int>(tmpl6); } } <commit_msg>Re-enabled some code.<commit_after>#include "stdlibs_for_debugging.h" #include "foobar.h" // TODO (unit test): // - reflection.h, REFLECTABLE(function), namespace::ClassTemplate, namespace::function(ClassTemplate), SmartRef // - also make sure that no invalid free functions are added (e.g. push_back on a vector) #include <smartref/smartref.h> #include <iostream> #include <vector> #include <typeinfo> using namespace std; using namespace foobar; using smartref::using_; template<typename T> class Property : public using_<T> { // TODO: Add proper reference-leaking control by allowing // the user-defined conversion functions to be private. public: operator T &() & { return data; } operator T &&() && { return move(data); } operator const T &() const & { return data; } operator const T &&() const && { return move(data); } private: T data; }; /* class JSONValue : public using_<JSONValue, double>, public using_<JSONValue, string>, public using_<JSONValue, vector<JSONValue>>, public using_<JSONValue, map<JSONValue, JSONValue>> { public: operator double &() { return get<double>(data); } operator double &() { return get<string>(data); } operator double &() { return get<vector<JSONValue>>(data); } operator double &() { return get<map<JSONValue, JSONValue>>(data); } private: variant< double, string, vector<JSONValue>, map<JSONValue, JSONValue> > data; }; */ namespace foobar { void asdf(Foo) { cout << "asdf(Foo)" << endl; } void asdf(Derived) { cout << "asdf(Derived)" << endl; } template<typename T> void asdf(ClassTemplate<T>) { cout << "asdf(ClassTemplate<T>)" << endl; } } // namespace foobar namespace foobar2 { struct A {}; struct B {}; template<typename> void qwerty(A) { cout << "foobar2::qwerty<T>(A)" << endl; } template<typename> void qwerty(foobar::ClassTemplate<A>) { cout << "foobar2::qwerty<T>(foobar::ClassTemplate<A>)" << endl; } template<typename, typename U> void qwerty(foobar::ClassTemplate<U>) { cout << "foobar2::qwerty<T>(foobar::ClassTemplate<U>)" << endl; } } // namespace foobar2 int main() { /* JSONValue json = {}; json["asdf"] = 1.0; json[123456] = nullptr; json.DOT(qwerty) = "the other (third) operator dot proposal"; json.qwerty = "__getattr__ for C++"; */ cout << "Hello, Wandbox!" << endl; Property<vector<int>> v; v.push_back(1); v.push_back(2); v.push_back(3); //v.push_back(1, 2, 3); for (auto x : v) { cout << x << endl; } Property<int> x{}; Property<int> y{}; // TODO: Proper reference leaking control // i.e. {x + y} -> Property<decltype(delegate(x)+delegate(y))> auto z = x + y; cout << z << endl; cout << typeid(z).name() << endl; Property<Foo> foo; foo.foo(); Property<Bar> bar; bar.bar(); bar.bar2(); bar.bar3(); Property<Baz> baz; baz.baz(); baz.baz2(); Property<Bat> bat; bat.bat(); bat.bat2(); { Bar bar; bar.bar(); bar.bar2(); bar.bar3(); Baz baz; baz.baz(); baz.baz2(); Bat bat; bat.bat(); bat.bat2(); } { Property<Bla> bla; bla.foo(); bla.bar(); auto x = decltype(bla)::baz{1234}; cout << typeid(x).name() << " " << x << endl; auto y = decltype(bla)::bla{}; y.foo(); y.bar(); } { Property<Overloads> o; o.foo(); o.foo(0); o.bar<int>(); } { Property<GenericClassA> a; a.foobar(); a.foobar(1); a.foobar(1.0); static_assert(is_same<decltype(a)::some_type, GenericClassA::some_type>::value); Property<GenericClassB> b; b.foobar(); b.foobar(1); static_assert(is_same<decltype(b)::some_type, GenericClassB::some_type>::value); Property<ClassTemplate<int>> c; c.foobarbaz(); static_assert(is_same<decltype(c)::some_foo_type, ClassTemplate<int>::some_foo_type>::value); Property<ClassTemplate<float>> d; d.foobarbaz(); static_assert(is_same<decltype(d)::some_foo_type, ClassTemplate<float>::some_foo_type>::value); } { Property<ConstClass> non_const_obj; const Property<ConstClass> const_obj; non_const_obj.foo(); // Should compile non_const_obj.bar(); // Should compile const_obj.foo(); // Should compile // const_obj.bar(); // Should not compile } { Property<RefClass> obj; const Property<RefClass> cobj; obj.foo(); // "RefClass::foo() &" move(obj).foo(); // "RefClass::foo() &&" cobj.foo(); // "RefClass::foo() const &" move(cobj).foo(); // "RefClass::foo() const &&" } { Property<Foo> foo; Property<Derived> derived; Property<MoreDerived> moreDerived; Property<ClassTemplate<int>> tmpl; asdf(foo); // "asdf(Foo)" asdf(derived); // "asdf(Derived)" asdf(moreDerived); // "asdf(Derived)" asdf(tmpl); // "asdf(ClassTemplate<T>)" } { foobar2::A tmpl1; ClassTemplate<foobar2::A > tmpl2; ClassTemplate<foobar2::B > tmpl3; Property< foobar2::A > tmpl4; Property<ClassTemplate<foobar2::A>> tmpl5; Property<ClassTemplate<foobar2::B>> tmpl6; using reflectable::qwerty; qwerty<int>(tmpl1); qwerty<int>(tmpl2); qwerty<int>(tmpl3); qwerty<int>(tmpl4); qwerty<int>(tmpl5); qwerty<int>(tmpl6); } } <|endoftext|>
<commit_before>/*******************************************************************************/ /* Bela Csound Rendering functions */ /* */ /*******************************************************************************/ #include <Bela.h> #include <csound/csound.hpp> #include <vector> #include <sstream> struct csChan { std::vector<MYFLT> data; std::stringstream name; }; struct csData{ Csound *csound; int blocksize; int res; int count; csChan channel[8]; }; csData* gCsData; bool setup(BelaContext *context, void *userData) { Csound *csound = new Csound(); const char *csdfile = "my.csd"; /* CSD name */ int numArgs = 6; char *args[] = { "csound", csdfile, "-iadc", "-odac","-+rtaudio=null", "--realtime", "--daemon"}; gCsData = new csData; csound->SetHostImplementedAudioIO(1,0); gCsData->res = csound->Compile(numArgs, args); gCsData->csound = csound; gCsData->blocksize = csound->GetKsmps()*userData->csound->GetNchnls(); gCsData->count = 0; /* set up the channels */ for(int i; i < context->analogInChannels; i++) { gCsData.channel[i].data.resize(csound->GetKsmps()); gCsData.channel[i].name << "analogue" << i+1; } if(gCsData->res != 0) return false; else return true; } void render(BelaContext *context, void *Data) { csData *userData = gCsData; if(gCsData->res == 0) { int n,i,k,count, frmcount,blocksize,res; MYFLT scal = userData->csound->Get0dBFS(); MYFLT* audioIn = userData->csound->GetSpin(); MYFLT* audioOut = userData->csound->GetSpout(); int nchnls = userData->csound->GetNchnls(); int chns = nchnls; int an_chns = context->analogInChannels; CsChan *channel = userData->channel; float frm = 0, incr = ((float) context->analogFrames)/context->audioFrames; int an_chans = context->analogInChannels; count = userData->count; blocksize = userData->blocksize; /* this is called when Csound is not running */ if(count < 0) { for(n = 0; n < context->audioFrames; n++){ for(i = 0; i < context->audioOutChannels; i++){ audioWrite(context,n,i,0); } } return; } if(chns > context->audioOutChannels) chns = context->audioOutChannels; /* this is where Csound is called */ for(n = 0; n < context->audioFrames; n++, frm+=incr, count+=nchnls){ if(count == blocksize) { /* set the channels */ for(i = 0; i < an_chns; i++) { csound->SetChannel(channel[i].name.str().c_str(), &(channel[i].data[0])); } if((res = userData->csound->PerformKsmps()) == 0) count = 0; else { count = -1; break; } } /* read/write audio data */ for(i = 0; i < chns; i++){ audioIn[count+i] = audioRead(context,n,i); audioWrite(context,n,i,audioOut[count+i]/scal); } /* read analogue data analogue frame pos gets incremented according to the ratio analogFrames/audioFrames. */ frmcount = count/nchnls; for(i = 0; i < an_chns; i++) { k = (int) frm; channel[i].data[frmcount] = analogRead(context,k,i); } } gCsData->res = res; userData->count = count; } } void cleanup(BelaContext *context, void *Data) { csData *userData = gCsData; delete userData->csound; delete userData; } <commit_msg>bela MIDI<commit_after>/*******************************************************************************/ /* Bela Csound Rendering functions */ /* */ /*******************************************************************************/ #include <Bela.h> #include <csound/csound.hpp> #include <vector> #include <sstream> static int OpenMidiInDevice(CSOUND *csound, void **userData, const char *dev); static int CloseMidiInDevice(CSOUND *csound, void *userData); static int ReadMidiData(CSOUND *csound, void *userData, unsigned char *mbuf, int nbytes); struct csChan { std::vector<MYFLT> data; std::stringstream name; }; struct csData{ Csound *csound; int blocksize; int res; int count; csChan channel[8]; }; csData* gCsData; bool setup(BelaContext *context, void *userData) { Csound *csound = new Csound(); const char *csdfile = "my.csd"; /* CSD name */ int numArgs = 8; char *args[] = { "csound", csdfile, "-iadc", "-odac", "-+rtaudio=null", "--realtime", "--daemon", "-Mhw:1,0,0"}; gCsData = new csData; csound->SetHostImplementedAudioIO(1,0); csound>SetHostImplementedMIDIIO(1); csound->SetExternalMidiInOpenCallback(OpenMidiInDevice); csound->SetExternalMidiReadCallback(ReadMidiData); csound->SetExternalMidiInCloseCallback(CloseMidiInDevice); gCsData->res = csound->Compile(numArgs, args); gCsData->csound = csound; gCsData->blocksize = csound->GetKsmps()*userData->csound->GetNchnls(); gCsData->count = 0; /* set up the channels */ for(int i; i < context->analogInChannels; i++) { gCsData.channel[i].data.resize(csound->GetKsmps()); gCsData.channel[i].name << "analogue" << i+1; } if(gCsData->res != 0) return false; else return true; } void render(BelaContext *context, void *Data) { csData *userData = gCsData; if(gCsData->res == 0) { int n,i,k,count, frmcount,blocksize,res; MYFLT scal = userData->csound->Get0dBFS(); MYFLT* audioIn = userData->csound->GetSpin(); MYFLT* audioOut = userData->csound->GetSpout(); int nchnls = userData->csound->GetNchnls(); int chns = nchnls; int an_chns = context->analogInChannels; CsChan *channel = userData->channel; float frm = 0, incr = ((float) context->analogFrames)/context->audioFrames; int an_chans = context->analogInChannels; count = userData->count; blocksize = userData->blocksize; /* this is called when Csound is not running */ if(count < 0) { for(n = 0; n < context->audioFrames; n++){ for(i = 0; i < context->audioOutChannels; i++){ audioWrite(context,n,i,0); } } return; } if(chns > context->audioOutChannels) chns = context->audioOutChannels; /* this is where Csound is called */ for(n = 0; n < context->audioFrames; n++, frm+=incr, count+=nchnls){ if(count == blocksize) { /* set the channels */ for(i = 0; i < an_chns; i++) { csound->SetChannel(channel[i].name.str().c_str(), &(channel[i].data[0])); } /* run csound */ if((res = userData->csound->PerformKsmps()) == 0) count = 0; else { count = -1; break; } } /* read/write audio data */ for(i = 0; i < chns; i++){ audioIn[count+i] = audioRead(context,n,i); audioWrite(context,n,i,audioOut[count+i]/scal); } /* read analogue data analogue frame pos gets incremented according to the ratio analogFrames/audioFrames. */ frmcount = count/nchnls; for(i = 0; i < an_chns; i++) { k = (int) frm; channel[i].data[frmcount] = analogRead(context,k,i); } } gCsData->res = res; userData->count = count; } } void cleanup(BelaContext *context, void *Data) { csData *userData = gCsData; delete userData->csound; delete userData; } /** MIDI Input functions */ int OpenMidiInDevice(CSOUND *csound, void **userData, const char *dev) { CsMIDI *midiData = new CsMIDI; Midi &midi = midiData->midi; midi.readFrom(dev); midi.enableParser(false); *userData = (void *) midiData; } int CloseMidiInDevice(CSOUND *csound, void *userData) { CsMIDI *midiData = (CsMIDI *) userData; delete midiData; } int ReadMidiData(CSOUND *csound, void *userData, unsigned char *mbuf, int nbytes) { int n = 0; CsMIDI *midiData = (CsMIDI *) userData; Midi &midi = midiData->midi; while((byte = midi.getInput()) > 0) { *mbuf++ = (unsigned char) byte; if(++n == nbytes) break; } return n; } <|endoftext|>
<commit_before>#include <vector> #include <string> #include "analysis/ReachingDefinitions/RDMap.h" #include "analysis/ReachingDefinitions/ReachingDefinitions.h" #include "../tools/TimeMeasure.h" // create two random rd maps of the // size 'size' and merge them void run(int size, int times = 100000) { using namespace dg::analysis::rd; std::vector<RDNode> rdnodes(size, RDNode()); while (--times > 0) { RDMap A, B; // fill in the maps randomly for (int i = 0; i < size; ++i) { const DefSite& ds = DefSite(&rdnodes[rand() % size], rand(), rand()); A.add(ds, &rdnodes[rand() % size]); for (int j = 0; j < size; ++j) { A.update(ds, &rdnodes[rand() % size]); } } for (int i = 0; i < size; ++i) { const DefSite& ds = DefSite(&rdnodes[rand() % size], rand(), rand()); B.add(ds, &rdnodes[rand() % size]); for (int j = 0; j < size; ++j) { B.update(ds, &rdnodes[rand() % size]); } } // merge them A.merge(&B); } } void test(int size) { dg::debug::TimeMeasure tm; std::string msg = "[200000 iter] Sets of size max "; msg += std::to_string(size); msg += " -- "; tm.start(); run(size, 200000); tm.stop(); tm.report(msg.c_str()); } int main() { test(1); test(3); test(5); test(10); test(15); test(20); test(30); test(50); test(100); test(200); test(500); } <commit_msg>fix rdmap-benchmark<commit_after>#include <vector> #include <string> #include "dg/analysis/ReachingDefinitions/RDMap.h" #include "dg/analysis/ReachingDefinitions/ReachingDefinitions.h" #include "../tools/TimeMeasure.h" // create two random rd maps of the // size 'size' and merge them void run(int size, int times = 100000) { using namespace dg::analysis::rd; std::vector<RDNode> rdnodes(size, RDNode()); while (--times > 0) { RDMap A, B; // fill in the maps randomly for (int i = 0; i < size; ++i) { const DefSite& ds = DefSite(&rdnodes[rand() % size], rand(), rand()); A.add(ds, &rdnodes[rand() % size]); for (int j = 0; j < size; ++j) { A.update(ds, &rdnodes[rand() % size]); } } for (int i = 0; i < size; ++i) { const DefSite& ds = DefSite(&rdnodes[rand() % size], rand(), rand()); B.add(ds, &rdnodes[rand() % size]); for (int j = 0; j < size; ++j) { B.update(ds, &rdnodes[rand() % size]); } } // merge them A.merge(&B); } } void test(int size) { dg::debug::TimeMeasure tm; std::string msg = "[200000 iter] Sets of size max "; msg += std::to_string(size); msg += " -- "; tm.start(); run(size, 200000); tm.stop(); tm.report(msg.c_str()); } int main() { test(1); test(3); test(5); test(10); test(15); test(20); test(30); test(50); test(100); test(200); test(500); } <|endoftext|>
<commit_before>/***************************************************************************************** * * * GHOUL * * General Helpful Open Utility Library * * * * Copyright (c) 2012-2014 * * * * 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 <ghoul/filesystem/file.h> #include <ghoul/filesystem/filesystem.h> #include <ghoul/logging/logmanager.h> using std::function; using std::string; namespace ghoul { namespace filesystem { namespace { const string _loggerCat = "File"; #ifdef WIN32 const char pathSeparator = '\\'; const unsigned int changeBufferSize = 16384u; #define _CRT_SECURE_NO_WARNINGS #elif __APPLE__ const char pathSeparator = '/'; // the maximum latency allowed before a changed is registered const CFAbsoluteTime latency = 3.0; #else const char pathSeparator = '/'; #endif } File::File(const char* filename, bool isRawPath, FileChangedCallback fileChangedCallback) : _fileChangedCallback(std::move(fileChangedCallback)) #ifdef WIN32 , _directoryHandle(nullptr) , _activeBuffer(0) #elif __APPLE__ , _eventStream(nullptr) , _lastModifiedTime(0) #endif { if (isRawPath) _filename = string(filename); else _filename = FileSys.absolutePath(string(filename)); if (_fileChangedCallback) installFileChangeListener(); } File::File(std::string filename, bool isRawPath, FileChangedCallback fileChangedCallback) : _fileChangedCallback(std::move(fileChangedCallback)) #ifdef WIN32 , _directoryHandle(nullptr) , _activeBuffer(0) #elif __APPLE__ , _eventStream(nullptr) , _lastModifiedTime(0) #endif { if (isRawPath) _filename = std::move(filename); else _filename = std::move(FileSys.absolutePath(std::move(filename))); if (_fileChangedCallback) installFileChangeListener(); } File::~File() { removeFileChangeListener(); } void File::setCallback(FileChangedCallback callback) { if (_fileChangedCallback) removeFileChangeListener(); _fileChangedCallback = std::move(callback); if (_fileChangedCallback) installFileChangeListener(); } const File::FileChangedCallback& File::callback() const { return _fileChangedCallback; } File::operator const std::string&() const { return _filename; } const std::string& File::path() const { return _filename; } std::string File::filename() const { string::size_type separator = _filename.rfind(pathSeparator); if (separator != string::npos) return _filename.substr(separator + 1); else return _filename; } string File::baseName() const { string&& fileName = filename(); string::size_type dot = fileName.rfind("."); if (dot != string::npos) return fileName.substr(0, dot); else return fileName; } string File::fullBaseName() const { string::size_type dot = _filename.rfind("."); if (dot != string::npos) return _filename.substr(0, dot); else return _filename; } string File::directoryName() const { string::size_type separator = _filename.rfind(pathSeparator); if (separator != string::npos) return _filename.substr(0, separator); else return _filename; } string File::fileExtension() const { string::size_type dot = _filename.rfind("."); if (dot != string::npos) return _filename.substr(dot + 1); else return _filename; } std::string File::lastModifiedDate() const { if (!FileSys.fileExists(_filename)) { LERROR("Error retrieving last-modified date for file '" << _filename << "'." << "File did not exist"); return ""; } #ifdef WIN32 HANDLE fileHandle = CreateFile( _filename.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, OPEN_EXISTING, NULL, NULL); if (fileHandle == INVALID_HANDLE_VALUE) { LERROR("File handle for '" << _filename << "' could not be obtained"); return ""; } LPFILETIME lastWriteTime = NULL; BOOL success = GetFileTime(fileHandle, NULL, NULL, lastWriteTime); if (success == 0) { const DWORD error = GetLastError(); LPTSTR errorBuffer = nullptr; FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, error, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&errorBuffer, 0, NULL); if (errorBuffer != nullptr) { std::string error(errorBuffer); LERROR("Could not retrieve last-modified date for file '" << _filename << "':" << error); LocalFree(errorBuffer); } return ""; } else { LPSYSTEMTIME time = NULL; FileTimeToSystemTime(lastWriteTime, time); return std::to_string(time->wYear) + "-" + std::to_string(time->wMonth) + "-" + std::to_string(time->wDay) + "T" + std::to_string(time->wHour) + ":" + std::to_string(time->wMinute) + ":" + std::to_string(time->wSecond) + "." + std::to_string(time->wMilliseconds); } #else struct stat attrib; stat(_filename.c_str(), &attrib); struct tm* time = gmtime(&(attrib.st_ctime)); char buffer[128]; strftime(buffer, 128, "%Y-%m-%dT%H:%M:%S"); return buffer; #endif } void File::installFileChangeListener() { removeFileChangeListener(); #ifdef WIN32 string&& directory = directoryName(); // Create a handle to the directory that is non-blocking _directoryHandle = CreateFile( directory.c_str(), FILE_LIST_DIRECTORY, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OVERLAPPED, NULL); if (_directoryHandle == INVALID_HANDLE_VALUE) { LERROR("Directory handle for '" << _filename << "' could not be obtained"); return; } beginRead(); #elif __APPLE__ string&& directory = directoryName(); // Get the current last-modified time struct stat fileinfo; stat(_filename.c_str(), &fileinfo); _lastModifiedTime = fileinfo.st_mtimespec.tv_sec; // Create the FSEventStream responsible for this directory (Apple's callback system // only works on the granularity of the directory) CFStringRef path = CFStringCreateWithCString(NULL, directory.c_str(), kCFStringEncodingASCII); CFArrayRef pathsToWatch = CFArrayCreate(NULL, (const void **)&path, 1, NULL); FSEventStreamContext callbackInfo; callbackInfo.version = 0; callbackInfo.info = this; callbackInfo.release = NULL; callbackInfo.retain = NULL; callbackInfo.copyDescription = NULL; _eventStream = FSEventStreamCreate( NULL, &completionHandler, &callbackInfo, pathsToWatch, kFSEventStreamEventIdSinceNow, latency, kFSEventStreamEventFlagItemModified); // Add checking the event stream to the current run loop // If there is a performance bottleneck, this could be done on a separate thread? FSEventStreamScheduleWithRunLoop(_eventStream, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode); // Start monitoring FSEventStreamStart(_eventStream); #else // Linux FileSys.inotifyAddListener(this); #endif } void File::removeFileChangeListener() { #ifdef WIN32 if (_directoryHandle != nullptr) { CancelIo(_directoryHandle); CloseHandle(_directoryHandle); _directoryHandle = nullptr; } #elif __APPLE__ if (_eventStream != nullptr) { FSEventStreamStop(_eventStream); FSEventStreamInvalidate(_eventStream); FSEventStreamRelease(_eventStream); _eventStream = nullptr; } #else FileSys.inotifyRemoveListener(this); #endif } #ifdef WIN32 void CALLBACK File::completionHandler(DWORD /*dwErrorCode*/, DWORD, LPOVERLAPPED lpOverlapped) { File* file = static_cast<File*>(lpOverlapped->hEvent); unsigned char currentBuffer = file->_activeBuffer; // Change active buffer (ping-pong buffering) file->_activeBuffer = (file->_activeBuffer + 1) % 2; // Restart change listener as soon as possible file->beginRead(); string&& thisFilename = file->filename(); char* buffer = reinterpret_cast<char*>(&(file->_changeBuffer[currentBuffer][0])); // data might have queued up, so we need to check all changes while (true) { // extract the information which file has changed FILE_NOTIFY_INFORMATION& information = (FILE_NOTIFY_INFORMATION&)*buffer; char* currentFilenameBuffer = new char[information.FileNameLength]; size_t i; wcstombs_s(&i, currentFilenameBuffer, information.FileNameLength, information.FileName, information.FileNameLength); //std::wcstombs(currentFilenameBuffer, //information.FileName, information.FileNameLength); const string& currentFilename(currentFilenameBuffer); delete[] currentFilenameBuffer; if (currentFilename == thisFilename) { // if it is the file we are interested in, call the callback file->_fileChangedCallback(*file); break; } else { if (!information.NextEntryOffset) // we are done with all entries and didn't find our file break; else //continue with the next entry buffer += information.NextEntryOffset; } } } void File::beginRead() { ZeroMemory(&_overlappedBuffer, sizeof(OVERLAPPED)); _overlappedBuffer.hEvent = this; _changeBuffer[_activeBuffer].resize(changeBufferSize); ZeroMemory(&(_changeBuffer[_activeBuffer][0]), changeBufferSize); DWORD returnedBytes; BOOL success = ReadDirectoryChangesW( _directoryHandle, &_changeBuffer[_activeBuffer][0], static_cast<DWORD>(_changeBuffer[_activeBuffer].size()), false, FILE_NOTIFY_CHANGE_LAST_WRITE | FILE_NOTIFY_CHANGE_SIZE, &returnedBytes, &_overlappedBuffer, &completionHandler); if (success == 0) { const DWORD error = GetLastError(); LPTSTR errorBuffer = nullptr; FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, error, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&errorBuffer, 0, NULL); if (errorBuffer != nullptr) { std::string error(errorBuffer); LERROR("Error reading directory changes: " << error); LocalFree(errorBuffer); } } } #elif __APPLE__ void File::completionHandler( ConstFSEventStreamRef, void *clientCallBackInfo, size_t numEvents, void *eventPaths, const FSEventStreamEventFlags[], const FSEventStreamEventId[]) { File* fileObj = reinterpret_cast<File*>(clientCallBackInfo); char** paths = reinterpret_cast<char**>(eventPaths); for (size_t i=0; i<numEvents; i++) { const string path = string(paths[i]); const string directory = fileObj->directoryName() + '/'; if (path == directory) { struct stat fileinfo; stat(fileObj->_filename.c_str(), &fileinfo); if (fileinfo.st_mtimespec.tv_sec != fileObj->_lastModifiedTime) { fileObj->_lastModifiedTime = fileinfo.st_atimespec.tv_sec; fileObj->_fileChangedCallback(*fileObj); } } } } #else // Linux #endif std::ostream& operator<<(std::ostream& os, const File& f) { return os << f.path(); } } // namespace filesystem } // namespace ghoul <commit_msg>Compile fix for Linux<commit_after>/***************************************************************************************** * * * GHOUL * * General Helpful Open Utility Library * * * * Copyright (c) 2012-2014 * * * * 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 <ghoul/filesystem/file.h> #include <ghoul/filesystem/filesystem.h> #include <ghoul/logging/logmanager.h> #include <ctime> using std::function; using std::string; namespace ghoul { namespace filesystem { namespace { const string _loggerCat = "File"; #ifdef WIN32 const char pathSeparator = '\\'; const unsigned int changeBufferSize = 16384u; #define _CRT_SECURE_NO_WARNINGS #elif __APPLE__ const char pathSeparator = '/'; // the maximum latency allowed before a changed is registered const CFAbsoluteTime latency = 3.0; #else const char pathSeparator = '/'; #endif } File::File(const char* filename, bool isRawPath, FileChangedCallback fileChangedCallback) : _fileChangedCallback(std::move(fileChangedCallback)) #ifdef WIN32 , _directoryHandle(nullptr) , _activeBuffer(0) #elif __APPLE__ , _eventStream(nullptr) , _lastModifiedTime(0) #endif { if (isRawPath) _filename = string(filename); else _filename = FileSys.absolutePath(string(filename)); if (_fileChangedCallback) installFileChangeListener(); } File::File(std::string filename, bool isRawPath, FileChangedCallback fileChangedCallback) : _fileChangedCallback(std::move(fileChangedCallback)) #ifdef WIN32 , _directoryHandle(nullptr) , _activeBuffer(0) #elif __APPLE__ , _eventStream(nullptr) , _lastModifiedTime(0) #endif { if (isRawPath) _filename = std::move(filename); else _filename = std::move(FileSys.absolutePath(std::move(filename))); if (_fileChangedCallback) installFileChangeListener(); } File::~File() { removeFileChangeListener(); } void File::setCallback(FileChangedCallback callback) { if (_fileChangedCallback) removeFileChangeListener(); _fileChangedCallback = std::move(callback); if (_fileChangedCallback) installFileChangeListener(); } const File::FileChangedCallback& File::callback() const { return _fileChangedCallback; } File::operator const std::string&() const { return _filename; } const std::string& File::path() const { return _filename; } std::string File::filename() const { string::size_type separator = _filename.rfind(pathSeparator); if (separator != string::npos) return _filename.substr(separator + 1); else return _filename; } string File::baseName() const { string&& fileName = filename(); string::size_type dot = fileName.rfind("."); if (dot != string::npos) return fileName.substr(0, dot); else return fileName; } string File::fullBaseName() const { string::size_type dot = _filename.rfind("."); if (dot != string::npos) return _filename.substr(0, dot); else return _filename; } string File::directoryName() const { string::size_type separator = _filename.rfind(pathSeparator); if (separator != string::npos) return _filename.substr(0, separator); else return _filename; } string File::fileExtension() const { string::size_type dot = _filename.rfind("."); if (dot != string::npos) return _filename.substr(dot + 1); else return _filename; } std::string File::lastModifiedDate() const { if (!FileSys.fileExists(_filename)) { LERROR("Error retrieving last-modified date for file '" << _filename << "'." << "File did not exist"); return ""; } #ifdef WIN32 HANDLE fileHandle = CreateFile( _filename.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, OPEN_EXISTING, NULL, NULL); if (fileHandle == INVALID_HANDLE_VALUE) { LERROR("File handle for '" << _filename << "' could not be obtained"); return ""; } LPFILETIME lastWriteTime = NULL; BOOL success = GetFileTime(fileHandle, NULL, NULL, lastWriteTime); if (success == 0) { const DWORD error = GetLastError(); LPTSTR errorBuffer = nullptr; FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, error, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&errorBuffer, 0, NULL); if (errorBuffer != nullptr) { std::string error(errorBuffer); LERROR("Could not retrieve last-modified date for file '" << _filename << "':" << error); LocalFree(errorBuffer); } return ""; } else { LPSYSTEMTIME time = NULL; FileTimeToSystemTime(lastWriteTime, time); return std::to_string(time->wYear) + "-" + std::to_string(time->wMonth) + "-" + std::to_string(time->wDay) + "T" + std::to_string(time->wHour) + ":" + std::to_string(time->wMinute) + ":" + std::to_string(time->wSecond) + "." + std::to_string(time->wMilliseconds); } #else struct stat attrib; stat(_filename.c_str(), &attrib); struct tm* time = gmtime(&(attrib.st_ctime)); char buffer[128]; strftime(buffer, 128, "%Y-%m-%dT%H:%M:%S"); return buffer; #endif } void File::installFileChangeListener() { removeFileChangeListener(); #ifdef WIN32 string&& directory = directoryName(); // Create a handle to the directory that is non-blocking _directoryHandle = CreateFile( directory.c_str(), FILE_LIST_DIRECTORY, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OVERLAPPED, NULL); if (_directoryHandle == INVALID_HANDLE_VALUE) { LERROR("Directory handle for '" << _filename << "' could not be obtained"); return; } beginRead(); #elif __APPLE__ string&& directory = directoryName(); // Get the current last-modified time struct stat fileinfo; stat(_filename.c_str(), &fileinfo); _lastModifiedTime = fileinfo.st_mtimespec.tv_sec; // Create the FSEventStream responsible for this directory (Apple's callback system // only works on the granularity of the directory) CFStringRef path = CFStringCreateWithCString(NULL, directory.c_str(), kCFStringEncodingASCII); CFArrayRef pathsToWatch = CFArrayCreate(NULL, (const void **)&path, 1, NULL); FSEventStreamContext callbackInfo; callbackInfo.version = 0; callbackInfo.info = this; callbackInfo.release = NULL; callbackInfo.retain = NULL; callbackInfo.copyDescription = NULL; _eventStream = FSEventStreamCreate( NULL, &completionHandler, &callbackInfo, pathsToWatch, kFSEventStreamEventIdSinceNow, latency, kFSEventStreamEventFlagItemModified); // Add checking the event stream to the current run loop // If there is a performance bottleneck, this could be done on a separate thread? FSEventStreamScheduleWithRunLoop(_eventStream, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode); // Start monitoring FSEventStreamStart(_eventStream); #else // Linux FileSys.inotifyAddListener(this); #endif } void File::removeFileChangeListener() { #ifdef WIN32 if (_directoryHandle != nullptr) { CancelIo(_directoryHandle); CloseHandle(_directoryHandle); _directoryHandle = nullptr; } #elif __APPLE__ if (_eventStream != nullptr) { FSEventStreamStop(_eventStream); FSEventStreamInvalidate(_eventStream); FSEventStreamRelease(_eventStream); _eventStream = nullptr; } #else FileSys.inotifyRemoveListener(this); #endif } #ifdef WIN32 void CALLBACK File::completionHandler(DWORD /*dwErrorCode*/, DWORD, LPOVERLAPPED lpOverlapped) { File* file = static_cast<File*>(lpOverlapped->hEvent); unsigned char currentBuffer = file->_activeBuffer; // Change active buffer (ping-pong buffering) file->_activeBuffer = (file->_activeBuffer + 1) % 2; // Restart change listener as soon as possible file->beginRead(); string&& thisFilename = file->filename(); char* buffer = reinterpret_cast<char*>(&(file->_changeBuffer[currentBuffer][0])); // data might have queued up, so we need to check all changes while (true) { // extract the information which file has changed FILE_NOTIFY_INFORMATION& information = (FILE_NOTIFY_INFORMATION&)*buffer; char* currentFilenameBuffer = new char[information.FileNameLength]; size_t i; wcstombs_s(&i, currentFilenameBuffer, information.FileNameLength, information.FileName, information.FileNameLength); //std::wcstombs(currentFilenameBuffer, //information.FileName, information.FileNameLength); const string& currentFilename(currentFilenameBuffer); delete[] currentFilenameBuffer; if (currentFilename == thisFilename) { // if it is the file we are interested in, call the callback file->_fileChangedCallback(*file); break; } else { if (!information.NextEntryOffset) // we are done with all entries and didn't find our file break; else //continue with the next entry buffer += information.NextEntryOffset; } } } void File::beginRead() { ZeroMemory(&_overlappedBuffer, sizeof(OVERLAPPED)); _overlappedBuffer.hEvent = this; _changeBuffer[_activeBuffer].resize(changeBufferSize); ZeroMemory(&(_changeBuffer[_activeBuffer][0]), changeBufferSize); DWORD returnedBytes; BOOL success = ReadDirectoryChangesW( _directoryHandle, &_changeBuffer[_activeBuffer][0], static_cast<DWORD>(_changeBuffer[_activeBuffer].size()), false, FILE_NOTIFY_CHANGE_LAST_WRITE | FILE_NOTIFY_CHANGE_SIZE, &returnedBytes, &_overlappedBuffer, &completionHandler); if (success == 0) { const DWORD error = GetLastError(); LPTSTR errorBuffer = nullptr; FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, error, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&errorBuffer, 0, NULL); if (errorBuffer != nullptr) { std::string error(errorBuffer); LERROR("Error reading directory changes: " << error); LocalFree(errorBuffer); } } } #elif __APPLE__ void File::completionHandler( ConstFSEventStreamRef, void *clientCallBackInfo, size_t numEvents, void *eventPaths, const FSEventStreamEventFlags[], const FSEventStreamEventId[]) { File* fileObj = reinterpret_cast<File*>(clientCallBackInfo); char** paths = reinterpret_cast<char**>(eventPaths); for (size_t i=0; i<numEvents; i++) { const string path = string(paths[i]); const string directory = fileObj->directoryName() + '/'; if (path == directory) { struct stat fileinfo; stat(fileObj->_filename.c_str(), &fileinfo); if (fileinfo.st_mtimespec.tv_sec != fileObj->_lastModifiedTime) { fileObj->_lastModifiedTime = fileinfo.st_atimespec.tv_sec; fileObj->_fileChangedCallback(*fileObj); } } } } #else // Linux #endif std::ostream& operator<<(std::ostream& os, const File& f) { return os << f.path(); } } // namespace filesystem } // namespace ghoul <|endoftext|>
<commit_before>#ifndef _SDD_ORDER_ORDER_HH_ #define _SDD_ORDER_ORDER_HH_ #include <algorithm> // find #include <initializer_list> #include <iostream> #include <memory> // shared_ptr, unique_ptr #include <sstream> #include <utility> // pair #include <vector> #include "sdd/order/order_builder.hh" #include "sdd/util/boost_multiindex_no_warnings.hh" #include "sdd/util/hash.hh" namespace sdd { namespace bmi = boost::multi_index; /*------------------------------------------------------------------------------------------------*/ /// @brief Represent an order of identifiers, possibly with some hierarchy. /// /// It helps associate a variable (generated by the library) in an SDD to an identifiers /// (provided to the user). An identifier should appear only once by order. template <typename C> class order final { public: /// @brief A user's identifier type. typedef typename C::Identifier identifier_type; /// @brief A library's variable type. typedef typename C::Variable variable_type; private: /// @brief A node in an order. /// /// An order is actually represented as a linked list of node. struct node { /// @brief The (user's) identifier of this node. const identifier_type identifier; /// @brief The (library's) variable of this node. const variable_type variable; /// @brief Absolute position, when seeing the order as flatten. /// /// Used to establish a total order on identifiers. const unsigned int position; /// @brief A pointer to following order's head. const node* next; /// @brief A pointer to the nested order's head. const node* nested; /// @brief The path to this node. const std::shared_ptr<std::vector<identifier_type>> path_ptr; /// @brief Constructor. node( const identifier_type& id, const variable_type& var, unsigned int pos , const node* nxt, const node* nst , const std::shared_ptr<std::vector<identifier_type>>& path) : identifier(id) , variable(var) , position(pos) , next(nxt) , nested(nst) , path_ptr(path) {} /// @brief Compare two node using their abolute position. bool operator<(const node& other) const noexcept { return position < other.position; } }; /// @brief Tag to access nodes using their absolute positions. struct by_position {}; /// @brief Tag to access nodes using their identifiers. struct by_identifier {}; /// @brief The type of the container of nodes. /// /// A boost::multi_index::multi_index_container is used in order to be able to access nodes /// using different criterions. typedef bmi::multi_index_container < node , bmi::indexed_by < // sort by node::operator< bmi::ordered_unique< bmi::tag<by_position> , bmi::identity<node> > // retrieve using identifier's hash , bmi::hashed_unique< bmi::tag<by_identifier> , bmi::member<node, const identifier_type, &node::identifier> , std::hash<identifier_type> > > > nodes_type; /// @brief The concrete order. const std::shared_ptr<nodes_type> nodes_ptr_; /// @brief The first node in the order. const node* head_; /// @brief Extract the identifier of a node. struct extract_identifier { typedef const identifier_type& result_type; const identifier_type& operator()(const node& n) const noexcept { return n.identifier; } }; public: /// @brief Constructor. order(const order_builder<C>& builder) : nodes_ptr_(mk_nodes_ptr(builder)) , head_(mk_head()) {} /// @brief Tell if lhs is before rhs in this order. /// @param lhs Must belong to the order on which this method is called. /// @param rhs Must belong to the order on which this method is called. /// Here, 'before' mean that the order is seen as flatten and thus that an hierarchical /// identifier is located before its nested identifiers. bool compare(const identifier_type& lhs, const identifier_type& rhs) const noexcept { const auto& identifiers = nodes_ptr_->template get<by_identifier>(); const auto lhs_search = identifiers.find(lhs); const auto rhs_search = identifiers.find(rhs); return lhs_search->position < rhs_search->position; } /// @brief Tell if upper contains nested in its possibly contained hierarchy. bool contains(const identifier_type& upper, const identifier_type& nested) const noexcept { const auto& identifiers = nodes_ptr_->template get<by_identifier>(); const auto search = identifiers.find(nested); if (search == identifiers.end()) { return false; } else { const auto& path = *search->path_ptr; return std::find(path.begin(), path.end(), upper) != path.end(); } } /// @brief const typename nodes_type::template index<by_identifier>::type& identifiers() const noexcept { return nodes_ptr_->template get<by_identifier>(); } /// @brief Get the variable of this order's head. const variable_type& variable() const noexcept { return head_->variable; } /// @brief Get the identifier of this order's head. const identifier_type& identifier() const noexcept { return head_->identifier; } /// @brief Get the next order of this order's head. order next() const noexcept { return order(nodes_ptr_, head_->next); } /// @brief Get the nested order of this order's head. order nested() const noexcept { return order(nodes_ptr_, head_->nested); } /// @brief Tell if this order is empty. bool empty() const noexcept { return head_ == nullptr; } /// @internal std::size_t hash() const noexcept { std::size_t seed = 0; util::hash_combine(seed, nodes_ptr_.get()); util::hash_combine(seed, head_); return seed; } /// @internal bool operator==(const order& other) const noexcept { return nodes_ptr_ == other.nodes_ptr_ and head_ == other.head_; } private: /// @brief Construct whith a shallow copy an already existing order. order(const std::shared_ptr<nodes_type>& ptr, const node* head) : nodes_ptr_(ptr) , head_(head) {} /// @brief Create the concrete order using an order_builder. static std::shared_ptr<nodes_type> mk_nodes_ptr(const order_builder<C>& builder) { std::shared_ptr<nodes_type> nodes_ptr = std::make_shared<nodes_type>(); if (builder.empty()) { return nodes_ptr; } unsigned int pos = 0; // To enable recursion in the lambda. std::function< std::pair<const node*, variable_type> (const order_builder<C>&, const std::shared_ptr<std::vector<identifier_type>>&) > helper; helper = [&helper, &nodes_ptr, &pos] (const order_builder<C>& ob, const std::shared_ptr<std::vector<identifier_type>>& path) -> std::pair<const node*, unsigned int> { constexpr variable_type first_variable = 0; const unsigned int old_pos = pos++; std::pair<const node*, variable_type> nested(nullptr, first_variable); std::pair<const node*, variable_type> next(nullptr, first_variable); if (not ob.nested().empty()) { const auto new_path = std::make_shared<std::vector<identifier_type>>(*path); new_path->push_back(ob.identifier()); new_path->shrink_to_fit(); nested = helper(ob.nested(), new_path); } if (not ob.next().empty()) { next = helper(ob.next(), path); } const auto& variable = next.second; /// TODO Manage artificial identifiers. const node n(ob.identifier(), variable, old_pos, next.first, nested.first, path); const auto insertion = nodes_ptr->insert(n); if (not insertion.second) { std::stringstream ss; ss << "Duplicate identifier " << ob.identifier(); throw std::runtime_error(ss.str()); } return std::make_pair( &*(insertion.first), variable + 1); }; helper(builder, std::make_shared<std::vector<identifier_type>>()); return nodes_ptr; } /// @brief Get the first node in the order. const node* mk_head() const noexcept { const auto& positions = nodes_ptr_->template get<by_position>(); const auto begin = positions.begin(); return begin == positions.end() ? nullptr : &*begin; } }; /*------------------------------------------------------------------------------------------------*/ /// @brief Textual representation of an order. /// @related order template <typename C> std::ostream& operator<<(std::ostream& os, const order<C>& ord) { const std::function<std::ostream&(const order<C>&, unsigned int)> helper = [&helper, &os](const order<C>& o, unsigned int indent) -> std::ostream& { if (not o.empty()) { const std::string spaces(indent, ' '); os << spaces << o.identifier() << std::endl; if (not o.nested().empty()) { helper(o.nested(), indent + 2); } if (not o.next().empty()) { helper(o.next(), indent); } } return os; }; return helper(ord, 0); } /*------------------------------------------------------------------------------------------------*/ } // namespace sdd namespace std { /*------------------------------------------------------------------------------------------------*/ /// @internal /// @brief Hash specialization for sdd::order. template <typename C> struct hash<sdd::order<C>> { std::size_t operator()(const sdd::order<C>& o) const noexcept { return o.hash(); } }; /*------------------------------------------------------------------------------------------------*/ } // namespace std #endif // _SDD_ORDER_ORDER_HH_ <commit_msg>Remove useless functor.<commit_after>#ifndef _SDD_ORDER_ORDER_HH_ #define _SDD_ORDER_ORDER_HH_ #include <algorithm> // find #include <initializer_list> #include <iostream> #include <memory> // shared_ptr, unique_ptr #include <sstream> #include <utility> // pair #include <vector> #include "sdd/order/order_builder.hh" #include "sdd/util/boost_multiindex_no_warnings.hh" #include "sdd/util/hash.hh" namespace sdd { namespace bmi = boost::multi_index; /*------------------------------------------------------------------------------------------------*/ /// @brief Represent an order of identifiers, possibly with some hierarchy. /// /// It helps associate a variable (generated by the library) in an SDD to an identifiers /// (provided to the user). An identifier should appear only once by order. template <typename C> class order final { public: /// @brief A user's identifier type. typedef typename C::Identifier identifier_type; /// @brief A library's variable type. typedef typename C::Variable variable_type; private: /// @brief A node in an order. /// /// An order is actually represented as a linked list of node. struct node { /// @brief The (user's) identifier of this node. const identifier_type identifier; /// @brief The (library's) variable of this node. const variable_type variable; /// @brief Absolute position, when seeing the order as flatten. /// /// Used to establish a total order on identifiers. const unsigned int position; /// @brief A pointer to following order's head. const node* next; /// @brief A pointer to the nested order's head. const node* nested; /// @brief The path to this node. const std::shared_ptr<std::vector<identifier_type>> path_ptr; /// @brief Constructor. node( const identifier_type& id, const variable_type& var, unsigned int pos , const node* nxt, const node* nst , const std::shared_ptr<std::vector<identifier_type>>& path) : identifier(id) , variable(var) , position(pos) , next(nxt) , nested(nst) , path_ptr(path) {} /// @brief Compare two node using their abolute position. bool operator<(const node& other) const noexcept { return position < other.position; } }; /// @brief Tag to access nodes using their absolute positions. struct by_position {}; /// @brief Tag to access nodes using their identifiers. struct by_identifier {}; /// @brief The type of the container of nodes. /// /// A boost::multi_index::multi_index_container is used in order to be able to access nodes /// using different criterions. typedef bmi::multi_index_container < node , bmi::indexed_by < // sort by node::operator< bmi::ordered_unique< bmi::tag<by_position> , bmi::identity<node> > // retrieve using identifier's hash , bmi::hashed_unique< bmi::tag<by_identifier> , bmi::member<node, const identifier_type, &node::identifier> , std::hash<identifier_type> > > > nodes_type; /// @brief The concrete order. const std::shared_ptr<nodes_type> nodes_ptr_; /// @brief The first node in the order. const node* head_; public: /// @brief Constructor. order(const order_builder<C>& builder) : nodes_ptr_(mk_nodes_ptr(builder)) , head_(mk_head()) {} /// @brief Tell if lhs is before rhs in this order. /// @param lhs Must belong to the order on which this method is called. /// @param rhs Must belong to the order on which this method is called. /// Here, 'before' mean that the order is seen as flatten and thus that an hierarchical /// identifier is located before its nested identifiers. bool compare(const identifier_type& lhs, const identifier_type& rhs) const noexcept { const auto& identifiers = nodes_ptr_->template get<by_identifier>(); const auto lhs_search = identifiers.find(lhs); const auto rhs_search = identifiers.find(rhs); return lhs_search->position < rhs_search->position; } /// @brief Tell if upper contains nested in its possibly contained hierarchy. bool contains(const identifier_type& upper, const identifier_type& nested) const noexcept { const auto& identifiers = nodes_ptr_->template get<by_identifier>(); const auto search = identifiers.find(nested); if (search == identifiers.end()) { return false; } else { const auto& path = *search->path_ptr; return std::find(path.begin(), path.end(), upper) != path.end(); } } /// @brief const typename nodes_type::template index<by_identifier>::type& identifiers() const noexcept { return nodes_ptr_->template get<by_identifier>(); } /// @brief Get the variable of this order's head. const variable_type& variable() const noexcept { return head_->variable; } /// @brief Get the identifier of this order's head. const identifier_type& identifier() const noexcept { return head_->identifier; } /// @brief Get the next order of this order's head. order next() const noexcept { return order(nodes_ptr_, head_->next); } /// @brief Get the nested order of this order's head. order nested() const noexcept { return order(nodes_ptr_, head_->nested); } /// @brief Tell if this order is empty. bool empty() const noexcept { return head_ == nullptr; } /// @internal std::size_t hash() const noexcept { std::size_t seed = 0; util::hash_combine(seed, nodes_ptr_.get()); util::hash_combine(seed, head_); return seed; } /// @internal bool operator==(const order& other) const noexcept { return nodes_ptr_ == other.nodes_ptr_ and head_ == other.head_; } private: /// @brief Construct whith a shallow copy an already existing order. order(const std::shared_ptr<nodes_type>& ptr, const node* head) : nodes_ptr_(ptr) , head_(head) {} /// @brief Create the concrete order using an order_builder. static std::shared_ptr<nodes_type> mk_nodes_ptr(const order_builder<C>& builder) { std::shared_ptr<nodes_type> nodes_ptr = std::make_shared<nodes_type>(); if (builder.empty()) { return nodes_ptr; } unsigned int pos = 0; // To enable recursion in the lambda. std::function< std::pair<const node*, variable_type> (const order_builder<C>&, const std::shared_ptr<std::vector<identifier_type>>&) > helper; helper = [&helper, &nodes_ptr, &pos] (const order_builder<C>& ob, const std::shared_ptr<std::vector<identifier_type>>& path) -> std::pair<const node*, unsigned int> { constexpr variable_type first_variable = 0; const unsigned int old_pos = pos++; std::pair<const node*, variable_type> nested(nullptr, first_variable); std::pair<const node*, variable_type> next(nullptr, first_variable); if (not ob.nested().empty()) { const auto new_path = std::make_shared<std::vector<identifier_type>>(*path); new_path->push_back(ob.identifier()); new_path->shrink_to_fit(); nested = helper(ob.nested(), new_path); } if (not ob.next().empty()) { next = helper(ob.next(), path); } const auto& variable = next.second; /// TODO Manage artificial identifiers. const node n(ob.identifier(), variable, old_pos, next.first, nested.first, path); const auto insertion = nodes_ptr->insert(n); if (not insertion.second) { std::stringstream ss; ss << "Duplicate identifier " << ob.identifier(); throw std::runtime_error(ss.str()); } return std::make_pair( &*(insertion.first), variable + 1); }; helper(builder, std::make_shared<std::vector<identifier_type>>()); return nodes_ptr; } /// @brief Get the first node in the order. const node* mk_head() const noexcept { const auto& positions = nodes_ptr_->template get<by_position>(); const auto begin = positions.begin(); return begin == positions.end() ? nullptr : &*begin; } }; /*------------------------------------------------------------------------------------------------*/ /// @brief Textual representation of an order. /// @related order template <typename C> std::ostream& operator<<(std::ostream& os, const order<C>& ord) { const std::function<std::ostream&(const order<C>&, unsigned int)> helper = [&helper, &os](const order<C>& o, unsigned int indent) -> std::ostream& { if (not o.empty()) { const std::string spaces(indent, ' '); os << spaces << o.identifier() << std::endl; if (not o.nested().empty()) { helper(o.nested(), indent + 2); } if (not o.next().empty()) { helper(o.next(), indent); } } return os; }; return helper(ord, 0); } /*------------------------------------------------------------------------------------------------*/ } // namespace sdd namespace std { /*------------------------------------------------------------------------------------------------*/ /// @internal /// @brief Hash specialization for sdd::order. template <typename C> struct hash<sdd::order<C>> { std::size_t operator()(const sdd::order<C>& o) const noexcept { return o.hash(); } }; /*------------------------------------------------------------------------------------------------*/ } // namespace std #endif // _SDD_ORDER_ORDER_HH_ <|endoftext|>
<commit_before>#include "agenda.h" #include "errors.h" #include <unistd.h> #include <thread> #include <sstream> #include <unistd.h> #include <boost/bind.hpp> #include <time.h> #include <iostream> using namespace es3; agenda::agenda(size_t num_unbound, size_t num_cpu_bound, size_t num_io_bound, bool quiet, bool final_quiet, size_t segment_size, size_t max_segments_in_flight) : class_limits_ {{taskUnbound, num_unbound}, {taskCPUBound, num_cpu_bound}, {taskIOBound, num_io_bound}}, quiet_(quiet), final_quiet_(final_quiet), segment_size_(segment_size), max_segments_in_flight_(max_segments_in_flight), num_working_(), num_submitted_(), num_done_(), num_failed_(), segments_in_flight_() { clock_gettime(CLOCK_MONOTONIC, &start_time_) | libc_die2("Can't get time"); } namespace es3 { struct segment_deleter { agenda_ptr parent_; void operator()(segment *seg) { delete seg; u_guard_t guard(parent_->m_); assert(parent_->segments_in_flight_>0); parent_->segments_in_flight_--; parent_->condition_.notify_one(); } }; class task_executor { agenda_ptr agenda_; public: task_executor(agenda_ptr agenda) : agenda_(agenda) {} std::pair<sync_task_ptr, std::vector<segment_ptr> > claim_task() { std::pair<sync_task_ptr, std::vector<segment_ptr> > res_pair; while(true) { u_guard_t lock(agenda_->m_); if (agenda_->tasks_.empty()) { if (agenda_->num_working_==0) return res_pair; agenda_->condition_.wait(lock); continue; } //Iterate over classes to find one that is not yet full for(auto iter=agenda_->classes_.begin(); iter!=agenda_->classes_.end();++iter) { //Check if there are too many tasks of this type running task_type_e cur_class=iter->first; size_t cur_num=iter->second; size_t limit=agenda_->get_capability(cur_class); //Unbound tasks are allowed to exceed their limits and //borrow threads from other classes // if (cur_class!=taskUnbound && limit<=cur_num) // continue; //Too busy if (limit<=cur_num) continue; size_t segments_avail=agenda_->max_segments_in_flight_- agenda_->segments_in_flight_; //Good! We can work on this class. //Find the task with the greatest segment requirements agenda::size_map_t::iterator pair= --agenda_->tasks_.end(); size_t segments_needed=pair->first; if (segments_needed>segments_avail) { //Try the task with the least number of required segs printf("\nSegs bad %d\n\n", segments_needed); pair=agenda_->tasks_.begin(); segments_needed=pair->first; printf("Segs good %d\n", segments_needed); if (segments_needed>segments_avail) continue; //No such luck :( } if (!pair->second.count(cur_class)) continue; //No tasks for this class agenda::task_map_t &task_map=pair->second.at(cur_class); assert(!task_map.empty()); sync_task_ptr res=task_map.begin()->second; task_map.erase(task_map.begin()); if (task_map.empty()) { pair->second.erase(cur_class); if (pair->second.empty()) agenda_->tasks_.erase(pair->first); } agenda_->num_working_++; agenda_->classes_[cur_class]++; res_pair.first=res; if (segments_needed) res_pair.second=agenda_->get_segments(segments_needed); return res_pair; } agenda_->condition_.wait(lock); } } void cleanup(sync_task_ptr cur_task, bool fail) { u_guard_t lock(agenda_->m_); agenda_->num_working_--; assert(agenda_->classes_[cur_task->get_class()]>0); agenda_->classes_[cur_task->get_class()]--; if (agenda_->tasks_.empty() && agenda_->num_working_==0) agenda_->condition_.notify_all(); //We've finished our tasks! else agenda_->condition_.notify_one(); //Update stats guard_t lockst(agenda_->stats_m_); agenda_->num_done_++; if (fail) agenda_->num_failed_++; } void operator ()() { while(true) { std::pair<sync_task_ptr, std::vector<segment_ptr> > cur_task; cur_task=claim_task(); if (!cur_task.first) break; bool fail=true; for(int f=0; f<10; ++f) { try { (*cur_task.first)(agenda_, cur_task.second); fail=false; break; } catch (const es3_exception &ex) { const result_code_t &code = ex.err(); if (code.code()==errNone) { VLOG(2) << "INFO: " << ex.what(); sleep(5); continue; } else if (code.code()==errWarn) { VLOG(1) << "WARN: " << ex.what(); sleep(5); continue; } else { VLOG(0) << ex.what(); break; } } catch(const std::exception &ex) { VLOG(0) << "ERR: " << ex.what(); break; } catch(...) { VLOG(0) << "Unknown exception. Skipping"; break; } } cleanup(cur_task.first, fail); } } }; } std::vector<segment_ptr> agenda::get_segments(size_t num) { assert(segments_in_flight_+num<=max_segments_in_flight_); std::vector<segment_ptr> res; res.reserve(num); for(size_t f=0;f<num;++f) { segment_deleter del {shared_from_this()}; segment_ptr seg=segment_ptr(new segment(), del); res.push_back(seg); } segments_in_flight_+=num; return res; } void agenda::schedule(sync_task_ptr task) { u_guard_t lock(m_); // agenda_ptr ptr = shared_from_this(); // auto iter=std::lower_bound(tasks_.begin(), tasks_.end(), task); // if (iter!=tasks_.end()) // tasks_.insert(iter, task); // else // tasks_.push_back(task); classes_[task->get_class()]; //Force insertion of class entry task_map_t &task_map=tasks_[task->needs_segments()][task->get_class()]; task_map.insert(std::make_pair(task->ordinal(), task)); condition_.notify_one(); guard_t lockst(stats_m_); num_submitted_++; } size_t agenda::run() { std::vector<std::thread> threads; size_t thread_num=0; for(auto iter=class_limits_.begin();iter!=class_limits_.end();++iter) thread_num+=iter->second; for(int f=0;f<thread_num;++f) threads.push_back(std::thread(task_executor(shared_from_this()))); if (!quiet_) { threads.push_back(std::thread(boost::bind(&agenda::draw_progress, this))); for(int f=0;f<threads.size();++f) threads.at(f).join(); //Draw progress the last time draw_progress_widget(); std::cerr<<std::endl; } else { for(int f=0;f<threads.size();++f) threads.at(f).join(); } return num_failed_; } void agenda::print_epilog() { if (!final_quiet_) draw_stats(); } void agenda::draw_progress() { while(true) { { guard_t g(m_); if (num_working_==0 && tasks_.empty()) return; } draw_progress_widget(); usleep(500000); } } void agenda::add_stat_counter(const std::string &stat, uint64_t val) { guard_t lockst(stats_m_); cur_stats_[stat]+=val; } std::pair<std::string, std::string> agenda::format_si(uint64_t val, bool per_sec) { std::pair<std::string, std::string> res; uint64_t denom = 1; if (val<10000) { denom = 1; res.second = "B"; } else if (val<2000000) { denom = 1024; res.second = "K"; } else { denom = 1024*1024; res.second = "M"; } res.first = int_to_string(val/denom); if (val%denom) res.first+="."+int_to_string((val%denom)*100/denom); return res; } void agenda::draw_progress_widget() { uint64_t el = get_elapsed_millis(); std::stringstream str; { guard_t lockst(stats_m_); str << "Tasks: [" << num_done_ << "/" << num_submitted_ << "]"; if (num_failed_) str << " Failed tasks: " << num_failed_; uint64_t uploaded = cur_stats_["uploaded"]; uint64_t downloaded = cur_stats_["downloaded"]; if (downloaded) { auto dl=format_si(downloaded, false); auto ds=format_si(el==0? 0 : (downloaded*1000/el), true); str << " Downloaded: " << dl.first << " " << dl.second << ", speed: " << ds.first << " " << ds.second << "/sec"; } if (uploaded) { auto ul=format_si(uploaded, false); auto us=format_si(el==0? 0 : (uploaded*1000/el), true); str << " Uploaded: " << ul.first << " " << ul.second << ", speed: " << us.first << " " << us.second << "/sec"; } str << "\r"; } std::cerr << str.str(); //No std::endl std::cerr.flush(); } uint64_t agenda::get_elapsed_millis() const { struct timespec cur; clock_gettime(CLOCK_MONOTONIC, &cur) | libc_die2("Can't get time"); uint64_t start_tm = uint64_t(start_time_.tv_sec)*1000 + start_time_.tv_nsec/1000000; uint64_t cur_tm = uint64_t(cur.tv_sec)*1000+cur.tv_nsec/1000000; return cur_tm-start_tm; } void agenda::draw_stats() { uint64_t el = get_elapsed_millis(); std::cerr << "time taken [sec]: " << el/1000 << "." << el%1000 << std::endl; for(auto f=cur_stats_.begin();f!=cur_stats_.end();++f) { std::string name=f->first; uint64_t val=f->second; if (!val) continue; uint64_t avg = val*1000/el; std::cerr << name << " [B]: " << val << ", average [B/sec]: " << avg << std::endl; } } void agenda::print_queue() { std::cerr << "There are " << tasks_.size() << " task[s] present.\n"; for(auto by_segs=tasks_.begin();by_segs!=tasks_.end();++by_segs) { for(auto iter=by_segs->second.begin(); iter!=by_segs->second.end(); ++iter) { for(auto iter2=iter->second.begin(); iter2!=iter->second.end();++iter2) { sync_task_ptr task=iter2->second; task->print_to(std::cerr); std::cerr<<std::endl; } } } } <commit_msg>Remove tracing<commit_after>#include "agenda.h" #include "errors.h" #include <unistd.h> #include <thread> #include <sstream> #include <unistd.h> #include <boost/bind.hpp> #include <time.h> #include <iostream> using namespace es3; agenda::agenda(size_t num_unbound, size_t num_cpu_bound, size_t num_io_bound, bool quiet, bool final_quiet, size_t segment_size, size_t max_segments_in_flight) : class_limits_ {{taskUnbound, num_unbound}, {taskCPUBound, num_cpu_bound}, {taskIOBound, num_io_bound}}, quiet_(quiet), final_quiet_(final_quiet), segment_size_(segment_size), max_segments_in_flight_(max_segments_in_flight), num_working_(), num_submitted_(), num_done_(), num_failed_(), segments_in_flight_() { clock_gettime(CLOCK_MONOTONIC, &start_time_) | libc_die2("Can't get time"); } namespace es3 { struct segment_deleter { agenda_ptr parent_; void operator()(segment *seg) { delete seg; u_guard_t guard(parent_->m_); assert(parent_->segments_in_flight_>0); parent_->segments_in_flight_--; parent_->condition_.notify_one(); } }; class task_executor { agenda_ptr agenda_; public: task_executor(agenda_ptr agenda) : agenda_(agenda) {} std::pair<sync_task_ptr, std::vector<segment_ptr> > claim_task() { std::pair<sync_task_ptr, std::vector<segment_ptr> > res_pair; while(true) { u_guard_t lock(agenda_->m_); if (agenda_->tasks_.empty()) { if (agenda_->num_working_==0) return res_pair; agenda_->condition_.wait(lock); continue; } //Iterate over classes to find one that is not yet full for(auto iter=agenda_->classes_.begin(); iter!=agenda_->classes_.end();++iter) { //Check if there are too many tasks of this type running task_type_e cur_class=iter->first; size_t cur_num=iter->second; size_t limit=agenda_->get_capability(cur_class); //Unbound tasks are allowed to exceed their limits and //borrow threads from other classes // if (cur_class!=taskUnbound && limit<=cur_num) // continue; //Too busy if (limit<=cur_num) continue; size_t segments_avail=agenda_->max_segments_in_flight_- agenda_->segments_in_flight_; //Good! We can work on this class. //Find the task with the greatest segment requirements agenda::size_map_t::iterator pair= --agenda_->tasks_.end(); size_t segments_needed=pair->first; if (segments_needed>segments_avail) { //Try the task with the least number of required segs pair=agenda_->tasks_.begin(); segments_needed=pair->first; if (segments_needed>segments_avail) continue; //No such luck :( } if (!pair->second.count(cur_class)) continue; //No tasks for this class agenda::task_map_t &task_map=pair->second.at(cur_class); assert(!task_map.empty()); sync_task_ptr res=task_map.begin()->second; task_map.erase(task_map.begin()); if (task_map.empty()) { pair->second.erase(cur_class); if (pair->second.empty()) agenda_->tasks_.erase(pair->first); } agenda_->num_working_++; agenda_->classes_[cur_class]++; res_pair.first=res; if (segments_needed) res_pair.second=agenda_->get_segments(segments_needed); return res_pair; } agenda_->condition_.wait(lock); } } void cleanup(sync_task_ptr cur_task, bool fail) { u_guard_t lock(agenda_->m_); agenda_->num_working_--; assert(agenda_->classes_[cur_task->get_class()]>0); agenda_->classes_[cur_task->get_class()]--; if (agenda_->tasks_.empty() && agenda_->num_working_==0) agenda_->condition_.notify_all(); //We've finished our tasks! else agenda_->condition_.notify_one(); //Update stats guard_t lockst(agenda_->stats_m_); agenda_->num_done_++; if (fail) agenda_->num_failed_++; } void operator ()() { while(true) { std::pair<sync_task_ptr, std::vector<segment_ptr> > cur_task; cur_task=claim_task(); if (!cur_task.first) break; bool fail=true; for(int f=0; f<10; ++f) { try { (*cur_task.first)(agenda_, cur_task.second); fail=false; break; } catch (const es3_exception &ex) { const result_code_t &code = ex.err(); if (code.code()==errNone) { VLOG(2) << "INFO: " << ex.what(); sleep(5); continue; } else if (code.code()==errWarn) { VLOG(1) << "WARN: " << ex.what(); sleep(5); continue; } else { VLOG(0) << ex.what(); break; } } catch(const std::exception &ex) { VLOG(0) << "ERR: " << ex.what(); break; } catch(...) { VLOG(0) << "Unknown exception. Skipping"; break; } } cleanup(cur_task.first, fail); } } }; } std::vector<segment_ptr> agenda::get_segments(size_t num) { assert(segments_in_flight_+num<=max_segments_in_flight_); std::vector<segment_ptr> res; res.reserve(num); for(size_t f=0;f<num;++f) { segment_deleter del {shared_from_this()}; segment_ptr seg=segment_ptr(new segment(), del); res.push_back(seg); } segments_in_flight_+=num; return res; } void agenda::schedule(sync_task_ptr task) { u_guard_t lock(m_); // agenda_ptr ptr = shared_from_this(); // auto iter=std::lower_bound(tasks_.begin(), tasks_.end(), task); // if (iter!=tasks_.end()) // tasks_.insert(iter, task); // else // tasks_.push_back(task); classes_[task->get_class()]; //Force insertion of class entry task_map_t &task_map=tasks_[task->needs_segments()][task->get_class()]; task_map.insert(std::make_pair(task->ordinal(), task)); condition_.notify_one(); guard_t lockst(stats_m_); num_submitted_++; } size_t agenda::run() { std::vector<std::thread> threads; size_t thread_num=0; for(auto iter=class_limits_.begin();iter!=class_limits_.end();++iter) thread_num+=iter->second; for(int f=0;f<thread_num;++f) threads.push_back(std::thread(task_executor(shared_from_this()))); if (!quiet_) { threads.push_back(std::thread(boost::bind(&agenda::draw_progress, this))); for(int f=0;f<threads.size();++f) threads.at(f).join(); //Draw progress the last time draw_progress_widget(); std::cerr<<std::endl; } else { for(int f=0;f<threads.size();++f) threads.at(f).join(); } return num_failed_; } void agenda::print_epilog() { if (!final_quiet_) draw_stats(); } void agenda::draw_progress() { while(true) { { guard_t g(m_); if (num_working_==0 && tasks_.empty()) return; } draw_progress_widget(); usleep(500000); } } void agenda::add_stat_counter(const std::string &stat, uint64_t val) { guard_t lockst(stats_m_); cur_stats_[stat]+=val; } std::pair<std::string, std::string> agenda::format_si(uint64_t val, bool per_sec) { std::pair<std::string, std::string> res; uint64_t denom = 1; if (val<10000) { denom = 1; res.second = "B"; } else if (val<2000000) { denom = 1024; res.second = "K"; } else { denom = 1024*1024; res.second = "M"; } res.first = int_to_string(val/denom); if (val%denom) res.first+="."+int_to_string((val%denom)*100/denom); return res; } void agenda::draw_progress_widget() { uint64_t el = get_elapsed_millis(); std::stringstream str; { guard_t lockst(stats_m_); str << "Tasks: [" << num_done_ << "/" << num_submitted_ << "]"; if (num_failed_) str << " Failed tasks: " << num_failed_; uint64_t uploaded = cur_stats_["uploaded"]; uint64_t downloaded = cur_stats_["downloaded"]; if (downloaded) { auto dl=format_si(downloaded, false); auto ds=format_si(el==0? 0 : (downloaded*1000/el), true); str << " Downloaded: " << dl.first << " " << dl.second << ", speed: " << ds.first << " " << ds.second << "/sec"; } if (uploaded) { auto ul=format_si(uploaded, false); auto us=format_si(el==0? 0 : (uploaded*1000/el), true); str << " Uploaded: " << ul.first << " " << ul.second << ", speed: " << us.first << " " << us.second << "/sec"; } str << "\r"; } std::cerr << str.str(); //No std::endl std::cerr.flush(); } uint64_t agenda::get_elapsed_millis() const { struct timespec cur; clock_gettime(CLOCK_MONOTONIC, &cur) | libc_die2("Can't get time"); uint64_t start_tm = uint64_t(start_time_.tv_sec)*1000 + start_time_.tv_nsec/1000000; uint64_t cur_tm = uint64_t(cur.tv_sec)*1000+cur.tv_nsec/1000000; return cur_tm-start_tm; } void agenda::draw_stats() { uint64_t el = get_elapsed_millis(); std::cerr << "time taken [sec]: " << el/1000 << "." << el%1000 << std::endl; for(auto f=cur_stats_.begin();f!=cur_stats_.end();++f) { std::string name=f->first; uint64_t val=f->second; if (!val) continue; uint64_t avg = val*1000/el; std::cerr << name << " [B]: " << val << ", average [B/sec]: " << avg << std::endl; } } void agenda::print_queue() { std::cerr << "There are " << tasks_.size() << " task[s] present.\n"; for(auto by_segs=tasks_.begin();by_segs!=tasks_.end();++by_segs) { for(auto iter=by_segs->second.begin(); iter!=by_segs->second.end(); ++iter) { for(auto iter2=iter->second.begin(); iter2!=iter->second.end();++iter2) { sync_task_ptr task=iter2->second; task->print_to(std::cerr); std::cerr<<std::endl; } } } } <|endoftext|>
<commit_before>/** * This file is part of the CernVM File System. */ #define __STDC_FORMAT_MACROS #include "authz_fetch.h" #include <errno.h> #include <signal.h> #include <sys/wait.h> #include <syslog.h> #include <unistd.h> #include <algorithm> #include <cassert> #include <cstring> #include "clientctx.h" #include "logging.h" #include "platform.h" #include "smalloc.h" #include "util_concurrency.h" #include "util/pointer.h" #include "util/posix.h" #include "util/string.h" using namespace std; // NOLINT const int AuthzExternalFetcher::kMinTtl = 0; const uint32_t AuthzExternalFetcher::kProtocolVersion = 1; AuthzExternalFetcher::AuthzExternalFetcher( const string &fqrn, const string &progname) : fqrn_(fqrn) , progname_(progname) , fd_send_(-1) , fd_recv_(-1) , pid_(-1) , fail_state_(false) { InitLock(); } AuthzExternalFetcher::AuthzExternalFetcher( const string &fqrn, int fd_send, int fd_recv) : fqrn_(fqrn) , fd_send_(fd_send) , fd_recv_(fd_recv) , pid_(-1) , fail_state_(false) { InitLock(); } AuthzExternalFetcher::~AuthzExternalFetcher() { int retval = pthread_mutex_destroy(&lock_); assert(retval == 0); if (fd_send_ >= 0) close(fd_send_); if (fd_recv_ >= 0) close(fd_recv_); if (pid_ > 0) { uint64_t now = platform_monotonic_time(); int statloc; do { retval = waitpid(pid_, &statloc, WNOHANG); if (platform_monotonic_time() > (now + kChildTimeout)) { LogCvmfs(kLogAuthz, kLogSyslogWarn | kLogDebug, "authz helper %s unresponsive, killing", progname_.c_str()); kill(pid_, SIGKILL); break; } } while (retval == 0); } } void AuthzExternalFetcher::EnterFailState() { LogCvmfs(kLogAuthz, kLogSyslogErr | kLogDebug, "authz helper %s enters fail state, no more authorization", progname_.c_str()); fail_state_ = true; } /** * Uses execve to start progname_. The started program has stdin and stdout * connected to fd_send_ and fd_recv_ and the CVMFS_... environment variables * set. Special care must be taken when we call fork here in an unknown state * of the client. Therefore we can't use ManagedExec (we can't use malloc). * * A failed execve is not caught by this routine. It will be caught in the * next step, when mother and child start talking. */ void AuthzExternalFetcher::ExecHelper() { int pipe_send[2]; int pipe_recv[2]; MakePipe(pipe_send); MakePipe(pipe_recv); char *argv0 = strdupa(progname_.c_str()); char *argv[] = {argv0, NULL}; char *envp[] = {NULL}; int max_fd = sysconf(_SC_OPEN_MAX); assert(max_fd > 0); LogCvmfs(kLogAuthz, kLogDebug | kLogSyslog, "starting authz helper %s", argv0); pid_t pid = fork(); if (pid == 0) { // Child process, close file descriptors and run the helper int retval = dup2(pipe_send[0], 0); assert(retval == 0); retval = dup2(pipe_recv[1], 1); assert(retval == 1); for (int fd = 2; fd < max_fd; fd++) close(fd); execve(argv0, argv, envp); syslog(LOG_USER | LOG_ERR, "failed to start authz helper %s (%d)", argv0, errno); abort(); } assert(pid > 0); close(pipe_send[0]); close(pipe_recv[1]); // Don't receive a signal if the helper terminates signal(SIGPIPE, SIG_IGN); pid_ = pid; fd_send_ = pipe_send[1]; fd_recv_ = pipe_recv[0]; } AuthzStatus AuthzExternalFetcher::FetchWithinClientCtx( const std::string &membership, AuthzToken *authz_token, unsigned *ttl) { assert(ClientCtx::GetInstance()->IsSet()); uid_t uid; gid_t gid; pid_t pid; ClientCtx::GetInstance()->Get(&uid, &gid, &pid); *ttl = kDefaultTtl; MutexLockGuard lock_guard(lock_); if (fail_state_) return kAuthzNoHelper; bool retval; if (fd_send_ < 0) { ExecHelper(); retval = Handshake(); if (!retval) return kAuthzNoHelper; } assert((fd_send_ >= 0) && (fd_recv_ >= 0)); string json_msg = string("{\"cvmfs_authz_v1\":{") + "\"msgid\":" + StringifyInt(kAuthzMsgVerify) + "," + "\"revision\":0," + "\"uid\":" + StringifyInt(uid) + "," + "\"gid\":" + StringifyInt(gid) + "," + "\"pid\":" + StringifyInt(pid) + "," + "\"membership\":\"" + JsonDocument::EscapeString(membership) + "\"" + "}}"; retval = Send(json_msg) && Recv(&json_msg); if (!retval) return kAuthzNoHelper; AuthzExternalMsg binary_msg; retval = ParseMsg(json_msg, kAuthzMsgPermit, &binary_msg); if (!retval) return kAuthzNoHelper; if (binary_msg.permit.status == kAuthzOk) { *authz_token = binary_msg.permit.token; *ttl = binary_msg.permit.ttl; LogCvmfs(kLogAuthz, kLogDebug, "got token of type %d and size %u", binary_msg.permit.token.type, binary_msg.permit.token.size); } return binary_msg.permit.status; } /** * Establish communication link with a forked authz helper. */ bool AuthzExternalFetcher::Handshake() { string debug_log = GetLogDebugFile(); string json_debug_log; if (debug_log != "") json_debug_log = ",\"debug_log\":\"" + debug_log + "\""; string json_msg = string("{") + "\"cvmfs_authz_v1\":{" + "\"msgid\":" + StringifyInt(0) + "," + "\"revision\":0," + "\"fqrn\":\"" + fqrn_ + "\"," + "\"syslog_facility\":" + StringifyInt(GetLogSyslogFacility()) + "," + "\"syslog_level\":" + StringifyInt(GetLogSyslogLevel()) + json_debug_log + "}}"; bool retval = Send(json_msg); if (!retval) return false; retval = Recv(&json_msg); if (!retval) return false; AuthzExternalMsg binary_msg; retval = ParseMsg(json_msg, kAuthzMsgReady, &binary_msg); if (!retval) return false; return true; } void AuthzExternalFetcher::InitLock() { int retval = pthread_mutex_init(&lock_, NULL); assert(retval == 0); } bool AuthzExternalFetcher::Send(const string &msg) { // Line format: 4 byte protocol version, 4 byte length, message struct { uint32_t version; uint32_t length; } header; header.version = kProtocolVersion; header.length = msg.length(); unsigned raw_length = sizeof(header) + msg.length(); unsigned char *raw_msg = reinterpret_cast<unsigned char *>( alloca(raw_length)); memcpy(raw_msg, &header, sizeof(header)); memcpy(raw_msg + sizeof(header), msg.data(), header.length); bool retval = SafeWrite(fd_send_, raw_msg, raw_length); if (!retval) EnterFailState(); return retval; } /** * We want to see valid JSON in the form * { "cvmfs_authz_v1" : { * "msgid": * "revision": * ... * } * ... * } * * The contents of "cvmfs_authz_v1" depends on the msgid. Additional fields * are ignored. The protocol revision should indicate changes in the fields. */ bool AuthzExternalFetcher::ParseMsg( const std::string &json_msg, const AuthzExternalMsgIds expected_msgid, AuthzExternalMsg *binary_msg) { assert(binary_msg != NULL); UniquePtr<JsonDocument> json_document(JsonDocument::Create(json_msg)); if (!json_document.IsValid()) { LogCvmfs(kLogAuthz, kLogSyslogErr | kLogDebug, "invalid json from authz helper %s: %s", progname_.c_str(), json_msg.c_str()); EnterFailState(); return false; } JSON *json_authz = JsonDocument::SearchInObject( json_document->root(), "cvmfs_authz_v1", JSON_OBJECT); if (json_authz == NULL) { LogCvmfs(kLogAuthz, kLogSyslogErr | kLogDebug, "\"cvmfs_authz_v1\" not found in json from authz helper %s: %s", progname_.c_str(), json_msg.c_str()); EnterFailState(); return false; } if (!ParseMsgId(json_authz, binary_msg) || (binary_msg->msgid != expected_msgid)) { EnterFailState(); return false; } if (!ParseRevision(json_authz, binary_msg)) { EnterFailState(); return false; } if (binary_msg->msgid == kAuthzMsgPermit) { if (!ParsePermit(json_authz, binary_msg)) { EnterFailState(); return false; } } return true; } bool AuthzExternalFetcher::ParseMsgId( JSON *json_authz, AuthzExternalMsg *binary_msg) { JSON *json_msgid = JsonDocument::SearchInObject( json_authz, "msgid", JSON_INT); if (json_msgid == NULL) { LogCvmfs(kLogAuthz, kLogSyslogErr | kLogDebug, "\"msgid\" not found in json from authz helper %s", progname_.c_str()); EnterFailState(); return false; } if ((json_msgid->int_value < 0) || (json_msgid->int_value >= kAuthzMsgInvalid)) { LogCvmfs(kLogAuthz, kLogSyslogErr | kLogDebug, "invalid \"msgid\" in json from authz helper %s: %d", progname_.c_str(), json_msgid->int_value); EnterFailState(); return false; } binary_msg->msgid = static_cast<AuthzExternalMsgIds>(json_msgid->int_value); return true; } /** * A permit must contain the authorization status. Optionally it can come with * a "time to live" of the answer and a token (e.g. X.509 proxy certificate). */ bool AuthzExternalFetcher::ParsePermit( JSON *json_authz, AuthzExternalMsg *binary_msg) { JSON *json_status = JsonDocument::SearchInObject(json_authz, "status", JSON_INT); if (json_status == NULL) { LogCvmfs(kLogAuthz, kLogSyslogErr | kLogDebug, "\"status\" not found in json from authz helper %s", progname_.c_str()); EnterFailState(); return false; } if ((json_status->int_value < 0) || (json_status->int_value > kAuthzUnknown)) { binary_msg->permit.status = kAuthzUnknown; } else { binary_msg->permit.status = static_cast<AuthzStatus>( json_status->int_value); } JSON *json_ttl = JsonDocument::SearchInObject(json_authz, "ttl", JSON_INT); if (json_ttl == NULL) { LogCvmfs(kLogAuthz, kLogDebug, "no ttl, using default"); binary_msg->permit.ttl = kDefaultTtl; } else { binary_msg->permit.ttl = std::max(kMinTtl, json_ttl->int_value); } JSON *json_token = JsonDocument::SearchInObject(json_authz, "x509_proxy", JSON_STRING); if (json_token != NULL) { binary_msg->permit.token.type = kTokenX509; string token_binary; bool valid_base64 = Debase64(json_token->string_value, &token_binary); if (!valid_base64) { LogCvmfs(kLogAuthz, kLogSyslogErr | kLogDebug, "invalid Base64 in 'x509_proxy' from authz helper %s", progname_.c_str()); EnterFailState(); return false; } unsigned size = token_binary.size(); binary_msg->permit.token.size = size; if (size > 0) { // The token is passed to the AuthzSessionManager, which takes care of // freeing the memory binary_msg->permit.token.data = smalloc(size); memcpy(binary_msg->permit.token.data, token_binary.data(), size); } } return true; } bool AuthzExternalFetcher::ParseRevision( JSON *json_authz, AuthzExternalMsg *binary_msg) { JSON *json_revision = JsonDocument::SearchInObject( json_authz, "revision", JSON_INT); if (json_revision == NULL) { LogCvmfs(kLogAuthz, kLogSyslogErr | kLogDebug, "\"revision\" not found in json from authz helper %s", progname_.c_str()); EnterFailState(); return false; } if (json_revision->int_value < 0) { LogCvmfs(kLogAuthz, kLogSyslogErr | kLogDebug, "invalid \"revision\" in json from authz helper %s: %d", progname_.c_str(), json_revision->int_value); EnterFailState(); return false; } binary_msg->protocol_revision = json_revision->int_value; return true; } bool AuthzExternalFetcher::Recv(string *msg) { uint32_t version; ssize_t retval = SafeRead(fd_recv_, &version, sizeof(version)); if (retval != int(sizeof(version))) { EnterFailState(); return false; } if (version != kProtocolVersion) { LogCvmfs(kLogAuthz, kLogSyslogErr | kLogDebug, "authz helper uses unknown protocol version %u", version); EnterFailState(); return false; } uint32_t length; retval = SafeRead(fd_recv_, &length, sizeof(length)); if (retval != int(sizeof(length))) { EnterFailState(); return false; } msg->clear(); char buf[kPageSize]; unsigned nbytes = 0; while (nbytes < length) { const unsigned remaining = length - nbytes; retval = SafeRead(fd_recv_, buf, std::min(kPageSize, remaining)); if (retval < 0) { LogCvmfs(kLogAuthz, kLogSyslogErr | kLogDebug, "read failure from authz helper %s", progname_.c_str()); EnterFailState(); return false; } nbytes += retval; msg->append(buf, retval); } return true; } <commit_msg>respect authz ttl for negetive permits<commit_after>/** * This file is part of the CernVM File System. */ #define __STDC_FORMAT_MACROS #include "authz_fetch.h" #include <errno.h> #include <signal.h> #include <sys/wait.h> #include <syslog.h> #include <unistd.h> #include <algorithm> #include <cassert> #include <cstring> #include "clientctx.h" #include "logging.h" #include "platform.h" #include "smalloc.h" #include "util_concurrency.h" #include "util/pointer.h" #include "util/posix.h" #include "util/string.h" using namespace std; // NOLINT const int AuthzExternalFetcher::kMinTtl = 0; const uint32_t AuthzExternalFetcher::kProtocolVersion = 1; AuthzExternalFetcher::AuthzExternalFetcher( const string &fqrn, const string &progname) : fqrn_(fqrn) , progname_(progname) , fd_send_(-1) , fd_recv_(-1) , pid_(-1) , fail_state_(false) { InitLock(); } AuthzExternalFetcher::AuthzExternalFetcher( const string &fqrn, int fd_send, int fd_recv) : fqrn_(fqrn) , fd_send_(fd_send) , fd_recv_(fd_recv) , pid_(-1) , fail_state_(false) { InitLock(); } AuthzExternalFetcher::~AuthzExternalFetcher() { int retval = pthread_mutex_destroy(&lock_); assert(retval == 0); if (fd_send_ >= 0) close(fd_send_); if (fd_recv_ >= 0) close(fd_recv_); if (pid_ > 0) { uint64_t now = platform_monotonic_time(); int statloc; do { retval = waitpid(pid_, &statloc, WNOHANG); if (platform_monotonic_time() > (now + kChildTimeout)) { LogCvmfs(kLogAuthz, kLogSyslogWarn | kLogDebug, "authz helper %s unresponsive, killing", progname_.c_str()); kill(pid_, SIGKILL); break; } } while (retval == 0); } } void AuthzExternalFetcher::EnterFailState() { LogCvmfs(kLogAuthz, kLogSyslogErr | kLogDebug, "authz helper %s enters fail state, no more authorization", progname_.c_str()); fail_state_ = true; } /** * Uses execve to start progname_. The started program has stdin and stdout * connected to fd_send_ and fd_recv_ and the CVMFS_... environment variables * set. Special care must be taken when we call fork here in an unknown state * of the client. Therefore we can't use ManagedExec (we can't use malloc). * * A failed execve is not caught by this routine. It will be caught in the * next step, when mother and child start talking. */ void AuthzExternalFetcher::ExecHelper() { int pipe_send[2]; int pipe_recv[2]; MakePipe(pipe_send); MakePipe(pipe_recv); char *argv0 = strdupa(progname_.c_str()); char *argv[] = {argv0, NULL}; char *envp[] = {NULL}; int max_fd = sysconf(_SC_OPEN_MAX); assert(max_fd > 0); LogCvmfs(kLogAuthz, kLogDebug | kLogSyslog, "starting authz helper %s", argv0); pid_t pid = fork(); if (pid == 0) { // Child process, close file descriptors and run the helper int retval = dup2(pipe_send[0], 0); assert(retval == 0); retval = dup2(pipe_recv[1], 1); assert(retval == 1); for (int fd = 2; fd < max_fd; fd++) close(fd); execve(argv0, argv, envp); syslog(LOG_USER | LOG_ERR, "failed to start authz helper %s (%d)", argv0, errno); abort(); } assert(pid > 0); close(pipe_send[0]); close(pipe_recv[1]); // Don't receive a signal if the helper terminates signal(SIGPIPE, SIG_IGN); pid_ = pid; fd_send_ = pipe_send[1]; fd_recv_ = pipe_recv[0]; } AuthzStatus AuthzExternalFetcher::FetchWithinClientCtx( const std::string &membership, AuthzToken *authz_token, unsigned *ttl) { assert(ClientCtx::GetInstance()->IsSet()); uid_t uid; gid_t gid; pid_t pid; ClientCtx::GetInstance()->Get(&uid, &gid, &pid); *ttl = kDefaultTtl; MutexLockGuard lock_guard(lock_); if (fail_state_) return kAuthzNoHelper; bool retval; if (fd_send_ < 0) { ExecHelper(); retval = Handshake(); if (!retval) return kAuthzNoHelper; } assert((fd_send_ >= 0) && (fd_recv_ >= 0)); string json_msg = string("{\"cvmfs_authz_v1\":{") + "\"msgid\":" + StringifyInt(kAuthzMsgVerify) + "," + "\"revision\":0," + "\"uid\":" + StringifyInt(uid) + "," + "\"gid\":" + StringifyInt(gid) + "," + "\"pid\":" + StringifyInt(pid) + "," + "\"membership\":\"" + JsonDocument::EscapeString(membership) + "\"" + "}}"; retval = Send(json_msg) && Recv(&json_msg); if (!retval) return kAuthzNoHelper; AuthzExternalMsg binary_msg; retval = ParseMsg(json_msg, kAuthzMsgPermit, &binary_msg); if (!retval) return kAuthzNoHelper; *ttl = binary_msg.permit.ttl; if (binary_msg.permit.status == kAuthzOk) { *authz_token = binary_msg.permit.token; LogCvmfs(kLogAuthz, kLogDebug, "got token of type %d and size %u", binary_msg.permit.token.type, binary_msg.permit.token.size); } return binary_msg.permit.status; } /** * Establish communication link with a forked authz helper. */ bool AuthzExternalFetcher::Handshake() { string debug_log = GetLogDebugFile(); string json_debug_log; if (debug_log != "") json_debug_log = ",\"debug_log\":\"" + debug_log + "\""; string json_msg = string("{") + "\"cvmfs_authz_v1\":{" + "\"msgid\":" + StringifyInt(0) + "," + "\"revision\":0," + "\"fqrn\":\"" + fqrn_ + "\"," + "\"syslog_facility\":" + StringifyInt(GetLogSyslogFacility()) + "," + "\"syslog_level\":" + StringifyInt(GetLogSyslogLevel()) + json_debug_log + "}}"; bool retval = Send(json_msg); if (!retval) return false; retval = Recv(&json_msg); if (!retval) return false; AuthzExternalMsg binary_msg; retval = ParseMsg(json_msg, kAuthzMsgReady, &binary_msg); if (!retval) return false; return true; } void AuthzExternalFetcher::InitLock() { int retval = pthread_mutex_init(&lock_, NULL); assert(retval == 0); } bool AuthzExternalFetcher::Send(const string &msg) { // Line format: 4 byte protocol version, 4 byte length, message struct { uint32_t version; uint32_t length; } header; header.version = kProtocolVersion; header.length = msg.length(); unsigned raw_length = sizeof(header) + msg.length(); unsigned char *raw_msg = reinterpret_cast<unsigned char *>( alloca(raw_length)); memcpy(raw_msg, &header, sizeof(header)); memcpy(raw_msg + sizeof(header), msg.data(), header.length); bool retval = SafeWrite(fd_send_, raw_msg, raw_length); if (!retval) EnterFailState(); return retval; } /** * We want to see valid JSON in the form * { "cvmfs_authz_v1" : { * "msgid": * "revision": * ... * } * ... * } * * The contents of "cvmfs_authz_v1" depends on the msgid. Additional fields * are ignored. The protocol revision should indicate changes in the fields. */ bool AuthzExternalFetcher::ParseMsg( const std::string &json_msg, const AuthzExternalMsgIds expected_msgid, AuthzExternalMsg *binary_msg) { assert(binary_msg != NULL); UniquePtr<JsonDocument> json_document(JsonDocument::Create(json_msg)); if (!json_document.IsValid()) { LogCvmfs(kLogAuthz, kLogSyslogErr | kLogDebug, "invalid json from authz helper %s: %s", progname_.c_str(), json_msg.c_str()); EnterFailState(); return false; } JSON *json_authz = JsonDocument::SearchInObject( json_document->root(), "cvmfs_authz_v1", JSON_OBJECT); if (json_authz == NULL) { LogCvmfs(kLogAuthz, kLogSyslogErr | kLogDebug, "\"cvmfs_authz_v1\" not found in json from authz helper %s: %s", progname_.c_str(), json_msg.c_str()); EnterFailState(); return false; } if (!ParseMsgId(json_authz, binary_msg) || (binary_msg->msgid != expected_msgid)) { EnterFailState(); return false; } if (!ParseRevision(json_authz, binary_msg)) { EnterFailState(); return false; } if (binary_msg->msgid == kAuthzMsgPermit) { if (!ParsePermit(json_authz, binary_msg)) { EnterFailState(); return false; } } return true; } bool AuthzExternalFetcher::ParseMsgId( JSON *json_authz, AuthzExternalMsg *binary_msg) { JSON *json_msgid = JsonDocument::SearchInObject( json_authz, "msgid", JSON_INT); if (json_msgid == NULL) { LogCvmfs(kLogAuthz, kLogSyslogErr | kLogDebug, "\"msgid\" not found in json from authz helper %s", progname_.c_str()); EnterFailState(); return false; } if ((json_msgid->int_value < 0) || (json_msgid->int_value >= kAuthzMsgInvalid)) { LogCvmfs(kLogAuthz, kLogSyslogErr | kLogDebug, "invalid \"msgid\" in json from authz helper %s: %d", progname_.c_str(), json_msgid->int_value); EnterFailState(); return false; } binary_msg->msgid = static_cast<AuthzExternalMsgIds>(json_msgid->int_value); return true; } /** * A permit must contain the authorization status. Optionally it can come with * a "time to live" of the answer and a token (e.g. X.509 proxy certificate). */ bool AuthzExternalFetcher::ParsePermit( JSON *json_authz, AuthzExternalMsg *binary_msg) { JSON *json_status = JsonDocument::SearchInObject(json_authz, "status", JSON_INT); if (json_status == NULL) { LogCvmfs(kLogAuthz, kLogSyslogErr | kLogDebug, "\"status\" not found in json from authz helper %s", progname_.c_str()); EnterFailState(); return false; } if ((json_status->int_value < 0) || (json_status->int_value > kAuthzUnknown)) { binary_msg->permit.status = kAuthzUnknown; } else { binary_msg->permit.status = static_cast<AuthzStatus>( json_status->int_value); } JSON *json_ttl = JsonDocument::SearchInObject(json_authz, "ttl", JSON_INT); if (json_ttl == NULL) { LogCvmfs(kLogAuthz, kLogDebug, "no ttl, using default"); binary_msg->permit.ttl = kDefaultTtl; } else { binary_msg->permit.ttl = std::max(kMinTtl, json_ttl->int_value); } JSON *json_token = JsonDocument::SearchInObject(json_authz, "x509_proxy", JSON_STRING); if (json_token != NULL) { binary_msg->permit.token.type = kTokenX509; string token_binary; bool valid_base64 = Debase64(json_token->string_value, &token_binary); if (!valid_base64) { LogCvmfs(kLogAuthz, kLogSyslogErr | kLogDebug, "invalid Base64 in 'x509_proxy' from authz helper %s", progname_.c_str()); EnterFailState(); return false; } unsigned size = token_binary.size(); binary_msg->permit.token.size = size; if (size > 0) { // The token is passed to the AuthzSessionManager, which takes care of // freeing the memory binary_msg->permit.token.data = smalloc(size); memcpy(binary_msg->permit.token.data, token_binary.data(), size); } } return true; } bool AuthzExternalFetcher::ParseRevision( JSON *json_authz, AuthzExternalMsg *binary_msg) { JSON *json_revision = JsonDocument::SearchInObject( json_authz, "revision", JSON_INT); if (json_revision == NULL) { LogCvmfs(kLogAuthz, kLogSyslogErr | kLogDebug, "\"revision\" not found in json from authz helper %s", progname_.c_str()); EnterFailState(); return false; } if (json_revision->int_value < 0) { LogCvmfs(kLogAuthz, kLogSyslogErr | kLogDebug, "invalid \"revision\" in json from authz helper %s: %d", progname_.c_str(), json_revision->int_value); EnterFailState(); return false; } binary_msg->protocol_revision = json_revision->int_value; return true; } bool AuthzExternalFetcher::Recv(string *msg) { uint32_t version; ssize_t retval = SafeRead(fd_recv_, &version, sizeof(version)); if (retval != int(sizeof(version))) { EnterFailState(); return false; } if (version != kProtocolVersion) { LogCvmfs(kLogAuthz, kLogSyslogErr | kLogDebug, "authz helper uses unknown protocol version %u", version); EnterFailState(); return false; } uint32_t length; retval = SafeRead(fd_recv_, &length, sizeof(length)); if (retval != int(sizeof(length))) { EnterFailState(); return false; } msg->clear(); char buf[kPageSize]; unsigned nbytes = 0; while (nbytes < length) { const unsigned remaining = length - nbytes; retval = SafeRead(fd_recv_, buf, std::min(kPageSize, remaining)); if (retval < 0) { LogCvmfs(kLogAuthz, kLogSyslogErr | kLogDebug, "read failure from authz helper %s", progname_.c_str()); EnterFailState(); return false; } nbytes += retval; msg->append(buf, retval); } return true; } <|endoftext|>
<commit_before>#ifndef DIPLOMA_OBJECT_META_H #define DIPLOMA_OBJECT_META_H #include <cstring> #include <atomic> #include <libprecisegc/details/gc_handle.hpp> #include <libprecisegc/details/gc_tagging.hpp> #include <libprecisegc/details/managed_ptr.hpp> #include <libprecisegc/details/type_meta.hpp> #include <libprecisegc/details/types.hpp> namespace precisegc { namespace details { class object_meta { public: // computes pointer to object_meta by pointer to start of managed cell and its size static object_meta* get_meta_ptr(byte* ptr, size_t obj_size) { return get_meta_ptr_by_cell_start(ptr); } // computes pointer to object_meta by managed pointer to managed cell static object_meta* get_meta_ptr(const managed_ptr& ptr) { return ptr.is_derived() ? get_meta_ptr_by_cell_start(ptr.get_cell_begin()) : reinterpret_cast<object_meta*>(ptr.get() - sizeof(object_meta)); } // computes pointer to object itself by pointer to start of managed cell and its size static byte* get_object_ptr(byte* ptr, size_t obj_size) { return get_object_ptr_by_cell_start(ptr); } // computes pointer to object itself by managed pointer to managed cell static byte* get_object_ptr(const managed_ptr& ptr) { return ptr.is_derived() ? get_object_ptr_by_cell_start(ptr.get_cell_begin()) : ptr.get(); } object_meta(size_t count, const type_meta* meta) : m_type_meta(reinterpret_cast<std::uintptr_t>(meta)) , m_count(count) {} size_t type_size() const noexcept { return get_type_meta()->type_size(); } size_t object_count() const noexcept { return m_count; } size_t object_size() const noexcept { return object_count() * type_size(); } void set_object_count(size_t count) noexcept { m_count = count; } void increment_object_count() noexcept { ++m_count; } type_meta::offsets_range offsets() const noexcept { return get_type_meta()->offsets(); } const type_meta* get_type_meta() const noexcept { return reinterpret_cast<const type_meta*>(m_type_meta & ~FORWARD_BIT); } void set_type_meta(const type_meta* cls_meta) noexcept { std::uintptr_t frwd_bit = is_forwarded() ? FORWARD_BIT : 0; m_type_meta = reinterpret_cast<std::uintptr_t>(cls_meta) | frwd_bit; } byte* get_object_begin() const { return reinterpret_cast<byte*>(const_cast<object_meta*>(this)) + sizeof(object_meta); } byte* get_array_element_begin(byte* ptr) const { assert(contains(ptr)); byte* obj_begin = get_object_begin(); size_t elem_size = type_size(); size_t elem_ind = (ptr - obj_begin) / elem_size; return obj_begin + elem_ind * elem_size; } bool is_forwarded() const { return m_type_meta & FORWARD_BIT; } byte* forward_pointer() const noexcept { assert(is_forwarded()); byte* ptr; memcpy(&ptr, get_forward_pointer_address(), sizeof(void*)); return ptr; } void set_forward_pointer(byte* ptr) noexcept { m_type_meta |= FORWARD_BIT; memcpy(get_forward_pointer_address(), &ptr, sizeof(void*)); } template <typename Functor> void trace_children(Functor&& f) const { const type_meta* tmeta = get_type_meta(); if (!tmeta) { return; } size_t obj_size = tmeta->type_size(); auto offsets = tmeta->offsets(); if (offsets.empty()) { return; } byte* obj = get_object_begin(); size_t offsets_size = offsets.size(); for (size_t i = 0; i < m_count; i++) { for (size_t j = 0; j < offsets_size; j++) { f(reinterpret_cast<gc_handle*>(obj + offsets[j])); } obj += obj_size; } } private: static const std::uintptr_t FORWARD_BIT = 1; // computes pointer to object_meta by pointer to start of managed cell static object_meta* get_meta_ptr_by_cell_start(byte* ptr) { return reinterpret_cast<object_meta*>(ptr); } // computes pointer to object itself by pointer to start of managed cell static byte* get_object_ptr_by_cell_start(byte* ptr) { return ptr + sizeof(object_meta); } bool contains(byte* ptr) const { byte* obj_begin = get_object_begin(); return (obj_begin <= ptr) && (ptr < obj_begin + m_count * type_size()); } void* get_forward_pointer_address() { return reinterpret_cast<void*>(reinterpret_cast<byte*>(this) + sizeof(object_meta)); } const void* get_forward_pointer_address() const { return reinterpret_cast<const void*>(reinterpret_cast<const byte*>(this) + sizeof(object_meta)); } std::uintptr_t m_type_meta; size_t m_count; }; } } #endif //DIPLOMA_OBJECT_META_H <commit_msg>is_plain_object method<commit_after>#ifndef DIPLOMA_OBJECT_META_H #define DIPLOMA_OBJECT_META_H #include <cstring> #include <atomic> #include <libprecisegc/details/gc_handle.hpp> #include <libprecisegc/details/gc_tagging.hpp> #include <libprecisegc/details/managed_ptr.hpp> #include <libprecisegc/details/type_meta.hpp> #include <libprecisegc/details/types.hpp> namespace precisegc { namespace details { class object_meta { public: // computes pointer to object_meta by pointer to start of managed cell and its size static object_meta* get_meta_ptr(byte* ptr, size_t obj_size) { return get_meta_ptr_by_cell_start(ptr); } // computes pointer to object_meta by managed pointer to managed cell static object_meta* get_meta_ptr(const managed_ptr& ptr) { return ptr.is_derived() ? get_meta_ptr_by_cell_start(ptr.get_cell_begin()) : reinterpret_cast<object_meta*>(ptr.get() - sizeof(object_meta)); } // computes pointer to object itself by pointer to start of managed cell and its size static byte* get_object_ptr(byte* ptr, size_t obj_size) { return get_object_ptr_by_cell_start(ptr); } // computes pointer to object itself by managed pointer to managed cell static byte* get_object_ptr(const managed_ptr& ptr) { return ptr.is_derived() ? get_object_ptr_by_cell_start(ptr.get_cell_begin()) : ptr.get(); } object_meta(size_t count, const type_meta* meta) : m_type_meta(reinterpret_cast<std::uintptr_t>(meta)) , m_count(count) {} size_t type_size() const noexcept { return get_type_meta()->type_size(); } size_t object_count() const noexcept { return m_count; } size_t object_size() const noexcept { return object_count() * type_size(); } void set_object_count(size_t count) noexcept { m_count = count; } void increment_object_count() noexcept { ++m_count; } type_meta::offsets_range offsets() const noexcept { return get_type_meta()->offsets(); } bool is_plain_object() const noexcept { return m_type_meta == 0 || m_type_meta == FORWARD_BIT || get_type_meta()->is_plain_type(); } const type_meta* get_type_meta() const noexcept { return reinterpret_cast<const type_meta*>(m_type_meta & ~FORWARD_BIT); } void set_type_meta(const type_meta* cls_meta) noexcept { std::uintptr_t frwd_bit = is_forwarded() ? FORWARD_BIT : 0; m_type_meta = reinterpret_cast<std::uintptr_t>(cls_meta) | frwd_bit; } byte* get_object_begin() const { return reinterpret_cast<byte*>(const_cast<object_meta*>(this)) + sizeof(object_meta); } byte* get_array_element_begin(byte* ptr) const { assert(contains(ptr)); byte* obj_begin = get_object_begin(); size_t elem_size = type_size(); size_t elem_ind = (ptr - obj_begin) / elem_size; return obj_begin + elem_ind * elem_size; } bool is_forwarded() const { return m_type_meta & FORWARD_BIT; } byte* forward_pointer() const noexcept { assert(is_forwarded()); byte* ptr; memcpy(&ptr, get_forward_pointer_address(), sizeof(void*)); return ptr; } void set_forward_pointer(byte* ptr) noexcept { m_type_meta |= FORWARD_BIT; memcpy(get_forward_pointer_address(), &ptr, sizeof(void*)); } template <typename Functor> void trace_children(Functor&& f) const { const type_meta* tmeta = get_type_meta(); if (!tmeta) { return; } size_t obj_size = tmeta->type_size(); auto offsets = tmeta->offsets(); if (offsets.empty()) { return; } byte* obj = get_object_begin(); size_t offsets_size = offsets.size(); for (size_t i = 0; i < m_count; i++) { for (size_t j = 0; j < offsets_size; j++) { f(reinterpret_cast<gc_handle*>(obj + offsets[j])); } obj += obj_size; } } private: static const std::uintptr_t FORWARD_BIT = 1; // computes pointer to object_meta by pointer to start of managed cell static object_meta* get_meta_ptr_by_cell_start(byte* ptr) { return reinterpret_cast<object_meta*>(ptr); } // computes pointer to object itself by pointer to start of managed cell static byte* get_object_ptr_by_cell_start(byte* ptr) { return ptr + sizeof(object_meta); } bool contains(byte* ptr) const { byte* obj_begin = get_object_begin(); return (obj_begin <= ptr) && (ptr < obj_begin + m_count * type_size()); } void* get_forward_pointer_address() { return reinterpret_cast<void*>(reinterpret_cast<byte*>(this) + sizeof(object_meta)); } const void* get_forward_pointer_address() const { return reinterpret_cast<const void*>(reinterpret_cast<const byte*>(this) + sizeof(object_meta)); } std::uintptr_t m_type_meta; size_t m_count; }; } } #endif //DIPLOMA_OBJECT_META_H <|endoftext|>
<commit_before>/* -*- mode: c++; c-default-style: "google"; indent-tabs-mode: nil -*- */ /* Authors: Ethan Coon (ecoon@lanl.gov) */ #include "MatrixMFD.hh" #include "MatrixMFD_Factory.hh" #include "Function.hh" #include "FunctionFactory.hh" #include "implicit_snow_distribution_evaluator.hh" namespace Amanzi { namespace Flow { namespace FlowRelations { ImplicitSnowDistributionEvaluator::ImplicitSnowDistributionEvaluator(Teuchos::ParameterList& plist) : SecondaryVariableFieldEvaluator(plist), assembled_(false) { my_key_ = plist_.get<std::string>("precipitation snow field", "precipitation_snow"); // depenedencies mesh_name_ = plist_.get<std::string>("domain name", "surface"); if (mesh_name_ == "domain") { cell_vol_key_ = "cell_volume"; } else { cell_vol_key_ = mesh_name_+std::string("_cell_volume"); } dependencies_.insert(cell_vol_key_); elev_key_ = plist_.get<std::string>("elevation key", "elevation"); dependencies_.insert(elev_key_); slope_key_ = plist_.get<std::string>("slope key", "slope_magnitude"); dependencies_.insert(slope_key_); pd_key_ = plist_.get<std::string>("ponded depth key", "ponded_depth"); dependencies_.insert(pd_key_); snow_height_key_ = plist_.get<std::string>("snow height key", "snow_depth"); dependencies_.insert(snow_height_key_); // constant parameters kL_ = plist_.get<double>("snow distribution length"); kdx_ = plist_.get<double>("characteristic horizontal grid size", 0.25); ktmax_ = plist_.get<double>("faux integration time", 86400.); kS_ = plist_.get<double>("characteristic slope", 1.); kCFL_ = plist_.get<double>("Courant number", 1.); kSWE_conv_ = plist_.get<double>("SWE-to-snow conversion ratio", 10.); tol_ = plist_.get<double>("solver tolerance", 1.e-2); max_it_ = plist_.get<int>("max iterations", 10); FunctionFactory fac; precip_func_ = Teuchos::rcp(fac.Create(plist_.sublist("precipitation function"))); } ImplicitSnowDistributionEvaluator::ImplicitSnowDistributionEvaluator(const ImplicitSnowDistributionEvaluator& other) : SecondaryVariableFieldEvaluator(other), elev_key_(other.elev_key_), slope_key_(other.slope_key_), pd_key_(other.pd_key_), snow_height_key_(other.snow_height_key_), cell_vol_key_(other.cell_vol_key_), precip_func_(other.precip_func_), kL_(other.kL_), kdx_(other.kdx_), ktmax_(other.ktmax_), kS_(other.kS_), kCFL_(other.kCFL_), kSWE_conv_(other.kSWE_conv_), tol_(other.tol_), max_it_(other.max_it_), assembled_(other.assembled_), mesh_name_(other.mesh_name_), matrix_(other.matrix_) {} void ImplicitSnowDistributionEvaluator::EvaluateField_(const Teuchos::Ptr<State>& S, const Teuchos::Ptr<CompositeVector>& result) { Teuchos::OSTab tab = vo_->getOSTab(); if (!assembled_) AssembleOperator_(S); double time = S->time(); double Qe = (*precip_func_)(&time); double dt_sim = *S->GetScalarData("dt"); // NOTE: snow precip comes in SWE, must convert it to snow depth! if (Qe * dt_sim * kSWE_conv_ > 0.) { // determine scaling of flow const double kV = kL_/ktmax_; double dt = kCFL_ * kdx_ / kV; const double kh0 = Qe * ktmax_ * kSWE_conv_; const double nm = std::pow(kh0, 1./3) * std::sqrt(kS_) / kV; int nsteps = std::ceil(ktmax_ / dt); dt = ktmax_ / nsteps; // scale report if (vo_->os_OK(Teuchos::VERB_HIGH)) { *vo_->os() << "Snow Distribution: taking " << nsteps << " steps of size " << dt << " s for travel length " << kL_ << " m." << std::endl << " L = " << kL_ << std::endl << " t_max = " << ktmax_ << std::endl << " V = " << kV << std::endl << " Q = " << kV*kh0 << std::endl << " -------" << std::endl << " h0 = " << kh0 << std::endl << " nm = " << nm << std::endl << " V(man)= " << std::pow(kh0,1./3) * std::sqrt(kS_) / nm << std::endl << " -------" << std::endl; } // Gather mesh entities Teuchos::RCP<const AmanziMesh::Mesh> mesh = S->GetMesh(mesh_name_); int nfaces = mesh->num_entities(AmanziMesh::FACE, AmanziMesh::OWNED); int ncells = mesh->num_entities(AmanziMesh::CELL, AmanziMesh::OWNED); int nfaces_g = mesh->num_entities(AmanziMesh::FACE, AmanziMesh::USED); // Gather null boundary conditions (no flux of snow into or out of domain) std::vector<Operators::MatrixBC> bc_markers(nfaces_g, Operators::MATRIX_BC_NULL); std::vector<double> bc_values(nfaces_g, 0.0); // Create temporary work space // -- not necessarily ghosted workspace Teuchos::RCP<CompositeVector> residual = Teuchos::rcp(new CompositeVector(*result)); Teuchos::RCP<CompositeVector> result_prev = Teuchos::rcp(new CompositeVector(*result)); Teuchos::RCP<CompositeVector> dresult = Teuchos::rcp(new CompositeVector(*result)); // -- necessarily ghosted workspace CompositeVectorSpace ghosted_space(result->Map()); ghosted_space.SetGhosted(); Teuchos::RCP<CompositeVector> hz = Teuchos::rcp(new CompositeVector(ghosted_space)); Teuchos::RCP<CompositeVector> Krel_c = Teuchos::rcp(new CompositeVector(ghosted_space)); CompositeVectorSpace Krel_f_space; Krel_f_space.SetMesh(mesh)->SetGhosted()->SetComponent("face",AmanziMesh::FACE,1); Teuchos::RCP<CompositeVector> Krel_uw = Teuchos::rcp(new CompositeVector(Krel_f_space)); // Gather dependencies // NOTE: this is incorrect approximation... should be | sqrt( grad( z+h_pd ) ) | const Epetra_MultiVector& slope = *S->GetFieldData(slope_key_)->ViewComponent("cell",false); const Epetra_MultiVector& cv = *S->GetFieldData(cell_vol_key_)->ViewComponent("cell",false); Teuchos::RCP<const CompositeVector> elev = S->GetFieldData(elev_key_); Teuchos::RCP<const CompositeVector> pd = S->GetFieldData(pd_key_); Teuchos::RCP<const CompositeVector> snow_height = S->GetFieldData(snow_height_key_); // initialize and begin timestep loop result->PutScalar(Qe * ktmax_ * kSWE_conv_); for (int istep=0; istep!=nsteps; ++istep) { if (vo_->os_OK(Teuchos::VERB_HIGH)) *vo_->os() << "Snow distribution inner timestep " << istep << " with size " << dt << std::endl << " Qe*t_total =" << std::endl; *result_prev = *result; double norm0 = 0.; bool done = false; int ncycle = 0; while(!done) { // update snow potential, z + h_pd + h_s + Qe*dt *hz = *result; hz->Update(1., *elev, 1., *pd, 1.); hz->Update(1., *snow_height, 1.); if (vo_->os_OK(Teuchos::VERB_EXTREME)) { *vo_->os() << " z + h_pd + h_s potential = " << std::endl; hz->Print(*vo_->os()); } // update Krel { Epetra_MultiVector& Krel_c_vec = *Krel_c->ViewComponent("cell",false); const Epetra_MultiVector& result_c = *result->ViewComponent("cell",false); for (int c=0; c!=ncells; ++c) { Krel_c_vec[0][c] = std::pow(std::max(result_c[0][c],0.), 4./3) / (std::sqrt(std::max(slope[0][c], 1.e-6)) * nm); } } // communicate and upwind Krel_c->ScatterMasterToGhosted(); hz->ScatterMasterToGhosted(); { Epetra_MultiVector& Krel_uw_vec = *Krel_uw->ViewComponent("face",false); const Epetra_MultiVector& Krel_c_vec = *Krel_c->ViewComponent("cell",true); const Epetra_MultiVector& hz_c = *hz->ViewComponent("cell",true); for (int f=0; f!=nfaces; ++f) { AmanziMesh::Entity_ID_List cells; mesh->face_get_cells(f,AmanziMesh::USED,&cells); if (cells.size() == 1) { Krel_uw_vec[0][f] = Krel_c_vec[0][cells[0]]; } else { if (hz_c[0][cells[0]] > hz_c[0][cells[1]]) { Krel_uw_vec[0][f] = Krel_c_vec[0][cells[0]]; } else { Krel_uw_vec[0][f] = Krel_c_vec[0][cells[1]]; } } } } // Re-assemble Krel_uw->ScatterMasterToGhosted(); matrix_->CreateMFDstiffnessMatrices(Krel_uw.ptr()); matrix_->CreateMFDrhsVectors(); matrix_->ApplyBoundaryConditions(bc_markers, bc_values); matrix_->AssembleGlobalMatrices(); // Apply the operator to get div flux matrix_->ComputeNegativeResidual(*hz, residual.ptr()); if (vo_->os_OK(Teuchos::VERB_EXTREME)) { *vo_->os() << " DIFFUSION RESIDUAL = " << std::endl; residual->Print(*vo_->os()); } // Accumulation { Epetra_MultiVector& residual_c = *residual->ViewComponent("cell",false); const Epetra_MultiVector& result_prev_c = *result_prev->ViewComponent("cell",false); const Epetra_MultiVector& result_c = *result->ViewComponent("cell",false); unsigned int ncells = residual_c.MyLength(); for (unsigned int c=0; c!=ncells; ++c) { residual_c[0][c] += (result_c[0][c] - result_prev_c[0][c]) * cv[0][c] / dt; } } if (vo_->os_OK(Teuchos::VERB_EXTREME)) { *vo_->os() << " ACCUMULATION RESIDUAL = " << std::endl; residual->Print(*vo_->os()); } double norm = 0.; residual->NormInf(&norm); if (ncycle == 0) norm0 = norm; ncycle++; if (vo_->os_OK(Teuchos::VERB_HIGH)) { *vo_->os() << " inner iterate " << ncycle << " has error norm " << norm << std::endl; } if (vo_->os_OK(Teuchos::VERB_EXTREME)) { residual->Print(*vo_->os()); } if ((norm0 == 0.) || (norm / norm0 < tol_) || (ncycle > max_it_)) { done = true; continue; } // Apply the preconditioner matrix_->CreateMFDstiffnessMatrices(Krel_uw.ptr()); matrix_->CreateMFDrhsVectors(); matrix_->ApplyBoundaryConditions(bc_markers, bc_values); { std::vector<double>& Acc_cells = matrix_->Acc_cells(); unsigned int ncells = Acc_cells.size(); for (unsigned int c=0; c!=ncells; ++c) { Acc_cells[c] += cv[0][c] / dt; } } matrix_->AssembleGlobalMatrices(); matrix_->ComputeSchurComplement(bc_markers, bc_values); matrix_->UpdatePreconditioner(); dresult->PutScalar(0.); matrix_linsolve_->ApplyInverse(*residual, *dresult); if (vo_->os_OK(Teuchos::VERB_EXTREME)) { *vo_->os() << " precon'd update = " << std::endl; dresult->Print(*vo_->os()); } // Update result->Update(-1., *dresult, 1.); if (vo_->os_OK(Teuchos::VERB_EXTREME)) { *vo_->os() << " new snow depth = " << std::endl; result->Print(*vo_->os()); } } } // get Q back result->Scale(1./(ktmax_ * kSWE_conv_)); } else { result->PutScalar(0.); } } // This is hopefully never called? void ImplicitSnowDistributionEvaluator::EvaluateFieldPartialDerivative_(const Teuchos::Ptr<State>& S, Key wrt_key, const Teuchos::Ptr<CompositeVector>& results) { ASSERT(0); } void ImplicitSnowDistributionEvaluator::AssembleOperator_(const Teuchos::Ptr<State>& S) { Teuchos::RCP<const AmanziMesh::Mesh> mesh = S->GetMesh(mesh_name_); matrix_ = Operators::CreateMatrixMFD(plist_.sublist("Diffusion"), mesh); matrix_->set_symmetric(true); matrix_->SymbolicAssembleGlobalMatrices(); matrix_->CreateMFDmassMatrices(Teuchos::null); matrix_->InitPreconditioner(); AmanziSolvers::LinearOperatorFactory<CompositeMatrix,CompositeVector,CompositeVectorSpace> fac; matrix_linsolve_ = fac.Create(plist_.sublist("Diffusion Solver"), matrix_); } } //namespace } //namespace } //namespace <commit_msg>tweaks to debugging of snow distribution<commit_after>/* -*- mode: c++; c-default-style: "google"; indent-tabs-mode: nil -*- */ /* Authors: Ethan Coon (ecoon@lanl.gov) */ #include "MatrixMFD.hh" #include "MatrixMFD_Factory.hh" #include "Function.hh" #include "FunctionFactory.hh" #include "implicit_snow_distribution_evaluator.hh" namespace Amanzi { namespace Flow { namespace FlowRelations { ImplicitSnowDistributionEvaluator::ImplicitSnowDistributionEvaluator(Teuchos::ParameterList& plist) : SecondaryVariableFieldEvaluator(plist), assembled_(false) { my_key_ = plist_.get<std::string>("precipitation snow field", "precipitation_snow"); // depenedencies mesh_name_ = plist_.get<std::string>("domain name", "surface"); if (mesh_name_ == "domain") { cell_vol_key_ = "cell_volume"; } else { cell_vol_key_ = mesh_name_+std::string("_cell_volume"); } dependencies_.insert(cell_vol_key_); elev_key_ = plist_.get<std::string>("elevation key", "elevation"); dependencies_.insert(elev_key_); slope_key_ = plist_.get<std::string>("slope key", "slope_magnitude"); dependencies_.insert(slope_key_); pd_key_ = plist_.get<std::string>("ponded depth key", "ponded_depth"); dependencies_.insert(pd_key_); snow_height_key_ = plist_.get<std::string>("snow height key", "snow_depth"); dependencies_.insert(snow_height_key_); // constant parameters kL_ = plist_.get<double>("snow distribution length"); kdx_ = plist_.get<double>("characteristic horizontal grid size", 0.25); ktmax_ = plist_.get<double>("faux integration time", 86400.); kS_ = plist_.get<double>("characteristic slope", 1.); kCFL_ = plist_.get<double>("Courant number", 1.); kSWE_conv_ = plist_.get<double>("SWE-to-snow conversion ratio", 10.); tol_ = plist_.get<double>("solver tolerance", 1.e-2); max_it_ = plist_.get<int>("max iterations", 10); FunctionFactory fac; precip_func_ = Teuchos::rcp(fac.Create(plist_.sublist("precipitation function"))); } ImplicitSnowDistributionEvaluator::ImplicitSnowDistributionEvaluator(const ImplicitSnowDistributionEvaluator& other) : SecondaryVariableFieldEvaluator(other), elev_key_(other.elev_key_), slope_key_(other.slope_key_), pd_key_(other.pd_key_), snow_height_key_(other.snow_height_key_), cell_vol_key_(other.cell_vol_key_), precip_func_(other.precip_func_), kL_(other.kL_), kdx_(other.kdx_), ktmax_(other.ktmax_), kS_(other.kS_), kCFL_(other.kCFL_), kSWE_conv_(other.kSWE_conv_), tol_(other.tol_), max_it_(other.max_it_), assembled_(other.assembled_), mesh_name_(other.mesh_name_), matrix_(other.matrix_) {} void ImplicitSnowDistributionEvaluator::EvaluateField_(const Teuchos::Ptr<State>& S, const Teuchos::Ptr<CompositeVector>& result) { Teuchos::OSTab tab = vo_->getOSTab(); if (!assembled_) AssembleOperator_(S); double time = S->time(); double Qe = (*precip_func_)(&time); double dt_sim = *S->GetScalarData("dt"); // NOTE: snow precip comes in SWE, must convert it to snow depth! if (Qe * dt_sim * kSWE_conv_ > 0.) { // determine scaling of flow const double kV = kL_/ktmax_; double dt = kCFL_ * kdx_ / kV; const double kh0 = Qe * ktmax_ * kSWE_conv_; const double nm = std::pow(kh0, 1./3) * std::sqrt(kS_) / kV; int nsteps = std::ceil(ktmax_ / dt); dt = ktmax_ / nsteps; // scale report if (vo_->os_OK(Teuchos::VERB_MEDIUM)) { *vo_->os() << "Snow Distribution: taking " << nsteps << " steps of size " << dt << " s for travel length " << kL_ << " m." << std::endl << " L = " << kL_ << std::endl << " t_max = " << ktmax_ << std::endl << " V = " << kV << std::endl << " Q = " << kV*kh0 << std::endl << " -------" << std::endl << " h0 = " << kh0 << std::endl << " nm = " << nm << std::endl << " V(man)= " << std::pow(kh0,1./3) * std::sqrt(kS_) / nm << std::endl << " -------" << std::endl; } // Gather mesh entities Teuchos::RCP<const AmanziMesh::Mesh> mesh = S->GetMesh(mesh_name_); int nfaces = mesh->num_entities(AmanziMesh::FACE, AmanziMesh::OWNED); int ncells = mesh->num_entities(AmanziMesh::CELL, AmanziMesh::OWNED); int nfaces_g = mesh->num_entities(AmanziMesh::FACE, AmanziMesh::USED); // Gather null boundary conditions (no flux of snow into or out of domain) std::vector<Operators::MatrixBC> bc_markers(nfaces_g, Operators::MATRIX_BC_NULL); std::vector<double> bc_values(nfaces_g, 0.0); // Create temporary work space // -- not necessarily ghosted workspace Teuchos::RCP<CompositeVector> residual = Teuchos::rcp(new CompositeVector(*result)); Teuchos::RCP<CompositeVector> result_prev = Teuchos::rcp(new CompositeVector(*result)); Teuchos::RCP<CompositeVector> dresult = Teuchos::rcp(new CompositeVector(*result)); // -- necessarily ghosted workspace CompositeVectorSpace ghosted_space(result->Map()); ghosted_space.SetGhosted(); Teuchos::RCP<CompositeVector> hz = Teuchos::rcp(new CompositeVector(ghosted_space)); Teuchos::RCP<CompositeVector> Krel_c = Teuchos::rcp(new CompositeVector(ghosted_space)); CompositeVectorSpace Krel_f_space; Krel_f_space.SetMesh(mesh)->SetGhosted()->SetComponent("face",AmanziMesh::FACE,1); Teuchos::RCP<CompositeVector> Krel_uw = Teuchos::rcp(new CompositeVector(Krel_f_space)); // Gather dependencies // NOTE: this is incorrect approximation... should be | sqrt( grad( z+h_pd ) ) | const Epetra_MultiVector& slope = *S->GetFieldData(slope_key_)->ViewComponent("cell",false); const Epetra_MultiVector& cv = *S->GetFieldData(cell_vol_key_)->ViewComponent("cell",false); Teuchos::RCP<const CompositeVector> elev = S->GetFieldData(elev_key_); Teuchos::RCP<const CompositeVector> pd = S->GetFieldData(pd_key_); Teuchos::RCP<const CompositeVector> snow_height = S->GetFieldData(snow_height_key_); // initialize and begin timestep loop result->PutScalar(Qe * ktmax_ * kSWE_conv_); for (int istep=0; istep!=nsteps; ++istep) { if (vo_->os_OK(Teuchos::VERB_HIGH)) *vo_->os() << "Snow distribution inner timestep " << istep << " with size " << dt << std::endl << " Qe*t_total =" << std::endl; *result_prev = *result; double norm0 = 0.; bool done = false; int ncycle = 0; while(!done) { // update snow potential, z + h_pd + h_s + Qe*dt *hz = *result; hz->Update(1., *elev, 1., *pd, 1.); hz->Update(1., *snow_height, 1.); if (vo_->os_OK(Teuchos::VERB_EXTREME)) { *vo_->os() << " z + h_pd + h_s potential = " << std::endl; hz->Print(*vo_->os()); } // update Krel { Epetra_MultiVector& Krel_c_vec = *Krel_c->ViewComponent("cell",false); const Epetra_MultiVector& result_c = *result->ViewComponent("cell",false); for (int c=0; c!=ncells; ++c) { Krel_c_vec[0][c] = std::pow(std::max(result_c[0][c],0.), 4./3) / (std::sqrt(std::max(slope[0][c], 1.e-6)) * nm); } } // communicate and upwind Krel_c->ScatterMasterToGhosted(); hz->ScatterMasterToGhosted(); { Epetra_MultiVector& Krel_uw_vec = *Krel_uw->ViewComponent("face",false); const Epetra_MultiVector& Krel_c_vec = *Krel_c->ViewComponent("cell",true); const Epetra_MultiVector& hz_c = *hz->ViewComponent("cell",true); for (int f=0; f!=nfaces; ++f) { AmanziMesh::Entity_ID_List cells; mesh->face_get_cells(f,AmanziMesh::USED,&cells); if (cells.size() == 1) { Krel_uw_vec[0][f] = Krel_c_vec[0][cells[0]]; } else { if (hz_c[0][cells[0]] > hz_c[0][cells[1]]) { Krel_uw_vec[0][f] = Krel_c_vec[0][cells[0]]; } else { Krel_uw_vec[0][f] = Krel_c_vec[0][cells[1]]; } } } } // Re-assemble Krel_uw->ScatterMasterToGhosted(); matrix_->CreateMFDstiffnessMatrices(Krel_uw.ptr()); matrix_->CreateMFDrhsVectors(); matrix_->ApplyBoundaryConditions(bc_markers, bc_values); matrix_->AssembleGlobalMatrices(); // Apply the operator to get div flux matrix_->ComputeNegativeResidual(*hz, residual.ptr()); if (vo_->os_OK(Teuchos::VERB_EXTREME)) { *vo_->os() << " DIFFUSION RESIDUAL = " << std::endl; residual->Print(*vo_->os()); } // Accumulation { Epetra_MultiVector& residual_c = *residual->ViewComponent("cell",false); const Epetra_MultiVector& result_prev_c = *result_prev->ViewComponent("cell",false); const Epetra_MultiVector& result_c = *result->ViewComponent("cell",false); unsigned int ncells = residual_c.MyLength(); for (unsigned int c=0; c!=ncells; ++c) { residual_c[0][c] += (result_c[0][c] - result_prev_c[0][c]) * cv[0][c] / dt; } } if (vo_->os_OK(Teuchos::VERB_EXTREME)) { *vo_->os() << " ACCUMULATION RESIDUAL = " << std::endl; residual->Print(*vo_->os()); } double norm = 0.; residual->NormInf(&norm); if (ncycle == 0) norm0 = norm; ncycle++; if (vo_->os_OK(Teuchos::VERB_HIGH)) { *vo_->os() << " inner iterate " << ncycle << " has error norm " << norm << std::endl; } if (vo_->os_OK(Teuchos::VERB_EXTREME)) { residual->Print(*vo_->os()); } if ((norm0 == 0.) || (norm / norm0 < tol_) || (ncycle > max_it_)) { done = true; continue; } // Apply the preconditioner matrix_->CreateMFDstiffnessMatrices(Krel_uw.ptr()); matrix_->CreateMFDrhsVectors(); matrix_->ApplyBoundaryConditions(bc_markers, bc_values); { std::vector<double>& Acc_cells = matrix_->Acc_cells(); unsigned int ncells = Acc_cells.size(); for (unsigned int c=0; c!=ncells; ++c) { Acc_cells[c] += cv[0][c] / dt; } } matrix_->AssembleGlobalMatrices(); matrix_->ComputeSchurComplement(bc_markers, bc_values); matrix_->UpdatePreconditioner(); dresult->PutScalar(0.); matrix_linsolve_->ApplyInverse(*residual, *dresult); if (vo_->os_OK(Teuchos::VERB_EXTREME)) { *vo_->os() << " precon'd update = " << std::endl; dresult->Print(*vo_->os()); } // Update result->Update(-1., *dresult, 1.); if (vo_->os_OK(Teuchos::VERB_EXTREME)) { *vo_->os() << " new snow depth = " << std::endl; result->Print(*vo_->os()); } } } // get Q back result->Scale(1./(ktmax_ * kSWE_conv_)); } else { result->PutScalar(0.); } } // This is hopefully never called? void ImplicitSnowDistributionEvaluator::EvaluateFieldPartialDerivative_(const Teuchos::Ptr<State>& S, Key wrt_key, const Teuchos::Ptr<CompositeVector>& results) { ASSERT(0); } void ImplicitSnowDistributionEvaluator::AssembleOperator_(const Teuchos::Ptr<State>& S) { Teuchos::RCP<const AmanziMesh::Mesh> mesh = S->GetMesh(mesh_name_); matrix_ = Operators::CreateMatrixMFD(plist_.sublist("Diffusion"), mesh); matrix_->set_symmetric(true); matrix_->SymbolicAssembleGlobalMatrices(); matrix_->CreateMFDmassMatrices(Teuchos::null); matrix_->InitPreconditioner(); AmanziSolvers::LinearOperatorFactory<CompositeMatrix,CompositeVector,CompositeVectorSpace> fac; matrix_linsolve_ = fac.Create(plist_.sublist("Diffusion Solver"), matrix_); } } //namespace } //namespace } //namespace <|endoftext|>
<commit_before>#include "stdlibs_for_debugging.h" #include "foobar.h" // TODO (unit test): // - reflection.h, REFLECTABLE(function), namespace::ClassTemplate, namespace::function(ClassTemplate), SmartRef // - also make sure that no invalid free functions are added (e.g. push_back on a vector) #include <smartref/smartref.h> #include <iostream> #include <vector> #include <typeinfo> using namespace std; using namespace foobar; using smartref::using_; template<typename T> class Property : public using_<T> { // TODO: Add proper reference-leaking control by allowing // the user-defined conversion functions to be private. public: using using_<T>::operator=; operator T &() & { return data; } operator T &&() && { return move(data); } operator const T &() const & { return data; } operator const T &&() const && { return move(data); } public: T data; }; /* class JSONValue : public using_<JSONValue, double>, public using_<JSONValue, string>, public using_<JSONValue, vector<JSONValue>>, public using_<JSONValue, map<JSONValue, JSONValue>> { public: operator double &() { return get<double>(data); } operator double &() { return get<string>(data); } operator double &() { return get<vector<JSONValue>>(data); } operator double &() { return get<map<JSONValue, JSONValue>>(data); } private: variant< double, string, vector<JSONValue>, map<JSONValue, JSONValue> > data; }; */ namespace foobar { void asdf(Foo) { cout << "asdf(Foo)" << endl; } void asdf(Derived) { cout << "asdf(Derived)" << endl; } template<typename T> void asdf(ClassTemplate<T>) { cout << "asdf(ClassTemplate<T>)" << endl; } } // namespace foobar namespace foobar2 { struct A {}; struct B {}; template<typename> void qwerty(A) { cout << "foobar2::qwerty<T>(A)" << endl; } template<typename> void qwerty(foobar::ClassTemplate<A>) { cout << "foobar2::qwerty<T>(foobar::ClassTemplate<A>)" << endl; } template<typename, typename U> void qwerty(foobar::ClassTemplate<U>) { cout << "foobar2::qwerty<T>(foobar::ClassTemplate<U>)" << endl; } } // namespace foobar2 // TODO: Move this to fundamental operator support of library REFLECTABLE_OPERATOR_INFIX(+); REFLECTABLE_OPERATOR_ASSIGNMENT(=); int main() { /* JSONValue json = {}; json["asdf"] = 1.0; json[123456] = nullptr; json.DOT(qwerty) = "the other (third) operator dot proposal"; json.qwerty = "__getattr__ for C++"; */ cout << "Hello, Wandbox!" << endl; Property<vector<int>> v; v.push_back(1); v.push_back(2); v.push_back(3); // v.push_back(1, 2, 3); for (auto x : v) { cout << x << endl; } Property<int> x{}; Property<int> y{}; x = 5; cout << x.data << endl; cout << (x = 9) << endl; // TODO: Proper reference leaking control // i.e. {x + y} -> Property<decltype(delegate(x)+delegate(y))> { auto u = x + 1; auto v = 1 + y; auto w = x + y; cout << u << endl; cout << typeid(u).name() << endl; cout << v << endl; cout << typeid(v).name() << endl; cout << w << endl; cout << typeid(w).name() << endl; } Property<Foo> foo; foo.foo(); Property<Bar> bar; bar.bar(); bar.bar2(); bar.bar3(); Property<Baz> baz; baz.baz(); baz.baz2(); Property<Bat> bat; bat.bat(); bat.bat2(); { Bar bar; bar.bar(); bar.bar2(); bar.bar3(); Baz baz; baz.baz(); baz.baz2(); Bat bat; bat.bat(); bat.bat2(); } { Property<Bla> bla; bla.foo(); bla.bar(); auto x = decltype(bla)::baz{1234}; cout << typeid(x).name() << " " << x << endl; auto y = decltype(bla)::bla{}; y.foo(); y.bar(); } { Property<Overloads> o; o.foo(); o.foo(0); o.bar<int>(); } { Property<GenericClassA> a; a.foobar(); a.foobar(1); a.foobar(1.0); static_assert(is_same<decltype(a)::some_type, GenericClassA::some_type>::value); Property<GenericClassB> b; b.foobar(); b.foobar(1); static_assert(is_same<decltype(b)::some_type, GenericClassB::some_type>::value); Property<ClassTemplate<int>> c; c.foobarbaz(); static_assert(is_same<decltype(c)::some_foo_type, ClassTemplate<int>::some_foo_type>::value); Property<ClassTemplate<float>> d; d.foobarbaz(); static_assert(is_same<decltype(d)::some_foo_type, ClassTemplate<float>::some_foo_type>::value); } { Property<ConstClass> non_const_obj; const Property<ConstClass> const_obj; non_const_obj.foo(); // Should compile non_const_obj.bar(); // Should compile const_obj.foo(); // Should compile // const_obj.bar(); // Should not compile } { Property<RefClass> obj; const Property<RefClass> cobj; obj.foo(); // "RefClass::foo() &" move(obj).foo(); // "RefClass::foo() &&" cobj.foo(); // "RefClass::foo() const &" move(cobj).foo(); // "RefClass::foo() const &&" } { Property<Foo> foo; Property<Derived> derived; Property<MoreDerived> moreDerived; Property<ClassTemplate<int>> tmpl; asdf(foo); // "asdf(Foo)" asdf(derived); // "asdf(Derived)" asdf(moreDerived); // "asdf(Derived)" asdf(tmpl); // "asdf(ClassTemplate<T>)" } { foobar2::A tmpl1; ClassTemplate<foobar2::A > tmpl2; ClassTemplate<foobar2::B > tmpl3; Property< foobar2::A > tmpl4; Property<ClassTemplate<foobar2::A>> tmpl5; Property<ClassTemplate<foobar2::B>> tmpl6; using reflectable::qwerty; qwerty<int>(tmpl1); qwerty<int>(tmpl2); qwerty<int>(tmpl3); qwerty<int>(tmpl4); qwerty<int>(tmpl5); qwerty<int>(tmpl6); } } <commit_msg>Added another example of what should *not* compile.<commit_after>#include "stdlibs_for_debugging.h" #include "foobar.h" // TODO (unit test): // - reflection.h, REFLECTABLE(function), namespace::ClassTemplate, namespace::function(ClassTemplate), SmartRef // - also make sure that no invalid free functions are added (e.g. push_back on a vector) #include <smartref/smartref.h> #include <iostream> #include <vector> #include <typeinfo> using namespace std; using namespace foobar; using smartref::using_; template<typename T> class Property : public using_<T> { // TODO: Add proper reference-leaking control by allowing // the user-defined conversion functions to be private. public: using using_<T>::operator=; operator T &() & { return data; } operator T &&() && { return move(data); } operator const T &() const & { return data; } operator const T &&() const && { return move(data); } public: T data; }; /* class JSONValue : public using_<JSONValue, double>, public using_<JSONValue, string>, public using_<JSONValue, vector<JSONValue>>, public using_<JSONValue, map<JSONValue, JSONValue>> { public: operator double &() { return get<double>(data); } operator double &() { return get<string>(data); } operator double &() { return get<vector<JSONValue>>(data); } operator double &() { return get<map<JSONValue, JSONValue>>(data); } private: variant< double, string, vector<JSONValue>, map<JSONValue, JSONValue> > data; }; */ namespace foobar { void asdf(Foo) { cout << "asdf(Foo)" << endl; } void asdf(Derived) { cout << "asdf(Derived)" << endl; } template<typename T> void asdf(ClassTemplate<T>) { cout << "asdf(ClassTemplate<T>)" << endl; } } // namespace foobar namespace foobar2 { struct A {}; struct B {}; template<typename> void qwerty(A) { cout << "foobar2::qwerty<T>(A)" << endl; } template<typename> void qwerty(foobar::ClassTemplate<A>) { cout << "foobar2::qwerty<T>(foobar::ClassTemplate<A>)" << endl; } template<typename, typename U> void qwerty(foobar::ClassTemplate<U>) { cout << "foobar2::qwerty<T>(foobar::ClassTemplate<U>)" << endl; } } // namespace foobar2 // TODO: Move this to fundamental operator support of library REFLECTABLE_OPERATOR_INFIX(+); REFLECTABLE_OPERATOR_ASSIGNMENT(=); int main() { /* JSONValue json = {}; json["asdf"] = 1.0; json[123456] = nullptr; json.DOT(qwerty) = "the other (third) operator dot proposal"; json.qwerty = "__getattr__ for C++"; */ cout << "Hello, Wandbox!" << endl; Property<vector<int>> v; v.push_back(1); v.push_back(2); v.push_back(3); // The following statements should *not* compile // v.push_back(1, 2, 3); // push_back(v, 1); for (auto x : v) { cout << x << endl; } Property<int> x{}; Property<int> y{}; x = 5; cout << x.data << endl; cout << (x = 9) << endl; // TODO: Proper reference leaking control // i.e. {x + y} -> Property<decltype(delegate(x)+delegate(y))> { auto u = x + 1; auto v = 1 + y; auto w = x + y; cout << u << endl; cout << typeid(u).name() << endl; cout << v << endl; cout << typeid(v).name() << endl; cout << w << endl; cout << typeid(w).name() << endl; } Property<Foo> foo; foo.foo(); Property<Bar> bar; bar.bar(); bar.bar2(); bar.bar3(); Property<Baz> baz; baz.baz(); baz.baz2(); Property<Bat> bat; bat.bat(); bat.bat2(); { Bar bar; bar.bar(); bar.bar2(); bar.bar3(); Baz baz; baz.baz(); baz.baz2(); Bat bat; bat.bat(); bat.bat2(); } { Property<Bla> bla; bla.foo(); bla.bar(); auto x = decltype(bla)::baz{1234}; cout << typeid(x).name() << " " << x << endl; auto y = decltype(bla)::bla{}; y.foo(); y.bar(); } { Property<Overloads> o; o.foo(); o.foo(0); o.bar<int>(); } { Property<GenericClassA> a; a.foobar(); a.foobar(1); a.foobar(1.0); static_assert(is_same<decltype(a)::some_type, GenericClassA::some_type>::value); Property<GenericClassB> b; b.foobar(); b.foobar(1); static_assert(is_same<decltype(b)::some_type, GenericClassB::some_type>::value); Property<ClassTemplate<int>> c; c.foobarbaz(); static_assert(is_same<decltype(c)::some_foo_type, ClassTemplate<int>::some_foo_type>::value); Property<ClassTemplate<float>> d; d.foobarbaz(); static_assert(is_same<decltype(d)::some_foo_type, ClassTemplate<float>::some_foo_type>::value); } { Property<ConstClass> non_const_obj; const Property<ConstClass> const_obj; non_const_obj.foo(); // Should compile non_const_obj.bar(); // Should compile const_obj.foo(); // Should compile // const_obj.bar(); // Should not compile } { Property<RefClass> obj; const Property<RefClass> cobj; obj.foo(); // "RefClass::foo() &" move(obj).foo(); // "RefClass::foo() &&" cobj.foo(); // "RefClass::foo() const &" move(cobj).foo(); // "RefClass::foo() const &&" } { Property<Foo> foo; Property<Derived> derived; Property<MoreDerived> moreDerived; Property<ClassTemplate<int>> tmpl; asdf(foo); // "asdf(Foo)" asdf(derived); // "asdf(Derived)" asdf(moreDerived); // "asdf(Derived)" asdf(tmpl); // "asdf(ClassTemplate<T>)" } { foobar2::A tmpl1; ClassTemplate<foobar2::A > tmpl2; ClassTemplate<foobar2::B > tmpl3; Property< foobar2::A > tmpl4; Property<ClassTemplate<foobar2::A>> tmpl5; Property<ClassTemplate<foobar2::B>> tmpl6; using reflectable::qwerty; qwerty<int>(tmpl1); qwerty<int>(tmpl2); qwerty<int>(tmpl3); qwerty<int>(tmpl4); qwerty<int>(tmpl5); qwerty<int>(tmpl6); } } <|endoftext|>
<commit_before>/**************************************************************************** * * Copyright (C) 2019 PX4 Development Team. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name PX4 nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #include <board_config.h> #include <stdint.h> #include <drivers/drv_adc.h> #include <drivers/drv_hrt.h> #include <px4_arch/adc.h> #include <stm32_adc.h> #include <stm32_gpio.h> /* * Register accessors. * For now, no reason not to just use ADC1. */ #define REG(base, _reg) (*(volatile uint32_t *)((base) + (_reg))) #define rSR(base) REG((base), STM32_ADC_SR_OFFSET) #define rCR1(base) REG((base), STM32_ADC_CR1_OFFSET) #define rCR2(base) REG((base), STM32_ADC_CR2_OFFSET) #define rSMPR1(base) REG((base), STM32_ADC_SMPR1_OFFSET) #define rSMPR2(base) REG((base), STM32_ADC_SMPR2_OFFSET) #define rJOFR1(base) REG((base), STM32_ADC_JOFR1_OFFSET) #define rJOFR2(base) REG((base), STM32_ADC_JOFR2_OFFSET) #define rJOFR3(base) REG((base), STM32_ADC_JOFR3_OFFSET) #define rJOFR4(base) REG((base), STM32_ADC_JOFR4_OFFSET) #define rHTR(base) REG((base), STM32_ADC_HTR_OFFSET) #define rLTR(base) REG((base), STM32_ADC_LTR_OFFSET) #define rSQR1(base) REG((base), STM32_ADC_SQR1_OFFSET) #define rSQR2(base) REG((base), STM32_ADC_SQR2_OFFSET) #define rSQR3(base) REG((base), STM32_ADC_SQR3_OFFSET) #define rJSQR(base) REG((base), STM32_ADC_JSQR_OFFSET) #define rJDR1(base) REG((base), STM32_ADC_JDR1_OFFSET) #define rJDR2(base) REG((base), STM32_ADC_JDR2_OFFSET) #define rJDR3(base) REG((base), STM32_ADC_JDR3_OFFSET) #define rJDR4(base) REG((base), STM32_ADC_JDR4_OFFSET) #define rDR(base) REG((base), STM32_ADC_DR_OFFSET) #ifdef STM32_ADC_CCR # define rCCR(base) REG((base), STM32_ADC_CCR_OFFSET) /* Assuming VDC 2.4 - 3.6 */ #define ADC_MAX_FADC 36000000 # if STM32_PCLK2_FREQUENCY/2 <= ADC_MAX_FADC # define ADC_CCR_ADCPRE_DIV ADC_CCR_ADCPRE_DIV2 # elif STM32_PCLK2_FREQUENCY/4 <= ADC_MAX_FADC # define ADC_CCR_ADCPRE_DIV ADC_CCR_ADCPRE_DIV4 # elif STM32_PCLK2_FREQUENCY/6 <= ADC_MAX_FADC # define ADC_CCR_ADCPRE_DIV ADC_CCR_ADCPRE_DIV6 # elif STM32_PCLK2_FREQUENCY/8 <= ADC_MAX_FADC # define ADC_CCR_ADCPRE_DIV ADC_CCR_ADCPRE_DIV8 # else # error "ADC PCLK2 too high - no divisor found " # endif #endif int px4_arch_adc_init(uint32_t base_address) { /* Perform ADC init once per ADC */ static uint32_t once[SYSTEM_ADC_COUNT] {}; uint32_t *free = nullptr; for (uint32_t i = 0; i < SYSTEM_ADC_COUNT; i++) { if (once[i] == base_address) { /* This one was done already */ return OK; } /* Use first free slot */ if (free == nullptr && once[i] == 0) { free = &once[i]; } } if (free == nullptr) { /* ADC misconfigured SYSTEM_ADC_COUNT too small */; PANIC(); } *free = base_address; /* do calibration if supported */ #ifdef ADC_CR2_CAL rCR2(base_address) |= ADC_CR2_CAL; px4_usleep(100); if (rCR2(base_address) & ADC_CR2_CAL) { return -1; } #endif /* arbitrarily configure all channels for 55 cycle sample time */ rSMPR1(base_address) = 0b00000011011011011011011011011011; rSMPR2(base_address) = 0b00011011011011011011011011011011; /* XXX for F2/4, might want to select 12-bit mode? */ rCR1(base_address) = 0; /* enable the temperature sensor / Vrefint channel if supported*/ rCR2(base_address) = #ifdef ADC_CR2_TSVREFE /* enable the temperature sensor in CR2 */ ADC_CR2_TSVREFE | #endif 0; /* Soc have CCR */ #ifdef STM32_ADC_CCR # ifdef ADC_CCR_TSVREFE /* enable temperature sensor in CCR */ rCCR(base_address) = ADC_CCR_TSVREFE | ADC_CCR_ADCPRE_DIV; # else rCCR(base_address) = ADC_CCR_ADCPRE_DIV; # endif #endif /* configure for a single-channel sequence */ rSQR1(base_address) = 0; rSQR2(base_address) = 0; rSQR3(base_address) = 0; /* will be updated with the channel each tick */ /* power-cycle the ADC and turn it on */ rCR2(base_address) &= ~ADC_CR2_ADON; px4_usleep(10); rCR2(base_address) |= ADC_CR2_ADON; px4_usleep(10); rCR2(base_address) |= ADC_CR2_ADON; px4_usleep(10); /* kick off a sample and wait for it to complete */ hrt_abstime now = hrt_absolute_time(); rCR2(base_address) |= ADC_CR2_SWSTART; while (!(rSR(base_address) & ADC_SR_EOC)) { /* don't wait for more than 500us, since that means something broke - should reset here if we see this */ if ((hrt_absolute_time() - now) > 500) { return -1; } } return 0; } void px4_arch_adc_uninit(uint32_t base_address) { // nothing to do } uint32_t px4_arch_adc_sample(uint32_t base_address, unsigned channel) { irqstate_t flags = px4_enter_critical_section(); /* clear any previous EOC */ if (rSR(base_address) & ADC_SR_EOC) { rSR(base_address) &= ~ADC_SR_EOC; } /* run a single conversion right now - should take about 60 cycles (a few microseconds) max */ rSQR3(base_address) = channel; rCR2(base_address) |= ADC_CR2_SWSTART; /* wait for the conversion to complete */ const hrt_abstime now = hrt_absolute_time(); while (!(rSR(base_address) & ADC_SR_EOC)) { /* don't wait for more than 50us, since that means something broke - should reset here if we see this */ if ((hrt_absolute_time() - now) > 50) { px4_leave_critical_section(flags); return UINT32_MAX; } } /* read the result and clear EOC */ uint32_t result = rDR(base_address); px4_leave_critical_section(flags); return result; } float px4_arch_adc_reference_v() { return BOARD_ADC_POS_REF_V; // TODO: provide true vref } uint32_t px4_arch_adc_temp_sensor_mask() { return 1 << 16; } uint32_t px4_arch_adc_dn_fullcount() { return 1 << 12; // 12 bit ADC } <commit_msg>stm32_common:adc read & clear EOC on init<commit_after>/**************************************************************************** * * Copyright (C) 2019 PX4 Development Team. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name PX4 nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #include <board_config.h> #include <stdint.h> #include <drivers/drv_adc.h> #include <drivers/drv_hrt.h> #include <px4_arch/adc.h> #include <stm32_adc.h> #include <stm32_gpio.h> /* * Register accessors. * For now, no reason not to just use ADC1. */ #define REG(base, _reg) (*(volatile uint32_t *)((base) + (_reg))) #define rSR(base) REG((base), STM32_ADC_SR_OFFSET) #define rCR1(base) REG((base), STM32_ADC_CR1_OFFSET) #define rCR2(base) REG((base), STM32_ADC_CR2_OFFSET) #define rSMPR1(base) REG((base), STM32_ADC_SMPR1_OFFSET) #define rSMPR2(base) REG((base), STM32_ADC_SMPR2_OFFSET) #define rJOFR1(base) REG((base), STM32_ADC_JOFR1_OFFSET) #define rJOFR2(base) REG((base), STM32_ADC_JOFR2_OFFSET) #define rJOFR3(base) REG((base), STM32_ADC_JOFR3_OFFSET) #define rJOFR4(base) REG((base), STM32_ADC_JOFR4_OFFSET) #define rHTR(base) REG((base), STM32_ADC_HTR_OFFSET) #define rLTR(base) REG((base), STM32_ADC_LTR_OFFSET) #define rSQR1(base) REG((base), STM32_ADC_SQR1_OFFSET) #define rSQR2(base) REG((base), STM32_ADC_SQR2_OFFSET) #define rSQR3(base) REG((base), STM32_ADC_SQR3_OFFSET) #define rJSQR(base) REG((base), STM32_ADC_JSQR_OFFSET) #define rJDR1(base) REG((base), STM32_ADC_JDR1_OFFSET) #define rJDR2(base) REG((base), STM32_ADC_JDR2_OFFSET) #define rJDR3(base) REG((base), STM32_ADC_JDR3_OFFSET) #define rJDR4(base) REG((base), STM32_ADC_JDR4_OFFSET) #define rDR(base) REG((base), STM32_ADC_DR_OFFSET) #ifdef STM32_ADC_CCR # define rCCR(base) REG((base), STM32_ADC_CCR_OFFSET) /* Assuming VDC 2.4 - 3.6 */ #define ADC_MAX_FADC 36000000 # if STM32_PCLK2_FREQUENCY/2 <= ADC_MAX_FADC # define ADC_CCR_ADCPRE_DIV ADC_CCR_ADCPRE_DIV2 # elif STM32_PCLK2_FREQUENCY/4 <= ADC_MAX_FADC # define ADC_CCR_ADCPRE_DIV ADC_CCR_ADCPRE_DIV4 # elif STM32_PCLK2_FREQUENCY/6 <= ADC_MAX_FADC # define ADC_CCR_ADCPRE_DIV ADC_CCR_ADCPRE_DIV6 # elif STM32_PCLK2_FREQUENCY/8 <= ADC_MAX_FADC # define ADC_CCR_ADCPRE_DIV ADC_CCR_ADCPRE_DIV8 # else # error "ADC PCLK2 too high - no divisor found " # endif #endif int px4_arch_adc_init(uint32_t base_address) { /* Perform ADC init once per ADC */ static uint32_t once[SYSTEM_ADC_COUNT] {}; uint32_t *free = nullptr; for (uint32_t i = 0; i < SYSTEM_ADC_COUNT; i++) { if (once[i] == base_address) { /* This one was done already */ return OK; } /* Use first free slot */ if (free == nullptr && once[i] == 0) { free = &once[i]; } } if (free == nullptr) { /* ADC misconfigured SYSTEM_ADC_COUNT too small */; PANIC(); } *free = base_address; /* do calibration if supported */ #ifdef ADC_CR2_CAL rCR2(base_address) |= ADC_CR2_CAL; px4_usleep(100); if (rCR2(base_address) & ADC_CR2_CAL) { return -1; } #endif /* arbitrarily configure all channels for 55 cycle sample time */ rSMPR1(base_address) = 0b00000011011011011011011011011011; rSMPR2(base_address) = 0b00011011011011011011011011011011; /* XXX for F2/4, might want to select 12-bit mode? */ rCR1(base_address) = 0; /* enable the temperature sensor / Vrefint channel if supported*/ rCR2(base_address) = #ifdef ADC_CR2_TSVREFE /* enable the temperature sensor in CR2 */ ADC_CR2_TSVREFE | #endif 0; /* Soc have CCR */ #ifdef STM32_ADC_CCR # ifdef ADC_CCR_TSVREFE /* enable temperature sensor in CCR */ rCCR(base_address) = ADC_CCR_TSVREFE | ADC_CCR_ADCPRE_DIV; # else rCCR(base_address) = ADC_CCR_ADCPRE_DIV; # endif #endif /* configure for a single-channel sequence */ rSQR1(base_address) = 0; rSQR2(base_address) = 0; rSQR3(base_address) = 0; /* will be updated with the channel each tick */ /* power-cycle the ADC and turn it on */ rCR2(base_address) &= ~ADC_CR2_ADON; px4_usleep(10); rCR2(base_address) |= ADC_CR2_ADON; px4_usleep(10); rCR2(base_address) |= ADC_CR2_ADON; px4_usleep(10); /* kick off a sample and wait for it to complete */ hrt_abstime now = hrt_absolute_time(); rCR2(base_address) |= ADC_CR2_SWSTART; while (!(rSR(base_address) & ADC_SR_EOC)) { /* don't wait for more than 500us, since that means something broke - should reset here if we see this */ if ((hrt_absolute_time() - now) > 500) { return -1; } } /* Read out result, clear EOC */ (void) rDR(base_address); return 0; } void px4_arch_adc_uninit(uint32_t base_address) { // nothing to do } uint32_t px4_arch_adc_sample(uint32_t base_address, unsigned channel) { irqstate_t flags = px4_enter_critical_section(); /* clear any previous EOC */ if (rSR(base_address) & ADC_SR_EOC) { rSR(base_address) &= ~ADC_SR_EOC; } /* run a single conversion right now - should take about 60 cycles (a few microseconds) max */ rSQR3(base_address) = channel; rCR2(base_address) |= ADC_CR2_SWSTART; /* wait for the conversion to complete */ const hrt_abstime now = hrt_absolute_time(); while (!(rSR(base_address) & ADC_SR_EOC)) { /* don't wait for more than 50us, since that means something broke - should reset here if we see this */ if ((hrt_absolute_time() - now) > 50) { px4_leave_critical_section(flags); return UINT32_MAX; } } /* read the result and clear EOC */ uint32_t result = rDR(base_address); px4_leave_critical_section(flags); return result; } float px4_arch_adc_reference_v() { return BOARD_ADC_POS_REF_V; // TODO: provide true vref } uint32_t px4_arch_adc_temp_sensor_mask() { return 1 << 16; } uint32_t px4_arch_adc_dn_fullcount() { return 1 << 12; // 12 bit ADC } <|endoftext|>
<commit_before>// Copyright (c) 2020 The Orbit 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 "LibunwindstackUnwinder.h" #include <unwindstack/Memory.h> #include <unwindstack/Regs.h> #include <unwindstack/RegsX86_64.h> #include <array> #include <cstdint> namespace orbit_linux_tracing { std::unique_ptr<unwindstack::BufferMaps> LibunwindstackUnwinder::ParseMaps( const std::string& maps_buffer) { auto maps = std::make_unique<unwindstack::BufferMaps>(maps_buffer.c_str()); if (!maps->Parse()) { return nullptr; } return maps; } const std::array<size_t, unwindstack::X86_64_REG_LAST> LibunwindstackUnwinder::UNWINDSTACK_REGS_TO_PERF_REGS{ PERF_REG_X86_AX, PERF_REG_X86_DX, PERF_REG_X86_CX, PERF_REG_X86_BX, PERF_REG_X86_SI, PERF_REG_X86_DI, PERF_REG_X86_BP, PERF_REG_X86_SP, PERF_REG_X86_R8, PERF_REG_X86_R9, PERF_REG_X86_R10, PERF_REG_X86_R11, PERF_REG_X86_R12, PERF_REG_X86_R13, PERF_REG_X86_R14, PERF_REG_X86_R15, PERF_REG_X86_IP, }; std::vector<unwindstack::FrameData> LibunwindstackUnwinder::Unwind( unwindstack::Maps* maps, const std::array<uint64_t, PERF_REG_X86_64_MAX>& perf_regs, const void* stack_dump, uint64_t stack_dump_size) { unwindstack::RegsX86_64 regs{}; for (size_t perf_reg = 0; perf_reg < unwindstack::X86_64_REG_LAST; ++perf_reg) { regs[perf_reg] = perf_regs.at(UNWINDSTACK_REGS_TO_PERF_REGS[perf_reg]); } std::shared_ptr<unwindstack::Memory> memory = unwindstack::Memory::CreateOfflineMemory( static_cast<const uint8_t*>(stack_dump), regs[unwindstack::X86_64_REG_RSP], regs[unwindstack::X86_64_REG_RSP] + stack_dump_size); unwindstack::Unwinder unwinder{MAX_FRAMES, maps, &regs, memory}; // Careful: regs are modified. Use regs.Clone() if you need to reuse regs // later. unwinder.Unwind(); // Samples that fall inside a function dynamically-instrumented with // uretprobes often result in unwinding errors when hitting the trampoline // inserted by the uretprobe. Do not treat them as errors as we might want // those callstacks. if (unwinder.LastErrorCode() != 0 && unwinder.frames().back().map_name != "[uprobes]") { #ifndef NDEBUG ERROR("%s at %#016lx", LibunwindstackErrorString(unwinder.LastErrorCode()).c_str(), unwinder.LastErrorAddress()); #endif return {}; } return unwinder.frames(); } } // namespace orbit_linux_tracing <commit_msg>Fix build in debug mode<commit_after>// Copyright (c) 2020 The Orbit 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 "LibunwindstackUnwinder.h" #include <unwindstack/Memory.h> #include <unwindstack/Regs.h> #include <unwindstack/RegsX86_64.h> #include <array> #include <cstdint> #include "OrbitBase/Logging.h" // IWYU pragma: keep namespace orbit_linux_tracing { std::unique_ptr<unwindstack::BufferMaps> LibunwindstackUnwinder::ParseMaps( const std::string& maps_buffer) { auto maps = std::make_unique<unwindstack::BufferMaps>(maps_buffer.c_str()); if (!maps->Parse()) { return nullptr; } return maps; } const std::array<size_t, unwindstack::X86_64_REG_LAST> LibunwindstackUnwinder::UNWINDSTACK_REGS_TO_PERF_REGS{ PERF_REG_X86_AX, PERF_REG_X86_DX, PERF_REG_X86_CX, PERF_REG_X86_BX, PERF_REG_X86_SI, PERF_REG_X86_DI, PERF_REG_X86_BP, PERF_REG_X86_SP, PERF_REG_X86_R8, PERF_REG_X86_R9, PERF_REG_X86_R10, PERF_REG_X86_R11, PERF_REG_X86_R12, PERF_REG_X86_R13, PERF_REG_X86_R14, PERF_REG_X86_R15, PERF_REG_X86_IP, }; std::vector<unwindstack::FrameData> LibunwindstackUnwinder::Unwind( unwindstack::Maps* maps, const std::array<uint64_t, PERF_REG_X86_64_MAX>& perf_regs, const void* stack_dump, uint64_t stack_dump_size) { unwindstack::RegsX86_64 regs{}; for (size_t perf_reg = 0; perf_reg < unwindstack::X86_64_REG_LAST; ++perf_reg) { regs[perf_reg] = perf_regs.at(UNWINDSTACK_REGS_TO_PERF_REGS[perf_reg]); } std::shared_ptr<unwindstack::Memory> memory = unwindstack::Memory::CreateOfflineMemory( static_cast<const uint8_t*>(stack_dump), regs[unwindstack::X86_64_REG_RSP], regs[unwindstack::X86_64_REG_RSP] + stack_dump_size); unwindstack::Unwinder unwinder{MAX_FRAMES, maps, &regs, memory}; // Careful: regs are modified. Use regs.Clone() if you need to reuse regs // later. unwinder.Unwind(); // Samples that fall inside a function dynamically-instrumented with // uretprobes often result in unwinding errors when hitting the trampoline // inserted by the uretprobe. Do not treat them as errors as we might want // those callstacks. if (unwinder.LastErrorCode() != 0 && unwinder.frames().back().map_name != "[uprobes]") { #ifndef NDEBUG ERROR("%s at %#016lx", LibunwindstackErrorString(unwinder.LastErrorCode()).c_str(), unwinder.LastErrorAddress()); #endif return {}; } return unwinder.frames(); } } // namespace orbit_linux_tracing <|endoftext|>
<commit_before>// @(#)root/net:$Id$ // Author: Jan Fiete Grosse-Oetringhaus 28/9/2004 // Jancurova.lucia@cern.ch Slovakia 29/9/2008 /************************************************************************* * Copyright (C) 1995-2008, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // TGridJDL // // // // Abstract base class to generate JDL files for job submission to the // // Grid. // // // // Related classes are TGLiteJDL. // // // ////////////////////////////////////////////////////////////////////////// #include "TGridJDL.h" #include "TObjString.h" #include "Riostream.h" ClassImp(TGridJDL) //______________________________________________________________________________ TGridJDL::~TGridJDL() { // Cleanup. Clear(); } //______________________________________________________________________________ void TGridJDL::Clear(const Option_t*) { // Clears the JDL information. fMap.DeleteAll(); } //______________________________________________________________________________ void TGridJDL::SetValue(const char *key, const char *value) { // Sets a value. If the entry already exists the old one is replaced. TObject *object = fMap.FindObject(TString(key)); TPair *pair = dynamic_cast<TPair*>(object); if (pair) { TObject *oldObject = pair->Key(); if (oldObject) { TObject *oldValue = pair->Value(); fMap.Remove(oldObject); delete oldObject; oldObject = 0; if (oldValue) { delete oldValue; oldValue = 0; } } } fMap.Add(new TObjString(key), new TObjString(value)); } //______________________________________________________________________________ const char *TGridJDL::GetValue(const char *key) { // Returns the value corresponding to the provided key. Return 0 in case // key is not found. if (!key) return 0; TObject *object = fMap.FindObject(TString(key)); if (!object) return 0; TPair *pair = dynamic_cast<TPair*>(object); if (!pair) return 0; TObject *value = pair->Value(); if (!value) return 0; TObjString *string = dynamic_cast<TObjString*>(value); if (!string) return 0; return string->GetString(); } //______________________________________________________________________________ void TGridJDL::SetDescription(const char *key, const char* description) { // Sets a value. If the entry already exists the old one is replaced. TObject *object = fDescriptionMap.FindObject(TString(key)); TPair *pair = dynamic_cast<TPair*>(object); if (pair) { TObject *oldObject = pair->Key(); if (oldObject) { TObject *oldValue = pair->Value(); fDescriptionMap.Remove(oldObject); delete oldObject; oldObject = 0; if (oldValue) { delete oldValue; oldValue = 0; } } } fDescriptionMap.Add(new TObjString(key), new TObjString(description)); } //______________________________________________________________________________ const char *TGridJDL::GetDescription(const char *key) { // Returns the value corresponding to the provided key. Return 0 in case // key is not found. if (!key) return 0; TObject *object = fDescriptionMap.FindObject(TString(key)); if (!object) return 0; TPair *pair = dynamic_cast<TPair*>(object); if (!pair) return 0; TObject *value = pair->Value(); if (!value) return 0; TObjString *string = dynamic_cast<TObjString*>(value); if (!string) return 0; return string->GetString(); } //______________________________________________________________________________ TString TGridJDL::AddQuotes(const char *value) { // Adds quotes to the provided string. // E.g. Value --> "Value" TString temp = TString("\""); temp += value; temp += "\""; return temp; } //______________________________________________________________________________ void TGridJDL::AddToSet(const char *key, const char *value) { // Adds a value to a key value which hosts a set of values. // E.g. InputSandbox: {"file1","file2"} const char *oldValue = GetValue(key); TString newString; if (oldValue) newString = oldValue; if (newString.IsNull()) { newString = "{"; } else { newString.Remove(newString.Length()-1); newString += ","; } newString += AddQuotes(value); newString += "}"; SetValue(key, newString); } //______________________________________________________________________________ void TGridJDL::AddToSetDescription(const char *key, const char *description) { // Adds a value to a key value which hosts a set of values. // E.g. InputSandbox: {"file1","file2"} const char *oldValue = GetDescription(key); TString newString; if (oldValue) newString = oldValue; newString += description; SetDescription(key, newString); } //______________________________________________________________________________ TString TGridJDL::Generate() { // Generates the JDL snippet. TString output(""); TIter next(&fMap); TIter nextDescription(&fDescriptionMap); TObject *object = 0; TObject *objectD = 0; while ((object = next())) { TObjString *key = dynamic_cast<TObjString*>(object); if (key) { TObject *value = fMap.GetValue(object); TObjString *valueobj = dynamic_cast<TObjString*>(value); if (valueobj) { nextDescription.Reset(); while ((objectD = nextDescription())) { TObjString *keyD = dynamic_cast<TObjString*>(objectD); if (keyD) { TObject *valueD = fDescriptionMap.GetValue(objectD); TObjString *valueobjD = dynamic_cast<TObjString*>(valueD); if (!key->GetString().CompareTo(keyD->GetString())){ //Info("",Form("%s %s",key->GetString().Data(),keyD->GetString().Data())); output += "# "; output += valueobjD->GetString(); output += "\n"; } } } output += key->GetString(); output += " = "; output += valueobj->GetString(); output += ";\n\n"; } } } return output; } <commit_msg>fix coverity 11867.<commit_after>// @(#)root/net:$Id$ // Author: Jan Fiete Grosse-Oetringhaus 28/9/2004 // Jancurova.lucia@cern.ch Slovakia 29/9/2008 /************************************************************************* * Copyright (C) 1995-2008, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // TGridJDL // // // // Abstract base class to generate JDL files for job submission to the // // Grid. // // // // Related classes are TGLiteJDL. // // // ////////////////////////////////////////////////////////////////////////// #include "TGridJDL.h" #include "TObjString.h" #include "Riostream.h" ClassImp(TGridJDL) //______________________________________________________________________________ TGridJDL::~TGridJDL() { // Cleanup. Clear(); } //______________________________________________________________________________ void TGridJDL::Clear(const Option_t*) { // Clears the JDL information. fMap.DeleteAll(); } //______________________________________________________________________________ void TGridJDL::SetValue(const char *key, const char *value) { // Sets a value. If the entry already exists the old one is replaced. TObject *object = fMap.FindObject(TString(key)); TPair *pair = dynamic_cast<TPair*>(object); if (pair) { TObject *oldObject = pair->Key(); if (oldObject) { TObject *oldValue = pair->Value(); fMap.Remove(oldObject); delete oldObject; oldObject = 0; if (oldValue) { delete oldValue; oldValue = 0; } } } fMap.Add(new TObjString(key), new TObjString(value)); } //______________________________________________________________________________ const char *TGridJDL::GetValue(const char *key) { // Returns the value corresponding to the provided key. Return 0 in case // key is not found. if (!key) return 0; TObject *object = fMap.FindObject(TString(key)); if (!object) return 0; TPair *pair = dynamic_cast<TPair*>(object); if (!pair) return 0; TObject *value = pair->Value(); if (!value) return 0; TObjString *string = dynamic_cast<TObjString*>(value); if (!string) return 0; return string->GetString(); } //______________________________________________________________________________ void TGridJDL::SetDescription(const char *key, const char* description) { // Sets a value. If the entry already exists the old one is replaced. TObject *object = fDescriptionMap.FindObject(TString(key)); TPair *pair = dynamic_cast<TPair*>(object); if (pair) { TObject *oldObject = pair->Key(); if (oldObject) { TObject *oldValue = pair->Value(); fDescriptionMap.Remove(oldObject); delete oldObject; oldObject = 0; if (oldValue) { delete oldValue; oldValue = 0; } } } fDescriptionMap.Add(new TObjString(key), new TObjString(description)); } //______________________________________________________________________________ const char *TGridJDL::GetDescription(const char *key) { // Returns the value corresponding to the provided key. Return 0 in case // key is not found. if (!key) return 0; TObject *object = fDescriptionMap.FindObject(TString(key)); if (!object) return 0; TPair *pair = dynamic_cast<TPair*>(object); if (!pair) return 0; TObject *value = pair->Value(); if (!value) return 0; TObjString *string = dynamic_cast<TObjString*>(value); if (!string) return 0; return string->GetString(); } //______________________________________________________________________________ TString TGridJDL::AddQuotes(const char *value) { // Adds quotes to the provided string. // E.g. Value --> "Value" TString temp = TString("\""); temp += value; temp += "\""; return temp; } //______________________________________________________________________________ void TGridJDL::AddToSet(const char *key, const char *value) { // Adds a value to a key value which hosts a set of values. // E.g. InputSandbox: {"file1","file2"} const char *oldValue = GetValue(key); TString newString; if (oldValue) newString = oldValue; if (newString.IsNull()) { newString = "{"; } else { newString.Remove(newString.Length()-1); newString += ","; } newString += AddQuotes(value); newString += "}"; SetValue(key, newString); } //______________________________________________________________________________ void TGridJDL::AddToSetDescription(const char *key, const char *description) { // Adds a value to a key value which hosts a set of values. // E.g. InputSandbox: {"file1","file2"} const char *oldValue = GetDescription(key); TString newString; if (oldValue) newString = oldValue; newString += description; SetDescription(key, newString); } //______________________________________________________________________________ TString TGridJDL::Generate() { // Generates the JDL snippet. TString output(""); TIter next(&fMap); TIter nextDescription(&fDescriptionMap); TObject *object = 0; TObject *objectD = 0; while ((object = next())) { TObjString *key = dynamic_cast<TObjString*>(object); if (key) { TObject *value = fMap.GetValue(object); TObjString *valueobj = dynamic_cast<TObjString*>(value); if (valueobj) { nextDescription.Reset(); while ((objectD = nextDescription())) { TObjString *keyD = dynamic_cast<TObjString*>(objectD); if (keyD) { TObject *valueD = fDescriptionMap.GetValue(objectD); TObjString *valueobjD = dynamic_cast<TObjString*>(valueD); if (valueobjD && !key->GetString().CompareTo(keyD->GetString())){ //Info("",Form("%s %s",key->GetString().Data(),keyD->GetString().Data())); output += "# "; output += valueobjD->GetString(); output += "\n"; } } } output += key->GetString(); output += " = "; output += valueobj->GetString(); output += ";\n\n"; } } } return output; } <|endoftext|>
<commit_before>#include "Application.hpp" #include "GraphicsService.hpp" #include "SoundService.hpp" #include "TimeService.hpp" #include "Global.hpp" #include "MainMenuState.hpp" #include "PlayGameState.hpp" #include "Log.hpp" namespace Game { Application::Application() { LOGI("Application::Aplication"); } Application::~Application() { LOGI("Application::~Application"); } Core::Status Application::onActivate() { LOGI("Application::onActivate"); // Starts services. if (Global::pContext->pGraphicsService->Start() != Core::STATUS_OK) { LOGE("Application::onActivate failed to start graphics service"); return Core::STATUS_KO; } if (Global::pContext->pSoundService->Start() != Core::STATUS_OK) { LOGE("Application::onActivate failed to start sound service"); return Core::STATUS_KO; } Global::pContext->pSoundService->PlayBGMPlaylist("@playlist.txt"); Global::pContext->pTimeService->Reset(); m_pGameState = new MainMenu; return Core::STATUS_OK; } void Application::onDeactivate() { LOGI("Application::onDeactivate"); Global::pContext->pGraphicsService->Stop(); Global::pContext->pSoundService->Stop(); delete m_pGameState; } Core::Status Application::onStep() { // Updates services. Debug::InitFrame(); Global::pContext->pTimeService->Update(); Global::pContext->pGraphicsService->Update(); int action=m_pGameState->Update(); switch(action) { case EVENT_MAINMENU_NEWGAME: delete m_pGameState; m_pGameState=new PlayGame; m_pGameState->Update(); break; case EVENT_MAINMENU_HIGHSCORE: break; case EVENT_MAINMENU_CREDITS: break; case EVENT_MAINMENU_EXIT: return STATUS_KO; break; case EVENT_PLAYGAME_EXIT: delete m_pGameState; m_pGameState=new MainMenu; m_pGameState->Update(); break; } m_pGameState->Render(); //Debug Messages here static GLfloat time=0.0f; time+=Global::pContext->pTimeService->Elapsed(); Debug::Print(Global::pFont,"Elapsed time: %f",time); if (Global::pContext->pGraphicsService->Render() != Core::STATUS_OK) { return Core::STATUS_KO; } return Core::STATUS_OK; } void Application::onStart() { LOGI("Application::onStart"); } void Application::onResume() { LOGI("Application::onResume"); } void Application::onPause() { LOGI("Application::onPause"); } void Application::onStop() { LOGI("Application::onStop"); } void Application::onDestroy() { LOGI("Application::onDestroy"); } void Application::onSaveState(void** pData, size_t* pSize) { LOGI("Application::onSaveInstanceState"); } void Application::onConfigurationChanged() { LOGI("Application::onConfigurationChanged"); } void Application::onLowMemory() { LOGI("Application::onLowMemory"); LOGW("Please buy a better device!"); } void Application::onCreateWindow() { LOGI("Application::onCreateWindow"); } void Application::onDestroyWindow() { LOGI("Application::onDestroyWindow"); } void Application::onGainFocus() { LOGI("Application::onGainFocus"); } void Application::onLostFocus() { LOGI("Application::onLostFocus"); } } <commit_msg>PhysicsService is updated every frame from Application::onStep<commit_after>#include "Application.hpp" #include "GraphicsService.hpp" #include "SoundService.hpp" #include "TimeService.hpp" #include "Global.hpp" #include "MainMenuState.hpp" #include "PlayGameState.hpp" #include "Log.hpp" namespace Game { Application::Application() { LOGI("Application::Aplication"); } Application::~Application() { LOGI("Application::~Application"); } Core::Status Application::onActivate() { LOGI("Application::onActivate"); // Starts services. if (Global::pContext->pGraphicsService->Start() != Core::STATUS_OK) { LOGE("Application::onActivate failed to start graphics service"); return Core::STATUS_KO; } if (Global::pContext->pSoundService->Start() != Core::STATUS_OK) { LOGE("Application::onActivate failed to start sound service"); return Core::STATUS_KO; } Global::pContext->pSoundService->PlayBGMPlaylist("@playlist.txt"); Global::pContext->pTimeService->Reset(); m_pGameState = new MainMenu; return Core::STATUS_OK; } void Application::onDeactivate() { LOGI("Application::onDeactivate"); Global::pContext->pGraphicsService->Stop(); Global::pContext->pSoundService->Stop(); delete m_pGameState; } Core::Status Application::onStep() { // Updates services. Debug::InitFrame(); Global::pContext->pTimeService->Update(); Global::pContext->pGraphicsService->Update(); Global::pContext->pPhysicsService->Update(); int action=m_pGameState->Update(); switch(action) { case EVENT_MAINMENU_NEWGAME: delete m_pGameState; m_pGameState=new PlayGame; m_pGameState->Update(); break; case EVENT_MAINMENU_HIGHSCORE: break; case EVENT_MAINMENU_CREDITS: break; case EVENT_MAINMENU_EXIT: return STATUS_KO; break; case EVENT_PLAYGAME_EXIT: delete m_pGameState; m_pGameState=new MainMenu; m_pGameState->Update(); break; } m_pGameState->Render(); //Debug Messages here static GLfloat time=0.0f; time+=Global::pContext->pTimeService->Elapsed(); Debug::Print(Global::pFont,"Elapsed time: %f",time); if (Global::pContext->pGraphicsService->Render() != Core::STATUS_OK) { return Core::STATUS_KO; } return Core::STATUS_OK; } void Application::onStart() { LOGI("Application::onStart"); } void Application::onResume() { LOGI("Application::onResume"); } void Application::onPause() { LOGI("Application::onPause"); } void Application::onStop() { LOGI("Application::onStop"); } void Application::onDestroy() { LOGI("Application::onDestroy"); } void Application::onSaveState(void** pData, size_t* pSize) { LOGI("Application::onSaveInstanceState"); } void Application::onConfigurationChanged() { LOGI("Application::onConfigurationChanged"); } void Application::onLowMemory() { LOGI("Application::onLowMemory"); LOGW("Please buy a better device!"); } void Application::onCreateWindow() { LOGI("Application::onCreateWindow"); } void Application::onDestroyWindow() { LOGI("Application::onDestroyWindow"); } void Application::onGainFocus() { LOGI("Application::onGainFocus"); } void Application::onLostFocus() { LOGI("Application::onLostFocus"); } } <|endoftext|>
<commit_before>/************************************************************************************ ** * @copyright (c) 2013-2100, ChengDu Duyer Technology Co., LTD. All Right Reserved. * *************************************************************************************/ /** * @file g_client_factory.cpp * @version * @brief * @author duye * @date 2014-10-12 * @note * * 1. 2014-10-12 duye Created this file * */ #include <g_client_factory.h> <commit_msg>Update g_client_factory.cpp<commit_after>/************************************************************************************ ** * @copyright (c) 2013-2100, ChengDu Duyer Technology Co., LTD. All Right Reserved. * *************************************************************************************/ /** * @file g_client_factory.cpp * @version * @brief * @author duye * @date 2014-10-12 * @note * * 1. 2014-10-12 duye Created this file * */ #include <g_client_factory.h> ClientFactory::ClientFactory() {} ClientFactory::~ClientFactory() {} NetworkClient* ClientFactory::createClient(const ClientType& client_type) { NetworkClient* client = nullptr; switch (client_type) { case CLIENT_FTP: { client = new FtpClient; break; } case CLIENT_HTTP: { client = new HttpClient; break; } case CLIENT_RPC: { client = new RpcClient; break; } case CLIENT_TCP: { client = new TcpClient; break; } case CLIENT_UDP: { client = new UdpClient; break; } case CLIENT_CLI: { client = new CliClient; break; } default: break; } return client; } void ClientFactory::destroyClient(const ClientType& client_type, NetworkClient* client) { switch (client_type) { case CLIENT_FTP: { FtpClient* del_client = dynamic_cast<FtpClient*>client; delete del_client; break; } case CLIENT_HTTP: { HttpClient* del_client = dynamic_cast<HttpClient*>client; delete del_client; break; } case CLIENT_RPC: { RpcClient* del_client = dynamic_cast<RpcClient*>client; delete del_client; break; } case CLIENT_TCP: { TcpClient* del_client = dynamic_cast<TcpClient*>client; delete del_client; break; } case CLIENT_UDP: { UdpClient* del_client = dynamic_cast<UdpClient*>client; delete del_client; break; } case CLIENT_CLI: { CliClient* del_client = dynamic_cast<CliClient*>client; delete del_client; break; } default: break; } } <|endoftext|>
<commit_before>// *************************************************************************** // // Generated automatically by genwrapper. // Please DO NOT EDIT this file! // // *************************************************************************** #include <osgIntrospection/ReflectionMacros> #include <osgIntrospection/TypedMethodInfo> #include <osgIntrospection/StaticMethodInfo> #include <osgIntrospection/Attributes> #include <osg/Array> #include <osg/BoundingBox> #include <osg/CopyOp> #include <osg/Object> #include <osg/PrimitiveSet> #include <osg/RenderInfo> #include <osgTerrain/GeometryTechnique> #include <osgUtil/CullVisitor> #include <osgUtil/UpdateVisitor> // Must undefine IN and OUT macros defined in Windows headers #ifdef IN #undef IN #endif #ifdef OUT #undef OUT #endif BEGIN_OBJECT_REFLECTOR(osgTerrain::GeometryTechnique) I_DeclaringFile("osgTerrain/GeometryTechnique"); I_BaseType(osgTerrain::TerrainTechnique); I_Constructor0(____GeometryTechnique, "", ""); I_ConstructorWithDefaults2(IN, const osgTerrain::GeometryTechnique &, x, , IN, const osg::CopyOp &, copyop, osg::CopyOp::SHALLOW_COPY, ____GeometryTechnique__C5_GeometryTechnique_R1__C5_osg_CopyOp_R1, "Copy constructor using CopyOp to manage deep vs shallow copy. ", ""); I_Method0(void, init, Properties::VIRTUAL, __void__init, "", ""); I_Method1(void, update, IN, osgUtil::UpdateVisitor *, nv, Properties::VIRTUAL, __void__update__osgUtil_UpdateVisitor_P1, "", ""); I_Method1(void, cull, IN, osgUtil::CullVisitor *, nv, Properties::VIRTUAL, __void__cull__osgUtil_CullVisitor_P1, "", ""); I_Method0(void, cleanSceneGraph, Properties::VIRTUAL, __void__cleanSceneGraph, "Clean scene graph from any terrain technique specific nodes. ", ""); I_Method0(void, dirty, Properties::VIRTUAL, __void__dirty, "Dirty so that cached data structurese will be updated on next use. ", ""); END_REFLECTOR BEGIN_OBJECT_REFLECTOR(osgTerrain::TerrainGeometry) I_DeclaringFile("osgTerrain/GeometryTechnique"); I_BaseType(osg::Drawable); I_Constructor0(____TerrainGeometry, "", ""); I_ConstructorWithDefaults2(IN, const osgTerrain::TerrainGeometry &, geometry, , IN, const osg::CopyOp &, copyop, osg::CopyOp::SHALLOW_COPY, ____TerrainGeometry__C5_TerrainGeometry_R1__C5_osg_CopyOp_R1, "Copy constructor using CopyOp to manage deep vs shallow copy. ", ""); I_Method0(osg::Object *, cloneType, Properties::VIRTUAL, __osg_Object_P1__cloneType, "Clone the type of an object, with Object* return type. ", "Must be defined by derived classes. "); I_Method1(osg::Object *, clone, IN, const osg::CopyOp &, copyop, Properties::VIRTUAL, __osg_Object_P1__clone__C5_osg_CopyOp_R1, "Clone an object, with Object* return type. ", "Must be defined by derived classes. "); I_Method1(bool, isSameKindAs, IN, const osg::Object *, obj, Properties::VIRTUAL, __bool__isSameKindAs__C5_osg_Object_P1, "", ""); I_Method0(const char *, libraryName, Properties::VIRTUAL, __C5_char_P1__libraryName, "return the name of the object's library. ", "Must be defined by derived classes. The OpenSceneGraph convention is that the namespace of a library is the same as the library name. "); I_Method0(const char *, className, Properties::VIRTUAL, __C5_char_P1__className, "return the name of the object's class type. ", "Must be defined by derived classes. "); I_Method1(void, setVertices, IN, osg::Vec3Array *, vertices, Properties::NON_VIRTUAL, __void__setVertices__osg_Vec3Array_P1, "", ""); I_Method0(osg::Vec3Array *, getVertices, Properties::NON_VIRTUAL, __osg_Vec3Array_P1__getVertices, "", ""); I_Method0(const osg::Vec3Array *, getVertices, Properties::NON_VIRTUAL, __C5_osg_Vec3Array_P1__getVertices, "", ""); I_Method1(void, setNormals, IN, osg::Vec3Array *, normals, Properties::NON_VIRTUAL, __void__setNormals__osg_Vec3Array_P1, "", ""); I_Method0(osg::Vec3Array *, getNormals, Properties::NON_VIRTUAL, __osg_Vec3Array_P1__getNormals, "", ""); I_Method0(const osg::Vec3Array *, getNormals, Properties::NON_VIRTUAL, __C5_osg_Vec3Array_P1__getNormals, "", ""); I_Method1(void, setColors, IN, osg::Vec4Array *, colors, Properties::NON_VIRTUAL, __void__setColors__osg_Vec4Array_P1, "", ""); I_Method0(osg::Vec4Array *, getColors, Properties::NON_VIRTUAL, __osg_Vec4Array_P1__getColors, "", ""); I_Method0(const osg::Vec4Array *, getColors, Properties::NON_VIRTUAL, __C5_osg_Vec4Array_P1__getColors, "", ""); I_Method2(void, setTexCoords, IN, unsigned int, unit, IN, osg::Array *, array, Properties::NON_VIRTUAL, __void__setTexCoords__unsigned_int__osg_Array_P1, "", ""); I_Method1(osg::Array *, getTexCoords, IN, unsigned int, unit, Properties::NON_VIRTUAL, __osg_Array_P1__getTexCoords__unsigned_int, "", ""); I_Method1(const osg::Array *, getTexCoords, IN, unsigned int, unit, Properties::NON_VIRTUAL, __C5_osg_Array_P1__getTexCoords__unsigned_int, "", ""); I_Method1(void, addPrimitiveSet, IN, osg::PrimitiveSet *, primitiveSet, Properties::NON_VIRTUAL, __void__addPrimitiveSet__osg_PrimitiveSet_P1, "", ""); I_Method1(osg::PrimitiveSet *, getPrimtitiveSet, IN, unsigned int, i, Properties::NON_VIRTUAL, __osg_PrimitiveSet_P1__getPrimtitiveSet__unsigned_int, "", ""); I_Method1(const osg::PrimitiveSet *, getPrimtitiveSet, IN, unsigned int, i, Properties::NON_VIRTUAL, __C5_osg_PrimitiveSet_P1__getPrimtitiveSet__unsigned_int, "", ""); I_Method0(unsigned int, getNumPrimitiveSets, Properties::NON_VIRTUAL, __unsigned_int__getNumPrimitiveSets, "", ""); I_Method0(osg::BoundingBox, computeBound, Properties::VIRTUAL, __osg_BoundingBox__computeBound, "Compute the bounding box around Drawables's geometry. ", ""); I_Method1(void, drawImplementation, IN, osg::RenderInfo &, renderInfo, Properties::VIRTUAL, __void__drawImplementation__osg_RenderInfo_R1, "Draw Geometry directly ignoring an OpenGL display list which could be attached. ", "This is the internal draw method which does the drawing itself, and is the method to override when deriving from Geometry for user-drawn objects."); I_SimpleProperty(osg::Vec4Array *, Colors, __osg_Vec4Array_P1__getColors, __void__setColors__osg_Vec4Array_P1); I_SimpleProperty(osg::Vec3Array *, Normals, __osg_Vec3Array_P1__getNormals, __void__setNormals__osg_Vec3Array_P1); I_IndexedProperty(osg::Array *, TexCoords, __osg_Array_P1__getTexCoords__unsigned_int, __void__setTexCoords__unsigned_int__osg_Array_P1, 0); I_SimpleProperty(osg::Vec3Array *, Vertices, __osg_Vec3Array_P1__getVertices, __void__setVertices__osg_Vec3Array_P1); END_REFLECTOR <commit_msg>Updated wrappers<commit_after>// *************************************************************************** // // Generated automatically by genwrapper. // Please DO NOT EDIT this file! // // *************************************************************************** #include <osgIntrospection/ReflectionMacros> #include <osgIntrospection/TypedMethodInfo> #include <osgIntrospection/StaticMethodInfo> #include <osgIntrospection/Attributes> #include <osg/Array> #include <osg/BoundingBox> #include <osg/CopyOp> #include <osg/Object> #include <osg/PrimitiveSet> #include <osg/RenderInfo> #include <osg/Uniform> #include <osgTerrain/GeometryTechnique> #include <osgUtil/CullVisitor> #include <osgUtil/UpdateVisitor> // Must undefine IN and OUT macros defined in Windows headers #ifdef IN #undef IN #endif #ifdef OUT #undef OUT #endif BEGIN_ENUM_REFLECTOR(osgTerrain::GeometryTechnique::FilterType) I_DeclaringFile("osgTerrain/GeometryTechnique"); I_EnumLabel(osgTerrain::GeometryTechnique::GAUSSIAN); I_EnumLabel(osgTerrain::GeometryTechnique::SMOOTH); I_EnumLabel(osgTerrain::GeometryTechnique::SHARPEN); END_REFLECTOR BEGIN_OBJECT_REFLECTOR(osgTerrain::GeometryTechnique) I_DeclaringFile("osgTerrain/GeometryTechnique"); I_BaseType(osgTerrain::TerrainTechnique); I_Constructor0(____GeometryTechnique, "", ""); I_ConstructorWithDefaults2(IN, const osgTerrain::GeometryTechnique &, x, , IN, const osg::CopyOp &, copyop, osg::CopyOp::SHALLOW_COPY, ____GeometryTechnique__C5_GeometryTechnique_R1__C5_osg_CopyOp_R1, "Copy constructor using CopyOp to manage deep vs shallow copy. ", ""); I_Method0(void, init, Properties::VIRTUAL, __void__init, "", ""); I_Method1(void, update, IN, osgUtil::UpdateVisitor *, nv, Properties::VIRTUAL, __void__update__osgUtil_UpdateVisitor_P1, "", ""); I_Method1(void, cull, IN, osgUtil::CullVisitor *, nv, Properties::VIRTUAL, __void__cull__osgUtil_CullVisitor_P1, "", ""); I_Method0(void, cleanSceneGraph, Properties::VIRTUAL, __void__cleanSceneGraph, "Clean scene graph from any terrain technique specific nodes. ", ""); I_Method0(void, dirty, Properties::VIRTUAL, __void__dirty, "Dirty so that cached data structurese will be updated on next use. ", ""); I_Method1(void, setFilterBias, IN, float, filterBias, Properties::NON_VIRTUAL, __void__setFilterBias__float, "", ""); I_Method0(float, getFilterBias, Properties::NON_VIRTUAL, __float__getFilterBias, "", ""); I_Method1(void, setFilterWidth, IN, float, filterWidth, Properties::NON_VIRTUAL, __void__setFilterWidth__float, "", ""); I_Method0(float, getFilterWidth, Properties::NON_VIRTUAL, __float__getFilterWidth, "", ""); I_Method1(void, setFilterMatrix, IN, const osg::Matrix3 &, matrix, Properties::NON_VIRTUAL, __void__setFilterMatrix__C5_osg_Matrix3_R1, "", ""); I_Method0(osg::Matrix3 &, getFilterMatrix, Properties::NON_VIRTUAL, __osg_Matrix3_R1__getFilterMatrix, "", ""); I_Method0(const osg::Matrix3 &, getFilterMatrix, Properties::NON_VIRTUAL, __C5_osg_Matrix3_R1__getFilterMatrix, "", ""); I_Method1(void, setFilterMatrixAs, IN, osgTerrain::GeometryTechnique::FilterType, filterType, Properties::NON_VIRTUAL, __void__setFilterMatrixAs__FilterType, "", ""); I_SimpleProperty(float, FilterBias, __float__getFilterBias, __void__setFilterBias__float); I_SimpleProperty(const osg::Matrix3 &, FilterMatrix, __C5_osg_Matrix3_R1__getFilterMatrix, __void__setFilterMatrix__C5_osg_Matrix3_R1); I_SimpleProperty(osgTerrain::GeometryTechnique::FilterType, FilterMatrixAs, 0, __void__setFilterMatrixAs__FilterType); I_SimpleProperty(float, FilterWidth, __float__getFilterWidth, __void__setFilterWidth__float); END_REFLECTOR BEGIN_OBJECT_REFLECTOR(osgTerrain::TerrainGeometry) I_DeclaringFile("osgTerrain/GeometryTechnique"); I_BaseType(osg::Drawable); I_Constructor0(____TerrainGeometry, "", ""); I_ConstructorWithDefaults2(IN, const osgTerrain::TerrainGeometry &, geometry, , IN, const osg::CopyOp &, copyop, osg::CopyOp::SHALLOW_COPY, ____TerrainGeometry__C5_TerrainGeometry_R1__C5_osg_CopyOp_R1, "Copy constructor using CopyOp to manage deep vs shallow copy. ", ""); I_Method0(osg::Object *, cloneType, Properties::VIRTUAL, __osg_Object_P1__cloneType, "Clone the type of an object, with Object* return type. ", "Must be defined by derived classes. "); I_Method1(osg::Object *, clone, IN, const osg::CopyOp &, copyop, Properties::VIRTUAL, __osg_Object_P1__clone__C5_osg_CopyOp_R1, "Clone an object, with Object* return type. ", "Must be defined by derived classes. "); I_Method1(bool, isSameKindAs, IN, const osg::Object *, obj, Properties::VIRTUAL, __bool__isSameKindAs__C5_osg_Object_P1, "", ""); I_Method0(const char *, libraryName, Properties::VIRTUAL, __C5_char_P1__libraryName, "return the name of the object's library. ", "Must be defined by derived classes. The OpenSceneGraph convention is that the namespace of a library is the same as the library name. "); I_Method0(const char *, className, Properties::VIRTUAL, __C5_char_P1__className, "return the name of the object's class type. ", "Must be defined by derived classes. "); I_Method1(void, setVertices, IN, osg::Vec3Array *, vertices, Properties::NON_VIRTUAL, __void__setVertices__osg_Vec3Array_P1, "", ""); I_Method0(osg::Vec3Array *, getVertices, Properties::NON_VIRTUAL, __osg_Vec3Array_P1__getVertices, "", ""); I_Method0(const osg::Vec3Array *, getVertices, Properties::NON_VIRTUAL, __C5_osg_Vec3Array_P1__getVertices, "", ""); I_Method1(void, setNormals, IN, osg::Vec3Array *, normals, Properties::NON_VIRTUAL, __void__setNormals__osg_Vec3Array_P1, "", ""); I_Method0(osg::Vec3Array *, getNormals, Properties::NON_VIRTUAL, __osg_Vec3Array_P1__getNormals, "", ""); I_Method0(const osg::Vec3Array *, getNormals, Properties::NON_VIRTUAL, __C5_osg_Vec3Array_P1__getNormals, "", ""); I_Method1(void, setColors, IN, osg::Vec4Array *, colors, Properties::NON_VIRTUAL, __void__setColors__osg_Vec4Array_P1, "", ""); I_Method0(osg::Vec4Array *, getColors, Properties::NON_VIRTUAL, __osg_Vec4Array_P1__getColors, "", ""); I_Method0(const osg::Vec4Array *, getColors, Properties::NON_VIRTUAL, __C5_osg_Vec4Array_P1__getColors, "", ""); I_Method2(void, setTexCoords, IN, unsigned int, unit, IN, osg::Array *, array, Properties::NON_VIRTUAL, __void__setTexCoords__unsigned_int__osg_Array_P1, "", ""); I_Method1(osg::Array *, getTexCoords, IN, unsigned int, unit, Properties::NON_VIRTUAL, __osg_Array_P1__getTexCoords__unsigned_int, "", ""); I_Method1(const osg::Array *, getTexCoords, IN, unsigned int, unit, Properties::NON_VIRTUAL, __C5_osg_Array_P1__getTexCoords__unsigned_int, "", ""); I_Method1(void, addPrimitiveSet, IN, osg::PrimitiveSet *, primitiveSet, Properties::NON_VIRTUAL, __void__addPrimitiveSet__osg_PrimitiveSet_P1, "", ""); I_Method1(osg::PrimitiveSet *, getPrimtitiveSet, IN, unsigned int, i, Properties::NON_VIRTUAL, __osg_PrimitiveSet_P1__getPrimtitiveSet__unsigned_int, "", ""); I_Method1(const osg::PrimitiveSet *, getPrimtitiveSet, IN, unsigned int, i, Properties::NON_VIRTUAL, __C5_osg_PrimitiveSet_P1__getPrimtitiveSet__unsigned_int, "", ""); I_Method0(unsigned int, getNumPrimitiveSets, Properties::NON_VIRTUAL, __unsigned_int__getNumPrimitiveSets, "", ""); I_Method0(osg::BoundingBox, computeBound, Properties::VIRTUAL, __osg_BoundingBox__computeBound, "Compute the bounding box around Drawables's geometry. ", ""); I_Method1(void, drawImplementation, IN, osg::RenderInfo &, renderInfo, Properties::VIRTUAL, __void__drawImplementation__osg_RenderInfo_R1, "Draw Geometry directly ignoring an OpenGL display list which could be attached. ", "This is the internal draw method which does the drawing itself, and is the method to override when deriving from Geometry for user-drawn objects."); I_SimpleProperty(osg::Vec4Array *, Colors, __osg_Vec4Array_P1__getColors, __void__setColors__osg_Vec4Array_P1); I_SimpleProperty(osg::Vec3Array *, Normals, __osg_Vec3Array_P1__getNormals, __void__setNormals__osg_Vec3Array_P1); I_IndexedProperty(osg::Array *, TexCoords, __osg_Array_P1__getTexCoords__unsigned_int, __void__setTexCoords__unsigned_int__osg_Array_P1, 0); I_SimpleProperty(osg::Vec3Array *, Vertices, __osg_Vec3Array_P1__getVertices, __void__setVertices__osg_Vec3Array_P1); END_REFLECTOR <|endoftext|>
<commit_before>// @(#)root/net:$Id$ // Author: Fons Rademakers 19/12/96 /************************************************************************* * 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. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // TMessage // // // // Message buffer class used for serializing objects and sending them // // over a network. This class inherits from TBuffer the basic I/O // // serializer. // // // ////////////////////////////////////////////////////////////////////////// #include "TMessage.h" #include "Bytes.h" #include "TFile.h" extern "C" void R__zip (Int_t cxlevel, Int_t *nin, char *bufin, Int_t *lout, char *bufout, Int_t *nout); extern "C" void R__unzip(Int_t *nin, UChar_t *bufin, Int_t *lout, char *bufout, Int_t *nout); const Int_t kMAXBUF = 0xffffff; ClassImp(TMessage) //______________________________________________________________________________ TMessage::TMessage(UInt_t what) : TBufferFile(TBuffer::kWrite) { // Create a TMessage object for storing objects. The "what" integer // describes the type of message. Predifined ROOT system message types // can be found in MessageTypes.h. Make sure your own message types are // unique from the ROOT defined message types (i.e. 0 - 10000 are // reserved by ROOT). In case you OR "what" with kMESS_ACK, the message // will wait for an acknowledgement from the remote side. This makes // the sending process synchronous. In case you OR "what" with kMESS_ZIP, // the message will be compressed in TSocket using the zip algorithm // (only if message is > 256 bytes). // space at the beginning of the message reserved for the message length UInt_t reserved = 0; *this << reserved; fWhat = what; *this << what; fClass = 0; fCompress = 0; fBufComp = 0; fBufCompCur = 0; fCompPos = 0; } //______________________________________________________________________________ TMessage::TMessage(void *buf, Int_t bufsize) : TBufferFile(TBuffer::kRead, bufsize, buf) { // Create a TMessage object for reading objects. The objects will be // read from buf. Use the What() method to get the message type. // skip space at the beginning of the message reserved for the message length fBufCur += sizeof(UInt_t); *this >> fWhat; fCompress = 0; fBufComp = 0; fBufCompCur = 0; fCompPos = 0; if (fWhat & kMESS_ZIP) { // if buffer has kMESS_ZIP set, move it to fBufComp and uncompress fBufComp = fBuffer; fBufCompCur = fBuffer + bufsize; fBuffer = 0; Uncompress(); } if (fWhat == kMESS_OBJECT) { InitMap(); fClass = ReadClass(); // get first the class stored in message SetBufferOffset(sizeof(UInt_t) + sizeof(fWhat)); ResetMap(); } else { fClass = 0; } } //______________________________________________________________________________ TMessage::~TMessage() { // Clean up compression buffer. delete [] fBufComp; } //______________________________________________________________________________ void TMessage::Forward() { // Change a buffer that was received into one that can be send, i.e. // forward a just received message. if (IsReading()) { SetWriteMode(); SetBufferOffset(fBufSize); if (fBufComp) { fCompPos = fBufCur; } } } //______________________________________________________________________________ void TMessage::Reset() { // Reset the message buffer so we can use (i.e. fill) it again. SetBufferOffset(sizeof(UInt_t) + sizeof(fWhat)); ResetMap(); if (fBufComp) { delete [] fBufComp; fBufComp = 0; fBufCompCur = 0; fCompPos = 0; } } //______________________________________________________________________________ void TMessage::SetLength() const { // Set the message length at the beginning of the message buffer. // This method is only called by TSocket::Send(). if (IsWriting()) { char *buf = Buffer(); tobuf(buf, (UInt_t)(Length() - sizeof(UInt_t))); if (fBufComp) { buf = fBufComp; tobuf(buf, (UInt_t)(CompLength() - sizeof(UInt_t))); } } } //______________________________________________________________________________ void TMessage::SetWhat(UInt_t what) { // Using this method one can change the message type a-posteriory. // In case you OR "what" with kMESS_ACK, the message will wait for // an acknowledgement from the remote side. This makes the sending // process synchronous. fWhat = what; char *buf = Buffer(); buf += sizeof(UInt_t); // skip reserved length space tobuf(buf, what); if (fBufComp) { buf = fBufComp; buf += sizeof(UInt_t); // skip reserved length space tobuf(buf, what | kMESS_ZIP); } } //______________________________________________________________________________ void TMessage::SetCompressionLevel(Int_t level) { // Set the message compression level. Can be between 0 and 9 with 0 // being no compression and 9 maximum compression. In general the default // level of 1 is the best compromise between achieved compression and // cpu time. Compression will only happen when the message is > 256 bytes. if (level < 0) level = 0; if (level > 9) level = 9; if (level != fCompress && fBufComp) { delete [] fBufComp; fBufComp = 0; fBufCompCur = 0; fCompPos = 0; } fCompress = level; } //______________________________________________________________________________ Int_t TMessage::Compress() { // Compress the message. The message will only be compressed if the // compression level > 0 and the if the message is > 256 bytes. // Returns -1 in case of error (when compression fails or // when the message increases in size in some pathological cases), // otherwise returns 0. if (fCompress == 0) { // no compression specified if (fBufComp) { delete [] fBufComp; fBufComp = 0; fBufCompCur = 0; fCompPos = 0; } return 0; } if (fBufComp && fCompPos == fBufCur) { // the message was already compressed return 0; } // remove any existing compressed buffer before compressing modified message if (fBufComp) { delete [] fBufComp; fBufComp = 0; fBufCompCur = 0; fCompPos = 0; } if (Length() <= (Int_t)(256 + 2*sizeof(UInt_t))) { // this message is too small to be compressed return 0; } Int_t hdrlen = 2*sizeof(UInt_t); Int_t messlen = Length() - hdrlen; Int_t nbuffers = messlen / kMAXBUF; Int_t chdrlen = 3*sizeof(UInt_t); // compressed buffer header length Int_t buflen = TMath::Max(512, chdrlen + messlen + 9*nbuffers); fBufComp = new char[buflen]; char *messbuf = Buffer() + hdrlen; char *bufcur = fBufComp + chdrlen; Int_t noutot = 0; Int_t nzip = 0; Int_t nout, bufmax; for (Int_t i = 0; i <= nbuffers; i++) { if (i == nbuffers) bufmax = messlen - nzip; else bufmax = kMAXBUF; R__zip(fCompress, &bufmax, messbuf, &bufmax, bufcur, &nout); if (nout == 0 || nout >= messlen) { //this happens when the buffer cannot be compressed delete [] fBufComp; fBufComp = 0; fBufCompCur = 0; fCompPos = 0; return -1; } bufcur += nout; noutot += nout; messbuf += kMAXBUF; nzip += kMAXBUF; } fBufCompCur = bufcur; fCompPos = fBufCur; bufcur = fBufComp; tobuf(bufcur, (UInt_t)(CompLength() - sizeof(UInt_t))); Int_t what = fWhat | kMESS_ZIP; tobuf(bufcur, what); tobuf(bufcur, Length()); // original uncompressed buffer length return 0; } //______________________________________________________________________________ Int_t TMessage::Uncompress() { // Uncompress the message. The message will only be uncompressed when // kMESS_ZIP is set. Returns -1 in case of error, 0 otherwise. if (!fBufComp || !(fWhat & kMESS_ZIP)) return -1; Int_t buflen; Int_t hdrlen = 2*sizeof(UInt_t); char *bufcur = fBufComp + hdrlen; frombuf(bufcur, &buflen); fBuffer = new char[buflen]; fBufSize = buflen; fBufCur = fBuffer + sizeof(UInt_t) + sizeof(fWhat); fBufMax = fBuffer + fBufSize; char *messbuf = fBuffer + hdrlen; Int_t nin, nout, nbuf; Int_t noutot = 0; while (1) { nin = 9 + ((Int_t)bufcur[3] | ((Int_t)bufcur[4] << 8) | ((Int_t)bufcur[5] << 16)); nbuf = (Int_t)bufcur[6] | ((Int_t)bufcur[7] << 8) | ((Int_t)bufcur[8] << 16); R__unzip(&nin, (UChar_t*)bufcur, &nbuf, messbuf, &nout); if (!nout) break; noutot += nout; if (noutot >= buflen - hdrlen) break; bufcur += nin; messbuf += nout; } fWhat &= ~kMESS_ZIP; fCompress = 1; return 0; } <commit_msg>compressed buffer should be of UChar_t type to be able to correctly extract in and output buffer lenghts.<commit_after>// @(#)root/net:$Id$ // Author: Fons Rademakers 19/12/96 /************************************************************************* * 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. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // TMessage // // // // Message buffer class used for serializing objects and sending them // // over a network. This class inherits from TBuffer the basic I/O // // serializer. // // // ////////////////////////////////////////////////////////////////////////// #include "TMessage.h" #include "Bytes.h" #include "TFile.h" extern "C" void R__zip (Int_t cxlevel, Int_t *nin, char *bufin, Int_t *lout, char *bufout, Int_t *nout); extern "C" void R__unzip(Int_t *nin, UChar_t *bufin, Int_t *lout, char *bufout, Int_t *nout); const Int_t kMAXBUF = 0xffffff; ClassImp(TMessage) //______________________________________________________________________________ TMessage::TMessage(UInt_t what) : TBufferFile(TBuffer::kWrite) { // Create a TMessage object for storing objects. The "what" integer // describes the type of message. Predifined ROOT system message types // can be found in MessageTypes.h. Make sure your own message types are // unique from the ROOT defined message types (i.e. 0 - 10000 are // reserved by ROOT). In case you OR "what" with kMESS_ACK, the message // will wait for an acknowledgement from the remote side. This makes // the sending process synchronous. In case you OR "what" with kMESS_ZIP, // the message will be compressed in TSocket using the zip algorithm // (only if message is > 256 bytes). // space at the beginning of the message reserved for the message length UInt_t reserved = 0; *this << reserved; fWhat = what; *this << what; fClass = 0; fCompress = 0; fBufComp = 0; fBufCompCur = 0; fCompPos = 0; } //______________________________________________________________________________ TMessage::TMessage(void *buf, Int_t bufsize) : TBufferFile(TBuffer::kRead, bufsize, buf) { // Create a TMessage object for reading objects. The objects will be // read from buf. Use the What() method to get the message type. // skip space at the beginning of the message reserved for the message length fBufCur += sizeof(UInt_t); *this >> fWhat; fCompress = 0; fBufComp = 0; fBufCompCur = 0; fCompPos = 0; if (fWhat & kMESS_ZIP) { // if buffer has kMESS_ZIP set, move it to fBufComp and uncompress fBufComp = fBuffer; fBufCompCur = fBuffer + bufsize; fBuffer = 0; Uncompress(); } if (fWhat == kMESS_OBJECT) { InitMap(); fClass = ReadClass(); // get first the class stored in message SetBufferOffset(sizeof(UInt_t) + sizeof(fWhat)); ResetMap(); } else { fClass = 0; } } //______________________________________________________________________________ TMessage::~TMessage() { // Clean up compression buffer. delete [] fBufComp; } //______________________________________________________________________________ void TMessage::Forward() { // Change a buffer that was received into one that can be send, i.e. // forward a just received message. if (IsReading()) { SetWriteMode(); SetBufferOffset(fBufSize); if (fBufComp) { fCompPos = fBufCur; } } } //______________________________________________________________________________ void TMessage::Reset() { // Reset the message buffer so we can use (i.e. fill) it again. SetBufferOffset(sizeof(UInt_t) + sizeof(fWhat)); ResetMap(); if (fBufComp) { delete [] fBufComp; fBufComp = 0; fBufCompCur = 0; fCompPos = 0; } } //______________________________________________________________________________ void TMessage::SetLength() const { // Set the message length at the beginning of the message buffer. // This method is only called by TSocket::Send(). if (IsWriting()) { char *buf = Buffer(); tobuf(buf, (UInt_t)(Length() - sizeof(UInt_t))); if (fBufComp) { buf = fBufComp; tobuf(buf, (UInt_t)(CompLength() - sizeof(UInt_t))); } } } //______________________________________________________________________________ void TMessage::SetWhat(UInt_t what) { // Using this method one can change the message type a-posteriory. // In case you OR "what" with kMESS_ACK, the message will wait for // an acknowledgement from the remote side. This makes the sending // process synchronous. fWhat = what; char *buf = Buffer(); buf += sizeof(UInt_t); // skip reserved length space tobuf(buf, what); if (fBufComp) { buf = fBufComp; buf += sizeof(UInt_t); // skip reserved length space tobuf(buf, what | kMESS_ZIP); } } //______________________________________________________________________________ void TMessage::SetCompressionLevel(Int_t level) { // Set the message compression level. Can be between 0 and 9 with 0 // being no compression and 9 maximum compression. In general the default // level of 1 is the best compromise between achieved compression and // cpu time. Compression will only happen when the message is > 256 bytes. if (level < 0) level = 0; if (level > 9) level = 9; if (level != fCompress && fBufComp) { delete [] fBufComp; fBufComp = 0; fBufCompCur = 0; fCompPos = 0; } fCompress = level; } //______________________________________________________________________________ Int_t TMessage::Compress() { // Compress the message. The message will only be compressed if the // compression level > 0 and the if the message is > 256 bytes. // Returns -1 in case of error (when compression fails or // when the message increases in size in some pathological cases), // otherwise returns 0. if (fCompress == 0) { // no compression specified if (fBufComp) { delete [] fBufComp; fBufComp = 0; fBufCompCur = 0; fCompPos = 0; } return 0; } if (fBufComp && fCompPos == fBufCur) { // the message was already compressed return 0; } // remove any existing compressed buffer before compressing modified message if (fBufComp) { delete [] fBufComp; fBufComp = 0; fBufCompCur = 0; fCompPos = 0; } if (Length() <= (Int_t)(256 + 2*sizeof(UInt_t))) { // this message is too small to be compressed return 0; } Int_t hdrlen = 2*sizeof(UInt_t); Int_t messlen = Length() - hdrlen; Int_t nbuffers = messlen / kMAXBUF; Int_t chdrlen = 3*sizeof(UInt_t); // compressed buffer header length Int_t buflen = TMath::Max(512, chdrlen + messlen + 9*nbuffers); fBufComp = new char[buflen]; char *messbuf = Buffer() + hdrlen; char *bufcur = fBufComp + chdrlen; Int_t noutot = 0; Int_t nzip = 0; Int_t nout, bufmax; for (Int_t i = 0; i <= nbuffers; i++) { if (i == nbuffers) bufmax = messlen - nzip; else bufmax = kMAXBUF; R__zip(fCompress, &bufmax, messbuf, &bufmax, bufcur, &nout); if (nout == 0 || nout >= messlen) { //this happens when the buffer cannot be compressed delete [] fBufComp; fBufComp = 0; fBufCompCur = 0; fCompPos = 0; return -1; } bufcur += nout; noutot += nout; messbuf += kMAXBUF; nzip += kMAXBUF; } fBufCompCur = bufcur; fCompPos = fBufCur; bufcur = fBufComp; tobuf(bufcur, (UInt_t)(CompLength() - sizeof(UInt_t))); Int_t what = fWhat | kMESS_ZIP; tobuf(bufcur, what); tobuf(bufcur, Length()); // original uncompressed buffer length return 0; } //______________________________________________________________________________ Int_t TMessage::Uncompress() { // Uncompress the message. The message will only be uncompressed when // kMESS_ZIP is set. Returns -1 in case of error, 0 otherwise. if (!fBufComp || !(fWhat & kMESS_ZIP)) return -1; Int_t buflen; Int_t hdrlen = 2*sizeof(UInt_t); UChar_t *bufcur = (UChar_t*)(fBufComp + hdrlen); frombuf((char*&)bufcur, &buflen); fBuffer = new char[buflen]; fBufSize = buflen; fBufCur = fBuffer + sizeof(UInt_t) + sizeof(fWhat); fBufMax = fBuffer + fBufSize; char *messbuf = fBuffer + hdrlen; Int_t nin, nout, nbuf; Int_t noutot = 0; while (1) { nin = 9 + ((Int_t)bufcur[3] | ((Int_t)bufcur[4] << 8) | ((Int_t)bufcur[5] << 16)); nbuf = (Int_t)bufcur[6] | ((Int_t)bufcur[7] << 8) | ((Int_t)bufcur[8] << 16); R__unzip(&nin, bufcur, &nbuf, messbuf, &nout); if (!nout) break; noutot += nout; if (noutot >= buflen - hdrlen) break; bufcur += nin; messbuf += nout; } fWhat &= ~kMESS_ZIP; fCompress = 1; return 0; } <|endoftext|>
<commit_before>#include "stdafx.h" #include "common/RhoPort.h" #include "common/StringConverter.h" #include "ruby/ext/rho/rhoruby.h" #include "MainWindow.h" #ifdef OS_WINCE__ #include <tapi.h> #include <tsp.h> //#include <sms.h> #endif using namespace rho; using namespace rho::common; extern "C" HWND getMainWnd(); extern "C" char* wce_wctomb(const wchar_t* w); extern "C" { #ifdef OS_WINCE__ static const int PHONE_NUMBER_BUFFER_SIZE = 512; bool getPhoneNumFromSIMCard (String &number) { #define EXIT_ON_NULL(_p) if (_p == NULL){ hr = E_OUTOFMEMORY; goto FuncExit; } #define EXIT_ON_FALSE(_f) if (!(_f)) { hr = E_FAIL; goto FuncExit; } #define MAX(i, j) ((i) > (j) ? (i) : (j)) const int TAPI_API_LOW_VERSION = 0x00020000; const int TAPI_API_HIGH_VERSION = 0x00020000; const int LINE_NUMBER = 1; HRESULT hr = E_FAIL; LRESULT lResult = 0; HLINEAPP hLineApp; DWORD dwNumDevs; DWORD dwAPIVersion = TAPI_API_HIGH_VERSION; LINEINITIALIZEEXPARAMS liep; DWORD dwTAPILineDeviceID; const DWORD dwAddressID = LINE_NUMBER - 1; liep.dwTotalSize = sizeof(liep); liep.dwOptions = LINEINITIALIZEEXOPTION_USEEVENT; if (SUCCEEDED(lineInitializeEx(&hLineApp, 0, 0, TEXT("ExTapi_Lib"), &dwNumDevs, &dwAPIVersion, &liep))) { BYTE* pCapBuf = NULL; DWORD dwCapBufSize = PHONE_NUMBER_BUFFER_SIZE; LINEEXTENSIONID LineExtensionID; LINEDEVCAPS* pLineDevCaps = NULL; LINEADDRESSCAPS* placAddressCaps = NULL; pCapBuf = new BYTE[dwCapBufSize]; EXIT_ON_NULL(pCapBuf); pLineDevCaps = (LINEDEVCAPS*)pCapBuf; pLineDevCaps->dwTotalSize = dwCapBufSize; // Get TSP Line Device ID dwTAPILineDeviceID = 0xffffffff; for (DWORD dwCurrentDevID = 0 ; dwCurrentDevID < dwNumDevs ; dwCurrentDevID++) { if (0 == lineNegotiateAPIVersion(hLineApp, dwCurrentDevID, TAPI_API_LOW_VERSION, TAPI_API_HIGH_VERSION, &dwAPIVersion, &LineExtensionID)) { lResult = lineGetDevCaps(hLineApp, dwCurrentDevID, dwAPIVersion, 0, pLineDevCaps); if (dwCapBufSize < pLineDevCaps->dwNeededSize) { delete[] pCapBuf; dwCapBufSize = pLineDevCaps->dwNeededSize; pCapBuf = new BYTE[dwCapBufSize]; EXIT_ON_NULL(pCapBuf); pLineDevCaps = (LINEDEVCAPS*)pCapBuf; pLineDevCaps->dwTotalSize = dwCapBufSize; lResult = lineGetDevCaps(hLineApp, dwCurrentDevID, dwAPIVersion, 0, pLineDevCaps); } if ((0 == lResult) && (0 == _tcscmp((TCHAR*)((BYTE*)pLineDevCaps+pLineDevCaps->dwLineNameOffset), CELLTSP_LINENAME_STRING))) { dwTAPILineDeviceID = dwCurrentDevID; break; } } } placAddressCaps = (LINEADDRESSCAPS*)pCapBuf; placAddressCaps->dwTotalSize = dwCapBufSize; lResult = lineGetAddressCaps(hLineApp, dwTAPILineDeviceID, dwAddressID, dwAPIVersion, 0, placAddressCaps); if (dwCapBufSize < placAddressCaps->dwNeededSize) { delete[] pCapBuf; dwCapBufSize = placAddressCaps->dwNeededSize; pCapBuf = new BYTE[dwCapBufSize]; EXIT_ON_NULL(pCapBuf); placAddressCaps = (LINEADDRESSCAPS*)pCapBuf; placAddressCaps->dwTotalSize = dwCapBufSize; lResult = lineGetAddressCaps(hLineApp, dwTAPILineDeviceID, dwAddressID, dwAPIVersion, 0, placAddressCaps); } if (0 == lResult) { EXIT_ON_FALSE(0 != placAddressCaps->dwAddressSize); // A non-zero dwAddressSize means a phone number was found ASSERT(0 != placAddressCaps->dwAddressOffset); PWCHAR tsAddress = (WCHAR*)(((BYTE*)placAddressCaps)+placAddressCaps->dwAddressOffset); number = convertToStringA (tsAddress); hr = S_OK; } delete[] pCapBuf; } // End if () FuncExit: lineShutdown(hLineApp); if (hr != S_OK) { LOG(ERROR) + "failed to get phone number from SIM"; return false; } return true; #undef EXIT_ON_NULL #undef EXIT_ON_FALSE #undef MAX } /* bool getPhoneNumFromSMSBearer (String &number) { SMS_ADDRESS psmsaAddress; if (SmsGetPhoneNumber (&psmsaAddress) != S_OK) { LOG(ERROR) + "failed to get phone number using SMS bearer"; return false; } number = convertToStringA(psmsaAddress.ptsAddress); return true; } */ bool getPhoneNumFromOwnerInfo (String &number) { HKEY hKey; DWORD dwType, dwCount = PHONE_NUMBER_BUFFER_SIZE; TCHAR strValue [PHONE_NUMBER_BUFFER_SIZE]; LONG res; TCHAR errMsg[1024]; if ((res = RegOpenKeyEx(HKEY_CURRENT_USER, TEXT("ControlPanel\\Owner"), NULL, KEY_EXECUTE , &hKey)) == 0) { if ((res = RegQueryValueEx (hKey, TEXT("Telephone"), NULL, &dwType, (LPBYTE )strValue, &dwCount)) == 0) { if (dwType != REG_SZ) { LOG(ERROR) + "Settings/Owner Information/Telephone has invalid type"; RegCloseKey(hKey); return false; } if (dwCount > 0) { strValue[dwCount + 1] = '\0'; if (_tcslen((strValue)) == 0) { LOG(INFO) + "Settings/Owner Information/Telephone is empty"; RegCloseKey(hKey); return false; } number = convertToStringA(strValue); RegCloseKey(hKey); return true; } } } RegCloseKey(hKey); FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM, 0, GetLastError(), 0, errMsg, sizeof(errMsg), NULL); LOG(ERROR) + errMsg; return false; } VALUE phone_number() { String number; if (getPhoneNumFromSIMCard(number)) return rho_ruby_create_string(number.c_str()); // if (getPhoneNumFromSMSBearer(number)) // return rho_ruby_create_string(number.c_str()); if (getPhoneNumFromOwnerInfo(number)) return rho_ruby_create_string(number.c_str()); return rho_ruby_get_NIL(); } #else VALUE phone_number() { return rho_ruby_get_NIL(); } #endif static int has_camera() { #ifdef OS_WINCE /* DEVMGR_DEVICE_INFORMATION devInfo = {0}; GUID guidCamera = { 0xCB998A05, 0x122C, 0x4166, 0x84, 0x6A, 0x93, 0x3E, 0x4D, 0x7E, 0x3C, 0x86 }; devInfo.dwSize = sizeof(devInfo); HANDLE hDevice = FindFirstDevice( DeviceSearchByGuid, &guidCamera, &devInfo); if ( hDevice != INVALID_HANDLE_VALUE ) { FindClose(hDevice); return 1; } return 0;*/ return 1; #else return 0; #endif } static double get_screen_ppi_x() { HWND hWndDesktop = GetDesktopWindow(); HDC hdcDesktop = GetDC(hWndDesktop); int mms = GetDeviceCaps(hdcDesktop, HORZSIZE); int pixels = GetDeviceCaps(hdcDesktop, HORZRES); double ret = (pixels*25.4)/mms; return ret; } static double get_screen_ppi_y() { HWND hWndDesktop = GetDesktopWindow(); HDC hdcDesktop = GetDC(hWndDesktop); int mms = GetDeviceCaps(hdcDesktop, VERTSIZE); int pixels = GetDeviceCaps(hdcDesktop, VERTRES); double ret = (pixels*25.4)/mms; return ret; } VALUE rho_sys_get_locale() { wchar_t szLang[20]; int nRes = GetLocaleInfo(LOCALE_USER_DEFAULT,LOCALE_SABBREVLANGNAME , szLang, sizeof(szLang)/sizeof(szLang[0])); szLang[2] = 0; wcslwr(szLang); return rho_ruby_create_string(convertToStringA(szLang).c_str()); } int rho_sysimpl_get_property(char* szPropName, VALUE* resValue) { if (strcasecmp("has_camera",szPropName) == 0) {*resValue = rho_ruby_create_boolean(has_camera()); return 1;} if (strcasecmp("phone_number",szPropName) == 0) {*resValue = phone_number();return 1;} if (strcasecmp("ppi_x",szPropName) == 0) {*resValue = rho_ruby_create_double(get_screen_ppi_x()); return 1;} if (strcasecmp("ppi_y",szPropName) == 0) {*resValue = rho_ruby_create_double(get_screen_ppi_y()); return 1; } if (strcasecmp("locale",szPropName) == 0) {*resValue = rho_sys_get_locale(); return 1;} if (strcasecmp("country",szPropName) == 0) { wchar_t szCountry[20]; int nRes = GetLocaleInfo(LOCALE_USER_DEFAULT,LOCALE_SISO3166CTRYNAME , szCountry, sizeof(szCountry)/sizeof(szCountry[0])); szCountry[2] = 0; *resValue = rho_ruby_create_string(convertToStringA(szCountry).c_str()); return 1; } if (strcasecmp("device_name",szPropName) == 0) { #ifdef OS_WINDOWS *resValue = rho_ruby_create_string("Win32"); #else HKEY hKey; if (RegOpenKeyEx( HKEY_LOCAL_MACHINE, _T("Ident"), 0, KEY_READ, &hKey ) != ERROR_SUCCESS) return 0; DWORD dwType = REG_SZ; DWORD dwDataSize = 0; if ( RegQueryValueEx( hKey, _T("name"), 0, &dwType, (PBYTE)NULL, &dwDataSize ) != ERROR_SUCCESS) return 0; std::vector<wchar_t> deviceName(dwDataSize + 1); RegQueryValueEx( hKey, _T("name"), 0, &dwType, (PBYTE)&deviceName[0], &dwDataSize ); char *s = wce_wctomb(&deviceName[0]); *resValue = rho_ruby_create_string(s); ::free(s); RegCloseKey(hKey); return 1; #endif } if (strcasecmp("os_version",szPropName) == 0) { OSVERSIONINFO osv; osv.dwOSVersionInfoSize = sizeof(osv); if (!GetVersionEx(&osv)) return 0; char buf[50]; buf[sizeof(buf) - 1] = '\0'; snprintf(buf, sizeof(buf) - 1, "%u.%u.%u", (unsigned)osv.dwMajorVersion, (unsigned)osv.dwMinorVersion, (unsigned)osv.dwBuildNumber); *resValue = rho_ruby_create_string(&buf[0]); return 1; } return 0; } int rho_sys_get_screen_width() { #ifdef OS_WINCE return GetSystemMetrics(SM_CXSCREEN); #else return CMainWindow::getScreenWidth(); #endif } int rho_sys_get_screen_height() { #ifdef OS_WINCE return GetSystemMetrics(SM_CYSCREEN); #else return CMainWindow::getScreenHeight(); #endif } VALUE rho_sys_makephonecall(const char* callname, int nparams, char** param_names, char** param_values) { return rho_ruby_get_NIL(); } static int g_rho_has_network = 1; void rho_sysimpl_sethas_network(int nValue) { g_rho_has_network = nValue; } VALUE rho_sys_has_network() { return rho_ruby_create_boolean(g_rho_has_network!=0); } void rho_sys_app_exit() { ::PostMessage(getMainWnd(), WM_COMMAND, MAKEWPARAM(IDM_EXIT,0), (LPARAM )0); } } //extern "C" <commit_msg>fix system property device_name<commit_after>#include "stdafx.h" #include "common/RhoPort.h" #include "common/StringConverter.h" #include "ruby/ext/rho/rhoruby.h" #include "MainWindow.h" #ifdef OS_WINCE__ #include <tapi.h> #include <tsp.h> //#include <sms.h> #endif using namespace rho; using namespace rho::common; extern "C" HWND getMainWnd(); extern "C" char* wce_wctomb(const wchar_t* w); extern "C" { #ifdef OS_WINCE__ static const int PHONE_NUMBER_BUFFER_SIZE = 512; bool getPhoneNumFromSIMCard (String &number) { #define EXIT_ON_NULL(_p) if (_p == NULL){ hr = E_OUTOFMEMORY; goto FuncExit; } #define EXIT_ON_FALSE(_f) if (!(_f)) { hr = E_FAIL; goto FuncExit; } #define MAX(i, j) ((i) > (j) ? (i) : (j)) const int TAPI_API_LOW_VERSION = 0x00020000; const int TAPI_API_HIGH_VERSION = 0x00020000; const int LINE_NUMBER = 1; HRESULT hr = E_FAIL; LRESULT lResult = 0; HLINEAPP hLineApp; DWORD dwNumDevs; DWORD dwAPIVersion = TAPI_API_HIGH_VERSION; LINEINITIALIZEEXPARAMS liep; DWORD dwTAPILineDeviceID; const DWORD dwAddressID = LINE_NUMBER - 1; liep.dwTotalSize = sizeof(liep); liep.dwOptions = LINEINITIALIZEEXOPTION_USEEVENT; if (SUCCEEDED(lineInitializeEx(&hLineApp, 0, 0, TEXT("ExTapi_Lib"), &dwNumDevs, &dwAPIVersion, &liep))) { BYTE* pCapBuf = NULL; DWORD dwCapBufSize = PHONE_NUMBER_BUFFER_SIZE; LINEEXTENSIONID LineExtensionID; LINEDEVCAPS* pLineDevCaps = NULL; LINEADDRESSCAPS* placAddressCaps = NULL; pCapBuf = new BYTE[dwCapBufSize]; EXIT_ON_NULL(pCapBuf); pLineDevCaps = (LINEDEVCAPS*)pCapBuf; pLineDevCaps->dwTotalSize = dwCapBufSize; // Get TSP Line Device ID dwTAPILineDeviceID = 0xffffffff; for (DWORD dwCurrentDevID = 0 ; dwCurrentDevID < dwNumDevs ; dwCurrentDevID++) { if (0 == lineNegotiateAPIVersion(hLineApp, dwCurrentDevID, TAPI_API_LOW_VERSION, TAPI_API_HIGH_VERSION, &dwAPIVersion, &LineExtensionID)) { lResult = lineGetDevCaps(hLineApp, dwCurrentDevID, dwAPIVersion, 0, pLineDevCaps); if (dwCapBufSize < pLineDevCaps->dwNeededSize) { delete[] pCapBuf; dwCapBufSize = pLineDevCaps->dwNeededSize; pCapBuf = new BYTE[dwCapBufSize]; EXIT_ON_NULL(pCapBuf); pLineDevCaps = (LINEDEVCAPS*)pCapBuf; pLineDevCaps->dwTotalSize = dwCapBufSize; lResult = lineGetDevCaps(hLineApp, dwCurrentDevID, dwAPIVersion, 0, pLineDevCaps); } if ((0 == lResult) && (0 == _tcscmp((TCHAR*)((BYTE*)pLineDevCaps+pLineDevCaps->dwLineNameOffset), CELLTSP_LINENAME_STRING))) { dwTAPILineDeviceID = dwCurrentDevID; break; } } } placAddressCaps = (LINEADDRESSCAPS*)pCapBuf; placAddressCaps->dwTotalSize = dwCapBufSize; lResult = lineGetAddressCaps(hLineApp, dwTAPILineDeviceID, dwAddressID, dwAPIVersion, 0, placAddressCaps); if (dwCapBufSize < placAddressCaps->dwNeededSize) { delete[] pCapBuf; dwCapBufSize = placAddressCaps->dwNeededSize; pCapBuf = new BYTE[dwCapBufSize]; EXIT_ON_NULL(pCapBuf); placAddressCaps = (LINEADDRESSCAPS*)pCapBuf; placAddressCaps->dwTotalSize = dwCapBufSize; lResult = lineGetAddressCaps(hLineApp, dwTAPILineDeviceID, dwAddressID, dwAPIVersion, 0, placAddressCaps); } if (0 == lResult) { EXIT_ON_FALSE(0 != placAddressCaps->dwAddressSize); // A non-zero dwAddressSize means a phone number was found ASSERT(0 != placAddressCaps->dwAddressOffset); PWCHAR tsAddress = (WCHAR*)(((BYTE*)placAddressCaps)+placAddressCaps->dwAddressOffset); number = convertToStringA (tsAddress); hr = S_OK; } delete[] pCapBuf; } // End if () FuncExit: lineShutdown(hLineApp); if (hr != S_OK) { LOG(ERROR) + "failed to get phone number from SIM"; return false; } return true; #undef EXIT_ON_NULL #undef EXIT_ON_FALSE #undef MAX } /* bool getPhoneNumFromSMSBearer (String &number) { SMS_ADDRESS psmsaAddress; if (SmsGetPhoneNumber (&psmsaAddress) != S_OK) { LOG(ERROR) + "failed to get phone number using SMS bearer"; return false; } number = convertToStringA(psmsaAddress.ptsAddress); return true; } */ bool getPhoneNumFromOwnerInfo (String &number) { HKEY hKey; DWORD dwType, dwCount = PHONE_NUMBER_BUFFER_SIZE; TCHAR strValue [PHONE_NUMBER_BUFFER_SIZE]; LONG res; TCHAR errMsg[1024]; if ((res = RegOpenKeyEx(HKEY_CURRENT_USER, TEXT("ControlPanel\\Owner"), NULL, KEY_EXECUTE , &hKey)) == 0) { if ((res = RegQueryValueEx (hKey, TEXT("Telephone"), NULL, &dwType, (LPBYTE )strValue, &dwCount)) == 0) { if (dwType != REG_SZ) { LOG(ERROR) + "Settings/Owner Information/Telephone has invalid type"; RegCloseKey(hKey); return false; } if (dwCount > 0) { strValue[dwCount + 1] = '\0'; if (_tcslen((strValue)) == 0) { LOG(INFO) + "Settings/Owner Information/Telephone is empty"; RegCloseKey(hKey); return false; } number = convertToStringA(strValue); RegCloseKey(hKey); return true; } } } RegCloseKey(hKey); FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM, 0, GetLastError(), 0, errMsg, sizeof(errMsg), NULL); LOG(ERROR) + errMsg; return false; } VALUE phone_number() { String number; if (getPhoneNumFromSIMCard(number)) return rho_ruby_create_string(number.c_str()); // if (getPhoneNumFromSMSBearer(number)) // return rho_ruby_create_string(number.c_str()); if (getPhoneNumFromOwnerInfo(number)) return rho_ruby_create_string(number.c_str()); return rho_ruby_get_NIL(); } #else VALUE phone_number() { return rho_ruby_get_NIL(); } #endif static int has_camera() { #ifdef OS_WINCE /* DEVMGR_DEVICE_INFORMATION devInfo = {0}; GUID guidCamera = { 0xCB998A05, 0x122C, 0x4166, 0x84, 0x6A, 0x93, 0x3E, 0x4D, 0x7E, 0x3C, 0x86 }; devInfo.dwSize = sizeof(devInfo); HANDLE hDevice = FindFirstDevice( DeviceSearchByGuid, &guidCamera, &devInfo); if ( hDevice != INVALID_HANDLE_VALUE ) { FindClose(hDevice); return 1; } return 0;*/ return 1; #else return 0; #endif } static double get_screen_ppi_x() { HWND hWndDesktop = GetDesktopWindow(); HDC hdcDesktop = GetDC(hWndDesktop); int mms = GetDeviceCaps(hdcDesktop, HORZSIZE); int pixels = GetDeviceCaps(hdcDesktop, HORZRES); double ret = (pixels*25.4)/mms; return ret; } static double get_screen_ppi_y() { HWND hWndDesktop = GetDesktopWindow(); HDC hdcDesktop = GetDC(hWndDesktop); int mms = GetDeviceCaps(hdcDesktop, VERTSIZE); int pixels = GetDeviceCaps(hdcDesktop, VERTRES); double ret = (pixels*25.4)/mms; return ret; } VALUE rho_sys_get_locale() { wchar_t szLang[20]; int nRes = GetLocaleInfo(LOCALE_USER_DEFAULT,LOCALE_SABBREVLANGNAME , szLang, sizeof(szLang)/sizeof(szLang[0])); szLang[2] = 0; wcslwr(szLang); return rho_ruby_create_string(convertToStringA(szLang).c_str()); } int rho_sysimpl_get_property(char* szPropName, VALUE* resValue) { if (strcasecmp("has_camera",szPropName) == 0) {*resValue = rho_ruby_create_boolean(has_camera()); return 1;} if (strcasecmp("phone_number",szPropName) == 0) {*resValue = phone_number();return 1;} if (strcasecmp("ppi_x",szPropName) == 0) {*resValue = rho_ruby_create_double(get_screen_ppi_x()); return 1;} if (strcasecmp("ppi_y",szPropName) == 0) {*resValue = rho_ruby_create_double(get_screen_ppi_y()); return 1; } if (strcasecmp("locale",szPropName) == 0) {*resValue = rho_sys_get_locale(); return 1;} if (strcasecmp("country",szPropName) == 0) { wchar_t szCountry[20]; int nRes = GetLocaleInfo(LOCALE_USER_DEFAULT,LOCALE_SISO3166CTRYNAME , szCountry, sizeof(szCountry)/sizeof(szCountry[0])); szCountry[2] = 0; *resValue = rho_ruby_create_string(convertToStringA(szCountry).c_str()); return 1; } if (strcasecmp("device_name",szPropName) == 0) { #ifdef OS_WINDOWS *resValue = rho_ruby_create_string("Win32"); return 1; #else HKEY hKey; if (RegOpenKeyEx( HKEY_LOCAL_MACHINE, _T("Ident"), 0, KEY_READ, &hKey ) != ERROR_SUCCESS) return 0; DWORD dwType = REG_SZ; DWORD dwDataSize = 0; if ( RegQueryValueEx( hKey, _T("name"), 0, &dwType, (PBYTE)NULL, &dwDataSize ) != ERROR_SUCCESS) return 0; std::vector<wchar_t> deviceName(dwDataSize + 1); RegQueryValueEx( hKey, _T("name"), 0, &dwType, (PBYTE)&deviceName[0], &dwDataSize ); char *s = wce_wctomb(&deviceName[0]); *resValue = rho_ruby_create_string(s); ::free(s); RegCloseKey(hKey); return 1; #endif } if (strcasecmp("os_version",szPropName) == 0) { OSVERSIONINFO osv; osv.dwOSVersionInfoSize = sizeof(osv); if (!GetVersionEx(&osv)) return 0; char buf[50]; buf[sizeof(buf) - 1] = '\0'; snprintf(buf, sizeof(buf) - 1, "%u.%u.%u", (unsigned)osv.dwMajorVersion, (unsigned)osv.dwMinorVersion, (unsigned)osv.dwBuildNumber); *resValue = rho_ruby_create_string(&buf[0]); return 1; } return 0; } int rho_sys_get_screen_width() { #ifdef OS_WINCE return GetSystemMetrics(SM_CXSCREEN); #else return CMainWindow::getScreenWidth(); #endif } int rho_sys_get_screen_height() { #ifdef OS_WINCE return GetSystemMetrics(SM_CYSCREEN); #else return CMainWindow::getScreenHeight(); #endif } VALUE rho_sys_makephonecall(const char* callname, int nparams, char** param_names, char** param_values) { return rho_ruby_get_NIL(); } static int g_rho_has_network = 1; void rho_sysimpl_sethas_network(int nValue) { g_rho_has_network = nValue; } VALUE rho_sys_has_network() { return rho_ruby_create_boolean(g_rho_has_network!=0); } void rho_sys_app_exit() { ::PostMessage(getMainWnd(), WM_COMMAND, MAKEWPARAM(IDM_EXIT,0), (LPARAM )0); } } //extern "C" <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/hwpf/fapi2/include/return_code_defs.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2012,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ /** * @file return_code.H * @brief definitions for fapi2 return codes */ #ifndef __FAPI2_RETURN_CODE_DEFS_ #define __FAPI2_RETURN_CODE_DEFS_ #include <stdint.h> /// /// @brief Set HWP Error macro /// /// This macro should be used by a HWP to create an error. The ReturnCode's /// internal return code is set and any error information in the Error XML file /// is added to the ReturnCode /// #define FAPI_SET_HWP_ERROR(RC, ERROR) \ RC._setHwpError(fapi2::ERROR); \ ERROR##_CALL_FUNCS_TO_COLLECT_FFDC(RC); \ ERROR##_CALL_FUNCS_TO_COLLECT_REG_FFDC(RC); \ ERROR##_ADD_ERROR_INFO(RC) /// /// @brief Add info to HWP Error macro /// /// This macro should be used by an FFDC HWP to add error information from an /// Error XML file to an existing error. /// #define FAPI_ADD_INFO_TO_HWP_ERROR(RC, ERROR) \ ERROR##_CALL_FUNCS_TO_COLLECT_FFDC(RC); \ ERROR##_CALL_FUNCS_TO_COLLECT_REG_FFDC(RC); \ ERROR##_ADD_ERROR_INFO(RC) namespace fapi2 { /// /// @brief Enumeration of return codes /// enum ReturnCodes : uint32_t { ///< Success FAPI2_RC_SUCCESS = 0, // Flag bits indicating which code generated the error. FAPI2_RC_FAPI2_MASK = 0x04000000, ///< FAPI2 mask FAPI2_RC_PLAT_MASK = 0x02000000, ///< Platform mask FAPI2_RC_HWP_MASK = 0x00000000, ///< HWP mask // // FAPI generated return codes // FAPI2_RC_INVALID_ATTR_GET = FAPI2_RC_FAPI2_MASK | 0x01, ///< Initfile requested an attribute with an invalid attribute ID FAPI2_RC_INVALID_CHIP_EC_FEATURE_GET = FAPI2_RC_FAPI2_MASK | 0x02, ///< HWP requested a chip EC feature with an invalid attribute ID FAPI2_RC_INVALID_PARAMETER = FAPI2_RC_FAPI2_MASK | 0x04, ///< Invalid parameters to a FAPI2 function FAPI2_RC_OVERFLOW = FAPI2_RC_FAPI2_MASK | 0x05, ///< Overflow condition, typically a buffer operation FAPI2_RC_FALSE = FAPI2_RC_FAPI2_MASK | 0x06, ///< The logical opposite of SUCCESS. Needed where procedures want ///< a multi-bool type of operation (e.g., true, false, scom error) // // PLAT generated return codes. Additional details may be contained in // ReturnCode platData (this can only be looked at by PLAT code) // FAPI2_RC_PLAT_ERR_SEE_DATA = FAPI2_RC_PLAT_MASK | 0x01, ///< Generic platform error FAPI2_RC_PLAT_ERR_ADU_LOCKED = FAPI2_RC_PLAT_MASK | 0x02, ///< Operation to AlterDisplay unit failed because it is locked FAPI2_RC_PLAT_NOT_SUPPORTED_AT_RUNTIME = FAPI2_RC_PLAT_MASK | 0x03, ///< Operation not supported by HB runtime FAPI2_RC_PLAT_ERR_RING_HEADER_CHECK = FAPI2_RC_PLAT_MASK | 0x04, //Operation on putring fail because of header data mismatch // FAPI2_RC_PLAT_RING_DECODE_LENGTH_EXCEEDED = FAPI2_RC_PLAT_MASK | 0x05, //Operation on putring fail because of decode length greater than actual //ring length. FAPI2_RC_PLAT_RS4_HEADER_DATA_INVALID = FAPI2_RC_PLAT_MASK | 0x06, //Operation on putring fail because of ringId not found in RS4 image FAPI2_RC_PLAT_TOR_HEADER_DATA_INVALID = FAPI2_RC_PLAT_MASK | 0x07, //Accessing TOR ring section fail because TOR magic word not found FAPI2_RC_PLAT_MISCOMPARE = FAPI2_RC_PLAT_MASK | 0x08, ///< An operation (like a getScom using multicast-compare) failed ///< because the returned data was different from a reference value. }; } #endif <commit_msg>Add phal generic error to ekb return code definitions<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/hwpf/fapi2/include/return_code_defs.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2012,2020 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ /** * @file return_code.H * @brief definitions for fapi2 return codes */ #ifndef __FAPI2_RETURN_CODE_DEFS_ #define __FAPI2_RETURN_CODE_DEFS_ #include <stdint.h> /// /// @brief Set HWP Error macro /// /// This macro should be used by a HWP to create an error. The ReturnCode's /// internal return code is set and any error information in the Error XML file /// is added to the ReturnCode /// #define FAPI_SET_HWP_ERROR(RC, ERROR) \ RC._setHwpError(fapi2::ERROR); \ ERROR##_CALL_FUNCS_TO_COLLECT_FFDC(RC); \ ERROR##_CALL_FUNCS_TO_COLLECT_REG_FFDC(RC); \ ERROR##_ADD_ERROR_INFO(RC) /// /// @brief Add info to HWP Error macro /// /// This macro should be used by an FFDC HWP to add error information from an /// Error XML file to an existing error. /// #define FAPI_ADD_INFO_TO_HWP_ERROR(RC, ERROR) \ ERROR##_CALL_FUNCS_TO_COLLECT_FFDC(RC); \ ERROR##_CALL_FUNCS_TO_COLLECT_REG_FFDC(RC); \ ERROR##_ADD_ERROR_INFO(RC) namespace fapi2 { /// /// @brief Enumeration of return codes /// enum ReturnCodes : uint32_t { ///< Success FAPI2_RC_SUCCESS = 0, // Flag bits indicating which code generated the error. FAPI2_RC_PHAL_MASK = 0x08000000, ///< PHAL mask FAPI2_RC_FAPI2_MASK = 0x04000000, ///< FAPI2 mask FAPI2_RC_PLAT_MASK = 0x02000000, ///< Platform mask FAPI2_RC_HWP_MASK = 0x00000000, ///< HWP mask // // PHAL generic return codes // FAPI2_RC_PHAL_NOT_SUPPORTED = FAPI2_RC_PHAL_MASK | 0x01, // // FAPI generated return codes // FAPI2_RC_INVALID_ATTR_GET = FAPI2_RC_FAPI2_MASK | 0x01, ///< Initfile requested an attribute with an invalid attribute ID FAPI2_RC_INVALID_CHIP_EC_FEATURE_GET = FAPI2_RC_FAPI2_MASK | 0x02, ///< HWP requested a chip EC feature with an invalid attribute ID FAPI2_RC_INVALID_PARAMETER = FAPI2_RC_FAPI2_MASK | 0x04, ///< Invalid parameters to a FAPI2 function FAPI2_RC_OVERFLOW = FAPI2_RC_FAPI2_MASK | 0x05, ///< Overflow condition, typically a buffer operation FAPI2_RC_FALSE = FAPI2_RC_FAPI2_MASK | 0x06, ///< The logical opposite of SUCCESS. Needed where procedures want ///< a multi-bool type of operation (e.g., true, false, scom error) // // PLAT generated return codes. Additional details may be contained in // ReturnCode platData (this can only be looked at by PLAT code) // FAPI2_RC_PLAT_ERR_SEE_DATA = FAPI2_RC_PLAT_MASK | 0x01, ///< Generic platform error FAPI2_RC_PLAT_ERR_ADU_LOCKED = FAPI2_RC_PLAT_MASK | 0x02, ///< Operation to AlterDisplay unit failed because it is locked FAPI2_RC_PLAT_NOT_SUPPORTED_AT_RUNTIME = FAPI2_RC_PLAT_MASK | 0x03, ///< Operation not supported by HB runtime FAPI2_RC_PLAT_ERR_RING_HEADER_CHECK = FAPI2_RC_PLAT_MASK | 0x04, //Operation on putring fail because of header data mismatch // FAPI2_RC_PLAT_RING_DECODE_LENGTH_EXCEEDED = FAPI2_RC_PLAT_MASK | 0x05, //Operation on putring fail because of decode length greater than actual //ring length. FAPI2_RC_PLAT_RS4_HEADER_DATA_INVALID = FAPI2_RC_PLAT_MASK | 0x06, //Operation on putring fail because of ringId not found in RS4 image FAPI2_RC_PLAT_TOR_HEADER_DATA_INVALID = FAPI2_RC_PLAT_MASK | 0x07, //Accessing TOR ring section fail because TOR magic word not found FAPI2_RC_PLAT_MISCOMPARE = FAPI2_RC_PLAT_MASK | 0x08, ///< An operation (like a getScom using multicast-compare) failed ///< because the returned data was different from a reference value. }; } #endif <|endoftext|>
<commit_before>/* * VHDL code generation for statements. * * Copyright (C) 2008 Nick Gasson (nick@nickg.me.uk) * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "vhdl_target.h" #include <iostream> #include <cstring> #include <cassert> /* * Generate VHDL for the $display system task. * This is implemented using the functions in std.textio. Each * parameter is written to a line variable in the process and * then the line is written to the special variable `Output' * (which represents the console). Subsequent $displays will * use the same line variable. * * It's possible, although quite unlikely, that there will be * name collision with an existing variable called * `Verilog_Display_Line' -- do something about this? * It's also possible for there to be a name collision with * the special variable `Output'. */ static int draw_stask_display(vhdl_process *proc, ivl_statement_t stmt) { // Add the package requirement to the containing entity proc->get_parent()->get_parent()->requires_package("std.textio"); const char *display_line = "Verilog_Display_Line"; if (!proc->have_declared_var(display_line)) { vhdl_type *line_type = new vhdl_scalar_type("Line"); vhdl_var_decl *line_var = new vhdl_var_decl(display_line, line_type); line_var->set_comment("For generating $display output"); proc->add_decl(line_var); } // Write the data into the line int count = ivl_stmt_parm_count(stmt); for (int i = 0; i < count; i++) { // $display may have an empty parameter, in which case // the expression will be null // The behaviour here seems to be to output a space ivl_expr_t net = ivl_stmt_parm(stmt, i); vhdl_expr *e = NULL; if (net) { // TODO: Need to add a call to Type'Image for types not // supported by std.textio e = translate_expr(net); if (NULL == e) return 1; } else e = new vhdl_const_string(" "); vhdl_pcall_stmt *write = new vhdl_pcall_stmt("Write"); write->add_expr(new vhdl_var_ref(display_line)); write->add_expr(e); proc->add_stmt(write); } // WriteLine(Output, Verilog_Display_Line) vhdl_pcall_stmt *write_line = new vhdl_pcall_stmt("WriteLine"); write_line->add_expr(new vhdl_var_ref("Output")); write_line->add_expr(new vhdl_var_ref(display_line)); proc->add_stmt(write_line); return 0; } /* * Generate VHDL for system tasks (like $display). Not all of * these are supported. */ static int draw_stask(vhdl_process *proc, ivl_statement_t stmt) { const char *name = ivl_stmt_name(stmt); if (strcmp(name, "$display") == 0) return draw_stask_display(proc, stmt); else { error("No VHDL translation for system task %s", name); return 0; } } /* * Generate VHDL for a block of Verilog statements. This doesn't * actually do anything, other than recursively translate the * block's statements and add them to the process. This is OK as * `begin' and `end process' function like a Verilog block. */ static int draw_block(vhdl_process *proc, ivl_statement_t stmt) { int count = ivl_stmt_block_count(stmt); for (int i = 0; i < count; i++) { if (draw_stmt(proc, ivl_stmt_block_stmt(stmt, i)) != 0) return 1; } return 0; } /* * Generate VHDL statements for the given Verilog statement and * add them to the given VHDL process. */ int draw_stmt(vhdl_process *proc, ivl_statement_t stmt) { switch (ivl_statement_type(stmt)) { case IVL_ST_STASK: return draw_stask(proc, stmt); case IVL_ST_BLOCK: return draw_block(proc, stmt); default: error("No VHDL translation for statement at %s:%d (type = %d)", ivl_stmt_file(stmt), ivl_stmt_lineno(stmt), ivl_statement_type(stmt)); return 1; } } <commit_msg>Fully qualify std.textio.Output to avoid name collisions<commit_after>/* * VHDL code generation for statements. * * Copyright (C) 2008 Nick Gasson (nick@nickg.me.uk) * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "vhdl_target.h" #include <iostream> #include <cstring> #include <cassert> /* * Generate VHDL for the $display system task. * This is implemented using the functions in std.textio. Each * parameter is written to a line variable in the process and * then the line is written to the special variable `Output' * (which represents the console). Subsequent $displays will * use the same line variable. * * It's possible, although quite unlikely, that there will be * name collision with an existing variable called * `Verilog_Display_Line' -- do something about this? */ static int draw_stask_display(vhdl_process *proc, ivl_statement_t stmt) { // Add the package requirement to the containing entity proc->get_parent()->get_parent()->requires_package("std.textio"); const char *display_line = "Verilog_Display_Line"; if (!proc->have_declared_var(display_line)) { vhdl_type *line_type = new vhdl_scalar_type("Line"); vhdl_var_decl *line_var = new vhdl_var_decl(display_line, line_type); line_var->set_comment("For generating $display output"); proc->add_decl(line_var); } // Write the data into the line int count = ivl_stmt_parm_count(stmt); for (int i = 0; i < count; i++) { // $display may have an empty parameter, in which case // the expression will be null // The behaviour here seems to be to output a space ivl_expr_t net = ivl_stmt_parm(stmt, i); vhdl_expr *e = NULL; if (net) { // TODO: Need to add a call to Type'Image for types not // supported by std.textio e = translate_expr(net); if (NULL == e) return 1; } else e = new vhdl_const_string(" "); vhdl_pcall_stmt *write = new vhdl_pcall_stmt("Write"); write->add_expr(new vhdl_var_ref(display_line)); write->add_expr(e); proc->add_stmt(write); } // WriteLine(Output, Verilog_Display_Line) vhdl_pcall_stmt *write_line = new vhdl_pcall_stmt("WriteLine"); write_line->add_expr(new vhdl_var_ref("std.textio.Output")); write_line->add_expr(new vhdl_var_ref(display_line)); proc->add_stmt(write_line); return 0; } /* * Generate VHDL for system tasks (like $display). Not all of * these are supported. */ static int draw_stask(vhdl_process *proc, ivl_statement_t stmt) { const char *name = ivl_stmt_name(stmt); if (strcmp(name, "$display") == 0) return draw_stask_display(proc, stmt); else { error("No VHDL translation for system task %s", name); return 0; } } /* * Generate VHDL for a block of Verilog statements. This doesn't * actually do anything, other than recursively translate the * block's statements and add them to the process. This is OK as * `begin' and `end process' function like a Verilog block. */ static int draw_block(vhdl_process *proc, ivl_statement_t stmt) { int count = ivl_stmt_block_count(stmt); for (int i = 0; i < count; i++) { if (draw_stmt(proc, ivl_stmt_block_stmt(stmt, i)) != 0) return 1; } return 0; } /* * Generate VHDL statements for the given Verilog statement and * add them to the given VHDL process. */ int draw_stmt(vhdl_process *proc, ivl_statement_t stmt) { switch (ivl_statement_type(stmt)) { case IVL_ST_STASK: return draw_stask(proc, stmt); case IVL_ST_BLOCK: return draw_block(proc, stmt); default: error("No VHDL translation for statement at %s:%d (type = %d)", ivl_stmt_file(stmt), ivl_stmt_lineno(stmt), ivl_statement_type(stmt)); return 1; } } <|endoftext|>
<commit_before>//===- LoopUnrollAndJam.cpp - Code to perform loop unroll and jam ---------===// // // Copyright 2019 The MLIR Authors. // // 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. // ============================================================================= // // This file implements loop unroll and jam. Unroll and jam is a transformation // that improves locality, in particular, register reuse, while also improving // operation level parallelism. The example below shows what it does in nearly // the general case. Loop unroll and jam currently works if the bounds of the // loops inner to the loop being unroll-jammed do not depend on the latter. // // Before After unroll and jam of i by factor 2: // // for i, step = 2 // for i S1(i); // S1; S2(i); // S2; S1(i+1); // for j S2(i+1); // S3; for j // S4; S3(i, j); // S5; S4(i, j); // S6; S3(i+1, j) // S4(i+1, j) // S5(i); // S6(i); // S5(i+1); // S6(i+1); // // Note: 'if/else' blocks are not jammed. So, if there are loops inside if // op's, bodies of those loops will not be jammed. //===----------------------------------------------------------------------===// #include "mlir/Transforms/Passes.h" #include "mlir/Analysis/LoopAnalysis.h" #include "mlir/Dialect/AffineOps/AffineOps.h" #include "mlir/IR/AffineExpr.h" #include "mlir/IR/AffineMap.h" #include "mlir/IR/BlockAndValueMapping.h" #include "mlir/IR/Builders.h" #include "mlir/Pass/Pass.h" #include "mlir/Transforms/LoopUtils.h" #include "llvm/ADT/DenseMap.h" #include "llvm/Support/CommandLine.h" using namespace mlir; #define DEBUG_TYPE "affine-loop-unroll-jam" static llvm::cl::OptionCategory clOptionsCategory(DEBUG_TYPE " options"); // Loop unroll and jam factor. static llvm::cl::opt<unsigned> clUnrollJamFactor("unroll-jam-factor", llvm::cl::Hidden, llvm::cl::desc("Use this unroll jam factor for all loops" " (default 4)"), llvm::cl::cat(clOptionsCategory)); namespace { /// Loop unroll jam pass. Currently, this just unroll jams the first /// outer loop in a Function. struct LoopUnrollAndJam : public FunctionPass<LoopUnrollAndJam> { Optional<unsigned> unrollJamFactor; static const unsigned kDefaultUnrollJamFactor = 4; explicit LoopUnrollAndJam(Optional<unsigned> unrollJamFactor = None) : unrollJamFactor(unrollJamFactor) {} void runOnFunction() override; LogicalResult runOnAffineForOp(AffineForOp forOp); }; } // end anonymous namespace std::unique_ptr<OpPassBase<FuncOp>> mlir::createLoopUnrollAndJamPass(int unrollJamFactor) { return std::make_unique<LoopUnrollAndJam>( unrollJamFactor == -1 ? None : Optional<unsigned>(unrollJamFactor)); } void LoopUnrollAndJam::runOnFunction() { // Currently, just the outermost loop from the first loop nest is // unroll-and-jammed by this pass. However, runOnAffineForOp can be called on // any for operation. auto &entryBlock = getFunction().front(); if (auto forOp = dyn_cast<AffineForOp>(entryBlock.front())) runOnAffineForOp(forOp); } /// Unroll and jam a 'affine.for' op. Default unroll jam factor is /// kDefaultUnrollJamFactor. Return failure if nothing was done. LogicalResult LoopUnrollAndJam::runOnAffineForOp(AffineForOp forOp) { // Unroll and jam by the factor that was passed if any. if (unrollJamFactor.hasValue()) return loopUnrollJamByFactor(forOp, unrollJamFactor.getValue()); // Otherwise, unroll jam by the command-line factor if one was specified. if (clUnrollJamFactor.getNumOccurrences() > 0) return loopUnrollJamByFactor(forOp, clUnrollJamFactor); // Unroll and jam by four otherwise. return loopUnrollJamByFactor(forOp, kDefaultUnrollJamFactor); } LogicalResult mlir::loopUnrollJamUpToFactor(AffineForOp forOp, uint64_t unrollJamFactor) { Optional<uint64_t> mayBeConstantTripCount = getConstantTripCount(forOp); if (mayBeConstantTripCount.hasValue() && mayBeConstantTripCount.getValue() < unrollJamFactor) return loopUnrollJamByFactor(forOp, mayBeConstantTripCount.getValue()); return loopUnrollJamByFactor(forOp, unrollJamFactor); } /// Unrolls and jams this loop by the specified factor. LogicalResult mlir::loopUnrollJamByFactor(AffineForOp forOp, uint64_t unrollJamFactor) { // Gathers all maximal sub-blocks of operations that do not themselves // include a for op (a operation could have a descendant for op though // in its tree). Ignore the block terminators. struct JamBlockGatherer { // Store iterators to the first and last op of each sub-block found. std::vector<std::pair<Block::iterator, Block::iterator>> subBlocks; // This is a linear time walk. void walk(Operation *op) { for (auto &region : op->getRegions()) for (auto &block : region) walk(block); } void walk(Block &block) { for (auto it = block.begin(), e = std::prev(block.end()); it != e;) { auto subBlockStart = it; while (it != e && !isa<AffineForOp>(&*it)) ++it; if (it != subBlockStart) subBlocks.push_back({subBlockStart, std::prev(it)}); // Process all for insts that appear next. while (it != e && isa<AffineForOp>(&*it)) walk(&*it++); } } }; assert(unrollJamFactor >= 1 && "unroll jam factor should be >= 1"); if (unrollJamFactor == 1) return promoteIfSingleIteration(forOp); if (forOp.getBody()->empty() || forOp.getBody()->begin() == std::prev(forOp.getBody()->end())) return failure(); // Loops where both lower and upper bounds are multi-result maps won't be // unrolled (since the trip can't be expressed as an affine function in // general). // TODO(mlir-team): this may not be common, but we could support the case // where the lower bound is a multi-result map and the ub is a single result // one. if (forOp.getLowerBoundMap().getNumResults() != 1) return failure(); Optional<uint64_t> mayBeConstantTripCount = getConstantTripCount(forOp); // If the trip count is lower than the unroll jam factor, no unroll jam. if (mayBeConstantTripCount.hasValue() && mayBeConstantTripCount.getValue() < unrollJamFactor) return failure(); auto *forInst = forOp.getOperation(); // Gather all sub-blocks to jam upon the loop being unrolled. JamBlockGatherer jbg; jbg.walk(forInst); auto &subBlocks = jbg.subBlocks; // Generate the cleanup loop if trip count isn't a multiple of // unrollJamFactor. if (getLargestDivisorOfTripCount(forOp) % unrollJamFactor != 0) { // Insert the cleanup loop right after 'forOp'. OpBuilder builder(forInst->getBlock(), std::next(Block::iterator(forInst))); auto cleanupAffineForOp = cast<AffineForOp>(builder.clone(*forInst)); // Adjust the lower bound of the cleanup loop; its upper bound is the same // as the original loop's upper bound. AffineMap cleanupMap; SmallVector<Value *, 4> cleanupOperands; getCleanupLoopLowerBound(forOp, unrollJamFactor, &cleanupMap, &cleanupOperands, builder); cleanupAffineForOp.setLowerBound(cleanupOperands, cleanupMap); // Promote the cleanup loop if it has turned into a single iteration loop. promoteIfSingleIteration(cleanupAffineForOp); // Adjust the upper bound of the original loop - it will be the same as the // cleanup loop's lower bound. Its lower bound remains unchanged. forOp.setUpperBound(cleanupOperands, cleanupMap); } // Scale the step of loop being unroll-jammed by the unroll-jam factor. int64_t step = forOp.getStep(); forOp.setStep(step * unrollJamFactor); auto *forOpIV = forOp.getInductionVar(); // Unroll and jam (appends unrollJamFactor-1 additional copies). for (unsigned i = 1; i < unrollJamFactor; i++) { // Operand map persists across all sub-blocks. BlockAndValueMapping operandMapping; for (auto &subBlock : subBlocks) { // Builder to insert unroll-jammed bodies. Insert right at the end of // sub-block. OpBuilder builder(subBlock.first->getBlock(), std::next(subBlock.second)); // If the induction variable is used, create a remapping to the value for // this unrolled instance. if (!forOpIV->use_empty()) { // iv' = iv + i, i = 1 to unrollJamFactor-1. auto d0 = builder.getAffineDimExpr(0); auto bumpMap = builder.getAffineMap(1, 0, {d0 + i * step}); auto ivUnroll = builder.create<AffineApplyOp>(forInst->getLoc(), bumpMap, forOpIV); operandMapping.map(forOpIV, ivUnroll); } // Clone the sub-block being unroll-jammed. for (auto it = subBlock.first; it != std::next(subBlock.second); ++it) { builder.clone(*it, operandMapping); } } } // Promote the loop body up if this has turned into a single iteration loop. promoteIfSingleIteration(forOp); return success(); } static PassRegistration<LoopUnrollAndJam> pass("affine-loop-unroll-jam", "Unroll and jam loops"); <commit_msg>unroll and jam: fix order of jammed bodies<commit_after>//===- LoopUnrollAndJam.cpp - Code to perform loop unroll and jam ---------===// // // Copyright 2019 The MLIR Authors. // // 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. // ============================================================================= // // This file implements loop unroll and jam. Unroll and jam is a transformation // that improves locality, in particular, register reuse, while also improving // operation level parallelism. The example below shows what it does in nearly // the general case. Loop unroll and jam currently works if the bounds of the // loops inner to the loop being unroll-jammed do not depend on the latter. // // Before After unroll and jam of i by factor 2: // // for i, step = 2 // for i S1(i); // S1; S2(i); // S2; S1(i+1); // for j S2(i+1); // S3; for j // S4; S3(i, j); // S5; S4(i, j); // S6; S3(i+1, j) // S4(i+1, j) // S5(i); // S6(i); // S5(i+1); // S6(i+1); // // Note: 'if/else' blocks are not jammed. So, if there are loops inside if // op's, bodies of those loops will not be jammed. //===----------------------------------------------------------------------===// #include "mlir/Transforms/Passes.h" #include "mlir/Analysis/LoopAnalysis.h" #include "mlir/Dialect/AffineOps/AffineOps.h" #include "mlir/IR/AffineExpr.h" #include "mlir/IR/AffineMap.h" #include "mlir/IR/BlockAndValueMapping.h" #include "mlir/IR/Builders.h" #include "mlir/Pass/Pass.h" #include "mlir/Transforms/LoopUtils.h" #include "llvm/ADT/DenseMap.h" #include "llvm/Support/CommandLine.h" using namespace mlir; #define DEBUG_TYPE "affine-loop-unroll-jam" static llvm::cl::OptionCategory clOptionsCategory(DEBUG_TYPE " options"); // Loop unroll and jam factor. static llvm::cl::opt<unsigned> clUnrollJamFactor("unroll-jam-factor", llvm::cl::Hidden, llvm::cl::desc("Use this unroll jam factor for all loops" " (default 4)"), llvm::cl::cat(clOptionsCategory)); namespace { /// Loop unroll jam pass. Currently, this just unroll jams the first /// outer loop in a Function. struct LoopUnrollAndJam : public FunctionPass<LoopUnrollAndJam> { Optional<unsigned> unrollJamFactor; static const unsigned kDefaultUnrollJamFactor = 4; explicit LoopUnrollAndJam(Optional<unsigned> unrollJamFactor = None) : unrollJamFactor(unrollJamFactor) {} void runOnFunction() override; LogicalResult runOnAffineForOp(AffineForOp forOp); }; } // end anonymous namespace std::unique_ptr<OpPassBase<FuncOp>> mlir::createLoopUnrollAndJamPass(int unrollJamFactor) { return std::make_unique<LoopUnrollAndJam>( unrollJamFactor == -1 ? None : Optional<unsigned>(unrollJamFactor)); } void LoopUnrollAndJam::runOnFunction() { // Currently, just the outermost loop from the first loop nest is // unroll-and-jammed by this pass. However, runOnAffineForOp can be called on // any for operation. auto &entryBlock = getFunction().front(); if (auto forOp = dyn_cast<AffineForOp>(entryBlock.front())) runOnAffineForOp(forOp); } /// Unroll and jam a 'affine.for' op. Default unroll jam factor is /// kDefaultUnrollJamFactor. Return failure if nothing was done. LogicalResult LoopUnrollAndJam::runOnAffineForOp(AffineForOp forOp) { // Unroll and jam by the factor that was passed if any. if (unrollJamFactor.hasValue()) return loopUnrollJamByFactor(forOp, unrollJamFactor.getValue()); // Otherwise, unroll jam by the command-line factor if one was specified. if (clUnrollJamFactor.getNumOccurrences() > 0) return loopUnrollJamByFactor(forOp, clUnrollJamFactor); // Unroll and jam by four otherwise. return loopUnrollJamByFactor(forOp, kDefaultUnrollJamFactor); } LogicalResult mlir::loopUnrollJamUpToFactor(AffineForOp forOp, uint64_t unrollJamFactor) { Optional<uint64_t> mayBeConstantTripCount = getConstantTripCount(forOp); if (mayBeConstantTripCount.hasValue() && mayBeConstantTripCount.getValue() < unrollJamFactor) return loopUnrollJamByFactor(forOp, mayBeConstantTripCount.getValue()); return loopUnrollJamByFactor(forOp, unrollJamFactor); } /// Unrolls and jams this loop by the specified factor. LogicalResult mlir::loopUnrollJamByFactor(AffineForOp forOp, uint64_t unrollJamFactor) { // Gathers all maximal sub-blocks of operations that do not themselves // include a for op (a operation could have a descendant for op though // in its tree). Ignore the block terminators. struct JamBlockGatherer { // Store iterators to the first and last op of each sub-block found. std::vector<std::pair<Block::iterator, Block::iterator>> subBlocks; // This is a linear time walk. void walk(Operation *op) { for (auto &region : op->getRegions()) for (auto &block : region) walk(block); } void walk(Block &block) { for (auto it = block.begin(), e = std::prev(block.end()); it != e;) { auto subBlockStart = it; while (it != e && !isa<AffineForOp>(&*it)) ++it; if (it != subBlockStart) subBlocks.push_back({subBlockStart, std::prev(it)}); // Process all for insts that appear next. while (it != e && isa<AffineForOp>(&*it)) walk(&*it++); } } }; assert(unrollJamFactor >= 1 && "unroll jam factor should be >= 1"); if (unrollJamFactor == 1) return promoteIfSingleIteration(forOp); if (forOp.getBody()->empty() || forOp.getBody()->begin() == std::prev(forOp.getBody()->end())) return failure(); // Loops where both lower and upper bounds are multi-result maps won't be // unrolled (since the trip can't be expressed as an affine function in // general). // TODO(mlir-team): this may not be common, but we could support the case // where the lower bound is a multi-result map and the ub is a single result // one. if (forOp.getLowerBoundMap().getNumResults() != 1) return failure(); Optional<uint64_t> mayBeConstantTripCount = getConstantTripCount(forOp); // If the trip count is lower than the unroll jam factor, no unroll jam. if (mayBeConstantTripCount.hasValue() && mayBeConstantTripCount.getValue() < unrollJamFactor) return failure(); auto *forInst = forOp.getOperation(); // Gather all sub-blocks to jam upon the loop being unrolled. JamBlockGatherer jbg; jbg.walk(forInst); auto &subBlocks = jbg.subBlocks; // Generate the cleanup loop if trip count isn't a multiple of // unrollJamFactor. if (getLargestDivisorOfTripCount(forOp) % unrollJamFactor != 0) { // Insert the cleanup loop right after 'forOp'. OpBuilder builder(forInst->getBlock(), std::next(Block::iterator(forInst))); auto cleanupAffineForOp = cast<AffineForOp>(builder.clone(*forInst)); // Adjust the lower bound of the cleanup loop; its upper bound is the same // as the original loop's upper bound. AffineMap cleanupMap; SmallVector<Value *, 4> cleanupOperands; getCleanupLoopLowerBound(forOp, unrollJamFactor, &cleanupMap, &cleanupOperands, builder); cleanupAffineForOp.setLowerBound(cleanupOperands, cleanupMap); // Promote the cleanup loop if it has turned into a single iteration loop. promoteIfSingleIteration(cleanupAffineForOp); // Adjust the upper bound of the original loop - it will be the same as the // cleanup loop's lower bound. Its lower bound remains unchanged. forOp.setUpperBound(cleanupOperands, cleanupMap); } // Scale the step of loop being unroll-jammed by the unroll-jam factor. int64_t step = forOp.getStep(); forOp.setStep(step * unrollJamFactor); auto *forOpIV = forOp.getInductionVar(); // Unroll and jam (appends unrollJamFactor - 1 additional copies). for (unsigned i = unrollJamFactor - 1; i >= 1; --i) { // Operand map persists across all sub-blocks. BlockAndValueMapping operandMapping; for (auto &subBlock : subBlocks) { // Builder to insert unroll-jammed bodies. Insert right at the end of // sub-block. OpBuilder builder(subBlock.first->getBlock(), std::next(subBlock.second)); // If the induction variable is used, create a remapping to the value for // this unrolled instance. if (!forOpIV->use_empty()) { // iv' = iv + i, i = 1 to unrollJamFactor-1. auto d0 = builder.getAffineDimExpr(0); auto bumpMap = builder.getAffineMap(1, 0, {d0 + i * step}); auto ivUnroll = builder.create<AffineApplyOp>(forInst->getLoc(), bumpMap, forOpIV); operandMapping.map(forOpIV, ivUnroll); } // Clone the sub-block being unroll-jammed. for (auto it = subBlock.first; it != std::next(subBlock.second); ++it) { builder.clone(*it, operandMapping); } } } // Promote the loop body up if this has turned into a single iteration loop. promoteIfSingleIteration(forOp); return success(); } static PassRegistration<LoopUnrollAndJam> pass("affine-loop-unroll-jam", "Unroll and jam loops"); <|endoftext|>
<commit_before>#include "stdafx.h" #include "ImageIndexer.h" using namespace std; using namespace boost::assign; using namespace Magick; ImageIndexer::ImageIndexer() { } ImageIndexer::~ImageIndexer() { } bool HashesAreSimilar(const char* a, const char* b, const size_t size, const size_t threshold) { throw_assert(threshold <= size, "Invalid threshold, it surprasses the hash size"); unsigned __int64 returnValue = 1ULL; for (size_t i = 0; i < size; ++i) { if (a[i] - b[i] != 0) { returnValue <<= 1; } } return 1ULL << threshold >= returnValue; } double_t RankDFT(DftImageData a, DftImageData b, size_t n) { double_t subresult_a = 0.0; double_t subresult_b = 0.0; double_t subresult_c = 0.0; for (size_t i = 0; i < n; i++) { Color phaseColora = a.magColors[i]; Color phaseColorb = b.magColors[i]; double_t aSquaredModule = pow(phaseColora.quantumRed(), 2) + pow(phaseColora.quantumGreen(), 2) + pow(phaseColora.quantumBlue(), 2); double_t bSquaredModule = pow(phaseColorb.quantumRed(), 2) + pow(phaseColorb.quantumGreen(), 2) + pow(phaseColorb.quantumBlue(), 2); subresult_a += a.imageMagnitudes[i] * b.imageMagnitudes[i] - n * (a.frequencyMedian * b.frequencyMedian); subresult_b += aSquaredModule - n * pow(a.frequencyMedian, 2); subresult_c += bSquaredModule - n * pow(b.frequencyMedian, 2); } double_t result = pow(subresult_a, 2) / (subresult_b * subresult_c); return result; } vector<vector<pair<string, char*>>> ImageIndexer::CreateIndex(map<string, char*> imageHashes) { vector<vector<pair<string, char*>>> imageIndex; for (auto const& imageHash : imageHashes) { pair<string, char*> imageIndexKey = make_pair(imageHash.first, imageHash.second); if (imageIndex.size() == 0) { // Initialize index with the first hash vector<pair<string, char*>> imageIndexKeyList; imageIndexKeyList.push_back(imageIndexKey); imageIndex.push_back(imageIndexKeyList); continue; } // Traverse the index in search of matches in each indexKey lists bool match = false; for (vector<pair<string, char*>>& imageIndexElement : imageIndex) { // Traverse each index key from the index element for (pair<string, char*> indexKey : imageIndexElement) { if (HashesAreSimilar(indexKey.second, imageIndexKey.second, HASH_SIZE, HASH_THRESHOLD)) { // There is a match, so we add the current match to the index element match = true; imageIndexElement.push_back(imageIndexKey); break; } } } if (!match) { // No matches, add the key into its separate index element vector<pair<string, char*>> imageIndexKeyList; imageIndexKeyList.push_back(imageIndexKey); imageIndex.push_back(imageIndexKeyList); } } return imageIndex; } vector<vector<DftImageData>> ImageIndexer::CreateRankDFTIndex(map<string, DftImageData>& imageDftData) { vector<vector<DftImageData>> imageIndex; for (auto const& imageMagnitudeData : imageDftData) { DftImageData imageData; imageData.distance = 0.0; imageData.filePath = imageMagnitudeData.first; imageData.magnitudeMedian = imageMagnitudeData.second.magnitudeMedian; imageData.frequencyMedian = imageMagnitudeData.second.frequencyMedian; imageData.magnitudeQuantums = imageMagnitudeData.second.magnitudeQuantums; imageData.phaseColors = imageMagnitudeData.second.phaseColors; imageData.magnitudeColors = imageMagnitudeData.second.magnitudeColors; imageData.phaseQuantums = imageMagnitudeData.second.phaseQuantums; if (imageIndex.size() == 0) { // Initialize index with the first hash vector<DftImageData> imageIndexKeyList; imageData.distance = 1; imageIndexKeyList.push_back(imageData); imageIndex.push_back(imageIndexKeyList); continue; } // Traverse the index in search of matches in each indexKey lists bool match = false; for (vector<DftImageData>& imageIndexElement : imageIndex) { // Traverse each index key from the index element for (DftImageData& subImageData : imageIndexElement) { imageData.distance = RankDFT(imageData, subImageData, DFT_IMAGE_HEIGHT * DFT_IMAGE_WIDTH); if (imageData.distance/* > 1.00000000000*/) { //TODO TEST: Add a criteria after verifying the algorithm // There is a match, so we add the current match to the index element match = true; imageIndexElement.push_back(imageData); break; } } } if (!match) { // No matches, add the key into its separate index element vector<DftImageData> imageIndexKeyList; imageIndexKeyList.push_back(imageData); imageIndex.push_back(imageIndexKeyList); } } return imageIndex; }<commit_msg>Update renamed variables<commit_after>#include "stdafx.h" #include "ImageIndexer.h" using namespace std; using namespace boost::assign; using namespace Magick; ImageIndexer::ImageIndexer() { } ImageIndexer::~ImageIndexer() { } bool HashesAreSimilar(const char* a, const char* b, const size_t size, const size_t threshold) { throw_assert(threshold <= size, "Invalid threshold, it surprasses the hash size"); unsigned __int64 returnValue = 1ULL; for (size_t i = 0; i < size; ++i) { if (a[i] - b[i] != 0) { returnValue <<= 1; } } return 1ULL << threshold >= returnValue; } double_t RankDFT(DftImageData a, DftImageData b, size_t n) { double_t subresult_a = 0.0; double_t subresult_b = 0.0; double_t subresult_c = 0.0; for (size_t i = 0; i < n; i++) { Color phaseColora = a.magnitudeColors[i]; Color phaseColorb = b.magnitudeColors[i]; double_t aSquaredModule = pow(phaseColora.quantumRed(), 2) + pow(phaseColora.quantumGreen(), 2) + pow(phaseColora.quantumBlue(), 2); double_t bSquaredModule = pow(phaseColorb.quantumRed(), 2) + pow(phaseColorb.quantumGreen(), 2) + pow(phaseColorb.quantumBlue(), 2); subresult_a += a.magnitudeQuantums[i] * b.magnitudeQuantums[i] - n * (a.frequencyMedian * b.frequencyMedian); subresult_b += aSquaredModule - n * pow(a.frequencyMedian, 2); subresult_c += bSquaredModule - n * pow(b.frequencyMedian, 2); } double_t result = pow(subresult_a, 2) / (subresult_b * subresult_c); return result; } vector<vector<pair<string, char*>>> ImageIndexer::CreateIndex(map<string, char*> imageHashes) { vector<vector<pair<string, char*>>> imageIndex; for (auto const& imageHash : imageHashes) { pair<string, char*> imageIndexKey = make_pair(imageHash.first, imageHash.second); if (imageIndex.size() == 0) { // Initialize index with the first hash vector<pair<string, char*>> imageIndexKeyList; imageIndexKeyList.push_back(imageIndexKey); imageIndex.push_back(imageIndexKeyList); continue; } // Traverse the index in search of matches in each indexKey lists bool match = false; for (vector<pair<string, char*>>& imageIndexElement : imageIndex) { // Traverse each index key from the index element for (pair<string, char*> indexKey : imageIndexElement) { if (HashesAreSimilar(indexKey.second, imageIndexKey.second, HASH_SIZE, HASH_THRESHOLD)) { // There is a match, so we add the current match to the index element match = true; imageIndexElement.push_back(imageIndexKey); break; } } } if (!match) { // No matches, add the key into its separate index element vector<pair<string, char*>> imageIndexKeyList; imageIndexKeyList.push_back(imageIndexKey); imageIndex.push_back(imageIndexKeyList); } } return imageIndex; } vector<vector<DftImageData>> ImageIndexer::CreateRankDFTIndex(map<string, DftImageData>& imageDftData) { vector<vector<DftImageData>> imageIndex; for (auto const& imageMagnitudeData : imageDftData) { DftImageData imageData; imageData.distance = 0.0; imageData.filePath = imageMagnitudeData.first; imageData.magnitudeMedian = imageMagnitudeData.second.magnitudeMedian; imageData.frequencyMedian = imageMagnitudeData.second.frequencyMedian; imageData.magnitudeQuantums = imageMagnitudeData.second.magnitudeQuantums; imageData.phaseColors = imageMagnitudeData.second.phaseColors; imageData.magnitudeColors = imageMagnitudeData.second.magnitudeColors; imageData.phaseQuantums = imageMagnitudeData.second.phaseQuantums; if (imageIndex.size() == 0) { // Initialize index with the first hash vector<DftImageData> imageIndexKeyList; imageData.distance = 1; imageIndexKeyList.push_back(imageData); imageIndex.push_back(imageIndexKeyList); continue; } // Traverse the index in search of matches in each indexKey lists bool match = false; for (vector<DftImageData>& imageIndexElement : imageIndex) { // Traverse each index key from the index element for (DftImageData& subImageData : imageIndexElement) { imageData.distance = RankDFT(imageData, subImageData, DFT_IMAGE_HEIGHT * DFT_IMAGE_WIDTH); if (imageData.distance/* > 1.00000000000*/) { //TODO TEST: Add a criteria after verifying the algorithm // There is a match, so we add the current match to the index element match = true; imageIndexElement.push_back(imageData); break; } } } if (!match) { // No matches, add the key into its separate index element vector<DftImageData> imageIndexKeyList; imageIndexKeyList.push_back(imageData); imageIndex.push_back(imageIndexKeyList); } } return imageIndex; }<|endoftext|>
<commit_before>/******************************************************************** * @file : pluginbase.cpp * @author : zapline <zhuxianzhang@kingsoft.com> * @date : 2012/12/08 22:49 * @brief : * * *********************************************************************/ #include "pluginbase.h" CPluginBase::~CPluginBase() { } CPluginBase::CPluginBase() { } int CPluginBase::Init() { return 0; } int CPluginBase::UnInit() { return 0; } CDllPluginBase::CDllPluginBase() { } CDllPluginBase::~CDllPluginBase() { } int CDllPluginBase::Init() { } int CDllPluginBase::UnInit() { } <commit_msg>add return<commit_after>/******************************************************************** * @file : pluginbase.cpp * @author : zapline <zhuxianzhang@kingsoft.com> * @date : 2012/12/08 22:49 * @brief : * * *********************************************************************/ #include "pluginbase.h" CPluginBase::~CPluginBase() { } CPluginBase::CPluginBase() { } int CPluginBase::Init() { return 0; } int CPluginBase::UnInit() { return 0; } CDllPluginBase::CDllPluginBase() { } CDllPluginBase::~CDllPluginBase() { } int CDllPluginBase::Init() { return 0; } int CDllPluginBase::UnInit() { return 0; } <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2012 Research In Motion <blackberry-qt@qnx.com> ** Contact: http://www.qt-project.org/legal ** ** This file is part of the Qt Mobility Components. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** 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, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "bbmagnetometer.h" BbMagnetometer::BbMagnetometer(QSensor *sensor) : BbSensorBackend<QMagnetometerReading>(devicePath(), SENSOR_TYPE_MAGNETOMETER, sensor) { setDescription(QLatin1String("Magnetic flux density in Teslas (T)")); } QString BbMagnetometer::devicePath() { return QLatin1String("/dev/sensor/mag"); } bool BbMagnetometer::updateReadingFromEvent(const sensor_event_t &event, QMagnetometerReading *reading) { float x, y, z; QMagnetometer * const magnetometer = qobject_cast<QMagnetometer *>(sensor()); Q_ASSERT(magnetometer); const bool returnGeoValues = magnetometer->returnGeoValues(); if (returnGeoValues) { switch (event.accuracy) { case SENSOR_ACCURACY_UNRELIABLE: reading->setCalibrationLevel(0.0f); break; case SENSOR_ACCURACY_LOW: reading->setCalibrationLevel(0.1f); break; // We determined that MEDIUM should map to 1.0, because existing code samples // show users should pop a calibration screen when seeing < 1.0. The MEDIUM accuracy // is actually good enough not to require calibration, so we don't want to make it seem // like it is required artificially. case SENSOR_ACCURACY_MEDIUM: reading->setCalibrationLevel(1.0f); break; case SENSOR_ACCURACY_HIGH: reading->setCalibrationLevel(1.0f); break; } x = convertValue(event.motion.dsp.x); y = convertValue(event.motion.dsp.y); z = convertValue(event.motion.dsp.z); } else { reading->setCalibrationLevel(1.0f); #ifndef Q_OS_BLACKBERRY_TABLET x = convertValue(event.motion.raw.x); y = convertValue(event.motion.raw.y); z = convertValue(event.motion.raw.z); #else // Blackberry Tablet OS does not support raw reading values x = convertValue(event.motion.dsp.x); y = convertValue(event.motion.dsp.y); z = convertValue(event.motion.dsp.z); #endif } remapAxes(&x, &y, &z); reading->setX(x); reading->setY(y); reading->setZ(z); return true; } qreal BbMagnetometer::convertValue(float bbValueInMicroTesla) { // Convert from microtesla to tesla return bbValueInMicroTesla * 1.0e-6; } <commit_msg>BlackBerry: Fix for GeoValues support<commit_after>/**************************************************************************** ** ** Copyright (C) 2012 Research In Motion <blackberry-qt@qnx.com> ** Contact: http://www.qt-project.org/legal ** ** This file is part of the Qt Mobility Components. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** 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, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "bbmagnetometer.h" BbMagnetometer::BbMagnetometer(QSensor *sensor) : BbSensorBackend<QMagnetometerReading>(devicePath(), SENSOR_TYPE_MAGNETOMETER, sensor) { setDescription(QLatin1String("Magnetic flux density in Teslas (T)")); } QString BbMagnetometer::devicePath() { return QLatin1String("/dev/sensor/mag"); } bool BbMagnetometer::updateReadingFromEvent(const sensor_event_t &event, QMagnetometerReading *reading) { float x, y, z; QMagnetometer * const magnetometer = qobject_cast<QMagnetometer *>(sensor()); if (magnetometer && magnetometer->returnGeoValues()) { switch (event.accuracy) { case SENSOR_ACCURACY_UNRELIABLE: reading->setCalibrationLevel(0.0f); break; case SENSOR_ACCURACY_LOW: reading->setCalibrationLevel(0.1f); break; // We determined that MEDIUM should map to 1.0, because existing code samples // show users should pop a calibration screen when seeing < 1.0. The MEDIUM accuracy // is actually good enough not to require calibration, so we don't want to make it seem // like it is required artificially. case SENSOR_ACCURACY_MEDIUM: reading->setCalibrationLevel(1.0f); break; case SENSOR_ACCURACY_HIGH: reading->setCalibrationLevel(1.0f); break; } x = convertValue(event.motion.dsp.x); y = convertValue(event.motion.dsp.y); z = convertValue(event.motion.dsp.z); } else { reading->setCalibrationLevel(1.0f); #ifndef Q_OS_BLACKBERRY_TABLET x = convertValue(event.motion.raw.x); y = convertValue(event.motion.raw.y); z = convertValue(event.motion.raw.z); #else // Blackberry Tablet OS does not support raw reading values x = convertValue(event.motion.dsp.x); y = convertValue(event.motion.dsp.y); z = convertValue(event.motion.dsp.z); #endif } remapAxes(&x, &y, &z); reading->setX(x); reading->setY(y); reading->setZ(z); return true; } qreal BbMagnetometer::convertValue(float bbValueInMicroTesla) { // Convert from microtesla to tesla return bbValueInMicroTesla * 1.0e-6; } <|endoftext|>
<commit_before>/* * NetworkFmu.cpp * * Created on: 03.06.2016 * Author: hartung */ #include "../include/EmptyFmu.hpp" namespace FMI { EmptyFmu::EmptyFmu(const Initialization::FmuPlan & in) : AbstractFmu(in) { } EmptyFmu::~EmptyFmu() { } FMI::AbstractFmu* EmptyFmu::duplicate() { throw std::runtime_error("Network FMUs can't be duplicated."); } void EmptyFmu::stepCompleted() { } FMI::FmuEventInfo EmptyFmu::eventUpdate() { return FMI::FmuEventInfo(); } double EmptyFmu::getDefaultStart() const { return 0.0; } double EmptyFmu::getDefaultStop() const { return 0.0; } void EmptyFmu::initialize() { } void EmptyFmu::getValuesInternal(vector<real_type>& out, const vector<size_type>& references) const { _values.getValues<real_type>(out,references); } void EmptyFmu::getValuesInternal(vector<int_type>& out, const vector<size_type>& references) const { _values.getValues<int_type>(out,references); } void EmptyFmu::getValuesInternal(vector<bool_type>& out, const vector<size_type>& references) const { _values.getValues<bool_type>(out,references); } void EmptyFmu::getValuesInternal(vector<string_type>& out, const vector<size_type>& references) const { _values.getValues<string_type>(out,references); } void EmptyFmu::setValuesInternal(const vector<real_type>& out, const vector<size_type>& references) { _values.setValues<real_type>(out,references); } void EmptyFmu::setValuesInternal(const vector<int_type>& out, const vector<size_type>& references) { _values.setValues<int_type>(out,references); } void EmptyFmu::setValuesInternal(const vector<bool_type>& out, const vector<size_type>& references) { _values.setValues<bool_type>(out,references); } void EmptyFmu::setValuesInternal(const vector<string_type>& out, const vector<size_type>& references) { _values.setValues<string_type>(out,references); } void EmptyFmu::getStatesInternal(real_type* states) const { } void EmptyFmu::setStatesInternal(const real_type* states) { } void EmptyFmu::getStateDerivativesInternal(real_type* stateDerivatives) { } void EmptyFmu::setNumValues(const size_type& numReals, const size_type& numInts, const size_type& numBools, const size_type& numStrings) { _values = FMI::ValueCollection(numReals,numInts,numBools,numStrings); FMI::ValueReferenceCollection collection(numReals,numInts,numBools,numStrings); for(size_type i=0;i<collection.getValues<real_type>().size();++i) collection.getValues<real_type>()[i] = i; for(size_type i=0;i<collection.getValues<int_type>().size();++i) collection.getValues<int_type>()[i] = i; for(size_type i=0;i<collection.getValues<bool_type>().size();++i) collection.getValues<bool_type>()[i] = i; for(size_type i=0;i<collection.getValues<string_type>().size();++i) collection.getValues<string_type>()[i] = i; this->_allValueReferences = collection; this->_eventValueReferences = collection; } const FMI::ValueCollection & EmptyFmu::getEmptyFmuValues() const { return _values; } void EmptyFmu::getEventIndicatorsInternal(real_type* eventIndicators) { } } /* namespace Network */ <commit_msg>Remove namespace<commit_after>/* * NetworkFmu.cpp * * Created on: 03.06.2016 * Author: hartung */ #include "../include/EmptyFmu.hpp" namespace FMI { EmptyFmu::EmptyFmu(const Initialization::FmuPlan & in) : AbstractFmu(in) { } EmptyFmu::~EmptyFmu() { } AbstractFmu* EmptyFmu::duplicate() { throw std::runtime_error("Network FMUs can't be duplicated."); } void EmptyFmu::stepCompleted() { } FmuEventInfo EmptyFmu::eventUpdate() { return FmuEventInfo(); } double EmptyFmu::getDefaultStart() const { return 0.0; } double EmptyFmu::getDefaultStop() const { return 0.0; } void EmptyFmu::initialize() { } void EmptyFmu::getValuesInternal(vector<real_type>& out, const vector<size_type>& references) const { _values.getValues<real_type>(out,references); } void EmptyFmu::getValuesInternal(vector<int_type>& out, const vector<size_type>& references) const { _values.getValues<int_type>(out,references); } void EmptyFmu::getValuesInternal(vector<bool_type>& out, const vector<size_type>& references) const { _values.getValues<bool_type>(out,references); } void EmptyFmu::getValuesInternal(vector<string_type>& out, const vector<size_type>& references) const { _values.getValues<string_type>(out,references); } void EmptyFmu::setValuesInternal(const vector<real_type>& out, const vector<size_type>& references) { _values.setValues<real_type>(out,references); } void EmptyFmu::setValuesInternal(const vector<int_type>& out, const vector<size_type>& references) { _values.setValues<int_type>(out,references); } void EmptyFmu::setValuesInternal(const vector<bool_type>& out, const vector<size_type>& references) { _values.setValues<bool_type>(out,references); } void EmptyFmu::setValuesInternal(const vector<string_type>& out, const vector<size_type>& references) { _values.setValues<string_type>(out,references); } void EmptyFmu::getStatesInternal(real_type* states) const { } void EmptyFmu::setStatesInternal(const real_type* states) { } void EmptyFmu::getStateDerivativesInternal(real_type* stateDerivatives) { } void EmptyFmu::setNumValues(const size_type& numReals, const size_type& numInts, const size_type& numBools, const size_type& numStrings) { _values = ValueCollection(numReals,numInts,numBools,numStrings); ValueReferenceCollection collection(numReals,numInts,numBools,numStrings); for(size_type i=0;i<collection.getValues<real_type>().size();++i) collection.getValues<real_type>()[i] = i; for(size_type i=0;i<collection.getValues<int_type>().size();++i) collection.getValues<int_type>()[i] = i; for(size_type i=0;i<collection.getValues<bool_type>().size();++i) collection.getValues<bool_type>()[i] = i; for(size_type i=0;i<collection.getValues<string_type>().size();++i) collection.getValues<string_type>()[i] = i; this->_allValueReferences = collection; this->_eventValueReferences = collection; } const ValueCollection & EmptyFmu::getEmptyFmuValues() const { return _values; } void EmptyFmu::getEventIndicatorsInternal(real_type* eventIndicators) { } } /* namespace Network */ <|endoftext|>
<commit_before>/* Copyright (C) 1998 by Jorrit Tyberghein and Dan Ogles. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ // HICACHE.CPP // Hi-color texture/lightmap cache // An abstract class: derive the specific class from this class // Written by Dan Ogles #include "sysdef.h" #include "cssys/common/system.h" #include "cs3d/opengl/ogl_hicache.h" #include "cs3d/opengl/ogl_txtmgr.h" #include "ilghtmap.h" #include "ipolygon.h" #include "itexture.h" HighColorCache::HighColorCache(int max_size, HIGHCOLOR_TYPE type, int bpp) { HighColorCache::type = type; cache_size=max_size; num=0; total_size=0; head=tail=NULL; HighColorCache::bpp = bpp; } HighColorCache::~HighColorCache() { } void HighColorCache::Add (ITextureHandle* txt_handle) { HighColorCache_Data *cached_texture; int size = 0; if (type!=HIGHCOLOR_TEXCACHE) return; for (int c =0; c<4; c++) { int width, height; txt_handle->GetMipMapDimensions (c, width, height); size += width * height; } size *= bpp/8; bool bIsInVideoMemory; csTextureMMOpenGL* txt_mm = (csTextureMMOpenGL*)GetcsTextureMMFromITextureHandle (txt_handle); bIsInVideoMemory = txt_mm->is_in_videomemory (); if (bIsInVideoMemory) { // move unit to front (MRU) cached_texture = txt_mm->get_hicolorcache (); if (!cached_texture) return; if (cached_texture != head) { if (cached_texture->prev) cached_texture->prev->next = cached_texture->next; else head = cached_texture->next; if (cached_texture->next) cached_texture->next->prev = cached_texture->prev; else tail = cached_texture->prev; cached_texture->prev = NULL; cached_texture->next = head; if (head) head->prev = cached_texture; else tail = cached_texture; head = cached_texture; } } else { // unit is not in memory. load it into the cache while (total_size + size >= cache_size) { // out of memory. remove units from bottom of list. HighColorCache_Data* l = tail; ITextureHandle* piMMC; l->pSource->QueryInterface (IID_ITextureHandle, (void**)&piMMC); tail = tail->prev; if (tail) tail->next = NULL; else head = NULL; l->prev = NULL; csTextureMMOpenGL* txt_mm2 = (csTextureMMOpenGL*)GetcsTextureMMFromITextureHandle (piMMC); txt_mm2->set_in_videomemory (false); txt_mm2->set_hicolorcache (NULL); Unload (l); // unload it. num--; total_size -= l->lSize; piMMC->Release (); } // now load the unit. num++; total_size += size; CHK (cached_texture = new HighColorCache_Data); cached_texture->next = head; cached_texture->prev = NULL; if (head) head->prev = cached_texture; else tail = cached_texture; head = cached_texture; cached_texture->pSource = txt_handle; cached_texture->lSize = size; txt_mm->set_in_videomemory (true); txt_mm->set_hicolorcache (cached_texture); Load (cached_texture); // load it. } } void HighColorCache::Add(IPolygonTexture *polytex) { HighColorCache_Data *cached_texture; ILightMap *piLM; HighColorCache_Data* l; // first recalculation of lightmap bool dl; polytex->RecalculateDynamicLights(dl); polytex->GetLightMap (&piLM); if (type != HIGHCOLOR_LITCACHE || piLM == NULL) return; int size, width, height; piLM->GetWidth(width); piLM->GetHeight(height); size = width*height*(bpp/8); bool bInVideoMemory; piLM->GetInVideoMemory( bInVideoMemory ); if (bInVideoMemory) { piLM->GetHighColorCache(&l); if (l->next != NULL) l->next->prev = l->prev; if (l->prev != NULL) l->prev->next = l->next; piLM->SetInVideoMemory(false); piLM->SetHighColorCache(NULL); Unload(l); // unload it. num--; total_size -= l->lSize; } piLM->GetInVideoMemory( bInVideoMemory ); if (bInVideoMemory) { // move unit to front (MRU) piLM->GetHighColorCache(&cached_texture); //ASSERT(cached_texture); if(cached_texture != head) { if(cached_texture->prev) cached_texture->prev->next = cached_texture->next; else head = cached_texture->next; if(cached_texture->next) cached_texture->next->prev = cached_texture->prev; else tail = cached_texture->prev; cached_texture->prev = NULL; cached_texture->next = head; if(head) head->prev = cached_texture; else tail = cached_texture; head = cached_texture; } } else { // unit is not in memory. load it into the cache while(total_size + size >= cache_size) { ILightMap* ilm; l->pSource->QueryInterface( IID_ILightMap, (void**)&ilm ); assert( ilm ); // out of memory. remove units from bottom of list. l = tail; tail = tail->prev; if(tail) tail->next = NULL; else head = NULL; l->prev = NULL; ilm->SetInVideoMemory(false); ilm->SetHighColorCache(NULL); Unload(l); // unload it. num--; total_size -= l->lSize; ilm->Release(); } // now load the unit. num++; total_size += size; CHK (cached_texture = new HighColorCache_Data); cached_texture->next = head; cached_texture->prev = NULL; if(head) head->prev = cached_texture; else tail = cached_texture; head = cached_texture; cached_texture->pSource = piLM; cached_texture->lSize = size; piLM->SetInVideoMemory(true); piLM->SetHighColorCache(cached_texture); Load(cached_texture); // load it. } FINAL_RELEASE( piLM ); } void HighColorCache::Clear () { while(head) { HighColorCache_Data *n = head->next; head->next = head->prev = NULL; Unload (head); if(type==HIGHCOLOR_TEXCACHE) { ITextureHandle* piMMC; head->pSource->QueryInterface (IID_ITextureHandle, (void**)&piMMC); csTextureMMOpenGL* txt_mm2 = (csTextureMMOpenGL*)GetcsTextureMMFromITextureHandle (piMMC); txt_mm2->set_in_videomemory (false); txt_mm2->set_hicolorcache (NULL); piMMC->Release (); } else if(type==HIGHCOLOR_LITCACHE) { ILightMap* piLM; head->pSource->QueryInterface( IID_ILightMap, (void**)&piLM ); piLM->SetHighColorCache(NULL); piLM->SetInVideoMemory(false); piLM->Release(); } head = n; } head = tail = NULL; total_size = 0; num = 0; } <commit_msg><commit_after>/* Copyright (C) 1998 by Jorrit Tyberghein and Dan Ogles. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ // HICACHE.CPP // Hi-color texture/lightmap cache // An abstract class: derive the specific class from this class // Written by Dan Ogles #include "sysdef.h" #include "cssys/common/system.h" #include "cs3d/opengl/ogl_hicache.h" #include "cs3d/opengl/ogl_txtmgr.h" #include "ilghtmap.h" #include "ipolygon.h" #include "itexture.h" HighColorCache::HighColorCache(int max_size, HIGHCOLOR_TYPE type, int bpp) { HighColorCache::type = type; cache_size=max_size; num=0; total_size=0; head=tail=NULL; HighColorCache::bpp = bpp; } HighColorCache::~HighColorCache() { } void HighColorCache::Add (ITextureHandle* txt_handle) { HighColorCache_Data *cached_texture; int size = 0; if (type!=HIGHCOLOR_TEXCACHE) return; for (int c =0; c<4; c++) { int width, height; txt_handle->GetMipMapDimensions (c, width, height); size += width * height; } size *= bpp/8; bool bIsInVideoMemory; csTextureMMOpenGL* txt_mm = (csTextureMMOpenGL*)GetcsTextureMMFromITextureHandle (txt_handle); bIsInVideoMemory = txt_mm->is_in_videomemory (); if (bIsInVideoMemory) { // move unit to front (MRU) cached_texture = txt_mm->get_hicolorcache (); if (!cached_texture) return; if (cached_texture != head) { if (cached_texture->prev) cached_texture->prev->next = cached_texture->next; else head = cached_texture->next; if (cached_texture->next) cached_texture->next->prev = cached_texture->prev; else tail = cached_texture->prev; cached_texture->prev = NULL; cached_texture->next = head; if (head) head->prev = cached_texture; else tail = cached_texture; head = cached_texture; } } else { // unit is not in memory. load it into the cache while (total_size + size >= cache_size) { // out of memory. remove units from bottom of list. HighColorCache_Data* l = tail; ITextureHandle* piMMC; l->pSource->QueryInterface (IID_ITextureHandle, (void**)&piMMC); tail = tail->prev; if (tail) tail->next = NULL; else head = NULL; l->prev = NULL; csTextureMMOpenGL* txt_mm2 = (csTextureMMOpenGL*)GetcsTextureMMFromITextureHandle (piMMC); txt_mm2->set_in_videomemory (false); txt_mm2->set_hicolorcache (NULL); Unload (l); // unload it. num--; total_size -= l->lSize; piMMC->Release (); } // now load the unit. num++; total_size += size; CHK (cached_texture = new HighColorCache_Data); cached_texture->next = head; cached_texture->prev = NULL; if (head) head->prev = cached_texture; else tail = cached_texture; head = cached_texture; cached_texture->pSource = txt_handle; cached_texture->lSize = size; txt_mm->set_in_videomemory (true); txt_mm->set_hicolorcache (cached_texture); Load (cached_texture); // load it. } } void HighColorCache::Add(IPolygonTexture *polytex) { HighColorCache_Data *cached_texture; ILightMap *piLM; HighColorCache_Data* l; polytex->GetLightMap (&piLM); if (type != HIGHCOLOR_LITCACHE || piLM == NULL) return; int size, width, height; piLM->GetWidth(width); piLM->GetHeight(height); size = width*height*(bpp/8); bool bInVideoMemory; piLM->GetInVideoMemory( bInVideoMemory ); // first recalculation of lightmap bool lightmapchanged; polytex->RecalculateDynamicLights(lightmapchanged); // if lightmap has changed, uncache it if it was cached so we // can reload it if (lightmapchanged && bInVideoMemory) { piLM->GetHighColorCache(&l); if (l->next != NULL) l->next->prev = l->prev; if (l->prev != NULL) l->prev->next = l->next; piLM->SetInVideoMemory(false); piLM->SetHighColorCache(NULL); Unload(l); // unload it. num--; total_size -= l->lSize; } piLM->GetInVideoMemory( bInVideoMemory ); if (bInVideoMemory) { // move unit to front (MRU) piLM->GetHighColorCache(&cached_texture); //ASSERT(cached_texture); if(cached_texture != head) { if(cached_texture->prev) cached_texture->prev->next = cached_texture->next; else head = cached_texture->next; if(cached_texture->next) cached_texture->next->prev = cached_texture->prev; else tail = cached_texture->prev; cached_texture->prev = NULL; cached_texture->next = head; if(head) head->prev = cached_texture; else tail = cached_texture; head = cached_texture; } } else { // unit is not in memory. load it into the cache while(total_size + size >= cache_size) { ILightMap* ilm; l->pSource->QueryInterface( IID_ILightMap, (void**)&ilm ); assert( ilm ); // out of memory. remove units from bottom of list. l = tail; tail = tail->prev; if(tail) tail->next = NULL; else head = NULL; l->prev = NULL; ilm->SetInVideoMemory(false); ilm->SetHighColorCache(NULL); Unload(l); // unload it. num--; total_size -= l->lSize; ilm->Release(); } // now load the unit. num++; total_size += size; CHK (cached_texture = new HighColorCache_Data); cached_texture->next = head; cached_texture->prev = NULL; if(head) head->prev = cached_texture; else tail = cached_texture; head = cached_texture; cached_texture->pSource = piLM; cached_texture->lSize = size; piLM->SetInVideoMemory(true); piLM->SetHighColorCache(cached_texture); Load(cached_texture); // load it. } FINAL_RELEASE( piLM ); } void HighColorCache::Clear () { while(head) { HighColorCache_Data *n = head->next; head->next = head->prev = NULL; Unload (head); if(type==HIGHCOLOR_TEXCACHE) { ITextureHandle* piMMC; head->pSource->QueryInterface (IID_ITextureHandle, (void**)&piMMC); csTextureMMOpenGL* txt_mm2 = (csTextureMMOpenGL*)GetcsTextureMMFromITextureHandle (piMMC); txt_mm2->set_in_videomemory (false); txt_mm2->set_hicolorcache (NULL); piMMC->Release (); } else if(type==HIGHCOLOR_LITCACHE) { ILightMap* piLM; head->pSource->QueryInterface( IID_ILightMap, (void**)&piLM ); piLM->SetHighColorCache(NULL); piLM->SetInVideoMemory(false); piLM->Release(); } head = n; } head = tail = NULL; total_size = 0; num = 0; } <|endoftext|>
<commit_before>#include "selfdrive/ui/ui.h" #include <unistd.h> #include <cassert> #include <cmath> #include <cstdio> #include "selfdrive/common/util.h" #include "selfdrive/common/watchdog.h" #include "selfdrive/hardware/hw.h" #define BACKLIGHT_DT 0.05 #define BACKLIGHT_TS 10.00 #define BACKLIGHT_OFFROAD 75 // Projects a point in car to space to the corresponding point in full frame // image space. static bool calib_frame_to_full_frame(const UIState *s, float in_x, float in_y, float in_z, vertex_data *out) { const float margin = 500.0f; const vec3 pt = (vec3){{in_x, in_y, in_z}}; const vec3 Ep = matvecmul3(s->scene.view_from_calib, pt); const vec3 KEp = matvecmul3(s->wide_camera ? ecam_intrinsic_matrix : fcam_intrinsic_matrix, Ep); // Project. float x = KEp.v[0] / KEp.v[2]; float y = KEp.v[1] / KEp.v[2]; nvgTransformPoint(&out->x, &out->y, s->car_space_transform, x, y); return out->x >= -margin && out->x <= s->fb_w + margin && out->y >= -margin && out->y <= s->fb_h + margin; } static int get_path_length_idx(const cereal::ModelDataV2::XYZTData::Reader &line, const float path_height) { const auto line_x = line.getX(); int max_idx = 0; for (int i = 0; i < TRAJECTORY_SIZE && line_x[i] < path_height; ++i) { max_idx = i; } return max_idx; } static void update_leads(UIState *s, const cereal::ModelDataV2::Reader &model) { auto leads = model.getLeadsV3(); auto model_position = model.getPosition(); for (int i = 0; i < 2; ++i) { if (leads[i].getProb() > 0.5) { float z = model_position.getZ()[get_path_length_idx(model_position, leads[i].getX()[0])]; calib_frame_to_full_frame(s, leads[i].getX()[0], leads[i].getY()[0], z + 1.22, &s->scene.lead_vertices[i]); } } } static void update_line_data(const UIState *s, const cereal::ModelDataV2::XYZTData::Reader &line, float y_off, float z_off, line_vertices_data *pvd, int max_idx) { const auto line_x = line.getX(), line_y = line.getY(), line_z = line.getZ(); vertex_data *v = &pvd->v[0]; for (int i = 0; i <= max_idx; i++) { v += calib_frame_to_full_frame(s, line_x[i], line_y[i] - y_off, line_z[i] + z_off, v); } for (int i = max_idx; i >= 0; i--) { v += calib_frame_to_full_frame(s, line_x[i], line_y[i] + y_off, line_z[i] + z_off, v); } pvd->cnt = v - pvd->v; assert(pvd->cnt <= std::size(pvd->v)); } static void update_model(UIState *s, const cereal::ModelDataV2::Reader &model) { UIScene &scene = s->scene; auto model_position = model.getPosition(); float max_distance = std::clamp(model_position.getX()[TRAJECTORY_SIZE - 1], MIN_DRAW_DISTANCE, MAX_DRAW_DISTANCE); // update lane lines const auto lane_lines = model.getLaneLines(); const auto lane_line_probs = model.getLaneLineProbs(); int max_idx = get_path_length_idx(lane_lines[0], max_distance); for (int i = 0; i < std::size(scene.lane_line_vertices); i++) { scene.lane_line_probs[i] = lane_line_probs[i]; update_line_data(s, lane_lines[i], 0.025 * scene.lane_line_probs[i], 0, &scene.lane_line_vertices[i], max_idx); } // update road edges const auto road_edges = model.getRoadEdges(); const auto road_edge_stds = model.getRoadEdgeStds(); for (int i = 0; i < std::size(scene.road_edge_vertices); i++) { scene.road_edge_stds[i] = road_edge_stds[i]; update_line_data(s, road_edges[i], 0.025, 0, &scene.road_edge_vertices[i], max_idx); } // update path auto lead_one = model.getLeadsV3()[0]; if (lead_one.getProb() > 0.5) { const float lead_d = lead_one.getX()[0] * 2.; max_distance = std::clamp((float)(lead_d - fmin(lead_d * 0.35, 10.)), 0.0f, max_distance); } max_idx = get_path_length_idx(model_position, max_distance); update_line_data(s, model_position, 0.5, 1.22, &scene.track_vertices, max_idx); } static void update_sockets(UIState *s) { s->sm->update(0); } static void update_state(UIState *s) { SubMaster &sm = *(s->sm); UIScene &scene = s->scene; // update engageability and DM icons at 2Hz if (sm.frame % (UI_FREQ / 2) == 0) { auto cs = sm["controlsState"].getControlsState(); scene.engageable = cs.getEngageable() || cs.getEnabled(); scene.dm_active = sm["driverMonitoringState"].getDriverMonitoringState().getIsActiveMode(); } if (sm.updated("modelV2") && s->vg) { auto model = sm["modelV2"].getModelV2(); update_model(s, model); update_leads(s, model); } if (sm.updated("liveCalibration")) { scene.world_objects_visible = true; auto rpy_list = sm["liveCalibration"].getLiveCalibration().getRpyCalib(); Eigen::Vector3d rpy; rpy << rpy_list[0], rpy_list[1], rpy_list[2]; Eigen::Matrix3d device_from_calib = euler2rot(rpy); Eigen::Matrix3d view_from_device; view_from_device << 0,1,0, 0,0,1, 1,0,0; Eigen::Matrix3d view_from_calib = view_from_device * device_from_calib; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { scene.view_from_calib.v[i*3 + j] = view_from_calib(i,j); } } } if (sm.updated("pandaStates")) { auto pandaStates = sm["pandaStates"].getPandaStates(); if (pandaStates.size() > 0) { scene.pandaType = pandaStates[0].getPandaType(); if (scene.pandaType != cereal::PandaState::PandaType::UNKNOWN) { scene.ignition = false; for (const auto& pandaState : pandaStates) { scene.ignition |= pandaState.getIgnitionLine() || pandaState.getIgnitionCan(); } } } } else if ((s->sm->frame - s->sm->rcv_frame("pandaStates")) > 5*UI_FREQ) { scene.pandaType = cereal::PandaState::PandaType::UNKNOWN; } if (sm.updated("carParams")) { scene.longitudinal_control = sm["carParams"].getCarParams().getOpenpilotLongitudinalControl(); } if (sm.updated("sensorEvents")) { for (auto sensor : sm["sensorEvents"].getSensorEvents()) { if (!scene.started && sensor.which() == cereal::SensorEventData::ACCELERATION) { auto accel = sensor.getAcceleration().getV(); if (accel.totalSize().wordCount) { // TODO: sometimes empty lists are received. Figure out why scene.accel_sensor = accel[2]; } } else if (!scene.started && sensor.which() == cereal::SensorEventData::GYRO_UNCALIBRATED) { auto gyro = sensor.getGyroUncalibrated().getV(); if (gyro.totalSize().wordCount) { scene.gyro_sensor = gyro[1]; } } } } if (sm.updated("roadCameraState")) { auto camera_state = sm["roadCameraState"].getRoadCameraState(); float max_lines = Hardware::EON() ? 5408 : 1904; float max_gain = Hardware::EON() ? 1.0: 10.0; float max_ev = max_lines * max_gain; if (Hardware::TICI) { max_ev /= 6; } float ev = camera_state.getGain() * float(camera_state.getIntegLines()); scene.light_sensor = std::clamp<float>(1.0 - (ev / max_ev), 0.0, 1.0); } scene.started = sm["deviceState"].getDeviceState().getStarted() && scene.ignition; } static void update_params(UIState *s) { const uint64_t frame = s->sm->frame; UIScene &scene = s->scene; if (frame % (5*UI_FREQ) == 0) { scene.is_metric = Params().getBool("IsMetric"); } } static void update_status(UIState *s) { if (s->scene.started && s->sm->updated("controlsState")) { auto controls_state = (*s->sm)["controlsState"].getControlsState(); auto alert_status = controls_state.getAlertStatus(); if (alert_status == cereal::ControlsState::AlertStatus::USER_PROMPT) { s->status = STATUS_WARNING; } else if (alert_status == cereal::ControlsState::AlertStatus::CRITICAL) { s->status = STATUS_ALERT; } else { s->status = controls_state.getEnabled() ? STATUS_ENGAGED : STATUS_DISENGAGED; } } // Handle onroad/offroad transition static bool started_prev = false; if (s->scene.started != started_prev) { if (s->scene.started) { s->status = STATUS_DISENGAGED; s->scene.started_frame = s->sm->frame; s->scene.end_to_end = Params().getBool("EndToEndToggle"); s->wide_camera = Hardware::TICI() ? Params().getBool("EnableWideCamera") : false; } // Invisible until we receive a calibration message. s->scene.world_objects_visible = false; } started_prev = s->scene.started; } QUIState::QUIState(QObject *parent) : QObject(parent) { ui_state.sm = std::make_unique<SubMaster, const std::initializer_list<const char *>>({ "modelV2", "controlsState", "liveCalibration", "deviceState", "roadCameraState", "pandaStates", "carParams", "driverMonitoringState", "sensorEvents", "carState", "liveLocationKalman", }); ui_state.wide_camera = Hardware::TICI() ? Params().getBool("EnableWideCamera") : false; // update timer timer = new QTimer(this); QObject::connect(timer, &QTimer::timeout, this, &QUIState::update); timer->start(1000 / UI_FREQ); } void QUIState::update() { update_params(&ui_state); update_sockets(&ui_state); update_state(&ui_state); update_status(&ui_state); if (ui_state.scene.started != started_prev || ui_state.sm->frame == 1) { started_prev = ui_state.scene.started; emit offroadTransition(!ui_state.scene.started); } watchdog_kick(); emit uiUpdate(ui_state); } Device::Device(QObject *parent) : brightness_filter(BACKLIGHT_OFFROAD, BACKLIGHT_TS, BACKLIGHT_DT), QObject(parent) { } void Device::update(const UIState &s) { updateBrightness(s); updateWakefulness(s); // TODO: remove from UIState and use signals QUIState::ui_state.awake = awake; } void Device::setAwake(bool on, bool reset) { if (on != awake) { awake = on; Hardware::set_display_power(awake); LOGD("setting display power %d", awake); emit displayPowerChanged(awake); } if (reset) { awake_timeout = 30 * UI_FREQ; } } void Device::updateBrightness(const UIState &s) { // Scale to 0% to 100% float clipped_brightness = 100.0 * s.scene.light_sensor; // CIE 1931 - https://www.photonstophotos.net/GeneralTopics/Exposure/Psychometric_Lightness_and_Gamma.htm if (clipped_brightness <= 8) { clipped_brightness = (clipped_brightness / 903.3); } else { clipped_brightness = std::pow((clipped_brightness + 16.0) / 116.0, 3.0); } // Scale back to 10% to 100% clipped_brightness = std::clamp(100.0f * clipped_brightness, 10.0f, 100.0f); if (!s.scene.started) { clipped_brightness = BACKLIGHT_OFFROAD; } int brightness = brightness_filter.update(clipped_brightness); if (!awake) { brightness = 0; } if (brightness != last_brightness) { std::thread{Hardware::set_brightness, brightness}.detach(); } last_brightness = brightness; } void Device::updateWakefulness(const UIState &s) { awake_timeout = std::max(awake_timeout - 1, 0); bool should_wake = s.scene.started || s.scene.ignition; if (!should_wake) { // tap detection while display is off bool accel_trigger = abs(s.scene.accel_sensor - accel_prev) > 0.2; bool gyro_trigger = abs(s.scene.gyro_sensor - gyro_prev) > 0.15; should_wake = accel_trigger && gyro_trigger; gyro_prev = s.scene.gyro_sensor; accel_prev = (accel_prev * (accel_samples - 1) + s.scene.accel_sensor) / accel_samples; } setAwake(awake_timeout, should_wake); } <commit_msg>ui.cc: fix Hardware::TICI() check for screen brightness (#22847)<commit_after>#include "selfdrive/ui/ui.h" #include <unistd.h> #include <cassert> #include <cmath> #include <cstdio> #include "selfdrive/common/util.h" #include "selfdrive/common/watchdog.h" #include "selfdrive/hardware/hw.h" #define BACKLIGHT_DT 0.05 #define BACKLIGHT_TS 10.00 #define BACKLIGHT_OFFROAD 75 // Projects a point in car to space to the corresponding point in full frame // image space. static bool calib_frame_to_full_frame(const UIState *s, float in_x, float in_y, float in_z, vertex_data *out) { const float margin = 500.0f; const vec3 pt = (vec3){{in_x, in_y, in_z}}; const vec3 Ep = matvecmul3(s->scene.view_from_calib, pt); const vec3 KEp = matvecmul3(s->wide_camera ? ecam_intrinsic_matrix : fcam_intrinsic_matrix, Ep); // Project. float x = KEp.v[0] / KEp.v[2]; float y = KEp.v[1] / KEp.v[2]; nvgTransformPoint(&out->x, &out->y, s->car_space_transform, x, y); return out->x >= -margin && out->x <= s->fb_w + margin && out->y >= -margin && out->y <= s->fb_h + margin; } static int get_path_length_idx(const cereal::ModelDataV2::XYZTData::Reader &line, const float path_height) { const auto line_x = line.getX(); int max_idx = 0; for (int i = 0; i < TRAJECTORY_SIZE && line_x[i] < path_height; ++i) { max_idx = i; } return max_idx; } static void update_leads(UIState *s, const cereal::ModelDataV2::Reader &model) { auto leads = model.getLeadsV3(); auto model_position = model.getPosition(); for (int i = 0; i < 2; ++i) { if (leads[i].getProb() > 0.5) { float z = model_position.getZ()[get_path_length_idx(model_position, leads[i].getX()[0])]; calib_frame_to_full_frame(s, leads[i].getX()[0], leads[i].getY()[0], z + 1.22, &s->scene.lead_vertices[i]); } } } static void update_line_data(const UIState *s, const cereal::ModelDataV2::XYZTData::Reader &line, float y_off, float z_off, line_vertices_data *pvd, int max_idx) { const auto line_x = line.getX(), line_y = line.getY(), line_z = line.getZ(); vertex_data *v = &pvd->v[0]; for (int i = 0; i <= max_idx; i++) { v += calib_frame_to_full_frame(s, line_x[i], line_y[i] - y_off, line_z[i] + z_off, v); } for (int i = max_idx; i >= 0; i--) { v += calib_frame_to_full_frame(s, line_x[i], line_y[i] + y_off, line_z[i] + z_off, v); } pvd->cnt = v - pvd->v; assert(pvd->cnt <= std::size(pvd->v)); } static void update_model(UIState *s, const cereal::ModelDataV2::Reader &model) { UIScene &scene = s->scene; auto model_position = model.getPosition(); float max_distance = std::clamp(model_position.getX()[TRAJECTORY_SIZE - 1], MIN_DRAW_DISTANCE, MAX_DRAW_DISTANCE); // update lane lines const auto lane_lines = model.getLaneLines(); const auto lane_line_probs = model.getLaneLineProbs(); int max_idx = get_path_length_idx(lane_lines[0], max_distance); for (int i = 0; i < std::size(scene.lane_line_vertices); i++) { scene.lane_line_probs[i] = lane_line_probs[i]; update_line_data(s, lane_lines[i], 0.025 * scene.lane_line_probs[i], 0, &scene.lane_line_vertices[i], max_idx); } // update road edges const auto road_edges = model.getRoadEdges(); const auto road_edge_stds = model.getRoadEdgeStds(); for (int i = 0; i < std::size(scene.road_edge_vertices); i++) { scene.road_edge_stds[i] = road_edge_stds[i]; update_line_data(s, road_edges[i], 0.025, 0, &scene.road_edge_vertices[i], max_idx); } // update path auto lead_one = model.getLeadsV3()[0]; if (lead_one.getProb() > 0.5) { const float lead_d = lead_one.getX()[0] * 2.; max_distance = std::clamp((float)(lead_d - fmin(lead_d * 0.35, 10.)), 0.0f, max_distance); } max_idx = get_path_length_idx(model_position, max_distance); update_line_data(s, model_position, 0.5, 1.22, &scene.track_vertices, max_idx); } static void update_sockets(UIState *s) { s->sm->update(0); } static void update_state(UIState *s) { SubMaster &sm = *(s->sm); UIScene &scene = s->scene; // update engageability and DM icons at 2Hz if (sm.frame % (UI_FREQ / 2) == 0) { auto cs = sm["controlsState"].getControlsState(); scene.engageable = cs.getEngageable() || cs.getEnabled(); scene.dm_active = sm["driverMonitoringState"].getDriverMonitoringState().getIsActiveMode(); } if (sm.updated("modelV2") && s->vg) { auto model = sm["modelV2"].getModelV2(); update_model(s, model); update_leads(s, model); } if (sm.updated("liveCalibration")) { scene.world_objects_visible = true; auto rpy_list = sm["liveCalibration"].getLiveCalibration().getRpyCalib(); Eigen::Vector3d rpy; rpy << rpy_list[0], rpy_list[1], rpy_list[2]; Eigen::Matrix3d device_from_calib = euler2rot(rpy); Eigen::Matrix3d view_from_device; view_from_device << 0,1,0, 0,0,1, 1,0,0; Eigen::Matrix3d view_from_calib = view_from_device * device_from_calib; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { scene.view_from_calib.v[i*3 + j] = view_from_calib(i,j); } } } if (sm.updated("pandaStates")) { auto pandaStates = sm["pandaStates"].getPandaStates(); if (pandaStates.size() > 0) { scene.pandaType = pandaStates[0].getPandaType(); if (scene.pandaType != cereal::PandaState::PandaType::UNKNOWN) { scene.ignition = false; for (const auto& pandaState : pandaStates) { scene.ignition |= pandaState.getIgnitionLine() || pandaState.getIgnitionCan(); } } } } else if ((s->sm->frame - s->sm->rcv_frame("pandaStates")) > 5*UI_FREQ) { scene.pandaType = cereal::PandaState::PandaType::UNKNOWN; } if (sm.updated("carParams")) { scene.longitudinal_control = sm["carParams"].getCarParams().getOpenpilotLongitudinalControl(); } if (sm.updated("sensorEvents")) { for (auto sensor : sm["sensorEvents"].getSensorEvents()) { if (!scene.started && sensor.which() == cereal::SensorEventData::ACCELERATION) { auto accel = sensor.getAcceleration().getV(); if (accel.totalSize().wordCount) { // TODO: sometimes empty lists are received. Figure out why scene.accel_sensor = accel[2]; } } else if (!scene.started && sensor.which() == cereal::SensorEventData::GYRO_UNCALIBRATED) { auto gyro = sensor.getGyroUncalibrated().getV(); if (gyro.totalSize().wordCount) { scene.gyro_sensor = gyro[1]; } } } } if (sm.updated("roadCameraState")) { auto camera_state = sm["roadCameraState"].getRoadCameraState(); float max_lines = Hardware::EON() ? 5408 : 1904; float max_gain = Hardware::EON() ? 1.0: 10.0; float max_ev = max_lines * max_gain; if (Hardware::TICI()) { max_ev /= 6; } float ev = camera_state.getGain() * float(camera_state.getIntegLines()); scene.light_sensor = std::clamp<float>(1.0 - (ev / max_ev), 0.0, 1.0); } scene.started = sm["deviceState"].getDeviceState().getStarted() && scene.ignition; } static void update_params(UIState *s) { const uint64_t frame = s->sm->frame; UIScene &scene = s->scene; if (frame % (5*UI_FREQ) == 0) { scene.is_metric = Params().getBool("IsMetric"); } } static void update_status(UIState *s) { if (s->scene.started && s->sm->updated("controlsState")) { auto controls_state = (*s->sm)["controlsState"].getControlsState(); auto alert_status = controls_state.getAlertStatus(); if (alert_status == cereal::ControlsState::AlertStatus::USER_PROMPT) { s->status = STATUS_WARNING; } else if (alert_status == cereal::ControlsState::AlertStatus::CRITICAL) { s->status = STATUS_ALERT; } else { s->status = controls_state.getEnabled() ? STATUS_ENGAGED : STATUS_DISENGAGED; } } // Handle onroad/offroad transition static bool started_prev = false; if (s->scene.started != started_prev) { if (s->scene.started) { s->status = STATUS_DISENGAGED; s->scene.started_frame = s->sm->frame; s->scene.end_to_end = Params().getBool("EndToEndToggle"); s->wide_camera = Hardware::TICI() ? Params().getBool("EnableWideCamera") : false; } // Invisible until we receive a calibration message. s->scene.world_objects_visible = false; } started_prev = s->scene.started; } QUIState::QUIState(QObject *parent) : QObject(parent) { ui_state.sm = std::make_unique<SubMaster, const std::initializer_list<const char *>>({ "modelV2", "controlsState", "liveCalibration", "deviceState", "roadCameraState", "pandaStates", "carParams", "driverMonitoringState", "sensorEvents", "carState", "liveLocationKalman", }); ui_state.wide_camera = Hardware::TICI() ? Params().getBool("EnableWideCamera") : false; // update timer timer = new QTimer(this); QObject::connect(timer, &QTimer::timeout, this, &QUIState::update); timer->start(1000 / UI_FREQ); } void QUIState::update() { update_params(&ui_state); update_sockets(&ui_state); update_state(&ui_state); update_status(&ui_state); if (ui_state.scene.started != started_prev || ui_state.sm->frame == 1) { started_prev = ui_state.scene.started; emit offroadTransition(!ui_state.scene.started); } watchdog_kick(); emit uiUpdate(ui_state); } Device::Device(QObject *parent) : brightness_filter(BACKLIGHT_OFFROAD, BACKLIGHT_TS, BACKLIGHT_DT), QObject(parent) { } void Device::update(const UIState &s) { updateBrightness(s); updateWakefulness(s); // TODO: remove from UIState and use signals QUIState::ui_state.awake = awake; } void Device::setAwake(bool on, bool reset) { if (on != awake) { awake = on; Hardware::set_display_power(awake); LOGD("setting display power %d", awake); emit displayPowerChanged(awake); } if (reset) { awake_timeout = 30 * UI_FREQ; } } void Device::updateBrightness(const UIState &s) { // Scale to 0% to 100% float clipped_brightness = 100.0 * s.scene.light_sensor; // CIE 1931 - https://www.photonstophotos.net/GeneralTopics/Exposure/Psychometric_Lightness_and_Gamma.htm if (clipped_brightness <= 8) { clipped_brightness = (clipped_brightness / 903.3); } else { clipped_brightness = std::pow((clipped_brightness + 16.0) / 116.0, 3.0); } // Scale back to 10% to 100% clipped_brightness = std::clamp(100.0f * clipped_brightness, 10.0f, 100.0f); if (!s.scene.started) { clipped_brightness = BACKLIGHT_OFFROAD; } int brightness = brightness_filter.update(clipped_brightness); if (!awake) { brightness = 0; } if (brightness != last_brightness) { std::thread{Hardware::set_brightness, brightness}.detach(); } last_brightness = brightness; } void Device::updateWakefulness(const UIState &s) { awake_timeout = std::max(awake_timeout - 1, 0); bool should_wake = s.scene.started || s.scene.ignition; if (!should_wake) { // tap detection while display is off bool accel_trigger = abs(s.scene.accel_sensor - accel_prev) > 0.2; bool gyro_trigger = abs(s.scene.gyro_sensor - gyro_prev) > 0.15; should_wake = accel_trigger && gyro_trigger; gyro_prev = s.scene.gyro_sensor; accel_prev = (accel_prev * (accel_samples - 1) + s.scene.accel_sensor) / accel_samples; } setAwake(awake_timeout, should_wake); } <|endoftext|>
<commit_before>#include <iostream> #include <fstream> #include <string> #include <stack> enum class InputType { Console, File, Constructor }; class CalculationNotDoneException: public std::exception { virtual const char* what() const throw() { return "The Input() method should be executed before Output()"; } } calc_not_done; class Calculator { public: std::string InputFileName; std::string OutputFileName; Calculator() : InputFileName("Input.txt"), OutputFileName("Output.txt"), result(0), calculationDone(false) { // empty constructor, totally legit } Calculator(const InputType& inputFrom) { Calculator(); Input(inputFrom); } Calculator(const InputType& inputFrom, const std::string& expression) { Calculator(); Input(inputFrom, expression); } Calculator(const InputType& inputFrom, const std::string& inputFileName, const std::string& outputFileName) { Calculator(); InputFileName = inputFileName; OutputFileName = outputFileName; Input(inputFrom); } void Input(const InputType& inputFrom, const std::string& expression = "") { inputType = inputFrom; if (InputType::Console == inputType) { std::getline(std::cin, input); } else if (InputType::File == inputType) { std::ifstream inputFile(InputFileName); if (inputFile.is_open()) { std::getline(inputFile, input); inputFile.close(); } else { std::cout << "Can't read from file named " << InputFileName << std::endl; return; } } else if (InputType::Constructor == inputType) { input = expression; } processInput(); } long Output() { if (!calculationDone) throw calc_not_done; if (InputType::Console == inputType) { std::cout << result << std::endl; } else if (InputType::File == inputType) { std::ofstream outputFile(OutputFileName); if (outputFile.is_open()) { outputFile << result << std::endl; outputFile.close(); } else { std::cout << "Can't create a file named " << OutputFileName << std::endl; return result; } } else if (InputType::Constructor == inputType) { // nothing specific, just return the result } calculationDone = false; return result; } private: long result; bool calculationDone; InputType inputType; std::string input; // add ^ operator void processInput() { std::stack<char> st; std::string out; for (int i = 0; i < input.length(); ++i) { char c = input[i]; if (c == ')') { while (st.top() != '(') { out += st.top(); st.pop(); } st.pop(); } if (c >= '0' && c <= '9') { out += c; } if (c == '(') { st.push(c); } if(c == '+' || c == '-' || c == '/' || c == '*') { if (st.empty()) { st.push(c); } else { if (operationPriority(st.top()) < operationPriority(c)) { st.push(c); } else { while (!st.empty() && (operationPriority(st.top()) >= operationPriority(c))) { out += st.top(); st.pop(); } st.push(c); } } } } while (!st.empty()) { out += st.top(); st.pop(); } input = out; // std::cout << "RPN: " << out << std::endl; result = calculateOutput(); } // add ^ operator int operationPriority(char sign) { switch(sign) { case '*': case '/': return 3; case '-': case '+': return 2; case '(': return 1; } } // add ^ operator long calculateOutput() { std::stack<std::string> st; for (int i = 0; i < input.length(); ++i) { char c = input[i]; // std::cout << "c: " << c << std::endl; if (c == '+' || c == '-' || c == '*' || c == '/') { long a = std::stol(st.top()); // std::cout << "a: " << a; st.pop(); long b = std::stol(st.top()); // std::cout << "b: " << b << std::endl; st.pop(); switch(c) { case '+': st.push(std::to_string(b + a)); break; case '-': st.push(std::to_string(b - a)); break; case '*': st.push(std::to_string(b * a)); break; case '/': st.push(std::to_string(b / a)); break; } } else { st.push(std::string(1, c)); // std::cout << "pushed c: " << std::string(1, c) << std::endl; } } calculationDone = true; return std::stol(st.top()); } }; // add an option to use command line arguments // int argc, char* argv[] int main() { // Use case #1 - expression comes from console auto calc1 = new Calculator(InputType::Console); // Input() method called automatically calc1->Output(); // Use case #2 - expression comes from file auto calc2 = new Calculator(InputType::File, "test.in", "test.out"); // custom filenames calc2->Output(); // Use case #3 - expression in a constructor auto calc3 = new Calculator(InputType::Constructor, "(9+1)*(1+1)-5"); // brackets supported calc3->Output(); } <commit_msg>Made calculateOutput() use argument instead of private field<commit_after>#include <iostream> #include <fstream> #include <string> #include <stack> enum class InputType { Console, File, Constructor }; class CalculationNotDoneException: public std::exception { virtual const char* what() const throw() { return "The Input() method should be executed before Output()"; } } calc_not_done; class Calculator { public: std::string InputFileName; std::string OutputFileName; Calculator() : InputFileName("Input.txt"), OutputFileName("Output.txt"), result(0), calculationDone(false) { // empty constructor, totally legit } Calculator(const InputType& inputFrom) { Calculator(); Input(inputFrom); } Calculator(const InputType& inputFrom, const std::string& expression) { Calculator(); Input(inputFrom, expression); } Calculator(const InputType& inputFrom, const std::string& inputFileName, const std::string& outputFileName) { Calculator(); InputFileName = inputFileName; OutputFileName = outputFileName; Input(inputFrom); } void Input(const InputType& inputFrom, const std::string& expression = "") { inputType = inputFrom; if (InputType::Console == inputType) { std::getline(std::cin, input); } else if (InputType::File == inputType) { std::ifstream inputFile(InputFileName); if (inputFile.is_open()) { std::getline(inputFile, input); inputFile.close(); } else { std::cout << "Can't read from file named " << InputFileName << std::endl; return; } } else if (InputType::Constructor == inputType) { input = expression; } processInput(); } long Output() { if (!calculationDone) throw calc_not_done; if (InputType::Console == inputType) { std::cout << result << std::endl; } else if (InputType::File == inputType) { std::ofstream outputFile(OutputFileName); if (outputFile.is_open()) { outputFile << result << std::endl; outputFile.close(); } else { std::cout << "Can't create a file named " << OutputFileName << std::endl; return result; } } else if (InputType::Constructor == inputType) { // nothing specific, just return the result } calculationDone = false; return result; } private: long result; bool calculationDone; InputType inputType; std::string input; // add ^ operator void processInput() { std::stack<char> st; std::string out; for (int i = 0; i < input.length(); ++i) { char c = input[i]; if (c == ')') { while (st.top() != '(') { out += st.top(); st.pop(); } st.pop(); } if (c >= '0' && c <= '9') { out += c; } if (c == '(') { st.push(c); } if(c == '+' || c == '-' || c == '/' || c == '*') { if (st.empty()) { st.push(c); } else { if (operationPriority(st.top()) < operationPriority(c)) { st.push(c); } else { while (!st.empty() && (operationPriority(st.top()) >= operationPriority(c))) { out += st.top(); st.pop(); } st.push(c); } } } } while (!st.empty()) { out += st.top(); st.pop(); } // std::cout << "RPN: " << out << std::endl; result = calculateOutput(out); } // add ^ operator int operationPriority(char sign) { switch(sign) { case '*': case '/': return 3; case '-': case '+': return 2; case '(': return 1; } } // add ^ operator long calculateOutput(const string& rpnString) { std::stack<std::string> st; for (int i = 0; i < rpnString.length(); ++i) { char c = rpnString[i]; // std::cout << "c: " << c << std::endl; if (c == '+' || c == '-' || c == '*' || c == '/') { long a = std::stol(st.top()); // std::cout << "a: " << a; st.pop(); long b = std::stol(st.top()); // std::cout << "b: " << b << std::endl; st.pop(); switch(c) { case '+': st.push(std::to_string(b + a)); break; case '-': st.push(std::to_string(b - a)); break; case '*': st.push(std::to_string(b * a)); break; case '/': st.push(std::to_string(b / a)); break; } } else { st.push(std::string(1, c)); // std::cout << "pushed c: " << std::string(1, c) << std::endl; } } calculationDone = true; return std::stol(st.top()); } }; // add an option to use command line arguments // int argc, char* argv[] int main() { // Use case #1 - expression comes from console auto calc1 = new Calculator(InputType::Console); // Input() method called automatically calc1->Output(); // Use case #2 - expression comes from file auto calc2 = new Calculator(InputType::File, "test.in", "test.out"); // custom filenames calc2->Output(); // Use case #3 - expression in a constructor auto calc3 = new Calculator(InputType::Constructor, "(9+1)*(1+1)-5"); // brackets supported calc3->Output(); } <|endoftext|>
<commit_before>/** * Copyright (c) 2016-2018 mvs developers * * This file is part of metaverse-explorer. * * metaverse-explorer is free software: you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License with * additional permissions to the one published by the Free Software * Foundation, either version 3 of the License, or (at your option) * any later version. For more information see LICENSE. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <metaverse/explorer/json_helper.hpp> #include <metaverse/explorer/version.hpp> #include <metaverse/explorer/extensions/commands/getinfo.hpp> #include <metaverse/explorer/extensions/command_extension_func.hpp> #include <metaverse/explorer/extensions/exception.hpp> #include <metaverse/explorer/extensions/node_method_wrapper.hpp> namespace libbitcoin { namespace explorer { namespace commands { using namespace bc::explorer::config; /************************ getinfo *************************/ console_result getinfo::invoke (Json::Value& jv_output, libbitcoin::server::server_node& node) { auto& blockchain = node.chain_impl(); administrator_required_checker(node, auth_.name, auth_.auth); auto& jv = jv_output; jv["protocol-version"] = node.network_settings().protocol; jv["wallet-version"] = MVS_EXPLORER_VERSION; jv["database-version"] = MVS_DATABASE_VERSION; jv["testnet"] = blockchain.chain_settings().use_testnet_rules; jv["peers"] = get_connections_count(node); jv["network-assets-count"] = static_cast<uint64_t>(blockchain.get_issued_assets()->size()); jv["wallet-account-count"] = static_cast<uint64_t>(blockchain.get_accounts()->size()); uint64_t height; uint64_t rate; std::string difficulty; bool is_solo_mining; node.miner().get_state(height, rate, difficulty, is_solo_mining); jv["height"] = height; jv["difficulty"] = difficulty; jv["is-mining"] = is_solo_mining; jv["hash-rate"] = rate; return console_result::okay; } } // namespace commands } // namespace explorer } // namespace libbitcoin <commit_msg>network-assets-count should consider second issue situation.<commit_after>/** * Copyright (c) 2016-2018 mvs developers * * This file is part of metaverse-explorer. * * metaverse-explorer is free software: you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License with * additional permissions to the one published by the Free Software * Foundation, either version 3 of the License, or (at your option) * any later version. For more information see LICENSE. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <metaverse/explorer/json_helper.hpp> #include <metaverse/explorer/version.hpp> #include <metaverse/explorer/extensions/commands/getinfo.hpp> #include <metaverse/explorer/extensions/command_extension_func.hpp> #include <metaverse/explorer/extensions/exception.hpp> #include <metaverse/explorer/extensions/node_method_wrapper.hpp> namespace libbitcoin { namespace explorer { namespace commands { using namespace bc::explorer::config; /************************ getinfo *************************/ console_result getinfo::invoke (Json::Value& jv_output, libbitcoin::server::server_node& node) { auto& blockchain = node.chain_impl(); administrator_required_checker(node, auth_.name, auth_.auth); auto& jv = jv_output; jv["protocol-version"] = node.network_settings().protocol; jv["wallet-version"] = MVS_EXPLORER_VERSION; jv["database-version"] = MVS_DATABASE_VERSION; jv["testnet"] = blockchain.chain_settings().use_testnet_rules; jv["peers"] = get_connections_count(node); auto sh_vec = blockchain.get_issued_assets(); std::set<std::string> symbols; for (const auto& elem: *sh_vec) { symbols.insert(elem.get_symbol()); } jv["network-assets-count"] = static_cast<uint64_t>(symbols.size()); jv["wallet-account-count"] = static_cast<uint64_t>(blockchain.get_accounts()->size()); uint64_t height; uint64_t rate; std::string difficulty; bool is_solo_mining; node.miner().get_state(height, rate, difficulty, is_solo_mining); jv["height"] = height; jv["difficulty"] = difficulty; jv["is-mining"] = is_solo_mining; jv["hash-rate"] = rate; return console_result::okay; } } // namespace commands } // namespace explorer } // namespace libbitcoin <|endoftext|>
<commit_before>#ifndef STAN_COMMAND_STANC_HELPER_HPP #define STAN_COMMAND_STANC_HELPER_HPP #include <stan/version.hpp> #include <stan/lang/compiler.hpp> #include <stan/io/cmd_line.hpp> #include <exception> #include <fstream> #include <iostream> #include <stdexcept> #include <string> #include <vector> /** * Print the version of stanc with major, minor and patch. * * @param[in,out] out_stream stream to which version is written. */ void print_version(std::ostream* out_stream) { if (!out_stream) return; *out_stream << "stanc version " << stan::MAJOR_VERSION << "." << stan::MINOR_VERSION << "." << stan::PATCH_VERSION << std::endl; } /** * Prints the Stan compiler (stanc) help. * * @param[in,out] out_stream stream to which help is written */ void print_stanc_help(std::ostream* out_stream) { using stan::io::print_help_option; if (!out_stream) return; *out_stream << std::endl; print_version(out_stream); *out_stream << std::endl; *out_stream << "USAGE: " << "stanc [options] <model_file>" << std::endl; *out_stream << std::endl; *out_stream << "OPTIONS:" << std::endl; *out_stream << std::endl; print_help_option(out_stream, "help", "", "Display this information"); print_help_option(out_stream, "version", "", "Display stanc version number"); print_help_option(out_stream, "name", "string", "Model name", "default = \"$model_filename_model\""); print_help_option(out_stream, "o", "file", "Output file for generated C++ code", "default = \"$name.cpp\""); print_help_option(out_stream, "allow_undefined", "", "Do not fail if a function is declared but not defined"); } /** * Delte the file at the specified path, writing messages to error * stream if not possible. Do nothing on zero size file name input. * Only write to error stream if it is non-null. * * @param[in,out] err_stream stream to which error messages are * written * @param[in] file_name path of file */ void delete_file(std::ostream* err_stream, const std::string& file_name) { if (file_name.size() == 0) return; int return_code = std::remove(file_name.c_str()); if (return_code != 0) if (err_stream) *err_stream << "Could not remove output file=" << file_name << std::endl; } /** * Invoke the stanc command on the specified argument list, writing * output and error messages to the specified streams, return a return * code. * * <p>The return codes are: 0 for success, -1 for an exception, * -2 is parsing failed, and -3 if there are invalid arguments. * * @param[in] argc number of arguments * @param[in] argv arguments * @param[in,out] out_stream stream to which output is written * @param[in,out] err_stream stream to which error messages are * written * @return return code */ int stanc_helper(int argc, const char* argv[], std::ostream* out_stream, std::ostream* err_stream) { static const int SUCCESS_RC = 0; static const int EXCEPTION_RC = -1; static const int PARSE_FAIL_RC = -2; static const int INVALID_ARGUMENT_RC = -3; std::string out_file_name; // declare outside of try to delete in catch try { stan::io::cmd_line cmd(argc, argv); if (cmd.has_flag("help")) { print_stanc_help(out_stream); return SUCCESS_RC; } if (cmd.has_flag("version")) { print_version(out_stream); return SUCCESS_RC; } if (cmd.bare_size() != 1) { std::string msg("Require model file as argument. "); throw std::invalid_argument(msg); } std::string in_file_name; cmd.bare(0, in_file_name); std::ifstream in(in_file_name.c_str()); if (!in.is_open()) { std::stringstream msg; msg << "Failed to open model file " << in_file_name.c_str(); throw std::invalid_argument(msg.str()); } std::string model_name; if (cmd.has_key("name")) { cmd.val("name", model_name); } else { size_t slashInd = in_file_name.rfind('/'); size_t ptInd = in_file_name.rfind('.'); if (ptInd == std::string::npos) ptInd = in_file_name.length(); if (slashInd == std::string::npos) { slashInd = in_file_name.rfind('\\'); } if (slashInd == std::string::npos) { slashInd = 0; } else { slashInd++; } model_name = in_file_name.substr(slashInd, ptInd - slashInd) + "_model"; for (std::string::iterator strIt = model_name.begin(); strIt != model_name.end(); strIt++) { if (!isalnum(*strIt) && *strIt != '_') { *strIt = '_'; } } } if (cmd.has_key("o")) { cmd.val("o", out_file_name); } else { out_file_name = model_name; // TODO(carpenter): shouldn't this be .hpp without a main()? out_file_name += ".cpp"; } if (!isalpha(model_name[0]) && model_name[0] != '_') { std::string msg("model_name must not start with a " "number or symbol other than _"); throw std::invalid_argument(msg); } for (std::string::iterator strIt = model_name.begin(); strIt != model_name.end(); strIt++) { if (!isalnum(*strIt) && *strIt != '_') { std::string msg("model_name must contain only letters, numbers and _"); throw std::invalid_argument(msg); } } bool allow_undefined = cmd.has_flag("allow_undefined"); std::fstream out(out_file_name.c_str(), std::fstream::out); if (out_stream) { *out_stream << "Model name=" << model_name << std::endl; *out_stream << "Input file=" << in_file_name << std::endl; *out_stream << "Output file=" << out_file_name << std::endl; } // check that we can write to out before invoking compiler if (!out.is_open()) { std::stringstream msg; msg << "Failed to open output file " << out_file_name.c_str(); throw std::invalid_argument(msg.str()); } std::vector<std::string> include_paths; include_paths.push_back(""); bool valid_model = stan::lang::compile(err_stream, in, out, model_name, allow_undefined, in_file_name, include_paths); out.close(); if (out.bad()) { std::stringstream msg; msg << "Error writing output file " << out_file_name.c_str(); throw std::invalid_argument(msg.str()); } if (!valid_model) { if (err_stream) *err_stream << "PARSING FAILED." << std::endl; // FIXME: how to remove triple cut-and-paste? delete_file(out_stream, out_file_name); return PARSE_FAIL_RC; } } catch (const std::invalid_argument& e) { if (err_stream) { *err_stream << std::endl << e.what() << std::endl; delete_file(out_stream, out_file_name); } return INVALID_ARGUMENT_RC; } catch (const std::exception& e) { if (err_stream) { *err_stream << std::endl << e.what() << std::endl; } delete_file(out_stream, out_file_name); return EXCEPTION_RC; } return SUCCESS_RC; } #endif <commit_msg>sync to dev<commit_after>#ifndef STAN_COMMAND_STANC_HELPER_HPP #define STAN_COMMAND_STANC_HELPER_HPP #include <stan/version.hpp> #include <stan/lang/compiler.hpp> #include <stan/lang/compile_functions.hpp> #include <stan/io/cmd_line.hpp> #include <exception> #include <fstream> #include <iostream> #include <stdexcept> #include <string> #include <vector> /** * Print the version of stanc with major, minor and patch. * * @param[in,out] out_stream stream to which version is written. */ void print_version(std::ostream* out_stream) { if (!out_stream) return; *out_stream << "stanc version " << stan::MAJOR_VERSION << "." << stan::MINOR_VERSION << "." << stan::PATCH_VERSION << std::endl; } /** * Prints the Stan compiler (stanc) help. * * @param[in,out] out_stream stream to which help is written */ void print_stanc_help(std::ostream* out_stream) { using stan::io::print_help_option; if (!out_stream) return; *out_stream << std::endl; print_version(out_stream); *out_stream << std::endl; *out_stream << "USAGE: " << "stanc [options] <model_file>" << std::endl; *out_stream << std::endl; *out_stream << "OPTIONS:" << std::endl; *out_stream << std::endl; print_help_option(out_stream, "help", "", "Display this information"); print_help_option(out_stream, "version", "", "Display stanc version number"); print_help_option(out_stream, "name", "string", "Model name", "default = \"$model_filename_model\""); print_help_option(out_stream, "o", "file", "Output file for generated C++ code", "default = \"$name.cpp\""); print_help_option(out_stream, "allow_undefined", "", "Do not fail if a function is declared but not defined"); // TODO(martincerny) help for standalone function compilation } /** * Delte the file at the specified path, writing messages to error * stream if not possible. Do nothing on zero size file name input. * Only write to error stream if it is non-null. * * @param[in,out] err_stream stream to which error messages are * written * @param[in] file_name path of file */ void delete_file(std::ostream* err_stream, const std::string& file_name) { if (file_name.size() == 0) return; int return_code = std::remove(file_name.c_str()); if (return_code != 0) if (err_stream) *err_stream << "Could not remove output file=" << file_name << std::endl; } /** * Transform a provided input file name into a valid C++ identifier * @param[in] in_file_name the name of the input file * @return a valid C++ identifier based on the file name. */ std::string identifier_from_file_name(const std::string& in_file_name) { size_t slashInd = in_file_name.rfind('/'); size_t ptInd = in_file_name.rfind('.'); if (ptInd == std::string::npos) ptInd = in_file_name.length(); if (slashInd == std::string::npos) { slashInd = in_file_name.rfind('\\'); } if (slashInd == std::string::npos) { slashInd = 0; } else { slashInd++; } std::string result = in_file_name.substr(slashInd, ptInd - slashInd); for (std::string::iterator strIt = result.begin(); strIt != result.end(); strIt++) { if (!isalnum(*strIt) && *strIt != '_') { *strIt = '_'; } } return result; } /** * Check whether a given file has the specified extension. * * @param[in] file_name The name of the file * @param[in] extension The extension (WITHOUT dot)- e.g. "stan". * @return true if the file has the extension */ bool has_extension(const std::string& file_name, const std::string& extension) { if (file_name.length() >= extension.length() + 1) { // +1 for the dot if (0 == file_name.compare (file_name.length() - extension.length(), extension.length(), extension) && file_name[file_name.length() - extension.length() - 1] == '.') return true; else return false; } else { return false; } } /** * Test whether a given string is a valid C++ identifier and throw * an exception when it is not. * @param[in] identifier the identifier to be checked * @param[in] identifier_type the type of the identifier to be reported * in error messages */ void check_identifier(const std::string& identifier, const std::string& identifier_type) { if (!isalpha(identifier[0]) && identifier[0] != '_') { std::string msg(identifier_type + " must not start with a " "number or symbol other than _"); throw std::invalid_argument(msg); } for (std::string::const_iterator strIt = identifier.begin(); strIt != identifier.end(); strIt++) { if (!isalnum(*strIt) && *strIt != '_') { std::string msg(identifier_type + " must contain only letters, numbers and _"); throw std::invalid_argument(msg); } } } /** * Invoke the stanc command on the specified argument list, writing * output and error messages to the specified streams, return a return * code. * * <p>The return codes are: 0 for success, -1 for an exception, * -2 is parsing failed, and -3 if there are invalid arguments. * * @param[in] argc number of arguments * @param[in] argv arguments * @param[in,out] out_stream stream to which output is written * @param[in,out] err_stream stream to which error messages are * written * @return return code */ int stanc_helper(int argc, const char* argv[], std::ostream* out_stream, std::ostream* err_stream) { enum CompilationType { kModel, kStandaloneFunctions }; static const int SUCCESS_RC = 0; static const int EXCEPTION_RC = -1; static const int PARSE_FAIL_RC = -2; static const int INVALID_ARGUMENT_RC = -3; std::string out_file_name; // declare outside of try to delete in catch try { stan::io::cmd_line cmd(argc, argv); if (cmd.has_flag("help")) { print_stanc_help(out_stream); return SUCCESS_RC; } if (cmd.has_flag("version")) { print_version(out_stream); return SUCCESS_RC; } if (cmd.bare_size() != 1) { std::string msg("Require model file as argument. "); throw std::invalid_argument(msg); } std::string in_file_name; cmd.bare(0, in_file_name); CompilationType compilation_type; if (has_extension(in_file_name, "stanfuncs")) { compilation_type = kStandaloneFunctions; } else { compilation_type = kModel; } std::ifstream in(in_file_name.c_str()); if (!in.is_open()) { std::stringstream msg; msg << "Failed to open model file " << in_file_name.c_str(); throw std::invalid_argument(msg.str()); } bool allow_undefined = cmd.has_flag("allow_undefined"); bool valid_input = false; switch (compilation_type) { case kModel: { std::string model_name; if (cmd.has_key("name")) { cmd.val("name", model_name); } else { model_name = identifier_from_file_name(in_file_name) + "_model"; } // TODO(martincerny) Check that the -namespace flag is not set if (cmd.has_key("o")) { cmd.val("o", out_file_name); } else { out_file_name = model_name; // TODO(carpenter): shouldn't this be .hpp without a main()? out_file_name += ".cpp"; } check_identifier(model_name, "model_name"); std::fstream out(out_file_name.c_str(), std::fstream::out); if (out_stream) { *out_stream << "Model name=" << model_name << std::endl; *out_stream << "Input file=" << in_file_name << std::endl; *out_stream << "Output file=" << out_file_name << std::endl; } if (!out.is_open()) { std::stringstream msg; msg << "Failed to open output file " << out_file_name.c_str(); throw std::invalid_argument(msg.str()); } valid_input = stan::lang::compile(err_stream, in, out, model_name, allow_undefined); out.close(); break; } case kStandaloneFunctions: { if (cmd.has_key("o")) { cmd.val("o", out_file_name); } else { out_file_name = identifier_from_file_name(in_file_name); out_file_name += ".hpp"; } // TODO(martincerny) Allow multiple namespaces // (split namespace argument by "::") std::vector<std::string> namespaces; if (cmd.has_key("namespace")) { std::string ns; cmd.val("namespace", ns); namespaces.push_back(ns); } else { namespaces.push_back( identifier_from_file_name(in_file_name) + "_functions"); } // TODO(martincerny) Check that the -name flag is not set for (size_t namespace_i = 0; namespace_i < namespaces.size(); ++namespace_i) { check_identifier(namespaces[namespace_i], "namespace"); } std::fstream out(out_file_name.c_str(), std::fstream::out); if (out_stream) { *out_stream << "Parsing a fuctions-only file" << std::endl; *out_stream << "Target namespace= "; for (size_t namespace_i = 0; namespace_i < namespaces.size(); ++namespace_i) { *out_stream << "::" << namespaces[namespace_i]; } *out_stream << std::endl; *out_stream << "Input file=" << in_file_name << std::endl; *out_stream << "Output file=" << out_file_name << std::endl; } valid_input = stan::lang::compile_functions(err_stream, in, out, namespaces, allow_undefined); out.close(); break; } default: { assert(false); } } if (!valid_input) { if (err_stream) *err_stream << "PARSING FAILED." << std::endl; // FIXME: how to remove triple cut-and-paste? delete_file(out_stream, out_file_name); return PARSE_FAIL_RC; } } catch (const std::invalid_argument& e) { if (err_stream) { *err_stream << std::endl << e.what() << std::endl; delete_file(out_stream, out_file_name); } return INVALID_ARGUMENT_RC; } catch (const std::exception& e) { if (err_stream) { *err_stream << std::endl << e.what() << std::endl; } delete_file(out_stream, out_file_name); return EXCEPTION_RC; } return SUCCESS_RC; } #endif <|endoftext|>
<commit_before>#ifndef STAN_IO_ARRAY_VAR_CONTEXT_HPP #define STAN_IO_ARRAY_VAR_CONTEXT_HPP #include <stan/io/var_context.hpp> #include <boost/throw_exception.hpp> #include <stan/math/prim/mat/fun/Eigen.hpp> #include <algorithm> #include <functional> #include <map> #include <numeric> #include <sstream> #include <string> #include <type_traits> #include <vector> namespace stan { namespace io { /** * An array_var_context object represents a named arrays * with dimensions constructed from an array, a vector * of names, and a vector of all dimensions for each element. */ class array_var_context : public var_context { private: // Pairs template <typename T> using pair_ = std::pair<std::string, std::pair<std::vector<T>, std::vector<size_t>>>; // Map holding reals using map_r_ = std::vector<pair_<double>>; map_r_ vars_r_; using map_i_ = std::vector<pair_<int>>; map_i_ vars_i_; // When search for variable name fails, return one these std::vector<double> const empty_vec_r_; std::vector<int> const empty_vec_i_; std::vector<size_t> const empty_vec_ui_; template <typename Str> auto find_var_r(Str&& name) const { auto found_val = std::find_if(vars_r_.begin(), vars_r_.end(), [&](auto& element){ return element.first == name;} ); return found_val; } template <typename Str> auto find_var_i(Str&& name) const { auto found_val = std::find_if(vars_i_.begin(), vars_i_.end(), [&](auto& element){ return element.first == name;} ); return found_val; } // Find method bool contains_r_only(const std::string& name) const { auto check_var = find_var_r(name); return check_var != vars_r_.end(); } /** * Check (1) if the vector size of dimensions is no smaller * than the name vector size; (2) if the size of the input * array is large enough for what is needed. * * @param names The names for each variable * @param array_size The total size of the vector holding the values we want * to access. * @param dims Vector holding the dimensions for each variable. * @return If the array size is equal to the number of dimensions, * a vector of the cumulative sum of the dimensions of each inner element of * dims. The return of this function is used in the add_* methods to get the * sequence of values For each variable. */ template <typename T> std::vector<size_t> validate_dims( const std::vector<std::string>& names, const T array_size, const std::vector<std::vector<size_t>>& dims) { const size_t num_par = names.size(); if (num_par > dims.size()) { std::stringstream msg; msg << "size of vector of dimensions (found " << dims.size() << ") " << "should be no smaller than number of parameters (found " << num_par << ")."; BOOST_THROW_EXCEPTION(std::invalid_argument(msg.str())); } std::vector<size_t> elem_dims_total(dims.size() + 1); elem_dims_total[0] = 0; int i = 0; for (i = 0; i < dims.size(); i++) { elem_dims_total[i + 1] = std::accumulate(dims[i].begin(), dims[i].end(), 1, std::multiplies<T>()); elem_dims_total[i + 1] += elem_dims_total[i]; } if (elem_dims_total[i] > array_size) { std::stringstream msg; msg << "array is not long enough for all elements: " << array_size << " is found, but " << elem_dims_total[i] << " is needed."; BOOST_THROW_EXCEPTION(std::invalid_argument(msg.str())); } return elem_dims_total; } /** * Adds a set of floating point variables to the floating point map. * @param names Names of each variable. * @param values The real values of variable in a contiguous * column major order container. * @param dims the dimensions for each variable. */ void add_r(const std::vector<std::string>& names, const std::vector<double>& values, const std::vector<std::vector<size_t>>& dims) { std::vector<size_t> dim_vec = validate_dims(names, values.size(), dims); using val_d_t = decltype(values.data()); for (size_t i = 0; i < names.size(); i++) { vars_r_.push_back( {names[i], {{values.data() + dim_vec[i], values.data() + dim_vec[i + 1]}, dims[i]}}); } } void add_r(const std::vector<std::string>& names, const Eigen::VectorXd& values, const std::vector<std::vector<size_t>>& dims) { std::vector<size_t> dim_vec = validate_dims(names, values.size(), dims); using val_d_t = decltype(values.data()); for (size_t i = 0; i < names.size(); i++) { vars_r_.push_back( {names[i], {{values.data() + dim_vec[i], values.data() + dim_vec[i + 1]}, dims[i]}}); } } /** * Adds a set of integer variables to the integer map. * @param names Names of each variable. * @param values The integer values of variable in a vector. * @param dims the dimensions for each variable. */ void add_i(const std::vector<std::string>& names, const std::vector<int>& values, const std::vector<std::vector<size_t>>& dims) { std::vector<size_t> dim_vec = validate_dims(names, values.size(), dims); for (size_t i = 0; i < names.size(); i++) { vars_i_.push_back( {names[i], {{values.data() + dim_vec[i], values.data() + dim_vec[i + 1]}, dims[i]}}); } } public: /** * Construct an array_var_context from only real value arrays. * * @param names_r names for each element * @param values_r a vector of double values for all elements * @param dim_r a vector of dimensions */ array_var_context(const std::vector<std::string>& names_r, const std::vector<double>& values_r, const std::vector<std::vector<size_t>>& dim_r) : vars_r_(names_r.size()) { add_r(names_r, values_r, dim_r); } array_var_context(const std::vector<std::string>& names_r, const Eigen::VectorXd& values_r, const std::vector<std::vector<size_t>>& dim_r) : vars_r_(names_r.size()) { add_r(names_r, values_r, dim_r); } /** * Construct an array_var_context from only integer value arrays. * * @param names_i names for each element * @param values_i a vector of integer values for all elements * @param dim_i a vector of dimensions */ array_var_context(const std::vector<std::string>& names_i, const std::vector<int>& values_i, const std::vector<std::vector<size_t>>& dim_i) : vars_i_(names_i.size()) { add_i(names_i, values_i, dim_i); } /** * Construct an array_var_context from arrays of both double * and integer separately * */ array_var_context(const std::vector<std::string>& names_r, const std::vector<double>& values_r, const std::vector<std::vector<size_t>>& dim_r, const std::vector<std::string>& names_i, const std::vector<int>& values_i, const std::vector<std::vector<size_t>>& dim_i) : vars_r_(names_r.size()), vars_i_(names_i.size()) { add_i(names_i, values_i, dim_i); add_r(names_r, values_r, dim_r); } array_var_context(const std::vector<std::string>& names_r, const Eigen::VectorXd& values_r, const std::vector<std::vector<size_t>>& dim_r, const std::vector<std::string>& names_i, const std::vector<int>& values_i, const std::vector<std::vector<size_t>>& dim_i) : vars_r_(names_r.size()), vars_i_(names_i.size()) { add_i(names_i, values_i, dim_i); add_r(names_r, values_r, dim_r); } /** * Return <code>true</code> if this dump contains the specified * variable name is defined. This method returns <code>true</code> * even if the values are all integers. * * @param name Variable name to test. * @return <code>true</code> if the variable exists. */ bool contains_r(const std::string& name) const { return contains_r_only(name) || contains_i(name); } /** * Return <code>true</code> if this dump contains an integer * valued array with the specified name. * * @param name Variable name to test. * @return <code>true</code> if the variable name has an integer * array value. */ bool contains_i(const std::string& name) const { return find_var_i(name) != vars_i_.end(); } /** * Return the double values for the variable with the specified * name or null. * * @param name Name of variable. * @return Values of variable. * */ std::vector<double> vals_r(const std::string& name) const { if (contains_r_only(name)) { return (find_var_r(name)->second).first; } else if (contains_i(name)) { std::vector<int> vec_int = (find_var_i(name)->second).first; return {vec_int.begin(), vec_int.end()}; } return empty_vec_r_; } /** * Return the dimensions for the double variable with the specified * name. * * @param name Name of variable. * @return Dimensions of variable. */ std::vector<size_t> dims_r(const std::string& name) const { if (contains_r_only(name)) { return (find_var_r(name)->second).second; } else if (contains_i(name)) { return (find_var_i(name)->second).second; } return empty_vec_ui_; } /** * Return the integer values for the variable with the specified * name. * * @param name Name of variable. * @return Values. */ std::vector<int> vals_i(const std::string& name) const { if (contains_i(name)) { return (find_var_i(name)->second).first; } return empty_vec_i_; } /** * Return the dimensions for the integer variable with the specified * name. * * @param name Name of variable. * @return Dimensions of variable. */ std::vector<size_t> dims_i(const std::string& name) const { if (contains_i(name)) { return (find_var_i(name)->second).second; } return empty_vec_ui_; } /** * Return a list of the names of the floating point variables in * the dump. * * @param names Vector to store the list of names in. */ virtual void names_r(std::vector<std::string>& names) const { names.clear(); for (const auto& vars_r_iter : vars_r_) { names.push_back(vars_r_iter.first); } } /** * Return a list of the names of the integer variables in * the dump. * * @param names Vector to store the list of names in. */ virtual void names_i(std::vector<std::string>& names) const { names.clear(); for (const auto& vars_i_iter : vars_r_) { names.push_back(vars_i_iter.first); } } /** * Remove variable from the object. * * @param name Name of the variable to remove. * @return If variable is removed returns <code>true</code>, else * returns <code>false</code>. */ bool remove(const std::string& name) { vars_i_.erase(find_var_i(name)); vars_r_.erase(find_var_r(name)); return true; } }; } // namespace io } // namespace stan #endif <commit_msg>use [] instead of push_back<commit_after>#ifndef STAN_IO_ARRAY_VAR_CONTEXT_HPP #define STAN_IO_ARRAY_VAR_CONTEXT_HPP #include <stan/io/var_context.hpp> #include <boost/throw_exception.hpp> #include <stan/math/prim/mat/fun/Eigen.hpp> #include <algorithm> #include <functional> #include <map> #include <numeric> #include <sstream> #include <string> #include <type_traits> #include <vector> namespace stan { namespace io { /** * An array_var_context object represents a named arrays * with dimensions constructed from an array, a vector * of names, and a vector of all dimensions for each element. */ class array_var_context : public var_context { private: // Pairs template <typename T> using pair_ = std::pair<std::string, std::pair<std::vector<T>, std::vector<size_t>>>; // Map holding reals using map_r_ = std::vector<pair_<double>>; map_r_ vars_r_; using map_i_ = std::vector<pair_<int>>; map_i_ vars_i_; // When search for variable name fails, return one these std::vector<double> const empty_vec_r_; std::vector<int> const empty_vec_i_; std::vector<size_t> const empty_vec_ui_; template <typename Str> auto find_var_r(Str&& name) const { auto found_val = std::find_if(vars_r_.begin(), vars_r_.end(), [&](auto& element){ return element.first == name;} ); return found_val; } template <typename Str> auto find_var_i(Str&& name) const { auto found_val = std::find_if(vars_i_.begin(), vars_i_.end(), [&](auto& element){ return element.first == name;} ); return found_val; } // Find method bool contains_r_only(const std::string& name) const { auto check_var = find_var_r(name); return check_var != vars_r_.end(); } /** * Check (1) if the vector size of dimensions is no smaller * than the name vector size; (2) if the size of the input * array is large enough for what is needed. * * @param names The names for each variable * @param array_size The total size of the vector holding the values we want * to access. * @param dims Vector holding the dimensions for each variable. * @return If the array size is equal to the number of dimensions, * a vector of the cumulative sum of the dimensions of each inner element of * dims. The return of this function is used in the add_* methods to get the * sequence of values For each variable. */ template <typename T> std::vector<size_t> validate_dims( const std::vector<std::string>& names, const T array_size, const std::vector<std::vector<size_t>>& dims) { const size_t num_par = names.size(); if (num_par > dims.size()) { std::stringstream msg; msg << "size of vector of dimensions (found " << dims.size() << ") " << "should be no smaller than number of parameters (found " << num_par << ")."; BOOST_THROW_EXCEPTION(std::invalid_argument(msg.str())); } std::vector<size_t> elem_dims_total(dims.size() + 1); elem_dims_total[0] = 0; int i = 0; for (i = 0; i < dims.size(); i++) { elem_dims_total[i + 1] = std::accumulate(dims[i].begin(), dims[i].end(), 1, std::multiplies<T>()); elem_dims_total[i + 1] += elem_dims_total[i]; } if (elem_dims_total[i] > array_size) { std::stringstream msg; msg << "array is not long enough for all elements: " << array_size << " is found, but " << elem_dims_total[i] << " is needed."; BOOST_THROW_EXCEPTION(std::invalid_argument(msg.str())); } return elem_dims_total; } /** * Adds a set of floating point variables to the floating point map. * @param names Names of each variable. * @param values The real values of variable in a contiguous * column major order container. * @param dims the dimensions for each variable. */ void add_r(const std::vector<std::string>& names, const std::vector<double>& values, const std::vector<std::vector<size_t>>& dims) { std::vector<size_t> dim_vec = validate_dims(names, values.size(), dims); using val_d_t = decltype(values.data()); for (size_t i = 0; i < names.size(); i++) { vars_r_[i] = {names[i], {{values.data() + dim_vec[i], values.data() + dim_vec[i + 1]}, dims[i]}}; } } void add_r(const std::vector<std::string>& names, const Eigen::VectorXd& values, const std::vector<std::vector<size_t>>& dims) { std::vector<size_t> dim_vec = validate_dims(names, values.size(), dims); using val_d_t = decltype(values.data()); for (size_t i = 0; i < names.size(); i++) { vars_r_[i] = {names[i], {{values.data() + dim_vec[i], values.data() + dim_vec[i + 1]}, dims[i]}}; } } /** * Adds a set of integer variables to the integer map. * @param names Names of each variable. * @param values The integer values of variable in a vector. * @param dims the dimensions for each variable. */ void add_i(const std::vector<std::string>& names, const std::vector<int>& values, const std::vector<std::vector<size_t>>& dims) { std::vector<size_t> dim_vec = validate_dims(names, values.size(), dims); for (size_t i = 0; i < names.size(); i++) { vars_i_[i] = {names[i], {{values.data() + dim_vec[i], values.data() + dim_vec[i + 1]}, dims[i]}}; } } public: /** * Construct an array_var_context from only real value arrays. * * @param names_r names for each element * @param values_r a vector of double values for all elements * @param dim_r a vector of dimensions */ array_var_context(const std::vector<std::string>& names_r, const std::vector<double>& values_r, const std::vector<std::vector<size_t>>& dim_r) : vars_r_(names_r.size()) { add_r(names_r, values_r, dim_r); } array_var_context(const std::vector<std::string>& names_r, const Eigen::VectorXd& values_r, const std::vector<std::vector<size_t>>& dim_r) : vars_r_(names_r.size()) { add_r(names_r, values_r, dim_r); } /** * Construct an array_var_context from only integer value arrays. * * @param names_i names for each element * @param values_i a vector of integer values for all elements * @param dim_i a vector of dimensions */ array_var_context(const std::vector<std::string>& names_i, const std::vector<int>& values_i, const std::vector<std::vector<size_t>>& dim_i) : vars_i_(names_i.size()) { add_i(names_i, values_i, dim_i); } /** * Construct an array_var_context from arrays of both double * and integer separately * */ array_var_context(const std::vector<std::string>& names_r, const std::vector<double>& values_r, const std::vector<std::vector<size_t>>& dim_r, const std::vector<std::string>& names_i, const std::vector<int>& values_i, const std::vector<std::vector<size_t>>& dim_i) : vars_r_(names_r.size()), vars_i_(names_i.size()) { add_i(names_i, values_i, dim_i); add_r(names_r, values_r, dim_r); } array_var_context(const std::vector<std::string>& names_r, const Eigen::VectorXd& values_r, const std::vector<std::vector<size_t>>& dim_r, const std::vector<std::string>& names_i, const std::vector<int>& values_i, const std::vector<std::vector<size_t>>& dim_i) : vars_r_(names_r.size()), vars_i_(names_i.size()) { add_i(names_i, values_i, dim_i); add_r(names_r, values_r, dim_r); } /** * Return <code>true</code> if this dump contains the specified * variable name is defined. This method returns <code>true</code> * even if the values are all integers. * * @param name Variable name to test. * @return <code>true</code> if the variable exists. */ bool contains_r(const std::string& name) const { return contains_r_only(name) || contains_i(name); } /** * Return <code>true</code> if this dump contains an integer * valued array with the specified name. * * @param name Variable name to test. * @return <code>true</code> if the variable name has an integer * array value. */ bool contains_i(const std::string& name) const { return find_var_i(name) != vars_i_.end(); } /** * Return the double values for the variable with the specified * name or null. * * @param name Name of variable. * @return Values of variable. * */ std::vector<double> vals_r(const std::string& name) const { if (contains_r_only(name)) { return (find_var_r(name)->second).first; } else if (contains_i(name)) { std::vector<int> vec_int = (find_var_i(name)->second).first; return {vec_int.begin(), vec_int.end()}; } return empty_vec_r_; } /** * Return the dimensions for the double variable with the specified * name. * * @param name Name of variable. * @return Dimensions of variable. */ std::vector<size_t> dims_r(const std::string& name) const { if (contains_r_only(name)) { return (find_var_r(name)->second).second; } else if (contains_i(name)) { return (find_var_i(name)->second).second; } return empty_vec_ui_; } /** * Return the integer values for the variable with the specified * name. * * @param name Name of variable. * @return Values. */ std::vector<int> vals_i(const std::string& name) const { if (contains_i(name)) { return (find_var_i(name)->second).first; } return empty_vec_i_; } /** * Return the dimensions for the integer variable with the specified * name. * * @param name Name of variable. * @return Dimensions of variable. */ std::vector<size_t> dims_i(const std::string& name) const { if (contains_i(name)) { return (find_var_i(name)->second).second; } return empty_vec_ui_; } /** * Return a list of the names of the floating point variables in * the dump. * * @param names Vector to store the list of names in. */ virtual void names_r(std::vector<std::string>& names) const { names.clear(); for (const auto& vars_r_iter : vars_r_) { names.push_back(vars_r_iter.first); } } /** * Return a list of the names of the integer variables in * the dump. * * @param names Vector to store the list of names in. */ virtual void names_i(std::vector<std::string>& names) const { names.clear(); for (const auto& vars_i_iter : vars_r_) { names.push_back(vars_i_iter.first); } } /** * Remove variable from the object. * * @param name Name of the variable to remove. * @return If variable is removed returns <code>true</code>, else * returns <code>false</code>. */ bool remove(const std::string& name) { vars_i_.erase(find_var_i(name)); vars_r_.erase(find_var_r(name)); return true; } }; } // namespace io } // namespace stan #endif <|endoftext|>
<commit_before><commit_msg>fixed bug with escape sequences<commit_after><|endoftext|>
<commit_before>#include "../../fswork/fswork.h" #include "../../windlg/windlg.h" #include <curses.h> #define TAB_KEY 9 using namespace std; void load_pair_fm() { init_pair (0, COLOR_WHITE, COLOR_BLACK); init_pair (1, COLOR_BLACK, COLOR_WHITE); init_pair (2, COLOR_RED, COLOR_BLACK); init_pair (3, COLOR_BLACK, COLOR_RED); init_pair (4, COLOR_GREEN, COLOR_BLACK); init_pair (5, COLOR_BLACK, COLOR_GREEN); init_pair (6, COLOR_BLUE, COLOR_BLACK); init_pair (7, COLOR_BLACK, COLOR_BLUE); init_pair (8, COLOR_YELLOW, COLOR_BLACK); init_pair (9, COLOR_BLACK, COLOR_YELLOW); return; } void load_properties(vector <string>& propvec) { propvec.insert(propvec.end(), "Open"); propvec.insert(propvec.end(), "Info"); propvec.insert(propvec.end(), "Delete"); propvec.insert(propvec.end(), "Move"); propvec.insert(propvec.end(), "Copy"); propvec.insert(propvec.end(), "Test.."); return; } void load_files(vector <FILEINFO> filevector, vector <string>& fileout) { FILEINFO temp; fileout.clear(); for (unsigned int vec = 0; vec < filevector.size();vec++) { temp = filevector[vec]; fileout.insert(fileout.end(), temp.name.c_str()); } return; } void properties_open(DLGSTR properties_menu, vector <string> propvec/*, link_to_file*/) { bool cycle = true; int key = 0; while (cycle) { menu_win(properties_menu, propvec); key = getch(); switch (key) { case KEY_UP: if (properties_menu.selected != 1) properties_menu.selected--; break; case KEY_DOWN: if (properties_menu.selected != properties_menu.second_border) properties_menu.selected++; break; case 27: return; break; } } return; } void interface_fm() { unsigned int maxX, maxY; getmaxyx(stdscr, maxY, maxX); vector <string> propvec; /*For windlg*/ DLGSTR winstr = {}; // Только так!!! winstr.line = "Please enter link to foldren"; /*For windlg END*/ /*For first panel*/ DLGSTR first_panel = {}; first_panel.xmax = maxX / 2 - 2; first_panel.ymax = maxY - 3; first_panel.xpos = 0; first_panel.ypos = 1; first_panel.style = 3; // first_panel.title = "TEST"; first_panel.border_menu = true; /*For first panel END*/ /*For second panel*/ DLGSTR second_panel = {}; second_panel.xmax = maxX / 2 - 2; second_panel.ymax = maxY - 3; second_panel.xpos = maxX / 2 + 1; second_panel.ypos = 1; second_panel.style = 0; second_panel.border_menu = true; /*For second panel END*/ /*For properties panel*/ DLGSTR properties_menu = {}; properties_menu.ymax = 4; properties_menu.style = 2; properties_menu.border_menu = true; /*For properties panel END*/ bool cycle = true; vector <FILEINFO> filevector_1; // Вектор для загрузки файлов первой панели vector <FILEINFO> filevector_2; // Вектор для загрузки файлов второйой панели vector <string> fileout_1; // Вектор вывода списка файлов первой панели vector <string> fileout_2; // Вектор вывода списка файлов второйой панели FILEINFO filestr; string link_to_foldren; link_to_foldren.clear(); link_to_foldren = "."; // dlg_win(winstr, link_to_foldren); /*while (get_files(link_to_foldren, filevector) == -1) { winstr.style = 1; winstr.line = "Wrong link!!! Try again!"; msg_win(winstr); winstr.style = 0; winstr.line = "Please enter link to foldren"; dlg_win(winstr, link_to_foldren); }*/ get_files(link_to_foldren, filevector_1); // TEST!!!! get_files(link_to_foldren + ".", filevector_2); // TEST!!!! files_sort_by('n', filevector_1); files_sort_by('t', filevector_2); load_files(filevector_1, fileout_1); load_files(filevector_2, fileout_2); load_properties(propvec); /*Init head START*/ load_pair_fm(); int selected_color = 0; string head; head.clear(); for (unsigned int i = 0; i < maxX; i++, head += " "); /*Init head END*/ /*Mode*/ unsigned int mode_select = 1, key_pressed = 0; /*0 - Menu 1 - First panel 2 - Second panel*/ /*Mode END*/ while (cycle) { timeout(-1); /*Head START*/ switch (mode_select) { case 0: selected_color = 6; first_panel.style = 0; second_panel.style = 0; break; case 1: first_panel.style = 3; second_panel.style = 0; break; case 2: second_panel.style = 3; first_panel.style = 0; break; } attron(COLOR_PAIR(1 + selected_color) | A_BOLD); mvprintw(0, 0, "%s", head.c_str()); mvprintw(0, 0, "(M)enu"); attroff(COLOR_PAIR(1 + selected_color) | A_BOLD); selected_color = 0; /*Head END*/ menu_win(first_panel, fileout_1); menu_win(second_panel, fileout_2); key_pressed = getch(); switch (key_pressed) { case TAB_KEY: if (mode_select != 2) mode_select++; else mode_select = 0; break; case KEY_UP: switch (mode_select) { case 1: if (first_panel.selected != 1) first_panel.selected--; break; case 2: if (second_panel.selected != 1) second_panel.selected--; break; } break; case KEY_DOWN: switch (mode_select) { case 1: if (first_panel.selected != first_panel.second_border) first_panel.selected++; break; case 2: if (second_panel.selected != second_panel.second_border) second_panel.selected++; break; } break; case '\n': switch (mode_select) { case 1: properties_menu.xpos = first_panel.xreturn; properties_menu.ypos = first_panel.yreturn; properties_open(properties_menu, propvec/*, link_to_file*/); break; case 2: properties_menu.xpos = second_panel.xreturn; properties_menu.ypos = second_panel.yreturn; properties_open(properties_menu, propvec/*, link_to_file*/); break; } break; } } return; } int main(int argc, char* argv[]) { setlocale(LC_ALL, ""); initscr(); start_color(); keypad (stdscr, TRUE); noecho(); curs_set(0); erase(); // get_files("./test", test_vec); /*for(unsigned int i = 0; i < test_vec.size(); i++) { test_str = test_vec[i]; printw("%s\n", test_str.name.c_str()); }*/ interface_fm(); /*for(unsigned int i = 0; i < test_vec.size(); i++) { test_str = test_vec[i]; printw("%i %s %s\n", (int)test_str.name[0], test_str.name.c_str(), ctime(&test_str.mtime)); }*/ endwin(); return 0; } <commit_msg>Many changes<commit_after>#include "../../fswork/fswork.h" #include "../../windlg/windlg.h" #include "../../lang/lang.h" #include <curses.h> #define TAB_KEY 9 using namespace std; void load_pair_fm() { init_pair (0, COLOR_WHITE, COLOR_BLACK); init_pair (1, COLOR_BLACK, COLOR_WHITE); init_pair (2, COLOR_RED, COLOR_BLACK); init_pair (3, COLOR_BLACK, COLOR_RED); init_pair (4, COLOR_GREEN, COLOR_BLACK); init_pair (5, COLOR_BLACK, COLOR_GREEN); init_pair (6, COLOR_BLUE, COLOR_BLACK); init_pair (7, COLOR_BLACK, COLOR_BLUE); init_pair (8, COLOR_YELLOW, COLOR_BLACK); init_pair (9, COLOR_BLACK, COLOR_YELLOW); return; } void load_properties(vector <string>& propvec) { propvec.insert(propvec.end(), "Open"); propvec.insert(propvec.end(), "Info"); propvec.insert(propvec.end(), "Delete"); propvec.insert(propvec.end(), "Move"); propvec.insert(propvec.end(), "Copy"); propvec.insert(propvec.end(), "Test.."); return; } void load_files(vector <FILEINFO> filevector, vector <string>& fileout) { FILEINFO temp; fileout.clear(); for (unsigned int vec = 0; vec < filevector.size();vec++) { temp = filevector[vec]; fileout.insert(fileout.end(), temp.name.c_str()); } return; } void properties_open(DLGSTR properties_menu, vector <string> propvec/*, link_to_file*/) { bool cycle = true; int key = 0; while (cycle) { menu_win(properties_menu, propvec); key = getch(); switch (key) { case KEY_UP: if (properties_menu.selected != 1) properties_menu.selected--; break; case KEY_DOWN: if (properties_menu.selected != properties_menu.second_border) properties_menu.selected++; break; case 27: return; break; } } return; } void interface_fm() { unsigned int maxX, maxY; getmaxyx(stdscr, maxY, maxX); vector <string> propvec; string link_first_panel = ".", link_second_panel = "."; /*For windlg*/ DLGSTR winstr = {}; // Только так!!! winstr.line = "Please enter link to foldren"; /*For windlg END*/ /*For first panel*/ DLGSTR first_panel = {}; first_panel.xmax = maxX / 2 - 2; first_panel.ymax = maxY - 4; first_panel.xpos = 0; first_panel.ypos = 1; first_panel.style = 3; first_panel.title = link_first_panel; if (llength(first_panel.title) > maxX / 2 - 2) { while (llength(first_panel.title) + 3 > (maxX / 2 - 2)) first_panel.title.erase(0, 1); first_panel.title.insert(0, "..."); } first_panel.border_menu = true; /*For first panel END*/ /*For second panel*/ DLGSTR second_panel = {}; second_panel.xmax = maxX / 2 - 2; second_panel.ymax = maxY - 4; second_panel.xpos = maxX / 2 + 1; second_panel.ypos = 1; second_panel.style = 0; second_panel.title = link_second_panel; if (llength(second_panel.title) > maxX / 2 - 2) { while (llength(second_panel.title) + 3 > (maxX / 2 - 2)) second_panel.title.erase(0, 1); second_panel.title.insert(0, "..."); } second_panel.border_menu = true; /*For second panel END*/ /*For properties panel*/ DLGSTR properties_menu = {}; properties_menu.ymax = 4; properties_menu.style = 2; properties_menu.border_menu = true; /*For properties panel END*/ bool cycle = true; vector <FILEINFO> filevector_1; // Вектор для загрузки файлов первой панели vector <FILEINFO> filevector_2; // Вектор для загрузки файлов второйой панели vector <string> fileout_1; // Вектор вывода списка файлов первой панели vector <string> fileout_2; // Вектор вывода списка файлов второйой панели FILEINFO filestr; while (get_files(link_first_panel, filevector_1) == -1) { winstr.style = 1; winstr.line = "Wrong link!!! Try again!"; msg_win(winstr); winstr.style = 0; winstr.line = "Please enter link to foldren"; dlg_win(winstr, link_first_panel); } while (get_files(link_second_panel, filevector_2) == -1) { winstr.style = 1; winstr.line = "Wrong link!!! Try again!"; msg_win(winstr); winstr.style = 0; winstr.line = "Please enter link to foldren"; dlg_win(winstr, link_second_panel); } get_files(link_second_panel, filevector_2); // TEST!!!! files_sort_by('n', filevector_1); files_sort_by('t', filevector_2); load_files(filevector_1, fileout_1); load_files(filevector_2, fileout_2); load_properties(propvec); /*Init head START*/ load_pair_fm(); int selected_color = 0; string head; head.clear(); for (unsigned int i = 0; i < maxX; i++, head += " "); /*Init head END*/ /*Mode*/ unsigned int mode_select = 1, key_pressed = 0; /*0 - Menu 1 - First panel 2 - Second panel*/ /*Mode END*/ while (cycle) { timeout(-1); /*Head START*/ switch (mode_select) { case 0: selected_color = 6; first_panel.style = 0; second_panel.style = 0; break; case 1: first_panel.style = 3; second_panel.style = 0; break; case 2: second_panel.style = 3; first_panel.style = 0; break; } attron(COLOR_PAIR(1 + selected_color) | A_BOLD); mvprintw(0, 0, "%s", head.c_str()); mvprintw(0, 0, "(M)enu"); attroff(COLOR_PAIR(1 + selected_color) | A_BOLD); selected_color = 0; /*Head END*/ menu_win(first_panel, fileout_1); menu_win(second_panel, fileout_2); key_pressed = getch(); switch (key_pressed) { case TAB_KEY: if (mode_select != 2) mode_select++; else mode_select = 0; break; case KEY_UP: switch (mode_select) { case 1: if (first_panel.selected != 1) first_panel.selected--; break; case 2: if (second_panel.selected != 1) second_panel.selected--; break; } break; case KEY_DOWN: switch (mode_select) { case 1: if (first_panel.selected != first_panel.second_border) first_panel.selected++; break; case 2: if (second_panel.selected != second_panel.second_border) second_panel.selected++; break; } break; case '\n': switch (mode_select) { case 1: properties_menu.xpos = first_panel.xreturn; properties_menu.ypos = first_panel.yreturn; properties_open(properties_menu, propvec/*, link_to_file*/); break; case 2: properties_menu.xpos = second_panel.xreturn; properties_menu.ypos = second_panel.yreturn; properties_open(properties_menu, propvec/*, link_to_file*/); break; } break; } } return; } int main(int argc, char* argv[]) { setlocale(LC_ALL, ""); initscr(); start_color(); keypad (stdscr, TRUE); noecho(); curs_set(0); erase(); // get_files("./test", test_vec); /*for(unsigned int i = 0; i < test_vec.size(); i++) { test_str = test_vec[i]; printw("%s\n", test_str.name.c_str()); }*/ interface_fm(); /*for(unsigned int i = 0; i < test_vec.size(); i++) { test_str = test_vec[i]; printw("%i %s %s\n", (int)test_str.name[0], test_str.name.c_str(), ctime(&test_str.mtime)); }*/ endwin(); return 0; } <|endoftext|>
<commit_before>#include <QChar> #include <QByteArray> #include <QCryptographicHash> #include <QFileDialog> #include <QKeyEvent> #include <QList> #include <QMessageBox> #include <QMetaEnum> #include <QNetworkAccessManager> #include <QNetworkReply> #include <QNetworkRequest> #include <QProgressDialog> #include <QRegExp> #include <QString> #include <QTextStream> #include <QUrl> #include <QtCore> #include <QtDebug> #include <QtIOCompressor.hh> #include "OpenCorpusDialog.hh" #include "ArchiveModel.hh" #include <config.hh> #include <AlpinoCorpus/CorpusReaderFactory.hh> #include <AlpinoCorpus/Error.hh> #include "ui_OpenCorpusDialog.h" namespace ac = alpinocorpus; QString const DOWNLOAD_EXTENSION(".dact.gz"); OpenCorpusDialog::OpenCorpusDialog(QWidget *parent, Qt::WindowFlags f) : QDialog(parent, f), d_ui(QSharedPointer<Ui::OpenCorpusDialog>(new Ui::OpenCorpusDialog)), d_archiveModel(new ArchiveModel(this)), d_corpusAccessManager(new QNetworkAccessManager(this)), d_downloadProgressDialog(new QProgressDialog(this)), d_inflateProgressDialog(new QProgressDialog(this)), d_reply(0), d_cancelInflate(false) { d_ui->setupUi(this); d_ui->corpusListView->setModel(d_archiveModel.data()); // We only enable the download button when a corpus is selected. d_ui->openButton->setEnabled(false); d_downloadProgressDialog->setWindowTitle("Downloading corpus"); d_downloadProgressDialog->setRange(0, 100); d_inflateProgressDialog->setWindowTitle("Decompressing corpus"); d_inflateProgressDialog->setLabelText("Decompressing downloaded corpus"); d_inflateProgressDialog->setRange(0, 100); connect(d_archiveModel.data(), SIGNAL(networkError(QString)), SLOT(archiveNetworkError(QString))); connect(d_archiveModel.data(), SIGNAL(processingError(QString)), SLOT(archiveProcessingError(QString))); connect(d_ui->corpusListView->selectionModel(), SIGNAL(currentRowChanged(QModelIndex const &, QModelIndex const &)), SLOT(rowChanged(QModelIndex const &, QModelIndex const &))); connect(d_ui->corpusListView, SIGNAL(activated(QModelIndex const &)), SLOT(openSelectedCorpus(QModelIndex const &))); connect(d_archiveModel.data(), SIGNAL(retrievalFinished()), SLOT(archiveRetrieved())); connect(d_corpusAccessManager.data(), SIGNAL(finished(QNetworkReply *)), SLOT(corpusReplyFinished(QNetworkReply*))); connect(d_downloadProgressDialog.data(), SIGNAL(canceled()), SLOT(downloadCanceled())); connect(d_inflateProgressDialog.data(), SIGNAL(canceled()), SLOT(cancelInflate())); connect(this, SIGNAL(inflateProgressed(int)), d_inflateProgressDialog.data(), SLOT(setValue(int))); connect(this, SIGNAL(inflateError(QString)), SLOT(inflateHandleError(QString))); connect(this, SIGNAL(inflateFinished()), d_inflateProgressDialog.data(), SLOT(accept())); connect(this, SIGNAL(inflateFinished()), SLOT(accept())); connect(d_archiveModel.data(), SIGNAL(retrieving()), d_ui->activityIndicator, SLOT(show())); connect(d_archiveModel.data(), SIGNAL(retrievalFinished()), d_ui->activityIndicator, SLOT(hide())); connect(d_archiveModel.data(), SIGNAL(networkError(QString)), d_ui->activityIndicator, SLOT(hide())); refreshCorpusList(); } OpenCorpusDialog::~OpenCorpusDialog() { // } void OpenCorpusDialog::archiveNetworkError(QString error) { QMessageBox box(QMessageBox::Warning, "Failed to fetch corpus index", QString("Could not fetch the list of corpora, failed with error: %1").arg(error), QMessageBox::Ok); box.exec(); } void OpenCorpusDialog::archiveProcessingError(QString error) { QMessageBox box(QMessageBox::Warning, "Could not process archive index", QString("Could not process the index of the archive: %1").arg(error), QMessageBox::Ok); box.exec(); } void OpenCorpusDialog::archiveRetrieved() { // } void OpenCorpusDialog::corpusReplyFinished(QNetworkReply *reply) { d_reply = 0; QNetworkReply::NetworkError error = reply->error(); if (error != QNetworkReply::NoError) { reply->deleteLater(); if (error == QNetworkReply::OperationCanceledError) return; QString errorValue(networkErrorToString(error)); QMessageBox box(QMessageBox::Warning, "Failed to download corpus", QString("Downloading of corpus failed with error: %1").arg(errorValue), QMessageBox::Ok); d_downloadProgressDialog->accept(); box.exec(); return; } d_downloadProgressDialog->accept(); d_inflateProgressDialog->setValue(0); d_inflateProgressDialog->open(); QtConcurrent::run(this, &OpenCorpusDialog::inflate, reply); } void OpenCorpusDialog::download(ArchiveEntry const &entry) { QString name = entry.name; QString hash = entry.checksum; QString corpusName = name + DOWNLOAD_EXTENSION; QString filename = entry.filePath(); d_filename = filename; d_hash = hash; d_downloadProgressDialog->setLabelText(QString("Downloading '%1'").arg(corpusName)); d_downloadProgressDialog->reset(); d_downloadProgressDialog->open(); QString corpusUrl = QString("%1/%2").arg(d_baseUrl).arg(corpusName); QNetworkRequest request(corpusUrl); d_reply = d_corpusAccessManager->get(request); connect(d_reply, SIGNAL(downloadProgress(qint64, qint64)), SLOT(downloadProgress(qint64, qint64))); } void OpenCorpusDialog::downloadCanceled() { Q_ASSERT(d_reply != 0); d_reply->abort(); } void OpenCorpusDialog::downloadProgress(qint64 progress, qint64 maximum) { if (maximum == 0) return; d_downloadProgressDialog->setValue((progress * 100) / maximum); } QString OpenCorpusDialog::getCorpusFileName(QWidget *parent) { OpenCorpusDialog dialog(parent); return dialog.exec() == QDialog::Accepted ? dialog.d_filename : QString(); } QSharedPointer<ac::CorpusReader> OpenCorpusDialog::getCorpusReader(QWidget *parent) { // In the most ideal case, the OpenCorpusDialog would return just a corpus reader // which could be reading a local file, or a webservice, or anything else Dact // can open. All code to open a file and create a reader would be moved to // OpenCorpusDialog. One problem remains: where should the code live that is used // to open files passed as arguments on the command line? return QSharedPointer<ac::CorpusReader>(0); } void OpenCorpusDialog::inflate(QIODevice *dev) { qint64 initAvailable = dev->bytesAvailable(); QtIOCompressor data(dev); data.setStreamFormat(QtIOCompressor::GzipFormat); if (!data.open(QIODevice::ReadOnly)) { dev->deleteLater(); emit inflateError("could not compressed data stream."); return; } // Make sure the directory exists in which we want to store the result if (!QDir::current().mkpath(QFileInfo(d_filename).path())) { dev->deleteLater(); emit inflateError("could not create output directory"); return; } QFile out(d_filename); if (!out.open(QIODevice::WriteOnly)) { dev->deleteLater(); emit inflateError("could not open output file for writing."); return; } // We'll check whether the uncompressed data matches the given hash. QCryptographicHash sha1(QCryptographicHash::Sha1); while (!data.atEnd() && !d_cancelInflate) { emit inflateProgressed(static_cast<int>( ((initAvailable - dev->bytesAvailable()) * 100) / initAvailable)); QByteArray newData = data.read(65535); sha1.addData(newData); out.write(newData); } dev->deleteLater(); if (d_cancelInflate) { d_cancelInflate = false; out.remove(); emit inflateCanceled(); return; } QString hash(sha1.result().toHex()); if (hash != d_hash) { out.remove(); emit inflateError("invalid checksum, data was corrupted."); } emit inflateFinished(); } void OpenCorpusDialog::cancelInflate() { d_cancelInflate = true; } void OpenCorpusDialog::inflateHandleError(QString error) { d_inflateProgressDialog->accept(); QMessageBox box(QMessageBox::Warning, "Failed to decompress corpus", QString("Could not decompress corpus: %1").arg(error), QMessageBox::Ok); box.exec(); } void OpenCorpusDialog::keyPressEvent(QKeyEvent *event) { // Close window on ESC and CMD + W. if (event->key() == Qt::Key_Escape || (event->key() == Qt::Key_W && event->modifiers() == Qt::ControlModifier)) { reject(); event->accept(); } else QWidget::keyPressEvent(event); } void OpenCorpusDialog::openLocalFile() { d_filename = QFileDialog::getOpenFileName(this, "Open corpus", QString(), "Dact corpora (*.dact)"); if (!d_filename.isNull()) accept(); } void OpenCorpusDialog::openSelectedCorpus() { QItemSelectionModel *selectionModel = d_ui->corpusListView->selectionModel(); if (selectionModel->selectedIndexes().size() > 0) openSelectedCorpus(selectionModel->selectedIndexes().at(0)); } void OpenCorpusDialog::openSelectedCorpus(QModelIndex const &index) { ArchiveEntry const &entry = d_archiveModel->entryAtRow(index.row()); if (QFile(entry.filePath()).exists()) { d_filename = entry.filePath(); accept(); } else { download(entry); } } void OpenCorpusDialog::refreshCorpusList() { QSettings settings; d_baseUrl = settings.value(ARCHIVE_BASEURL_KEY, DEFAULT_ARCHIVE_BASEURL).toString(); d_archiveModel->setUrl(QUrl(QString("%1/index.xml").arg(d_baseUrl))); } void OpenCorpusDialog::rowChanged(QModelIndex const &current, QModelIndex const &previous) { Q_UNUSED(previous); d_ui->openButton->setEnabled(current.isValid()); } QString OpenCorpusDialog::networkErrorToString(QNetworkReply::NetworkError error) { QString errorValue; QMetaObject meta = QNetworkReply::staticMetaObject; for (int i = 0; i < meta.enumeratorCount(); ++i) { QMetaEnum m = meta.enumerator(i); if (m.name() == QLatin1String("NetworkError")) { errorValue = QLatin1String(m.valueToKey(error)); break; } } return errorValue; } <commit_msg>Avoid double managed classes.<commit_after>#include <QChar> #include <QByteArray> #include <QCryptographicHash> #include <QFileDialog> #include <QKeyEvent> #include <QList> #include <QMessageBox> #include <QMetaEnum> #include <QNetworkAccessManager> #include <QNetworkReply> #include <QNetworkRequest> #include <QProgressDialog> #include <QRegExp> #include <QString> #include <QTextStream> #include <QUrl> #include <QtCore> #include <QtDebug> #include <QtIOCompressor.hh> #include "OpenCorpusDialog.hh" #include "ArchiveModel.hh" #include <config.hh> #include <AlpinoCorpus/CorpusReaderFactory.hh> #include <AlpinoCorpus/Error.hh> #include "ui_OpenCorpusDialog.h" namespace ac = alpinocorpus; QString const DOWNLOAD_EXTENSION(".dact.gz"); OpenCorpusDialog::OpenCorpusDialog(QWidget *parent, Qt::WindowFlags f) : QDialog(parent, f), d_ui(QSharedPointer<Ui::OpenCorpusDialog>(new Ui::OpenCorpusDialog)), d_archiveModel(new ArchiveModel()), d_corpusAccessManager(new QNetworkAccessManager()), d_downloadProgressDialog(new QProgressDialog()), d_inflateProgressDialog(new QProgressDialog()), d_reply(0), d_cancelInflate(false) { d_ui->setupUi(this); d_ui->corpusListView->setModel(d_archiveModel.data()); // We only enable the download button when a corpus is selected. d_ui->openButton->setEnabled(false); d_downloadProgressDialog->setWindowTitle("Downloading corpus"); d_downloadProgressDialog->setRange(0, 100); d_inflateProgressDialog->setWindowTitle("Decompressing corpus"); d_inflateProgressDialog->setLabelText("Decompressing downloaded corpus"); d_inflateProgressDialog->setRange(0, 100); connect(d_archiveModel.data(), SIGNAL(networkError(QString)), SLOT(archiveNetworkError(QString))); connect(d_archiveModel.data(), SIGNAL(processingError(QString)), SLOT(archiveProcessingError(QString))); connect(d_ui->corpusListView->selectionModel(), SIGNAL(currentRowChanged(QModelIndex const &, QModelIndex const &)), SLOT(rowChanged(QModelIndex const &, QModelIndex const &))); connect(d_ui->corpusListView, SIGNAL(activated(QModelIndex const &)), SLOT(openSelectedCorpus(QModelIndex const &))); connect(d_archiveModel.data(), SIGNAL(retrievalFinished()), SLOT(archiveRetrieved())); connect(d_corpusAccessManager.data(), SIGNAL(finished(QNetworkReply *)), SLOT(corpusReplyFinished(QNetworkReply*))); connect(d_downloadProgressDialog.data(), SIGNAL(canceled()), SLOT(downloadCanceled())); connect(d_inflateProgressDialog.data(), SIGNAL(canceled()), SLOT(cancelInflate())); connect(this, SIGNAL(inflateProgressed(int)), d_inflateProgressDialog.data(), SLOT(setValue(int))); connect(this, SIGNAL(inflateError(QString)), SLOT(inflateHandleError(QString))); connect(this, SIGNAL(inflateFinished()), d_inflateProgressDialog.data(), SLOT(accept())); connect(this, SIGNAL(inflateFinished()), SLOT(accept())); connect(d_archiveModel.data(), SIGNAL(retrieving()), d_ui->activityIndicator, SLOT(show())); connect(d_archiveModel.data(), SIGNAL(retrievalFinished()), d_ui->activityIndicator, SLOT(hide())); connect(d_archiveModel.data(), SIGNAL(networkError(QString)), d_ui->activityIndicator, SLOT(hide())); refreshCorpusList(); } OpenCorpusDialog::~OpenCorpusDialog() { // } void OpenCorpusDialog::archiveNetworkError(QString error) { QMessageBox box(QMessageBox::Warning, "Failed to fetch corpus index", QString("Could not fetch the list of corpora, failed with error: %1").arg(error), QMessageBox::Ok); box.exec(); } void OpenCorpusDialog::archiveProcessingError(QString error) { QMessageBox box(QMessageBox::Warning, "Could not process archive index", QString("Could not process the index of the archive: %1").arg(error), QMessageBox::Ok); box.exec(); } void OpenCorpusDialog::archiveRetrieved() { // } void OpenCorpusDialog::corpusReplyFinished(QNetworkReply *reply) { d_reply = 0; QNetworkReply::NetworkError error = reply->error(); if (error != QNetworkReply::NoError) { reply->deleteLater(); if (error == QNetworkReply::OperationCanceledError) return; QString errorValue(networkErrorToString(error)); QMessageBox box(QMessageBox::Warning, "Failed to download corpus", QString("Downloading of corpus failed with error: %1").arg(errorValue), QMessageBox::Ok); d_downloadProgressDialog->accept(); box.exec(); return; } d_downloadProgressDialog->accept(); d_inflateProgressDialog->setValue(0); d_inflateProgressDialog->open(); QtConcurrent::run(this, &OpenCorpusDialog::inflate, reply); } void OpenCorpusDialog::download(ArchiveEntry const &entry) { QString name = entry.name; QString hash = entry.checksum; QString corpusName = name + DOWNLOAD_EXTENSION; QString filename = entry.filePath(); d_filename = filename; d_hash = hash; d_downloadProgressDialog->setLabelText(QString("Downloading '%1'").arg(corpusName)); d_downloadProgressDialog->reset(); d_downloadProgressDialog->open(); QString corpusUrl = QString("%1/%2").arg(d_baseUrl).arg(corpusName); QNetworkRequest request(corpusUrl); d_reply = d_corpusAccessManager->get(request); connect(d_reply, SIGNAL(downloadProgress(qint64, qint64)), SLOT(downloadProgress(qint64, qint64))); } void OpenCorpusDialog::downloadCanceled() { Q_ASSERT(d_reply != 0); d_reply->abort(); } void OpenCorpusDialog::downloadProgress(qint64 progress, qint64 maximum) { if (maximum == 0) return; d_downloadProgressDialog->setValue((progress * 100) / maximum); } QString OpenCorpusDialog::getCorpusFileName(QWidget *parent) { OpenCorpusDialog dialog(parent); return dialog.exec() == QDialog::Accepted ? dialog.d_filename : QString(); } QSharedPointer<ac::CorpusReader> OpenCorpusDialog::getCorpusReader(QWidget *parent) { // In the most ideal case, the OpenCorpusDialog would return just a corpus reader // which could be reading a local file, or a webservice, or anything else Dact // can open. All code to open a file and create a reader would be moved to // OpenCorpusDialog. One problem remains: where should the code live that is used // to open files passed as arguments on the command line? return QSharedPointer<ac::CorpusReader>(0); } void OpenCorpusDialog::inflate(QIODevice *dev) { qint64 initAvailable = dev->bytesAvailable(); QtIOCompressor data(dev); data.setStreamFormat(QtIOCompressor::GzipFormat); if (!data.open(QIODevice::ReadOnly)) { dev->deleteLater(); emit inflateError("could not compressed data stream."); return; } // Make sure the directory exists in which we want to store the result if (!QDir::current().mkpath(QFileInfo(d_filename).path())) { dev->deleteLater(); emit inflateError("could not create output directory"); return; } QFile out(d_filename); if (!out.open(QIODevice::WriteOnly)) { dev->deleteLater(); emit inflateError("could not open output file for writing."); return; } // We'll check whether the uncompressed data matches the given hash. QCryptographicHash sha1(QCryptographicHash::Sha1); while (!data.atEnd() && !d_cancelInflate) { emit inflateProgressed(static_cast<int>( ((initAvailable - dev->bytesAvailable()) * 100) / initAvailable)); QByteArray newData = data.read(65535); sha1.addData(newData); out.write(newData); } dev->deleteLater(); if (d_cancelInflate) { d_cancelInflate = false; out.remove(); emit inflateCanceled(); return; } QString hash(sha1.result().toHex()); if (hash != d_hash) { out.remove(); emit inflateError("invalid checksum, data was corrupted."); } emit inflateFinished(); } void OpenCorpusDialog::cancelInflate() { d_cancelInflate = true; } void OpenCorpusDialog::inflateHandleError(QString error) { d_inflateProgressDialog->accept(); QMessageBox box(QMessageBox::Warning, "Failed to decompress corpus", QString("Could not decompress corpus: %1").arg(error), QMessageBox::Ok); box.exec(); } void OpenCorpusDialog::keyPressEvent(QKeyEvent *event) { // Close window on ESC and CMD + W. if (event->key() == Qt::Key_Escape || (event->key() == Qt::Key_W && event->modifiers() == Qt::ControlModifier)) { reject(); event->accept(); } else QWidget::keyPressEvent(event); } void OpenCorpusDialog::openLocalFile() { d_filename = QFileDialog::getOpenFileName(this, "Open corpus", QString(), "Dact corpora (*.dact)"); if (!d_filename.isNull()) accept(); } void OpenCorpusDialog::openSelectedCorpus() { QItemSelectionModel *selectionModel = d_ui->corpusListView->selectionModel(); if (selectionModel->selectedIndexes().size() > 0) openSelectedCorpus(selectionModel->selectedIndexes().at(0)); } void OpenCorpusDialog::openSelectedCorpus(QModelIndex const &index) { ArchiveEntry const &entry = d_archiveModel->entryAtRow(index.row()); if (QFile(entry.filePath()).exists()) { d_filename = entry.filePath(); accept(); } else { download(entry); } } void OpenCorpusDialog::refreshCorpusList() { QSettings settings; d_baseUrl = settings.value(ARCHIVE_BASEURL_KEY, DEFAULT_ARCHIVE_BASEURL).toString(); d_archiveModel->setUrl(QUrl(QString("%1/index.xml").arg(d_baseUrl))); } void OpenCorpusDialog::rowChanged(QModelIndex const &current, QModelIndex const &previous) { Q_UNUSED(previous); d_ui->openButton->setEnabled(current.isValid()); } QString OpenCorpusDialog::networkErrorToString(QNetworkReply::NetworkError error) { QString errorValue; QMetaObject meta = QNetworkReply::staticMetaObject; for (int i = 0; i < meta.enumeratorCount(); ++i) { QMetaEnum m = meta.enumerator(i); if (m.name() == QLatin1String("NetworkError")) { errorValue = QLatin1String(m.valueToKey(error)); break; } } return errorValue; } <|endoftext|>
<commit_before>//===-- Immediate.cpp - the swift immediate mode --------------------------===// // // 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 // //===----------------------------------------------------------------------===// // // This is the implementation of the swift interpreter, which takes a // TranslationUnit and JITs it. // //===----------------------------------------------------------------------===// #include "Immediate.h" #include "Frontend.h" #include "swift/Subsystems.h" #include "swift/IRGen/Options.h" #include "swift/AST/ASTContext.h" #include "swift/AST/Component.h" #include "swift/AST/Decl.h" #include "swift/AST/Diagnostics.h" #include "swift/AST/Module.h" #include "swift/AST/Stmt.h" #include "swift/Basic/DiagnosticConsumer.h" #include "llvm/ADT/SmallPtrSet.h" #include "llvm/ExecutionEngine/JIT.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/Host.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Support/Signals.h" #include "llvm/Support/SourceMgr.h" #include "llvm/Support/system_error.h" #include "llvm/Support/TargetSelect.h" #include "llvm/Linker.h" #include "llvm/LLVMContext.h" #include "llvm/Module.h" #include <histedit.h> #include <dlfcn.h> static void LoadSwiftRuntime() { // FIXME: Need error-checking. llvm::sys::Path LibPath = llvm::sys::Path::GetMainExecutable(0, (void*)&swift::RunImmediately); LibPath.eraseComponent(); LibPath.eraseComponent(); LibPath.appendComponent("lib"); LibPath.appendComponent("libswift_abi.dylib"); dlopen(LibPath.c_str(), 0); } void swift::RunImmediately(TranslationUnit *TU) { ASTContext &Context = TU->Ctx; irgen::Options Options; Options.OutputFilename = ""; Options.Triple = llvm::sys::getDefaultTargetTriple(); Options.OptLevel = 0; Options.OutputKind = irgen::OutputKind::Module; // IRGen the main module. llvm::LLVMContext LLVMContext; llvm::Module Module(TU->Name.str(), LLVMContext); performCaptureAnalysis(TU); performIRGeneration(Options, &Module, TU); if (Context.hadError()) return; llvm::SmallPtrSet<TranslationUnit*, 8> ImportedModules; // IRGen the modules this module depends on. for (auto ModPair : TU->getImportedModules()) { if (isa<BuiltinModule>(ModPair.second)) continue; TranslationUnit *SubTU = cast<TranslationUnit>(ModPair.second); if (!ImportedModules.insert(SubTU)) continue; // FIXME: Need to check whether this is actually safe in general. llvm::Module SubModule(SubTU->Name.str(), LLVMContext); performCaptureAnalysis(SubTU); performIRGeneration(Options, &SubModule, SubTU); if (Context.hadError()) return; std::string ErrorMessage; if (llvm::Linker::LinkModules(&Module, &SubModule, llvm::Linker::DestroySource, &ErrorMessage)) { llvm::errs() << "Error linking swift modules\n"; llvm::errs() << ErrorMessage << "\n"; return; } } LoadSwiftRuntime(); // Run the generated program. // FIXME: This isn't the right entry point! (But what is?) llvm::Function *EntryFn = Module.getFunction("main"); llvm::EngineBuilder builder(&Module); std::string ErrorMsg; builder.setErrorStr(&ErrorMsg); builder.setEngineKind(llvm::EngineKind::JIT); llvm::ExecutionEngine *EE = builder.create(); EE->runFunctionAsMain(EntryFn, std::vector<std::string>(), 0); } struct InitEditLine { EditLine *e; InitEditLine() { e = el_init("swift", stdin, stdout, stderr); el_set(e, EL_EDITOR, "emacs"); char *(*PromptFn)(EditLine *) = [](EditLine *e) { return (char*)"swift> "; }; el_set(e, EL_PROMPT, PromptFn); } ~InitEditLine() { el_end(e); } operator EditLine*() { return e; } }; void swift::REPL(ASTContext &Context) { // FIXME: We should do something a bit more elaborate than // "allocate a 1MB buffer and hope it's enough". llvm::MemoryBuffer *Buffer = llvm::MemoryBuffer::getNewMemBuffer(1 << 20, "<REPL Buffer>"); Component *Comp = new (Context.Allocate<Component>(1)) Component(); unsigned BufferID = Context.SourceMgr.AddNewSourceBuffer(Buffer, llvm::SMLoc()); Identifier ID = Context.getIdentifier("REPL"); TranslationUnit *TU = new (Context) TranslationUnit(ID, Comp, Context, /*IsMainModule=*/true); llvm::SmallPtrSet<TranslationUnit*, 8> ImportedModules; llvm::LLVMContext LLVMContext; llvm::Module Module("REPL", LLVMContext); LoadSwiftRuntime(); irgen::Options Options; Options.OutputFilename = ""; Options.Triple = llvm::sys::getDefaultTargetTriple(); Options.OptLevel = 0; Options.OutputKind = irgen::OutputKind::Module; char* CurBuffer = const_cast<char*>(Buffer->getBufferStart()); unsigned CurBufferOffset = 0; unsigned CurBufferEndOffset = 0; InitEditLine e; unsigned CurTUElem = 0; while (1) { int LineCount; const char* Line = el_gets(e, &LineCount); if (!Line) return; // FIXME: Should continue reading lines when there is an unbalanced // brace/paren/bracket. strcpy(CurBuffer, Line); CurBuffer += strlen(Line); *CurBuffer++ = '\n'; CurBufferEndOffset += strlen(Line) + 1; bool ShouldRun = swift::appendToMainTranslationUnit(TU, BufferID, CurTUElem, CurBufferOffset, CurBufferEndOffset); // FIXME: Better error recovery would be really nice here. if (Context.hadError()) return; if (!ShouldRun) continue; // IRGen the main module. performCaptureAnalysis(TU, CurTUElem); performIRGeneration(Options, &Module, TU, CurTUElem); CurTUElem = TU->Body->getNumElements(); if (Context.hadError()) return; // IRGen the modules this module depends on. for (auto ModPair : TU->getImportedModules()) { if (isa<BuiltinModule>(ModPair.second)) continue; TranslationUnit *SubTU = cast<TranslationUnit>(ModPair.second); if (!ImportedModules.insert(SubTU)) continue; // FIXME: Need to check whether this is actually safe in general. llvm::Module SubModule(SubTU->Name.str(), LLVMContext); performCaptureAnalysis(SubTU); performIRGeneration(Options, &SubModule, SubTU); if (Context.hadError()) return; std::string ErrorMessage; if (llvm::Linker::LinkModules(&Module, &SubModule, llvm::Linker::DestroySource, &ErrorMessage)) { llvm::errs() << "Error linking swift modules\n"; llvm::errs() << ErrorMessage << "\n"; return; } } // The way we do this is really ugly... we should be able to improve this. llvm::Function *EntryFn = Module.getFunction("main"); { llvm::EngineBuilder builder(&Module); std::string ErrorMsg; builder.setErrorStr(&ErrorMsg); builder.setEngineKind(llvm::EngineKind::JIT); llvm::ExecutionEngine *EE = builder.create(); EE->runFunctionAsMain(EntryFn, std::vector<std::string>(), 0); } EntryFn->eraseFromParent(); } } // FIXME: We shouldn't be writing implemenetations for functions in the swift // module in C, and this isn't really an ideal place to put those // implementations. extern "C" void _TSs5printFT3valNSs5Int64_T_(int64_t l) { printf("%lld", l); } extern "C" void _TSs5printFT3valNSs6Double_T_(double l) { printf("%f", l); } extern "C" void _TSs9printCharFT9characterNSs5Int64_T_(int64_t l) { printf("%c", (char)l); } extern "C" void _TSs5printFT3valNSs6String_T_(char* l) { printf("%s", l); } extern "C" bool _TNSs4Bool13getLogicValuefRS_FT_i1(bool* b) { return *b; } extern "C" void _TSs4exitFT8exitCodeNSs5Int64_T_(int64_t l) { exit(l); } <commit_msg>eliminate gratuitous lambda that crashes Xcode 4.3 clang.<commit_after>//===-- Immediate.cpp - the swift immediate mode --------------------------===// // // 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 // //===----------------------------------------------------------------------===// // // This is the implementation of the swift interpreter, which takes a // TranslationUnit and JITs it. // //===----------------------------------------------------------------------===// #include "Immediate.h" #include "Frontend.h" #include "swift/Subsystems.h" #include "swift/IRGen/Options.h" #include "swift/AST/ASTContext.h" #include "swift/AST/Component.h" #include "swift/AST/Decl.h" #include "swift/AST/Diagnostics.h" #include "swift/AST/Module.h" #include "swift/AST/Stmt.h" #include "swift/Basic/DiagnosticConsumer.h" #include "llvm/ADT/SmallPtrSet.h" #include "llvm/ExecutionEngine/JIT.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/Host.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Support/Signals.h" #include "llvm/Support/SourceMgr.h" #include "llvm/Support/system_error.h" #include "llvm/Support/TargetSelect.h" #include "llvm/Linker.h" #include "llvm/LLVMContext.h" #include "llvm/Module.h" #include <histedit.h> #include <dlfcn.h> static void LoadSwiftRuntime() { // FIXME: Need error-checking. llvm::sys::Path LibPath = llvm::sys::Path::GetMainExecutable(0, (void*)&swift::RunImmediately); LibPath.eraseComponent(); LibPath.eraseComponent(); LibPath.appendComponent("lib"); LibPath.appendComponent("libswift_abi.dylib"); dlopen(LibPath.c_str(), 0); } void swift::RunImmediately(TranslationUnit *TU) { ASTContext &Context = TU->Ctx; irgen::Options Options; Options.OutputFilename = ""; Options.Triple = llvm::sys::getDefaultTargetTriple(); Options.OptLevel = 0; Options.OutputKind = irgen::OutputKind::Module; // IRGen the main module. llvm::LLVMContext LLVMContext; llvm::Module Module(TU->Name.str(), LLVMContext); performCaptureAnalysis(TU); performIRGeneration(Options, &Module, TU); if (Context.hadError()) return; llvm::SmallPtrSet<TranslationUnit*, 8> ImportedModules; // IRGen the modules this module depends on. for (auto ModPair : TU->getImportedModules()) { if (isa<BuiltinModule>(ModPair.second)) continue; TranslationUnit *SubTU = cast<TranslationUnit>(ModPair.second); if (!ImportedModules.insert(SubTU)) continue; // FIXME: Need to check whether this is actually safe in general. llvm::Module SubModule(SubTU->Name.str(), LLVMContext); performCaptureAnalysis(SubTU); performIRGeneration(Options, &SubModule, SubTU); if (Context.hadError()) return; std::string ErrorMessage; if (llvm::Linker::LinkModules(&Module, &SubModule, llvm::Linker::DestroySource, &ErrorMessage)) { llvm::errs() << "Error linking swift modules\n"; llvm::errs() << ErrorMessage << "\n"; return; } } LoadSwiftRuntime(); // Run the generated program. // FIXME: This isn't the right entry point! (But what is?) llvm::Function *EntryFn = Module.getFunction("main"); llvm::EngineBuilder builder(&Module); std::string ErrorMsg; builder.setErrorStr(&ErrorMsg); builder.setEngineKind(llvm::EngineKind::JIT); llvm::ExecutionEngine *EE = builder.create(); EE->runFunctionAsMain(EntryFn, std::vector<std::string>(), 0); } struct InitEditLine { EditLine *e; static char *PromptFn(EditLine *) { return (char*)"swift> "; }; InitEditLine() { e = el_init("swift", stdin, stdout, stderr); el_set(e, EL_EDITOR, "emacs"); el_set(e, EL_PROMPT, PromptFn); } ~InitEditLine() { el_end(e); } operator EditLine*() { return e; } }; void swift::REPL(ASTContext &Context) { // FIXME: We should do something a bit more elaborate than // "allocate a 1MB buffer and hope it's enough". llvm::MemoryBuffer *Buffer = llvm::MemoryBuffer::getNewMemBuffer(1 << 20, "<REPL Buffer>"); Component *Comp = new (Context.Allocate<Component>(1)) Component(); unsigned BufferID = Context.SourceMgr.AddNewSourceBuffer(Buffer, llvm::SMLoc()); Identifier ID = Context.getIdentifier("REPL"); TranslationUnit *TU = new (Context) TranslationUnit(ID, Comp, Context, /*IsMainModule=*/true); llvm::SmallPtrSet<TranslationUnit*, 8> ImportedModules; llvm::LLVMContext LLVMContext; llvm::Module Module("REPL", LLVMContext); LoadSwiftRuntime(); irgen::Options Options; Options.OutputFilename = ""; Options.Triple = llvm::sys::getDefaultTargetTriple(); Options.OptLevel = 0; Options.OutputKind = irgen::OutputKind::Module; char* CurBuffer = const_cast<char*>(Buffer->getBufferStart()); unsigned CurBufferOffset = 0; unsigned CurBufferEndOffset = 0; InitEditLine e; unsigned CurTUElem = 0; while (1) { int LineCount; const char* Line = el_gets(e, &LineCount); if (!Line) return; // FIXME: Should continue reading lines when there is an unbalanced // brace/paren/bracket. strcpy(CurBuffer, Line); CurBuffer += strlen(Line); *CurBuffer++ = '\n'; CurBufferEndOffset += strlen(Line) + 1; bool ShouldRun = swift::appendToMainTranslationUnit(TU, BufferID, CurTUElem, CurBufferOffset, CurBufferEndOffset); // FIXME: Better error recovery would be really nice here. if (Context.hadError()) return; if (!ShouldRun) continue; // IRGen the main module. performCaptureAnalysis(TU, CurTUElem); performIRGeneration(Options, &Module, TU, CurTUElem); CurTUElem = TU->Body->getNumElements(); if (Context.hadError()) return; // IRGen the modules this module depends on. for (auto ModPair : TU->getImportedModules()) { if (isa<BuiltinModule>(ModPair.second)) continue; TranslationUnit *SubTU = cast<TranslationUnit>(ModPair.second); if (!ImportedModules.insert(SubTU)) continue; // FIXME: Need to check whether this is actually safe in general. llvm::Module SubModule(SubTU->Name.str(), LLVMContext); performCaptureAnalysis(SubTU); performIRGeneration(Options, &SubModule, SubTU); if (Context.hadError()) return; std::string ErrorMessage; if (llvm::Linker::LinkModules(&Module, &SubModule, llvm::Linker::DestroySource, &ErrorMessage)) { llvm::errs() << "Error linking swift modules\n"; llvm::errs() << ErrorMessage << "\n"; return; } } // The way we do this is really ugly... we should be able to improve this. llvm::Function *EntryFn = Module.getFunction("main"); { llvm::EngineBuilder builder(&Module); std::string ErrorMsg; builder.setErrorStr(&ErrorMsg); builder.setEngineKind(llvm::EngineKind::JIT); llvm::ExecutionEngine *EE = builder.create(); EE->runFunctionAsMain(EntryFn, std::vector<std::string>(), 0); } EntryFn->eraseFromParent(); } } // FIXME: We shouldn't be writing implemenetations for functions in the swift // module in C, and this isn't really an ideal place to put those // implementations. extern "C" void _TSs5printFT3valNSs5Int64_T_(int64_t l) { printf("%lld", l); } extern "C" void _TSs5printFT3valNSs6Double_T_(double l) { printf("%f", l); } extern "C" void _TSs9printCharFT9characterNSs5Int64_T_(int64_t l) { printf("%c", (char)l); } extern "C" void _TSs5printFT3valNSs6String_T_(char* l) { printf("%s", l); } extern "C" bool _TNSs4Bool13getLogicValuefRS_FT_i1(bool* b) { return *b; } extern "C" void _TSs4exitFT8exitCodeNSs5Int64_T_(int64_t l) { exit(l); } <|endoftext|>
<commit_before>/***************************Copyright-DO-NOT-REMOVE-THIS-LINE** * CONDOR Copyright Notice * * See LICENSE.TXT for additional notices and disclaimers. * * Copyright (c)1990-1998 CONDOR Team, Computer Sciences Department, * University of Wisconsin-Madison, Madison, WI. All Rights Reserved. * No use of the CONDOR Software Program Source Code is authorized * without the express consent of the CONDOR Team. For more information * contact: CONDOR Team, Attention: Professor Miron Livny, * 7367 Computer Sciences, 1210 W. Dayton St., Madison, WI 53706-1685, * (608) 262-0856 or miron@cs.wisc.edu. * * U.S. Government Rights Restrictions: Use, duplication, or disclosure * by the U.S. Government is subject to restrictions as set forth in * subparagraph (c)(1)(ii) of The Rights in Technical Data and Computer * Software clause at DFARS 252.227-7013 or subparagraphs (c)(1) and * (2) of Commercial Computer Software-Restricted Rights at 48 CFR * 52.227-19, as applicable, CONDOR Team, Attention: Professor Miron * Livny, 7367 Computer Sciences, 1210 W. Dayton St., Madison, * WI 53706-1685, (608) 262-0856 or miron@cs.wisc.edu. ****************************Copyright-DO-NOT-REMOVE-THIS-LINE**/ /* This file contains special stubs that are needed to make certain things work within a user job that can't use their normal functionality. For now, it includes a definition of my_ip_addr(), which is used by Sock::bind() to support Condor on machines with multiple network interfaces. This version, instead of looking in a config file for magic parameters, looks at the existing syscall_sock and grabs the IP address off of there. */ #include "condor_common.h" #include "condor_io.h" extern ReliSock* syscall_sock; extern "C" { unsigned int my_ip_addr() { return syscall_sock->get_ip_int(); } } /* extern "C" */ <commit_msg>Added a bunch of user-job specific versions of util_lib functions: + _condor_dprintf_va(), which deals with syscall mode, but none of the log file crap at all. It can also deal with DebugFlags, since that can now be set for any job. + _condor_fd_panic(), which doesn't close a bunch of stuff, so we'll still have the log socket open. + _condor_dprintf_exit(), which calls Suicide() to send itself SIGKILL instead of exit(), so the job doesn't leave the queue.<commit_after>/***************************Copyright-DO-NOT-REMOVE-THIS-LINE** * CONDOR Copyright Notice * * See LICENSE.TXT for additional notices and disclaimers. * * Copyright (c)1990-1998 CONDOR Team, Computer Sciences Department, * University of Wisconsin-Madison, Madison, WI. All Rights Reserved. * No use of the CONDOR Software Program Source Code is authorized * without the express consent of the CONDOR Team. For more information * contact: CONDOR Team, Attention: Professor Miron Livny, * 7367 Computer Sciences, 1210 W. Dayton St., Madison, WI 53706-1685, * (608) 262-0856 or miron@cs.wisc.edu. * * U.S. Government Rights Restrictions: Use, duplication, or disclosure * by the U.S. Government is subject to restrictions as set forth in * subparagraph (c)(1)(ii) of The Rights in Technical Data and Computer * Software clause at DFARS 252.227-7013 or subparagraphs (c)(1) and * (2) of Commercial Computer Software-Restricted Rights at 48 CFR * 52.227-19, as applicable, CONDOR Team, Attention: Professor Miron * Livny, 7367 Computer Sciences, 1210 W. Dayton St., Madison, * WI 53706-1685, (608) 262-0856 or miron@cs.wisc.edu. ****************************Copyright-DO-NOT-REMOVE-THIS-LINE**/ /* This file contains special stubs that are needed to make certain things work within a user job that can't use their normal functionality. */ #include "condor_common.h" #include "condor_io.h" #include "condor_sys.h" #include "condor_debug.h" #include "exit.h" extern ReliSock* syscall_sock; extern "C" { extern int DebugFlags; extern FILE* _condor_DebugFP; /* We need our own definition of my_ip_addr(), which is used by Sock::bind() to support Condor on machines with multiple network interfaces. This version, instead of looking in a config file for magic parameters, looks at the existing syscall_sock and grabs the IP address off of there. */ unsigned int my_ip_addr() { return syscall_sock->get_ip_int(); } /* _condor_dprintf_va is the real meat of dprintf(). We have different concerns inside the user job. All we need to care about in here is making sure we have the right syscall mode. Otherwise, we don't need to do anything complex with priv states, locking, etc. */ void _condor_dprintf_va( int flags, char* fmt, va_list args ) { int scm; int no_fp = FALSE; /* See if this is one of the messages we are logging */ if( !(flags&DebugFlags) ) { return; } /* If dprintf() isn't initialized, don't seg fault */ if( ! _condor_DebugFP ) { _condor_DebugFP = stderr; no_fp = TRUE; } /* When talking to the debug fd, you are talking to an fd that is not visible to the user. It is not entered in the virtual file table, and, hence, you should be in unmapped mode. */ scm = SetSyscalls( SYS_LOCAL | SYS_UNMAPPED ); /* Actually print the message */ vfprintf( _condor_DebugFP, fmt, args ); /* Restore our syscall mode */ (void) SetSyscalls( scm ); if( no_fp ) { _condor_DebugFP = NULL; } } /* This is called by the dprintf_init() linked in with the user job in case of fatal error. The regular _condor_dprintf_exit() has many more concerns. We can just exit, though we want to use Suicide() so we send ourselves SIGKILL, instead of actually exiting. If we exit, we leave the job queue, which isn't what we want. Hopefully, we'll never get here. */ void _condor_dprintf_exit( void ) { Suicide(); } #if !defined(WIN32) /* Can't open something because we are out of fd's. Try to let somebody know what happened. In the user job, we don't want to close a bunch of fds, since we'll loose our debug socket, which is always open. In fact, we shouldn't have to close anything to be able to dprintf(). So, just dprintf(), flush the fd for good measure, and call Suicide() (so we don't leave the job queue). */ void _condor_fd_panic( int line, char* file ) { int scm; dprintf( D_ALWAYS, "**** PANIC -- OUT OF FILE DESCRIPTORS at line %d in %s\n", line, file ); scm = SetSyscalls( SYS_LOCAL | SYS_UNMAPPED ); (void)fflush( _condor_DebugFP ); (void) SetSyscalls( scm ); Suicide(); } #endif /* ! LOOSE32 */ } /* extern "C" */ <|endoftext|>
<commit_before>// Id$ // Author: Valeriy Onuchin 15/11/2003 /************************************************************************* * Copyright (C) 1995-2001, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // TGWin32InterpreterProxy // // // // This class defines thread-safe interface to a command line // // interpreter (CINT). // // // ////////////////////////////////////////////////////////////////////////// #include "TGWin32ProxyDefs.h" #include "TGWin32InterpreterProxy.h" #include "TROOT.h" #include "TGWin32.h" //////////////////////////////////////////////////////////////////////////////// //______________________________________________________________________________ TInterpreter *TGWin32InterpreterProxy::RealObject() { // returns TCint object return gROOT->GetInterpreter(); } RETURN_PROXY_OBJECT(Interpreter) VOID_METHOD_ARG1(Interpreter,AddIncludePath,const char*,path,1) RETURN_METHOD_ARG1(Interpreter,Int_t,AutoLoad,const char *,classname) VOID_METHOD_ARG0(Interpreter,ClearFileBusy,1) VOID_METHOD_ARG0(Interpreter,ClearStack,1) VOID_METHOD_ARG0(Interpreter,EndOfLineAction,1) VOID_METHOD_ARG0(Interpreter,EnableAutoLoading,1) RETURN_METHOD_ARG0(Interpreter,Int_t,InitializeDictionaries) RETURN_METHOD_ARG3(Interpreter,Int_t,const char*,const char*,const char*,GenerateDictionary); RETURN_METHOD_ARG0(Interpreter,char*,GetPrompt) RETURN_METHOD_ARG0(Interpreter,const char*,GetSharedLibs) RETURN_METHOD_ARG0(Interpreter,const char*,GetIncludePath) RETURN_METHOD_ARG2(Interpreter,Int_t,Load,const char*,filenam,Bool_t,system) RETURN_METHOD_ARG1(Interpreter,Int_t,LoadLibraryMap,const char*,rootmapfile) RETURN_METHOD_ARG0(Interpreter,Int_t,RescanLibraryMap) RETURN_METHOD_ARG0(Interpreter,Int_t,ReloadAllSharedLibraryMaps) RETURN_METHOD_ARG0(Interpreter,Int_t,UnloadAllSharedLibraryMaps) RETURN_METHOD_ARG1(Interpreter,Int_t,UnloadLibraryMap,const char*,library) VOID_METHOD_ARG2(Interpreter,LoadMacro,const char*,filename,TInterpreter::EErrorCode*,error,1) RETURN_METHOD_ARG2(Interpreter,Long_t,ProcessLine,const char*,line,TInterpreter::EErrorCode*,error) RETURN_METHOD_ARG2(Interpreter,Long_t,ProcessLineSynch,const char*,line,TInterpreter::EErrorCode*,error) VOID_METHOD_ARG0(Interpreter,PrintIntro,1) typedef char* (*GetlineFunc_t)(const char* prompt); typedef void (*HistaddFunc_t)(char* line); VOID_METHOD_ARG2(Interpreter,SetGetline,GetlineFunc_t, getlineFunc,\ HistaddFunc_t, histaddFunc, 1) VOID_METHOD_ARG0(Interpreter,Reset,1) VOID_METHOD_ARG0(Interpreter,ResetAll,1) VOID_METHOD_ARG0(Interpreter,ResetGlobals,1) VOID_METHOD_ARG0(Interpreter,RewindDictionary,1) RETURN_METHOD_ARG1(Interpreter,Int_t,DeleteGlobal,void*,obj) VOID_METHOD_ARG0(Interpreter,SaveContext,1) VOID_METHOD_ARG0(Interpreter,SaveGlobalsContext,1) VOID_METHOD_ARG0_LOCK(Interpreter,UpdateListOfGlobals) VOID_METHOD_ARG0_LOCK(Interpreter,UpdateListOfGlobalFunctions) VOID_METHOD_ARG0_LOCK(Interpreter,UpdateListOfTypes) VOID_METHOD_ARG2_LOCK(Interpreter,SetClassInfo,TClass*,cl,Bool_t,reload) RETURN_METHOD_ARG2(Interpreter,Bool_t,CheckClassInfo,const char*,name,Bool_t,autoload) RETURN_METHOD_ARG2(Interpreter,Long_t,Calc,const char*,line,TInterpreter::EErrorCode*,error) VOID_METHOD_ARG1_LOCK(Interpreter,CreateListOfBaseClasses,TClass*,cl) VOID_METHOD_ARG1_LOCK(Interpreter,CreateListOfDataMembers,TClass*,cl) VOID_METHOD_ARG1_LOCK(Interpreter,CreateListOfMethods,TClass*,cl) VOID_METHOD_ARG1_LOCK(Interpreter,CreateListOfMethodArgs,TFunction*,m) VOID_METHOD_ARG1_LOCK(Interpreter,UpdateListOfMethods,TClass*,cl) RETURN_METHOD_ARG3(Interpreter,TString,GetMangledName,TClass*,cl,const char*,method,const char*,params) RETURN_METHOD_ARG3(Interpreter,TString,GetMangledNameWithPrototype,TClass*,cl,const char*,method,const char*,proto) RETURN_METHOD_ARG3(Interpreter,void*,GetInterfaceMethod,TClass*,cl,const char*,method,const char*,params) RETURN_METHOD_ARG3(Interpreter,void*,GetInterfaceMethodWithPrototype,TClass*,cl,const char*,method,const char*,proto) RETURN_METHOD_ARG1(Interpreter,const char*,GetClassSharedLibs,const char*,s) RETURN_METHOD_ARG1(Interpreter,const char*,GetSharedLibDeps,const char*,s) RETURN_METHOD_ARG2(Interpreter,const char*,GetInterpreterTypeName,const char*,s,Bool_t,full) VOID_METHOD_ARG3(Interpreter,Execute,const char*,function,const char*,params,int*,error,1) VOID_METHOD_ARG5(Interpreter,Execute,TObject*,obj,TClass*,cl,const char*,method,const char*,params,int*,error,1) VOID_METHOD_ARG5(Interpreter,Execute,TObject*,object,TClass*,cl,TMethod*,method,TObjArray*,params,int*,error,1) RETURN_METHOD_ARG2(Interpreter,Long_t,ExecuteMacro,const char*,filename,TInterpreter::EErrorCode*,error) RETURN_METHOD_ARG1(Interpreter,Bool_t,SetErrorMessages,Bool_t,enable) VOID_METHOD_ARG1(Interpreter,SetProcessLineLock,Bool_t,lock,1) RETURN_METHOD_ARG1(Interpreter,const char*,TypeName,const char*,s) //Bool_t TGWin32InterpreterProxy::CheckClassInfo(const char* name) { return RealObject()->CheckClassInfo(name); } <commit_msg>Fix the order of arguments (and the compilations)<commit_after>// Id$ // Author: Valeriy Onuchin 15/11/2003 /************************************************************************* * Copyright (C) 1995-2001, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // TGWin32InterpreterProxy // // // // This class defines thread-safe interface to a command line // // interpreter (CINT). // // // ////////////////////////////////////////////////////////////////////////// #include "TGWin32ProxyDefs.h" #include "TGWin32InterpreterProxy.h" #include "TROOT.h" #include "TGWin32.h" //////////////////////////////////////////////////////////////////////////////// //______________________________________________________________________________ TInterpreter *TGWin32InterpreterProxy::RealObject() { // returns TCint object return gROOT->GetInterpreter(); } RETURN_PROXY_OBJECT(Interpreter) VOID_METHOD_ARG1(Interpreter,AddIncludePath,const char*,path,1) RETURN_METHOD_ARG1(Interpreter,Int_t,AutoLoad,const char *,classname) VOID_METHOD_ARG0(Interpreter,ClearFileBusy,1) VOID_METHOD_ARG0(Interpreter,ClearStack,1) VOID_METHOD_ARG0(Interpreter,EndOfLineAction,1) VOID_METHOD_ARG0(Interpreter,EnableAutoLoading,1) RETURN_METHOD_ARG0(Interpreter,Int_t,InitializeDictionaries) RETURN_METHOD_ARG3(Interpreter,Int_t,GenerateDictionary,const char*,classes,const char*,headers,const char*,options); RETURN_METHOD_ARG0(Interpreter,char*,GetPrompt) RETURN_METHOD_ARG0(Interpreter,const char*,GetSharedLibs) RETURN_METHOD_ARG0(Interpreter,const char*,GetIncludePath) RETURN_METHOD_ARG2(Interpreter,Int_t,Load,const char*,filenam,Bool_t,system) RETURN_METHOD_ARG1(Interpreter,Int_t,LoadLibraryMap,const char*,rootmapfile) RETURN_METHOD_ARG0(Interpreter,Int_t,RescanLibraryMap) RETURN_METHOD_ARG0(Interpreter,Int_t,ReloadAllSharedLibraryMaps) RETURN_METHOD_ARG0(Interpreter,Int_t,UnloadAllSharedLibraryMaps) RETURN_METHOD_ARG1(Interpreter,Int_t,UnloadLibraryMap,const char*,library) VOID_METHOD_ARG2(Interpreter,LoadMacro,const char*,filename,TInterpreter::EErrorCode*,error,1) RETURN_METHOD_ARG2(Interpreter,Long_t,ProcessLine,const char*,line,TInterpreter::EErrorCode*,error) RETURN_METHOD_ARG2(Interpreter,Long_t,ProcessLineSynch,const char*,line,TInterpreter::EErrorCode*,error) VOID_METHOD_ARG0(Interpreter,PrintIntro,1) typedef char* (*GetlineFunc_t)(const char* prompt); typedef void (*HistaddFunc_t)(char* line); VOID_METHOD_ARG2(Interpreter,SetGetline,GetlineFunc_t, getlineFunc,\ HistaddFunc_t, histaddFunc, 1) VOID_METHOD_ARG0(Interpreter,Reset,1) VOID_METHOD_ARG0(Interpreter,ResetAll,1) VOID_METHOD_ARG0(Interpreter,ResetGlobals,1) VOID_METHOD_ARG0(Interpreter,RewindDictionary,1) RETURN_METHOD_ARG1(Interpreter,Int_t,DeleteGlobal,void*,obj) VOID_METHOD_ARG0(Interpreter,SaveContext,1) VOID_METHOD_ARG0(Interpreter,SaveGlobalsContext,1) VOID_METHOD_ARG0_LOCK(Interpreter,UpdateListOfGlobals) VOID_METHOD_ARG0_LOCK(Interpreter,UpdateListOfGlobalFunctions) VOID_METHOD_ARG0_LOCK(Interpreter,UpdateListOfTypes) VOID_METHOD_ARG2_LOCK(Interpreter,SetClassInfo,TClass*,cl,Bool_t,reload) RETURN_METHOD_ARG2(Interpreter,Bool_t,CheckClassInfo,const char*,name,Bool_t,autoload) RETURN_METHOD_ARG2(Interpreter,Long_t,Calc,const char*,line,TInterpreter::EErrorCode*,error) VOID_METHOD_ARG1_LOCK(Interpreter,CreateListOfBaseClasses,TClass*,cl) VOID_METHOD_ARG1_LOCK(Interpreter,CreateListOfDataMembers,TClass*,cl) VOID_METHOD_ARG1_LOCK(Interpreter,CreateListOfMethods,TClass*,cl) VOID_METHOD_ARG1_LOCK(Interpreter,CreateListOfMethodArgs,TFunction*,m) VOID_METHOD_ARG1_LOCK(Interpreter,UpdateListOfMethods,TClass*,cl) RETURN_METHOD_ARG3(Interpreter,TString,GetMangledName,TClass*,cl,const char*,method,const char*,params) RETURN_METHOD_ARG3(Interpreter,TString,GetMangledNameWithPrototype,TClass*,cl,const char*,method,const char*,proto) RETURN_METHOD_ARG3(Interpreter,void*,GetInterfaceMethod,TClass*,cl,const char*,method,const char*,params) RETURN_METHOD_ARG3(Interpreter,void*,GetInterfaceMethodWithPrototype,TClass*,cl,const char*,method,const char*,proto) RETURN_METHOD_ARG1(Interpreter,const char*,GetClassSharedLibs,const char*,s) RETURN_METHOD_ARG1(Interpreter,const char*,GetSharedLibDeps,const char*,s) RETURN_METHOD_ARG2(Interpreter,const char*,GetInterpreterTypeName,const char*,s,Bool_t,full) VOID_METHOD_ARG3(Interpreter,Execute,const char*,function,const char*,params,int*,error,1) VOID_METHOD_ARG5(Interpreter,Execute,TObject*,obj,TClass*,cl,const char*,method,const char*,params,int*,error,1) VOID_METHOD_ARG5(Interpreter,Execute,TObject*,object,TClass*,cl,TMethod*,method,TObjArray*,params,int*,error,1) RETURN_METHOD_ARG2(Interpreter,Long_t,ExecuteMacro,const char*,filename,TInterpreter::EErrorCode*,error) RETURN_METHOD_ARG1(Interpreter,Bool_t,SetErrorMessages,Bool_t,enable) VOID_METHOD_ARG1(Interpreter,SetProcessLineLock,Bool_t,lock,1) RETURN_METHOD_ARG1(Interpreter,const char*,TypeName,const char*,s) //Bool_t TGWin32InterpreterProxy::CheckClassInfo(const char* name) { return RealObject()->CheckClassInfo(name); } <|endoftext|>
<commit_before>#include <ostream> #include <gtest/gtest.h> #include "KeyCode.hpp" #include "FlagStatus.hpp" #include "Config.hpp" using namespace org_pqrs_KeyRemap4MacBook; Config config; std::ostream& operator<<(std::ostream& os, const EventType& v) { return os << v.get(); } std::ostream& operator<<(std::ostream& os, const KeyboardType& v) { return os << v.get(); } std::ostream& operator<<(std::ostream& os, const ModifierFlag& v) { return os << v.get(); } std::ostream& operator<<(std::ostream& os, const Flags& v) { return os << v.get(); } std::ostream& operator<<(std::ostream& os, const KeyCode& v) { return os << v.get(); } std::ostream& operator<<(std::ostream& os, const ConsumerKeyCode& v) { return os << v.get(); } std::ostream& operator<<(std::ostream& os, const PointingButton& v) { return os << v.get(); } std::ostream& operator<<(std::ostream& os, const Buttons& v) { return os << v.get(); } TEST(FlagStatus, makeFlags) { ASSERT_TRUE(FlagStatus::initialize()); EXPECT_EQ(Flags(), FlagStatus::makeFlags()); FlagStatus::set(); EXPECT_EQ(Flags(), FlagStatus::makeFlags()); FlagStatus::set(KeyCode::A, 0); EXPECT_EQ(Flags(), FlagStatus::makeFlags()); // down SHIFT_L FlagStatus::set(KeyCode::SHIFT_L, ModifierFlag::SHIFT_L); EXPECT_EQ(Flags(ModifierFlag::SHIFT_L), FlagStatus::makeFlags()); // no effect with ModifierFlag::NONE FlagStatus::set(KeyCode::A, ModifierFlag::NONE); EXPECT_EQ(Flags(ModifierFlag::SHIFT_L), FlagStatus::makeFlags()); // down CONTROL_ FlagStatus::set(KeyCode::CONTROL_L, ModifierFlag::CONTROL_L | ModifierFlag::SHIFT_L); EXPECT_EQ(Flags(ModifierFlag::SHIFT_L | ModifierFlag::CONTROL_L), FlagStatus::makeFlags()); // down A FlagStatus::set(KeyCode::A, ModifierFlag::CONTROL_L | ModifierFlag::SHIFT_L); EXPECT_EQ(Flags(ModifierFlag::SHIFT_L | ModifierFlag::CONTROL_L), FlagStatus::makeFlags()); // up SHIFT_L FlagStatus::set(KeyCode::SHIFT_L, ModifierFlag::CONTROL_L); EXPECT_EQ(Flags(ModifierFlag::CONTROL_L), FlagStatus::makeFlags()); // up CONTROL_L FlagStatus::set(KeyCode::CONTROL_L, 0); EXPECT_EQ(Flags(), FlagStatus::makeFlags()); // All flags FlagStatus::reset(); FlagStatus::set(KeyCode::CAPSLOCK, ModifierFlag::CAPSLOCK); EXPECT_EQ(Flags(ModifierFlag::CAPSLOCK), FlagStatus::makeFlags()); FlagStatus::reset(); FlagStatus::set(KeyCode::SHIFT_L, ModifierFlag::SHIFT_L); EXPECT_EQ(Flags(ModifierFlag::SHIFT_L), FlagStatus::makeFlags()); FlagStatus::reset(); FlagStatus::set(KeyCode::SHIFT_R, ModifierFlag::SHIFT_R); EXPECT_EQ(Flags(ModifierFlag::SHIFT_R), FlagStatus::makeFlags()); FlagStatus::reset(); FlagStatus::set(KeyCode::CONTROL_L, ModifierFlag::CONTROL_L); EXPECT_EQ(Flags(ModifierFlag::CONTROL_L), FlagStatus::makeFlags()); FlagStatus::reset(); FlagStatus::set(KeyCode::CONTROL_R, ModifierFlag::CONTROL_R); EXPECT_EQ(Flags(ModifierFlag::CONTROL_R), FlagStatus::makeFlags()); FlagStatus::reset(); FlagStatus::set(KeyCode::OPTION_L, ModifierFlag::OPTION_L); EXPECT_EQ(Flags(ModifierFlag::OPTION_L), FlagStatus::makeFlags()); FlagStatus::reset(); FlagStatus::set(KeyCode::OPTION_R, ModifierFlag::OPTION_R); EXPECT_EQ(Flags(ModifierFlag::OPTION_R), FlagStatus::makeFlags()); FlagStatus::reset(); FlagStatus::set(KeyCode::COMMAND_L, ModifierFlag::COMMAND_L); EXPECT_EQ(Flags(ModifierFlag::COMMAND_L), FlagStatus::makeFlags()); FlagStatus::reset(); FlagStatus::set(KeyCode::COMMAND_R, ModifierFlag::COMMAND_R); EXPECT_EQ(Flags(ModifierFlag::COMMAND_R), FlagStatus::makeFlags()); FlagStatus::reset(); FlagStatus::set(KeyCode::FN, ModifierFlag::FN); EXPECT_EQ(Flags(ModifierFlag::FN), FlagStatus::makeFlags()); } TEST(FlagStatus, getFlag) { ASSERT_TRUE(FlagStatus::initialize()); EXPECT_EQ(ModifierFlag::CAPSLOCK, FlagStatus::getFlag(0)); } TEST(FlagStatus, getLockedFlags) { ASSERT_TRUE(FlagStatus::initialize()); EXPECT_EQ(Flags(0), FlagStatus::getLockedFlags()); FlagStatus::increase(ModifierFlag::SHIFT_L); FlagStatus::temporary_increase(ModifierFlag::SHIFT_R); FlagStatus::lock_increase(ModifierFlag::COMMAND_L); FlagStatus::lock_increase(ModifierFlag::OPTION_L); EXPECT_EQ(ModifierFlag::COMMAND_L | ModifierFlag::OPTION_L, FlagStatus::getLockedFlags()); } TEST(FlagStatus, increase) { ASSERT_TRUE(FlagStatus::initialize()); // Do nothing with ModifierFlag::NONE. FlagStatus::increase(ModifierFlag::NONE); EXPECT_EQ(Flags(0), FlagStatus::makeFlags()); FlagStatus::increase(ModifierFlag::SHIFT_L); EXPECT_EQ(Flags(ModifierFlag::SHIFT_L), FlagStatus::makeFlags()); FlagStatus::increase(ModifierFlag::COMMAND_L | ModifierFlag::CONTROL_L); EXPECT_EQ(Flags(ModifierFlag::COMMAND_L | ModifierFlag::CONTROL_L | ModifierFlag::SHIFT_L), FlagStatus::makeFlags()); FlagStatus::increase(ModifierFlag::NONE); EXPECT_EQ(Flags(ModifierFlag::COMMAND_L | ModifierFlag::CONTROL_L | ModifierFlag::SHIFT_L), FlagStatus::makeFlags()); } TEST(FlagStatus, decrease) { ASSERT_TRUE(FlagStatus::initialize()); FlagStatus::increase(ModifierFlag::COMMAND_L | ModifierFlag::CONTROL_L); EXPECT_EQ(Flags(ModifierFlag::COMMAND_L | ModifierFlag::CONTROL_L), FlagStatus::makeFlags()); FlagStatus::decrease(ModifierFlag::CONTROL_L); EXPECT_EQ(Flags(ModifierFlag::COMMAND_L), FlagStatus::makeFlags()); } TEST(FlagStatus, temporary_increase) { ASSERT_TRUE(FlagStatus::initialize()); // Do nothing with ModifierFlag::NONE. FlagStatus::temporary_increase(ModifierFlag::NONE); EXPECT_EQ(Flags(0), FlagStatus::makeFlags()); FlagStatus::increase(ModifierFlag::COMMAND_L | ModifierFlag::CONTROL_L); EXPECT_EQ(Flags(ModifierFlag::COMMAND_L | ModifierFlag::CONTROL_L), FlagStatus::makeFlags()); FlagStatus::temporary_increase(ModifierFlag::OPTION_L); EXPECT_EQ(Flags(ModifierFlag::COMMAND_L | ModifierFlag::CONTROL_L | ModifierFlag::OPTION_L), FlagStatus::makeFlags()); // temporary_increase will reset by FlagStatus::set FlagStatus::set(KeyCode::COMMAND_L, ModifierFlag::COMMAND_L); EXPECT_EQ(Flags(ModifierFlag::COMMAND_L | ModifierFlag::CONTROL_L), FlagStatus::makeFlags()); } TEST(FlagStatus, temporary_decrease) { ASSERT_TRUE(FlagStatus::initialize()); FlagStatus::increase(ModifierFlag::COMMAND_L | ModifierFlag::CONTROL_L); EXPECT_EQ(Flags(ModifierFlag::COMMAND_L | ModifierFlag::CONTROL_L), FlagStatus::makeFlags()); FlagStatus::temporary_decrease(ModifierFlag::CONTROL_L); EXPECT_EQ(Flags(ModifierFlag::COMMAND_L), FlagStatus::makeFlags()); // temporary_increase will reset by FlagStatus::set FlagStatus::set(KeyCode::COMMAND_L, ModifierFlag::COMMAND_L); EXPECT_EQ(Flags(ModifierFlag::COMMAND_L | ModifierFlag::CONTROL_L), FlagStatus::makeFlags()); } TEST(FlagStatus, lock_increase) { ASSERT_TRUE(FlagStatus::initialize()); // Do nothing with ModifierFlag::NONE. FlagStatus::lock_increase(ModifierFlag::NONE); EXPECT_EQ(Flags(0), FlagStatus::makeFlags()); FlagStatus::lock_increase(ModifierFlag::COMMAND_L); EXPECT_EQ(Flags(ModifierFlag::COMMAND_L), FlagStatus::makeFlags()); // lock don't cancel by reset & set. FlagStatus::reset(); FlagStatus::set(KeyCode::A, 0); EXPECT_EQ(Flags(ModifierFlag::COMMAND_L), FlagStatus::makeFlags()); FlagStatus::lock_decrease(ModifierFlag::COMMAND_L); EXPECT_EQ(Flags(), FlagStatus::makeFlags()); } TEST(FlagStatus, lock_toggle) { ASSERT_TRUE(FlagStatus::initialize()); FlagStatus::lock_increase(ModifierFlag::COMMAND_L); EXPECT_EQ(Flags(ModifierFlag::COMMAND_L), FlagStatus::makeFlags()); FlagStatus::lock_toggle(ModifierFlag::COMMAND_L); EXPECT_EQ(Flags(0), FlagStatus::makeFlags()); FlagStatus::lock_toggle(ModifierFlag::COMMAND_L); EXPECT_EQ(Flags(ModifierFlag::COMMAND_L), FlagStatus::makeFlags()); } TEST(FlagStatus, lock_clear) { ASSERT_TRUE(FlagStatus::initialize()); FlagStatus::lock_increase(ModifierFlag::COMMAND_L | ModifierFlag::FN | ModifierFlag::SHIFT_L); EXPECT_EQ(ModifierFlag::COMMAND_L | ModifierFlag::FN | ModifierFlag::SHIFT_L, FlagStatus::makeFlags()); FlagStatus::lock_clear(); EXPECT_EQ(Flags(0), FlagStatus::makeFlags()); } TEST(FlagStatus, sticky_increase) { ASSERT_TRUE(FlagStatus::initialize()); // Do nothing with ModifierFlag::NONE. FlagStatus::sticky_increase(ModifierFlag::NONE); EXPECT_EQ(Flags(0), FlagStatus::makeFlags()); FlagStatus::sticky_increase(ModifierFlag::COMMAND_L | ModifierFlag::FN); EXPECT_EQ(Flags(ModifierFlag::COMMAND_L | ModifierFlag::FN), FlagStatus::makeFlags()); FlagStatus::sticky_decrease(ModifierFlag::COMMAND_L); EXPECT_EQ(Flags(ModifierFlag::FN), FlagStatus::makeFlags()); } TEST(FlagStatus, sticky_toggle) { ASSERT_TRUE(FlagStatus::initialize()); FlagStatus::sticky_increase(ModifierFlag::COMMAND_L); EXPECT_EQ(Flags(ModifierFlag::COMMAND_L), FlagStatus::makeFlags()); FlagStatus::sticky_toggle(ModifierFlag::COMMAND_L); EXPECT_EQ(Flags(0), FlagStatus::makeFlags()); FlagStatus::sticky_toggle(ModifierFlag::COMMAND_L); EXPECT_EQ(Flags(ModifierFlag::COMMAND_L), FlagStatus::makeFlags()); } TEST(FlagStatus, sticky_clear) { ASSERT_TRUE(FlagStatus::initialize()); FlagStatus::sticky_increase(ModifierFlag::COMMAND_L | ModifierFlag::FN | ModifierFlag::SHIFT_L); EXPECT_EQ(ModifierFlag::COMMAND_L | ModifierFlag::FN | ModifierFlag::SHIFT_L, FlagStatus::makeFlags()); FlagStatus::sticky_clear(); EXPECT_EQ(Flags(0), FlagStatus::makeFlags()); } TEST(FlagStatus, CapsLock) { ASSERT_TRUE(FlagStatus::initialize()); FlagStatus::set(KeyCode::CAPSLOCK, ModifierFlag::CAPSLOCK); EXPECT_EQ(Flags(ModifierFlag::CAPSLOCK), FlagStatus::makeFlags()); FlagStatus::set(KeyCode::A, ModifierFlag::CAPSLOCK); EXPECT_EQ(Flags(ModifierFlag::CAPSLOCK), FlagStatus::makeFlags()); // reset FlagStatus::set(KeyCode::A, 0); EXPECT_EQ(Flags(), FlagStatus::makeFlags()); // some keyboard send key with ModifierFlag::CAPSLOCK without KeyCode::CAPSLOCK. FlagStatus::set(KeyCode::A, ModifierFlag::CAPSLOCK); EXPECT_EQ(Flags(ModifierFlag::CAPSLOCK), FlagStatus::makeFlags()); // reset FlagStatus::set(KeyCode::A, 0); EXPECT_EQ(Flags(), FlagStatus::makeFlags()); // soft caps FlagStatus::lock_increase(ModifierFlag::CAPSLOCK); FlagStatus::set(KeyCode::A, 0); EXPECT_EQ(Flags(ModifierFlag::CAPSLOCK), FlagStatus::makeFlags()); // soft caps will be canceled by hardware caps FlagStatus::set(KeyCode::A, ModifierFlag::CAPSLOCK); EXPECT_EQ(Flags(ModifierFlag::CAPSLOCK), FlagStatus::makeFlags()); FlagStatus::set(KeyCode::A, 0); EXPECT_EQ(Flags(), FlagStatus::makeFlags()); } TEST(FlagStatus, ScopedTemporaryFlagsChanger) { ASSERT_TRUE(FlagStatus::initialize()); FlagStatus::increase(ModifierFlag::SHIFT_L); FlagStatus::increase(ModifierFlag::SHIFT_L); FlagStatus::increase(ModifierFlag::SHIFT_L); FlagStatus::increase(ModifierFlag::SHIFT_L); FlagStatus::increase(ModifierFlag::SHIFT_R); FlagStatus::temporary_increase(ModifierFlag::CONTROL_L); FlagStatus::lock_increase(ModifierFlag::COMMAND_R); FlagStatus::sticky_increase(ModifierFlag::OPTION_R); EXPECT_EQ(Flags(ModifierFlag::SHIFT_L | ModifierFlag::SHIFT_R | ModifierFlag::CONTROL_L | ModifierFlag::COMMAND_R | ModifierFlag::OPTION_R), FlagStatus::makeFlags()); { FlagStatus::ScopedTemporaryFlagsChanger stfc(ModifierFlag::FN | ModifierFlag::OPTION_L | ModifierFlag::SHIFT_R); EXPECT_EQ(Flags(ModifierFlag::FN | ModifierFlag::OPTION_L | ModifierFlag::SHIFT_R), FlagStatus::makeFlags()); } EXPECT_EQ(Flags(ModifierFlag::SHIFT_L | ModifierFlag::SHIFT_R | ModifierFlag::CONTROL_L | ModifierFlag::COMMAND_R | ModifierFlag::OPTION_R), FlagStatus::makeFlags()); } <commit_msg>update Tests/kext/FlagStatus/test.cpp<commit_after>#include <ostream> #include <gtest/gtest.h> #include "KeyCode.hpp" #include "FlagStatus.hpp" #include "Config.hpp" using namespace org_pqrs_KeyRemap4MacBook; Config config; std::ostream& operator<<(std::ostream& os, const EventType& v) { return os << v.get(); } std::ostream& operator<<(std::ostream& os, const KeyboardType& v) { return os << v.get(); } std::ostream& operator<<(std::ostream& os, const ModifierFlag& v) { return os << v.get(); } std::ostream& operator<<(std::ostream& os, const Flags& v) { return os << v.get(); } std::ostream& operator<<(std::ostream& os, const KeyCode& v) { return os << v.get(); } std::ostream& operator<<(std::ostream& os, const ConsumerKeyCode& v) { return os << v.get(); } std::ostream& operator<<(std::ostream& os, const PointingButton& v) { return os << v.get(); } std::ostream& operator<<(std::ostream& os, const Buttons& v) { return os << v.get(); } TEST(FlagStatus, makeFlags) { ASSERT_TRUE(FlagStatus::initialize()); EXPECT_EQ(Flags(), FlagStatus::makeFlags()); FlagStatus::set(); EXPECT_EQ(Flags(), FlagStatus::makeFlags()); FlagStatus::set(KeyCode::A, 0); EXPECT_EQ(Flags(), FlagStatus::makeFlags()); // down SHIFT_L FlagStatus::set(KeyCode::SHIFT_L, ModifierFlag::SHIFT_L); EXPECT_EQ(Flags(ModifierFlag::SHIFT_L), FlagStatus::makeFlags()); // no effect with ModifierFlag::NONE FlagStatus::set(KeyCode::A, ModifierFlag::NONE); EXPECT_EQ(Flags(ModifierFlag::SHIFT_L), FlagStatus::makeFlags()); // down CONTROL_ FlagStatus::set(KeyCode::CONTROL_L, ModifierFlag::CONTROL_L | ModifierFlag::SHIFT_L); EXPECT_EQ(Flags(ModifierFlag::SHIFT_L | ModifierFlag::CONTROL_L), FlagStatus::makeFlags()); // down A FlagStatus::set(KeyCode::A, ModifierFlag::CONTROL_L | ModifierFlag::SHIFT_L); EXPECT_EQ(Flags(ModifierFlag::SHIFT_L | ModifierFlag::CONTROL_L), FlagStatus::makeFlags()); // up SHIFT_L FlagStatus::set(KeyCode::SHIFT_L, ModifierFlag::CONTROL_L); EXPECT_EQ(Flags(ModifierFlag::CONTROL_L), FlagStatus::makeFlags()); // up CONTROL_L FlagStatus::set(KeyCode::CONTROL_L, 0); EXPECT_EQ(Flags(), FlagStatus::makeFlags()); // All flags FlagStatus::reset(); FlagStatus::set(KeyCode::CAPSLOCK, ModifierFlag::CAPSLOCK); EXPECT_EQ(Flags(ModifierFlag::CAPSLOCK), FlagStatus::makeFlags()); FlagStatus::reset(); FlagStatus::set(KeyCode::SHIFT_L, ModifierFlag::SHIFT_L); EXPECT_EQ(Flags(ModifierFlag::SHIFT_L), FlagStatus::makeFlags()); FlagStatus::reset(); FlagStatus::set(KeyCode::SHIFT_R, ModifierFlag::SHIFT_R); EXPECT_EQ(Flags(ModifierFlag::SHIFT_R), FlagStatus::makeFlags()); FlagStatus::reset(); FlagStatus::set(KeyCode::CONTROL_L, ModifierFlag::CONTROL_L); EXPECT_EQ(Flags(ModifierFlag::CONTROL_L), FlagStatus::makeFlags()); FlagStatus::reset(); FlagStatus::set(KeyCode::CONTROL_R, ModifierFlag::CONTROL_R); EXPECT_EQ(Flags(ModifierFlag::CONTROL_R), FlagStatus::makeFlags()); FlagStatus::reset(); FlagStatus::set(KeyCode::OPTION_L, ModifierFlag::OPTION_L); EXPECT_EQ(Flags(ModifierFlag::OPTION_L), FlagStatus::makeFlags()); FlagStatus::reset(); FlagStatus::set(KeyCode::OPTION_R, ModifierFlag::OPTION_R); EXPECT_EQ(Flags(ModifierFlag::OPTION_R), FlagStatus::makeFlags()); FlagStatus::reset(); FlagStatus::set(KeyCode::COMMAND_L, ModifierFlag::COMMAND_L); EXPECT_EQ(Flags(ModifierFlag::COMMAND_L), FlagStatus::makeFlags()); FlagStatus::reset(); FlagStatus::set(KeyCode::COMMAND_R, ModifierFlag::COMMAND_R); EXPECT_EQ(Flags(ModifierFlag::COMMAND_R), FlagStatus::makeFlags()); FlagStatus::reset(); FlagStatus::set(KeyCode::FN, ModifierFlag::FN); EXPECT_EQ(Flags(ModifierFlag::FN), FlagStatus::makeFlags()); } TEST(FlagStatus, getFlag) { ASSERT_TRUE(FlagStatus::initialize()); EXPECT_EQ(ModifierFlag::CAPSLOCK, FlagStatus::getFlag(0)); } TEST(FlagStatus, getLockedFlags) { ASSERT_TRUE(FlagStatus::initialize()); EXPECT_EQ(Flags(0), FlagStatus::getLockedFlags()); FlagStatus::increase(ModifierFlag::SHIFT_L); FlagStatus::temporary_increase(ModifierFlag::SHIFT_R); FlagStatus::lock_increase(ModifierFlag::COMMAND_L); FlagStatus::lock_increase(ModifierFlag::OPTION_L); EXPECT_EQ(ModifierFlag::COMMAND_L | ModifierFlag::OPTION_L, FlagStatus::getLockedFlags()); } TEST(FlagStatus, increase) { ASSERT_TRUE(FlagStatus::initialize()); // Do nothing with ModifierFlag::NONE. FlagStatus::increase(ModifierFlag::NONE); EXPECT_EQ(Flags(0), FlagStatus::makeFlags()); FlagStatus::increase(ModifierFlag::SHIFT_L); EXPECT_EQ(Flags(ModifierFlag::SHIFT_L), FlagStatus::makeFlags()); FlagStatus::increase(ModifierFlag::COMMAND_L | ModifierFlag::CONTROL_L); EXPECT_EQ(Flags(ModifierFlag::COMMAND_L | ModifierFlag::CONTROL_L | ModifierFlag::SHIFT_L), FlagStatus::makeFlags()); FlagStatus::increase(ModifierFlag::NONE); EXPECT_EQ(Flags(ModifierFlag::COMMAND_L | ModifierFlag::CONTROL_L | ModifierFlag::SHIFT_L), FlagStatus::makeFlags()); } TEST(FlagStatus, decrease) { ASSERT_TRUE(FlagStatus::initialize()); FlagStatus::increase(ModifierFlag::COMMAND_L | ModifierFlag::CONTROL_L); EXPECT_EQ(Flags(ModifierFlag::COMMAND_L | ModifierFlag::CONTROL_L), FlagStatus::makeFlags()); FlagStatus::decrease(ModifierFlag::CONTROL_L); EXPECT_EQ(Flags(ModifierFlag::COMMAND_L), FlagStatus::makeFlags()); } TEST(FlagStatus, temporary_increase) { ASSERT_TRUE(FlagStatus::initialize()); // Do nothing with ModifierFlag::NONE. FlagStatus::temporary_increase(ModifierFlag::NONE); EXPECT_EQ(Flags(0), FlagStatus::makeFlags()); FlagStatus::increase(ModifierFlag::COMMAND_L | ModifierFlag::CONTROL_L); EXPECT_EQ(Flags(ModifierFlag::COMMAND_L | ModifierFlag::CONTROL_L), FlagStatus::makeFlags()); FlagStatus::temporary_increase(ModifierFlag::OPTION_L); EXPECT_EQ(Flags(ModifierFlag::COMMAND_L | ModifierFlag::CONTROL_L | ModifierFlag::OPTION_L), FlagStatus::makeFlags()); // temporary_increase will reset by FlagStatus::set FlagStatus::set(KeyCode::COMMAND_L, ModifierFlag::COMMAND_L); EXPECT_EQ(Flags(ModifierFlag::COMMAND_L | ModifierFlag::CONTROL_L), FlagStatus::makeFlags()); } TEST(FlagStatus, temporary_decrease) { ASSERT_TRUE(FlagStatus::initialize()); FlagStatus::increase(ModifierFlag::COMMAND_L | ModifierFlag::CONTROL_L); EXPECT_EQ(Flags(ModifierFlag::COMMAND_L | ModifierFlag::CONTROL_L), FlagStatus::makeFlags()); FlagStatus::temporary_decrease(ModifierFlag::CONTROL_L); EXPECT_EQ(Flags(ModifierFlag::COMMAND_L), FlagStatus::makeFlags()); // temporary_increase will reset by FlagStatus::set FlagStatus::set(KeyCode::COMMAND_L, ModifierFlag::COMMAND_L); EXPECT_EQ(Flags(ModifierFlag::COMMAND_L | ModifierFlag::CONTROL_L), FlagStatus::makeFlags()); } TEST(FlagStatus, lock_increase) { ASSERT_TRUE(FlagStatus::initialize()); // Do nothing with ModifierFlag::NONE. FlagStatus::lock_increase(ModifierFlag::NONE); EXPECT_EQ(Flags(0), FlagStatus::makeFlags()); FlagStatus::lock_increase(ModifierFlag::COMMAND_L); EXPECT_EQ(Flags(ModifierFlag::COMMAND_L), FlagStatus::makeFlags()); // lock don't cancel by reset & set. FlagStatus::reset(); FlagStatus::set(KeyCode::A, 0); EXPECT_EQ(Flags(ModifierFlag::COMMAND_L), FlagStatus::makeFlags()); FlagStatus::lock_decrease(ModifierFlag::COMMAND_L); EXPECT_EQ(Flags(), FlagStatus::makeFlags()); } TEST(FlagStatus, lock_toggle) { ASSERT_TRUE(FlagStatus::initialize()); FlagStatus::lock_increase(ModifierFlag::COMMAND_L); EXPECT_EQ(Flags(ModifierFlag::COMMAND_L), FlagStatus::makeFlags()); FlagStatus::lock_toggle(ModifierFlag::COMMAND_L); EXPECT_EQ(Flags(0), FlagStatus::makeFlags()); FlagStatus::lock_toggle(ModifierFlag::COMMAND_L); EXPECT_EQ(Flags(ModifierFlag::COMMAND_L), FlagStatus::makeFlags()); } TEST(FlagStatus, lock_clear) { ASSERT_TRUE(FlagStatus::initialize()); FlagStatus::lock_increase(ModifierFlag::COMMAND_L | ModifierFlag::FN | ModifierFlag::SHIFT_L); EXPECT_EQ(ModifierFlag::COMMAND_L | ModifierFlag::FN | ModifierFlag::SHIFT_L, FlagStatus::makeFlags()); FlagStatus::lock_clear(); EXPECT_EQ(Flags(0), FlagStatus::makeFlags()); } TEST(FlagStatus, sticky_increase) { ASSERT_TRUE(FlagStatus::initialize()); // Do nothing with ModifierFlag::NONE. FlagStatus::sticky_increase(ModifierFlag::NONE); EXPECT_EQ(Flags(0), FlagStatus::makeFlags()); FlagStatus::sticky_increase(ModifierFlag::COMMAND_L | ModifierFlag::FN); EXPECT_EQ(Flags(ModifierFlag::COMMAND_L | ModifierFlag::FN), FlagStatus::makeFlags()); FlagStatus::sticky_decrease(ModifierFlag::COMMAND_L); EXPECT_EQ(Flags(ModifierFlag::FN), FlagStatus::makeFlags()); } TEST(FlagStatus, sticky_toggle) { ASSERT_TRUE(FlagStatus::initialize()); FlagStatus::sticky_increase(ModifierFlag::COMMAND_L); EXPECT_EQ(Flags(ModifierFlag::COMMAND_L), FlagStatus::makeFlags()); FlagStatus::sticky_toggle(ModifierFlag::COMMAND_L); EXPECT_EQ(Flags(0), FlagStatus::makeFlags()); FlagStatus::sticky_toggle(ModifierFlag::COMMAND_L); EXPECT_EQ(Flags(ModifierFlag::COMMAND_L), FlagStatus::makeFlags()); } TEST(FlagStatus, sticky_clear) { ASSERT_TRUE(FlagStatus::initialize()); FlagStatus::sticky_increase(ModifierFlag::COMMAND_L | ModifierFlag::FN | ModifierFlag::SHIFT_L); EXPECT_EQ(ModifierFlag::COMMAND_L | ModifierFlag::FN | ModifierFlag::SHIFT_L, FlagStatus::makeFlags()); FlagStatus::sticky_clear(); EXPECT_EQ(Flags(0), FlagStatus::makeFlags()); } TEST(FlagStatus, CapsLock) { ASSERT_TRUE(FlagStatus::initialize()); FlagStatus::set(KeyCode::CAPSLOCK, ModifierFlag::CAPSLOCK); EXPECT_EQ(Flags(ModifierFlag::CAPSLOCK), FlagStatus::makeFlags()); FlagStatus::set(KeyCode::A, ModifierFlag::CAPSLOCK); EXPECT_EQ(Flags(ModifierFlag::CAPSLOCK), FlagStatus::makeFlags()); // reset FlagStatus::set(KeyCode::A, 0); EXPECT_EQ(Flags(), FlagStatus::makeFlags()); // some keyboard send key with ModifierFlag::CAPSLOCK without KeyCode::CAPSLOCK. FlagStatus::set(KeyCode::A, ModifierFlag::CAPSLOCK); EXPECT_EQ(Flags(ModifierFlag::CAPSLOCK), FlagStatus::makeFlags()); // reset FlagStatus::set(KeyCode::A, 0); EXPECT_EQ(Flags(), FlagStatus::makeFlags()); // soft caps FlagStatus::lock_increase(ModifierFlag::CAPSLOCK); FlagStatus::set(KeyCode::A, 0); EXPECT_EQ(Flags(ModifierFlag::CAPSLOCK), FlagStatus::makeFlags()); // soft caps will be canceled by hardware caps FlagStatus::set(KeyCode::A, ModifierFlag::CAPSLOCK); EXPECT_EQ(Flags(ModifierFlag::CAPSLOCK), FlagStatus::makeFlags()); FlagStatus::set(KeyCode::A, 0); EXPECT_EQ(Flags(), FlagStatus::makeFlags()); } TEST(FlagStatus, ScopedTemporaryFlagsChanger) { ASSERT_TRUE(FlagStatus::initialize()); FlagStatus::increase(ModifierFlag::SHIFT_L); FlagStatus::increase(ModifierFlag::SHIFT_L); FlagStatus::increase(ModifierFlag::SHIFT_L); FlagStatus::increase(ModifierFlag::SHIFT_L); FlagStatus::increase(ModifierFlag::SHIFT_R); FlagStatus::temporary_increase(ModifierFlag::CONTROL_L); FlagStatus::lock_increase(ModifierFlag::COMMAND_R); FlagStatus::sticky_increase(ModifierFlag::OPTION_R); EXPECT_EQ(Flags(ModifierFlag::SHIFT_L | ModifierFlag::SHIFT_R | ModifierFlag::CONTROL_L | ModifierFlag::COMMAND_R | ModifierFlag::OPTION_R), FlagStatus::makeFlags()); { FlagStatus::ScopedTemporaryFlagsChanger stfc(ModifierFlag::FN | ModifierFlag::OPTION_L | ModifierFlag::SHIFT_R); EXPECT_EQ(Flags(ModifierFlag::FN | ModifierFlag::OPTION_L | ModifierFlag::SHIFT_R), FlagStatus::makeFlags()); } EXPECT_EQ(Flags(ModifierFlag::SHIFT_L | ModifierFlag::SHIFT_R | ModifierFlag::CONTROL_L | ModifierFlag::COMMAND_R | ModifierFlag::OPTION_R), FlagStatus::makeFlags()); FlagStatus::decrease(ModifierFlag::SHIFT_L); FlagStatus::decrease(ModifierFlag::SHIFT_L); FlagStatus::decrease(ModifierFlag::SHIFT_L); EXPECT_EQ(Flags(ModifierFlag::SHIFT_L | ModifierFlag::SHIFT_R | ModifierFlag::CONTROL_L | ModifierFlag::COMMAND_R | ModifierFlag::OPTION_R), FlagStatus::makeFlags()); FlagStatus::decrease(ModifierFlag::SHIFT_L); EXPECT_EQ(Flags(ModifierFlag::SHIFT_R | ModifierFlag::CONTROL_L | ModifierFlag::COMMAND_R | ModifierFlag::OPTION_R), FlagStatus::makeFlags()); // ------------------------------------------------------------ ASSERT_TRUE(FlagStatus::initialize()); FlagStatus::decrease(ModifierFlag::SHIFT_L); FlagStatus::decrease(ModifierFlag::SHIFT_L); { FlagStatus::ScopedTemporaryFlagsChanger stfc(ModifierFlag::SHIFT_R); EXPECT_EQ(Flags(ModifierFlag::SHIFT_R), FlagStatus::makeFlags()); } FlagStatus::increase(ModifierFlag::SHIFT_L); FlagStatus::increase(ModifierFlag::SHIFT_L); EXPECT_EQ(Flags(0), FlagStatus::makeFlags()); } <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you under the Apache * License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.apache.org/licenses/LICENSE-2.0 . */ #ifndef INCLUDED_SW_SOURCE_FILTER_WW8_SORTEDARRAY_HXX #define INCLUDED_SW_SOURCE_FILTER_WW8_SORTEDARRAY_HXX #include <algorithm> //simple template that manages a static [] array by sorting at construction namespace ww { /** simple template that manages a static array The template sorts the array at construction in place. @author <a href="mailto:cmc@openoffice.org">Caol&aacute;n McNamara</a> */ template<class C> class SortedArray { private: //The array e.g. of sprms. C *mpWwSprmTab; size_t mnNoElems; //No copying SortedArray(const SortedArray&); SortedArray& operator=(const SortedArray&); public: //Find an entry, return its address if found and 0 if not const C *search(C aSrch) const { std::pair<C *, C *> aPair = std::equal_range(mpWwSprmTab, mpWwSprmTab + mnNoElems, aSrch); if (aPair.first != aPair.second) return aPair.first; else return 0; } SortedArray(C *pWwSprmTab, size_t nNoElems) : mpWwSprmTab(pWwSprmTab), mnNoElems(nNoElems) { OSL_ENSURE(mnNoElems && pWwSprmTab, "WW8: empty Array: Don't do that"); std::sort(mpWwSprmTab, mpWwSprmTab + mnNoElems); #if OSL_DEBUG_LEVEL > 1 bool bBroken=false; OUString sError; const C *pIter = mpWwSprmTab; const C *pBeforeEnd = mpWwSprmTab + mnNoElems - 1; while (pIter < pBeforeEnd) { if (pIter->nId == (pIter+1)->nId) { if (!bBroken) { sError = "WW8: Duplicate in list, almost certainly don't " "want that!\n" "(You will not see this message again unless you " "restart)\n" "Extra entries are...\n"; bBroken=true; } size_t nSize = sizeof(C); const sal_uInt8 *pHack = reinterpret_cast<const sal_uInt8 *>(&(*pIter)); for (size_t i=0; i < nSize; ++i) { sError += OUString::number( static_cast<sal_Int32>(pHack[i]), 16); sError += OUString(' '); } sError += OUString('\n'); while (pIter->nId == (pIter+1)->nId && pIter < pBeforeEnd) ++pIter; } else ++pIter; } if (bBroken) { OSL_FAIL( OUStringToOString( sError, RTL_TEXTENCODING_ASCII_US ).getStr() ); } #endif } }; } #endif /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>fix higher level debug build<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you under the Apache * License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.apache.org/licenses/LICENSE-2.0 . */ #ifndef INCLUDED_SW_SOURCE_FILTER_WW8_SORTEDARRAY_HXX #define INCLUDED_SW_SOURCE_FILTER_WW8_SORTEDARRAY_HXX #include <osl/diagnose.h> #include <algorithm> //simple template that manages a static [] array by sorting at construction namespace ww { /** simple template that manages a static array The template sorts the array at construction in place. @author <a href="mailto:cmc@openoffice.org">Caol&aacute;n McNamara</a> */ template<class C> class SortedArray { private: //The array e.g. of sprms. C *mpWwSprmTab; size_t mnNoElems; //No copying SortedArray(const SortedArray&); SortedArray& operator=(const SortedArray&); public: //Find an entry, return its address if found and 0 if not const C *search(C aSrch) const { std::pair<C *, C *> aPair = std::equal_range(mpWwSprmTab, mpWwSprmTab + mnNoElems, aSrch); if (aPair.first != aPair.second) return aPair.first; else return 0; } SortedArray(C *pWwSprmTab, size_t nNoElems) : mpWwSprmTab(pWwSprmTab), mnNoElems(nNoElems) { OSL_ENSURE(mnNoElems && pWwSprmTab, "WW8: empty Array: Don't do that"); std::sort(mpWwSprmTab, mpWwSprmTab + mnNoElems); #if OSL_DEBUG_LEVEL > 1 bool bBroken=false; OUString sError; const C *pIter = mpWwSprmTab; const C *pBeforeEnd = mpWwSprmTab + mnNoElems - 1; while (pIter < pBeforeEnd) { if (pIter->nId == (pIter+1)->nId) { if (!bBroken) { sError = "WW8: Duplicate in list, almost certainly don't " "want that!\n" "(You will not see this message again unless you " "restart)\n" "Extra entries are...\n"; bBroken=true; } size_t nSize = sizeof(C); const sal_uInt8 *pHack = reinterpret_cast<const sal_uInt8 *>(&(*pIter)); for (size_t i=0; i < nSize; ++i) { sError += OUString::number( static_cast<sal_Int32>(pHack[i]), 16); sError += OUString(' '); } sError += OUString('\n'); while (pIter->nId == (pIter+1)->nId && pIter < pBeforeEnd) ++pIter; } else ++pIter; } if (bBroken) { OSL_FAIL( OUStringToOString( sError, RTL_TEXTENCODING_ASCII_US ).getStr() ); } #endif } }; } #endif /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>#include <iostream> #include <fstream> #include <memory> typedef struct node { node * next; int value; } Node, *PNode; PNode CreateList(const std::shared_ptr<int>& inputArray, int numberOfItems); PNode ReverseList(PNode head); void PrintList(PNode head); void FreeList(PNode head); int main(int argc, char * argv[]) { std::ifstream inputFile("input.txt"); if (inputFile.bad() || inputFile.eof()) { std::cout << "Unable to open input.txt" << std::endl; return 1; } int numberOfTestCases = 0; inputFile >> numberOfTestCases; for (int i = 0; i < numberOfTestCases; ++i) { int numberOfListItems = 0; inputFile >> numberOfListItems; std::shared_ptr<int> listItemsForThisTestCase(new int[numberOfListItems]); for (int j = 0; j < numberOfListItems; ++j) inputFile >> listItemsForThisTestCase.get()[j]; PNode head = CreateList(listItemsForThisTestCase, numberOfListItems); PNode newHead = ReverseList(head); PrintList(head); PrintList(newHead); FreeList(head); FreeList(newHead); std::cout << std::endl; } inputFile.close(); return 0; } PNode CreateList(const std::shared_ptr<int>& inputArray, int numberOfItems) { if (numberOfItems < 1) return nullptr; PNode head = new Node; PNode current = head; for (int i = 0; i < numberOfItems; ++i) { current->next = i + 1 == numberOfItems ? nullptr : new Node; current->value = inputArray.get()[i]; current = current->next; } return head; } PNode ReverseList(PNode head) { return nullptr; } void PrintList(PNode head) { PNode current = head; while (current != nullptr) { std::cout << current->value << " "; current = current->next; } std::cout << std::endl; } void FreeList(PNode head) { PNode current = head; while (current != nullptr) { PNode tmp = current; current = current->next; delete tmp; } }<commit_msg>Implement linked list reversal algorithm<commit_after>#include <iostream> #include <fstream> #include <memory> typedef struct node { node * next; int value; } Node, *PNode; PNode CreateList(const std::shared_ptr<int>& inputArray, int numberOfItems); PNode ReverseList(PNode head); void PrintList(PNode head); void FreeList(PNode head); int main(int argc, char * argv[]) { std::ifstream inputFile("input.txt"); if (inputFile.bad() || inputFile.eof()) { std::cout << "Unable to open input.txt" << std::endl; return 1; } int numberOfTestCases = 0; inputFile >> numberOfTestCases; for (int i = 0; i < numberOfTestCases; ++i) { int numberOfListItems = 0; inputFile >> numberOfListItems; std::shared_ptr<int> listItemsForThisTestCase(new int[numberOfListItems]); for (int j = 0; j < numberOfListItems; ++j) inputFile >> listItemsForThisTestCase.get()[j]; PNode head = CreateList(listItemsForThisTestCase, numberOfListItems); PNode newHead = ReverseList(head); PrintList(newHead); FreeList(newHead); } inputFile.close(); return 0; } PNode CreateList(const std::shared_ptr<int>& inputArray, int numberOfItems) { if (numberOfItems < 1) return nullptr; PNode head = new Node; PNode current = head; for (int i = 0; i < numberOfItems; ++i) { current->next = i + 1 == numberOfItems ? nullptr : new Node; current->value = inputArray.get()[i]; current = current->next; } return head; } PNode ReverseList(PNode head) { if (head == nullptr || head->next == nullptr) return head; PNode current = head; PNode previous = nullptr; while (current != nullptr) { PNode temp = current; current = current->next; temp->next = previous; previous = temp; } return previous; } void PrintList(PNode head) { PNode current = head; while (current != nullptr) { std::cout << current->value << " "; current = current->next; } std::cout << std::endl; } void FreeList(PNode head) { PNode current = head; while (current != nullptr) { PNode tmp = current; current = current->next; delete tmp; } }<|endoftext|>
<commit_before>#ifndef SAVE_STATE_H # define SAVE_STATE_H # pragma once struct statebuf { void* sp; void* label; }; inline bool savestate(statebuf& ssb) noexcept { bool r; #if defined(i386) || defined(__i386) || defined(__i386__) asm volatile ( "movl %%esp, %0\n\t" // store sp "movl $1f, %1\n\t" // store label "movb $0, %2\n\t" // return false "jmp 2f\n\t" "1:movb $1, %2\n\t" // return true "2:" : "=m" (ssb.sp), "=m" (ssb.label), "=r" (r) : : "memory" #elif defined(__amd64__) || defined(__amd64) || defined(__x86_64__) || defined(__x86_64) asm volatile ( "movq %%rsp, %0\n\t" // store sp "movq $1f, %1\n\t" // store label "movb $0, %2\n\t" // return false "jmp 2f\n\r" "1:movb $1, %2\n\t" // return true "2:" : "=m" (ssb.sp), "=m" (ssb.label), "=r" (r) : : "memory" #else # error "" #endif ); return r; } inline void restorestate(statebuf const& ssb) noexcept { #if defined(i386) || defined(__i386) || defined(__i386__) asm volatile ( "movl %0, %%esp\n\t" "jmp *%1" : : "m" (ssb.sp), "m" (ssb.label) ); #elif defined(__amd64__) || defined(__amd64) || defined(__x86_64__) || defined(__x86_64) asm volatile ( "movq %0, %%rsp\n\t" "jmp *%1" : : "m" (ssb.sp), "m" (ssb.label) ); #else # error "" #endif } #endif // SAVE_STATE_H <commit_msg>some fixes<commit_after>#ifndef SAVE_STATE_H # define SAVE_STATE_H # pragma once struct statebuf { void* sp; void* label; }; inline __attribute__((always_inline)) bool savestate(statebuf& ssb) noexcept { bool r; #if defined(i386) || defined(__i386) || defined(__i386__) asm volatile ( "movl %%esp, %0\n\t" // store sp "movl $1f, %1\n\t" // store label "movb $0, %2\n\t" // return false "jmp 2f\n\t" "1:movb $1, %2\n\t" // return true "2:" : "=m" (ssb.sp), "=m" (ssb.label), "=r" (r) : : "memory" #elif defined(__amd64__) || defined(__amd64) || defined(__x86_64__) || defined(__x86_64) asm volatile ( "movq %%rsp, %0\n\t" // store sp "movq $1f, %1\n\t" // store label "movb $0, %2\n\t" // return false "jmp 2f\n\r" "1:movb $1, %2\n\t" // return true "2:" : "=m" (ssb.sp), "=m" (ssb.label), "=r" (r) : : "memory" #else # error "" #endif ); return r; } inline __attribute__((always_inline)) void restorestate(statebuf const& ssb) noexcept { #if defined(i386) || defined(__i386) || defined(__i386__) asm volatile ( "movl %0, %%esp\n\t" "jmp *%1" : : "m" (ssb.sp), "m" (ssb.label) ); #elif defined(__amd64__) || defined(__amd64) || defined(__x86_64__) || defined(__x86_64) asm volatile ( "movq %0, %%rsp\n\t" "jmp *%1" : : "m" (ssb.sp), "m" (ssb.label) ); #else # error "" #endif } #endif // SAVE_STATE_H <|endoftext|>
<commit_before>// bdldfp_decimalconvertutil.cpp -*-C++-*- #include <bdldfp_decimalconvertutil.h> #include <bsls_ident.h> BSLS_IDENT_RCSID(bdldfp_decimalconvertutil_cpp,"$Id$ $CSID$") #include <bdldfp_decimalplatform.h> #include <bsls_assert.h> #ifdef BDLDFP_DECIMALPLATFORM_C99_TR # ifndef __STDC_WANT_DEC_FP__ # error __STDC_WANT_DEC_FP__ must be defined on the command line! char die[-42]; // if '#error' unsupported # endif #endif #include <bsl_algorithm.h> #include <bsl_cstdlib.h> #include <bsl_cstring.h> #include <ctype.h> #include <bsl_cmath.h> namespace BloombergLP { namespace bdldfp { namespace { // Reverse Memory static void memrev(void *buffer, size_t count) // Reverse the order of the first specified 'count' bytes, at the beginning // of the specified 'buffer'. 'count % 2' must be zero. { unsigned char *b = static_cast<unsigned char *>(buffer); bsl::reverse(b, b + count); } // Mem copy with reversal functions unsigned char *memReverseIfNeeded(void *buffer, size_t count) // Reverse the first specified 'count' bytes from the specified 'buffer`, // if the host endian is different from network endian, and return the // address computed from 'static_cast<unsigned char *>(buffer) + count'. { #ifdef BDLDFP_DECIMALPLATFORM_LITTLE_ENDIAN // little endian, needs to do some byte juggling memrev(buffer, count); #endif return static_cast<unsigned char*>(buffer) + count; } // Decimal-network conversion functions template <class DECIMAL_TYPE> const unsigned char *decimalFromNetworkT(DECIMAL_TYPE *decimal, const unsigned char *buffer) // Construct into the specified 'decimal', the base-10 value represented by // the network-ordered bytes in the specified 'buffer', and return a raw // memory pointer, providing modifiable access, to one byte past the last // byte read from 'buffer'. { bsl::memcpy(decimal, buffer, sizeof(DECIMAL_TYPE)); memReverseIfNeeded(decimal, sizeof(DECIMAL_TYPE)); DecimalConvertUtil::decimalFromDPD( decimal, reinterpret_cast<unsigned char *>(decimal)); return buffer + sizeof(DECIMAL_TYPE); } template <class DECIMAL_TYPE> unsigned char *decimalToNetworkT(unsigned char *buffer, DECIMAL_TYPE decimal) // Construct into the specified 'buffer', the network-ordered byte // representation of the base-10 value of the specified 'decimal', and, // return a raw memory pointer, providing modifiable access, to one byte // past the last written byte of the 'buffer'. { DecimalConvertUtil::decimalToDPD(buffer, decimal); return memReverseIfNeeded(buffer, sizeof(DECIMAL_TYPE)); } // ================= // class StdioFormat // ================= template <class FORMATTED_TYPE> struct StdioFormat; // This 'struct' template provides a method, 'format', that returns a // 'printf'-style format string to format values of the template parameter // type 'FORMATTED_TYPE' that can be used to restore a decimal value that // was previously converted to this type. template <> struct StdioFormat<float> { // This template specialization of 'StdioFormat' provides a function that // returns a 'printf'-style format string for 'float' values. static const char* format(); // Return a 'printf'-style format string that can be used to restore a // decimal value that was previously converted to a 'float' value. // Refer to the documentation of 'decimalFromFloat' for the conversion // rules. }; template <> struct StdioFormat<double> { // This template specialization of 'StdioFormat' provides a function that // returns a 'printf'-style format string for 'double' values. static char const* format(); // Return a 'printf'-style format string that can be used to restore a // decimal value that was previously converted to a 'double' value. // Refer to the documentation of 'decimalFromDouble' for the conversion // rules. }; // ----------------- // class StdioFormat // ----------------- const char* StdioFormat<float>::format() { return "%.6g"; } const char* StdioFormat<double>::format() { return "%.15g"; } // =================== // class DecimalTraits // =================== template <class DECIMAL_TYPE> struct DecimalTraits; // This 'struct' template provides a way to create an object of the // template parameter type 'DECIMAL_TYPE' though a consistent interface. template <> struct DecimalTraits<Decimal32> { // This template specialization of 'DecimalTraits' provides functions to // create 'Decimal32' values. typedef int SignificandType; // This 'typedef' defines a type that is large enough to hold the // significant of 'Decimal32'. static Decimal32 make(int significand, int exponent); // Return a 'Decimal32' value having the specified 'significand' and // the specified 'exponent'. }; template <> struct DecimalTraits<Decimal64> { // This template specialization of 'DecimalTraits' provides utilities to // create 'Decimal64' values. typedef long long SignificandType; // This 'typedef' defines a type that is large enough to hold the // significant of 'Decimal64'. static Decimal64 make(long long significand, int exponent); // Return a 'Decimal64' value having the specified 'significand' and // the specified 'exponent'. }; template <> struct DecimalTraits<bdldfp::Decimal128> { // This template specialization of 'DecimalTraits' provides utilities to // create 'Decimal128' values. typedef long long SignificandType; // This 'typedef' defines a type that is large enough to hold the // significant of 'Decimal128' if it's small enough to be convertible // to a double. static bdldfp::Decimal128 make(long long significand, int exponent); // Return a 'Decimal128' value having the specified 'significand' and // the specified 'exponent'. }; // =================== // class DecimalTraits // =================== Decimal32 DecimalTraits<Decimal32>::make(int significand, int exponent) { return bdldfp::DecimalUtil::makeDecimalRaw32(significand, exponent); } Decimal64 DecimalTraits<Decimal64>::make(long long significand, int exponent) { return bdldfp::DecimalUtil::makeDecimalRaw64(significand, exponent); } Decimal128 DecimalTraits<Decimal128>::make(long long significand, int exponent) { return bdldfp::DecimalUtil::makeDecimalRaw128(significand, exponent); } // Helpers for Restoring Decimal from Binary template <class DECIMAL_TYPE, class BINARY_TYPE> void restoreDecimalFromBinary(DECIMAL_TYPE *dfp, BINARY_TYPE bfp) // Construct, in the specified 'dfp', a decimal floating point // representation of the value of the binary floating point value specified // by 'bfp'. { if (bfp != bfp) { *dfp = bsl::numeric_limits<DECIMAL_TYPE>::quiet_NaN(); if (bfp < 0) { *dfp = -*dfp; } return; // RETURN } if (bfp == bsl::numeric_limits<BINARY_TYPE>::infinity()) { *dfp = bsl::numeric_limits<DECIMAL_TYPE>::infinity(); return; // RETURN } if (bfp == -bsl::numeric_limits<BINARY_TYPE>::infinity()) { *dfp = -bsl::numeric_limits<DECIMAL_TYPE>::infinity(); return; // RETURN } #ifdef BSLS_PLATFORM_OS_WINDOWS # define snprintf _snprintf #endif char buffer[48]; int rc = snprintf(buffer, sizeof(buffer), StdioFormat<BINARY_TYPE>::format(), bfp); (void)rc; BSLS_ASSERT(0 <= rc && rc < static_cast<int>(sizeof(buffer))); typename DecimalTraits<DECIMAL_TYPE>::SignificandType significand(0); int exponent(0); bool negative(false); char const* it(buffer); if (*it == '-') { negative = true; ++it; } for (; isdigit(static_cast<unsigned char>(*it)); ++it) { significand = significand * 10 + (*it - '0'); } if (*it == '.') { ++it; for (; isdigit(static_cast<unsigned char>(*it)); ++it) { significand = significand * 10 + (*it - '0'); --exponent; } } if (*it == 'e' || *it == 'E') { ++it; exponent += bsl::atoi(it); } *dfp = DecimalTraits<DECIMAL_TYPE>::make(significand, exponent); // Because the significand is a signed integer, it can not represent the // value -0, which distinct from +0 in decimal floating point. So instead // of converting the significand to a signed value, we change the decimal // value based on the sign appropriately after the decimal value is // created. if (negative) { *dfp = -(*dfp); } } } // close unnamed namespace // Network format converters // Note that we do not use platform or bslsl supported converters because they // work in terms of integers, so they would probably bleed out on the // strict-aliasing rules. We may solve that later on using the "union trick" // and delegating to 'bsls_byteorder', but for now let's take it slow. // Conversion to Network functions unsigned char *DecimalConvertUtil::decimal32ToNetwork(unsigned char *buffer, Decimal32 decimal) { BSLS_ASSERT(buffer != 0); return decimalToNetworkT(buffer, decimal); } unsigned char *DecimalConvertUtil::decimal64ToNetwork(unsigned char *buffer, Decimal64 decimal) { BSLS_ASSERT(buffer != 0); return decimalToNetworkT(buffer, decimal); } unsigned char *DecimalConvertUtil::decimal128ToNetwork(unsigned char *buffer, Decimal128 decimal) { BSLS_ASSERT(buffer != 0); return decimalToNetworkT(buffer, decimal); } unsigned char *DecimalConvertUtil::decimalToNetwork(unsigned char *buffer, Decimal32 decimal) { BSLS_ASSERT(buffer != 0); return decimalToNetworkT(buffer, decimal); } unsigned char *DecimalConvertUtil::decimalToNetwork(unsigned char *buffer, Decimal64 decimal) { BSLS_ASSERT(buffer != 0); return decimalToNetworkT(buffer, decimal); } unsigned char *DecimalConvertUtil::decimalToNetwork(unsigned char *buffer, Decimal128 decimal) { BSLS_ASSERT(buffer != 0); return decimalToNetworkT(buffer, decimal); } // Conversion to Network functions const unsigned char *DecimalConvertUtil::decimal32FromNetwork( Decimal32 *decimal, const unsigned char *buffer) { BSLS_ASSERT(decimal != 0); return decimalFromNetworkT(decimal, buffer); } const unsigned char *DecimalConvertUtil::decimal64FromNetwork( Decimal64 *decimal, const unsigned char *buffer) { BSLS_ASSERT(decimal != 0); return decimalFromNetworkT(decimal, buffer); } const unsigned char *DecimalConvertUtil::decimal128FromNetwork( Decimal128 *decimal, const unsigned char *buffer) { BSLS_ASSERT(decimal != 0); return decimalFromNetworkT(decimal, buffer); } const unsigned char *DecimalConvertUtil::decimalFromNetwork( Decimal32 *decimal, const unsigned char *buffer) { BSLS_ASSERT(decimal != 0); return decimalFromNetworkT(decimal, buffer); } const unsigned char *DecimalConvertUtil::decimalFromNetwork( Decimal64 *decimal, const unsigned char *buffer) { BSLS_ASSERT(decimal != 0); return decimalFromNetworkT(decimal, buffer); } const unsigned char *DecimalConvertUtil::decimalFromNetwork( Decimal128 *decimal, const unsigned char *buffer) { BSLS_ASSERT(decimal != 0); return decimalFromNetworkT(decimal, buffer); } // Restore a Decimal Floating-Point from a Binary // DecimalFromDouble functions Decimal32 DecimalConvertUtil::decimal32FromDouble(double binary) { Decimal32 rv; restoreDecimalFromBinary(&rv, binary); return rv; } Decimal64 DecimalConvertUtil::decimal64FromDouble(double binary) { Decimal64 rv; // Attempt the "Olkin-Farber" method for speed. Multiply the double by a // power of 10, round it to an integer, then use the faster scaled // conversion to decimal to produce a hoped-for result. The conversion is // correct if the result converts back to the original binary, provided // that the intermediate integer has no more than 15 (DBL_DIG) significant // digits (because no two decimal numbers with 15 or fewer significant // digits can convert to the same double). Since we want to deal with // original numbers that may have as many as 9 decimal places, we scale by // 1e9, and therefore the original number must be less than 1e7. if (binary != 0 && -1e7 < binary && binary < 1e7) { long long n = static_cast<long long>(binary * 1e9 + copysign(.5, binary)); int scale = -9; while ((n & 1) == 0 && n % 10 == 0 && scale < 0) { n /= 10; ++scale; } rv = DecimalUtil::makeDecimalRaw64(n, scale); double test = DecimalConvertUtil::decimalToDouble(rv); if (test == binary) { return rv; // RETURN } } restoreDecimalFromBinary(&rv, binary); return rv; } Decimal128 DecimalConvertUtil::decimal128FromDouble(double binary) { Decimal128 rv; restoreDecimalFromBinary(&rv, binary); return rv; } // DecimalFromFloat functions Decimal32 DecimalConvertUtil::decimal32FromFloat(float binary) { Decimal32 rv; restoreDecimalFromBinary(&rv, binary); return rv; } Decimal64 DecimalConvertUtil::decimal64FromFloat(float binary) { Decimal64 rv; restoreDecimalFromBinary(&rv, binary); return rv; } Decimal128 DecimalConvertUtil::decimal128FromFloat(float binary) { Decimal128 rv; restoreDecimalFromBinary(&rv, binary); return rv; } } // close package namespace } // close enterprise namespace // ---------------------------------------------------------------------------- // Copyright 2014 Bloomberg Finance L.P. // // 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. // ----------------------------- END-OF-FILE ---------------------------------- <commit_msg>Off-by-one (power of ten) on the range check.<commit_after>// bdldfp_decimalconvertutil.cpp -*-C++-*- #include <bdldfp_decimalconvertutil.h> #include <bsls_ident.h> BSLS_IDENT_RCSID(bdldfp_decimalconvertutil_cpp,"$Id$ $CSID$") #include <bdldfp_decimalplatform.h> #include <bsls_assert.h> #ifdef BDLDFP_DECIMALPLATFORM_C99_TR # ifndef __STDC_WANT_DEC_FP__ # error __STDC_WANT_DEC_FP__ must be defined on the command line! char die[-42]; // if '#error' unsupported # endif #endif #include <bsl_algorithm.h> #include <bsl_cstdlib.h> #include <bsl_cstring.h> #include <ctype.h> #include <bsl_cmath.h> namespace BloombergLP { namespace bdldfp { namespace { // Reverse Memory static void memrev(void *buffer, size_t count) // Reverse the order of the first specified 'count' bytes, at the beginning // of the specified 'buffer'. 'count % 2' must be zero. { unsigned char *b = static_cast<unsigned char *>(buffer); bsl::reverse(b, b + count); } // Mem copy with reversal functions unsigned char *memReverseIfNeeded(void *buffer, size_t count) // Reverse the first specified 'count' bytes from the specified 'buffer`, // if the host endian is different from network endian, and return the // address computed from 'static_cast<unsigned char *>(buffer) + count'. { #ifdef BDLDFP_DECIMALPLATFORM_LITTLE_ENDIAN // little endian, needs to do some byte juggling memrev(buffer, count); #endif return static_cast<unsigned char*>(buffer) + count; } // Decimal-network conversion functions template <class DECIMAL_TYPE> const unsigned char *decimalFromNetworkT(DECIMAL_TYPE *decimal, const unsigned char *buffer) // Construct into the specified 'decimal', the base-10 value represented by // the network-ordered bytes in the specified 'buffer', and return a raw // memory pointer, providing modifiable access, to one byte past the last // byte read from 'buffer'. { bsl::memcpy(decimal, buffer, sizeof(DECIMAL_TYPE)); memReverseIfNeeded(decimal, sizeof(DECIMAL_TYPE)); DecimalConvertUtil::decimalFromDPD( decimal, reinterpret_cast<unsigned char *>(decimal)); return buffer + sizeof(DECIMAL_TYPE); } template <class DECIMAL_TYPE> unsigned char *decimalToNetworkT(unsigned char *buffer, DECIMAL_TYPE decimal) // Construct into the specified 'buffer', the network-ordered byte // representation of the base-10 value of the specified 'decimal', and, // return a raw memory pointer, providing modifiable access, to one byte // past the last written byte of the 'buffer'. { DecimalConvertUtil::decimalToDPD(buffer, decimal); return memReverseIfNeeded(buffer, sizeof(DECIMAL_TYPE)); } // ================= // class StdioFormat // ================= template <class FORMATTED_TYPE> struct StdioFormat; // This 'struct' template provides a method, 'format', that returns a // 'printf'-style format string to format values of the template parameter // type 'FORMATTED_TYPE' that can be used to restore a decimal value that // was previously converted to this type. template <> struct StdioFormat<float> { // This template specialization of 'StdioFormat' provides a function that // returns a 'printf'-style format string for 'float' values. static const char* format(); // Return a 'printf'-style format string that can be used to restore a // decimal value that was previously converted to a 'float' value. // Refer to the documentation of 'decimalFromFloat' for the conversion // rules. }; template <> struct StdioFormat<double> { // This template specialization of 'StdioFormat' provides a function that // returns a 'printf'-style format string for 'double' values. static char const* format(); // Return a 'printf'-style format string that can be used to restore a // decimal value that was previously converted to a 'double' value. // Refer to the documentation of 'decimalFromDouble' for the conversion // rules. }; // ----------------- // class StdioFormat // ----------------- const char* StdioFormat<float>::format() { return "%.6g"; } const char* StdioFormat<double>::format() { return "%.15g"; } // =================== // class DecimalTraits // =================== template <class DECIMAL_TYPE> struct DecimalTraits; // This 'struct' template provides a way to create an object of the // template parameter type 'DECIMAL_TYPE' though a consistent interface. template <> struct DecimalTraits<Decimal32> { // This template specialization of 'DecimalTraits' provides functions to // create 'Decimal32' values. typedef int SignificandType; // This 'typedef' defines a type that is large enough to hold the // significant of 'Decimal32'. static Decimal32 make(int significand, int exponent); // Return a 'Decimal32' value having the specified 'significand' and // the specified 'exponent'. }; template <> struct DecimalTraits<Decimal64> { // This template specialization of 'DecimalTraits' provides utilities to // create 'Decimal64' values. typedef long long SignificandType; // This 'typedef' defines a type that is large enough to hold the // significant of 'Decimal64'. static Decimal64 make(long long significand, int exponent); // Return a 'Decimal64' value having the specified 'significand' and // the specified 'exponent'. }; template <> struct DecimalTraits<bdldfp::Decimal128> { // This template specialization of 'DecimalTraits' provides utilities to // create 'Decimal128' values. typedef long long SignificandType; // This 'typedef' defines a type that is large enough to hold the // significant of 'Decimal128' if it's small enough to be convertible // to a double. static bdldfp::Decimal128 make(long long significand, int exponent); // Return a 'Decimal128' value having the specified 'significand' and // the specified 'exponent'. }; // =================== // class DecimalTraits // =================== Decimal32 DecimalTraits<Decimal32>::make(int significand, int exponent) { return bdldfp::DecimalUtil::makeDecimalRaw32(significand, exponent); } Decimal64 DecimalTraits<Decimal64>::make(long long significand, int exponent) { return bdldfp::DecimalUtil::makeDecimalRaw64(significand, exponent); } Decimal128 DecimalTraits<Decimal128>::make(long long significand, int exponent) { return bdldfp::DecimalUtil::makeDecimalRaw128(significand, exponent); } // Helpers for Restoring Decimal from Binary template <class DECIMAL_TYPE, class BINARY_TYPE> void restoreDecimalFromBinary(DECIMAL_TYPE *dfp, BINARY_TYPE bfp) // Construct, in the specified 'dfp', a decimal floating point // representation of the value of the binary floating point value specified // by 'bfp'. { if (bfp != bfp) { *dfp = bsl::numeric_limits<DECIMAL_TYPE>::quiet_NaN(); if (bfp < 0) { *dfp = -*dfp; } return; // RETURN } if (bfp == bsl::numeric_limits<BINARY_TYPE>::infinity()) { *dfp = bsl::numeric_limits<DECIMAL_TYPE>::infinity(); return; // RETURN } if (bfp == -bsl::numeric_limits<BINARY_TYPE>::infinity()) { *dfp = -bsl::numeric_limits<DECIMAL_TYPE>::infinity(); return; // RETURN } #ifdef BSLS_PLATFORM_OS_WINDOWS # define snprintf _snprintf #endif char buffer[48]; int rc = snprintf(buffer, sizeof(buffer), StdioFormat<BINARY_TYPE>::format(), bfp); (void)rc; BSLS_ASSERT(0 <= rc && rc < static_cast<int>(sizeof(buffer))); typename DecimalTraits<DECIMAL_TYPE>::SignificandType significand(0); int exponent(0); bool negative(false); char const* it(buffer); if (*it == '-') { negative = true; ++it; } for (; isdigit(static_cast<unsigned char>(*it)); ++it) { significand = significand * 10 + (*it - '0'); } if (*it == '.') { ++it; for (; isdigit(static_cast<unsigned char>(*it)); ++it) { significand = significand * 10 + (*it - '0'); --exponent; } } if (*it == 'e' || *it == 'E') { ++it; exponent += bsl::atoi(it); } *dfp = DecimalTraits<DECIMAL_TYPE>::make(significand, exponent); // Because the significand is a signed integer, it can not represent the // value -0, which distinct from +0 in decimal floating point. So instead // of converting the significand to a signed value, we change the decimal // value based on the sign appropriately after the decimal value is // created. if (negative) { *dfp = -(*dfp); } } } // close unnamed namespace // Network format converters // Note that we do not use platform or bslsl supported converters because they // work in terms of integers, so they would probably bleed out on the // strict-aliasing rules. We may solve that later on using the "union trick" // and delegating to 'bsls_byteorder', but for now let's take it slow. // Conversion to Network functions unsigned char *DecimalConvertUtil::decimal32ToNetwork(unsigned char *buffer, Decimal32 decimal) { BSLS_ASSERT(buffer != 0); return decimalToNetworkT(buffer, decimal); } unsigned char *DecimalConvertUtil::decimal64ToNetwork(unsigned char *buffer, Decimal64 decimal) { BSLS_ASSERT(buffer != 0); return decimalToNetworkT(buffer, decimal); } unsigned char *DecimalConvertUtil::decimal128ToNetwork(unsigned char *buffer, Decimal128 decimal) { BSLS_ASSERT(buffer != 0); return decimalToNetworkT(buffer, decimal); } unsigned char *DecimalConvertUtil::decimalToNetwork(unsigned char *buffer, Decimal32 decimal) { BSLS_ASSERT(buffer != 0); return decimalToNetworkT(buffer, decimal); } unsigned char *DecimalConvertUtil::decimalToNetwork(unsigned char *buffer, Decimal64 decimal) { BSLS_ASSERT(buffer != 0); return decimalToNetworkT(buffer, decimal); } unsigned char *DecimalConvertUtil::decimalToNetwork(unsigned char *buffer, Decimal128 decimal) { BSLS_ASSERT(buffer != 0); return decimalToNetworkT(buffer, decimal); } // Conversion to Network functions const unsigned char *DecimalConvertUtil::decimal32FromNetwork( Decimal32 *decimal, const unsigned char *buffer) { BSLS_ASSERT(decimal != 0); return decimalFromNetworkT(decimal, buffer); } const unsigned char *DecimalConvertUtil::decimal64FromNetwork( Decimal64 *decimal, const unsigned char *buffer) { BSLS_ASSERT(decimal != 0); return decimalFromNetworkT(decimal, buffer); } const unsigned char *DecimalConvertUtil::decimal128FromNetwork( Decimal128 *decimal, const unsigned char *buffer) { BSLS_ASSERT(decimal != 0); return decimalFromNetworkT(decimal, buffer); } const unsigned char *DecimalConvertUtil::decimalFromNetwork( Decimal32 *decimal, const unsigned char *buffer) { BSLS_ASSERT(decimal != 0); return decimalFromNetworkT(decimal, buffer); } const unsigned char *DecimalConvertUtil::decimalFromNetwork( Decimal64 *decimal, const unsigned char *buffer) { BSLS_ASSERT(decimal != 0); return decimalFromNetworkT(decimal, buffer); } const unsigned char *DecimalConvertUtil::decimalFromNetwork( Decimal128 *decimal, const unsigned char *buffer) { BSLS_ASSERT(decimal != 0); return decimalFromNetworkT(decimal, buffer); } // Restore a Decimal Floating-Point from a Binary // DecimalFromDouble functions Decimal32 DecimalConvertUtil::decimal32FromDouble(double binary) { Decimal32 rv; restoreDecimalFromBinary(&rv, binary); return rv; } Decimal64 DecimalConvertUtil::decimal64FromDouble(double binary) { Decimal64 rv; // Attempt the "Olkin-Farber" method for speed. Multiply the double by a // power of 10, round it to an integer, then use the faster scaled // conversion to decimal to produce a hoped-for result. The conversion is // correct if the result converts back to the original binary, provided // that the intermediate integer has no more than 15 (DBL_DIG) significant // digits (because no two decimal numbers with 15 or fewer significant // digits can convert to the same double). Since we want to deal with // original numbers that may have as many as 9 decimal places, we scale by // 1e9, and therefore the original number must be less than 1e7. if (binary != 0 && -1e6 < binary && binary < 1e6) { long long n = static_cast<long long>(binary * 1e9 + copysign(.5, binary)); int scale = -9; while ((n & 1) == 0 && n % 10 == 0 && scale < 0) { n /= 10; ++scale; } rv = DecimalUtil::makeDecimalRaw64(n, scale); double test = DecimalConvertUtil::decimalToDouble(rv); if (test == binary) { return rv; // RETURN } } restoreDecimalFromBinary(&rv, binary); return rv; } Decimal128 DecimalConvertUtil::decimal128FromDouble(double binary) { Decimal128 rv; restoreDecimalFromBinary(&rv, binary); return rv; } // DecimalFromFloat functions Decimal32 DecimalConvertUtil::decimal32FromFloat(float binary) { Decimal32 rv; restoreDecimalFromBinary(&rv, binary); return rv; } Decimal64 DecimalConvertUtil::decimal64FromFloat(float binary) { Decimal64 rv; restoreDecimalFromBinary(&rv, binary); return rv; } Decimal128 DecimalConvertUtil::decimal128FromFloat(float binary) { Decimal128 rv; restoreDecimalFromBinary(&rv, binary); return rv; } } // close package namespace } // close enterprise namespace // ---------------------------------------------------------------------------- // Copyright 2014 Bloomberg Finance L.P. // // 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. // ----------------------------- END-OF-FILE ---------------------------------- <|endoftext|>
<commit_before>/*************************************************************************** Copyright (C) 2006-2008 by Marco Gulino <marco@kmobiletools.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.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 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. ***************************************************************************/ #include "mplayerthumbscfg.h" #include "videobackendiface.h" #include <klineedit.h> #include <kpushbutton.h> #include <qlabel.h> #include <klocale.h> #include <kstandarddirs.h> #include <kdebug.h> #include <qtimer.h> #include <keditlistbox.h> #include <kmessagebox.h> #include <kio/deletejob.h> #include <QDir> const QString MPlayerThumbsConfig::thumbnailsDir( QDir::homePath() + "/.thumbnails/" ); MPlayerThumbsConfig::MPlayerThumbsConfig(QWidget *parent, const QString &name, MPlayerThumbsCfg *config) : KConfigDialog(parent, name, config) { dialogUI=new Ui::configDialog(); mplayerConfigUI=new Ui::mplayerConfig(); QWidget *dialogWidget=new QWidget(); QWidget *mplayerConfigUIWidget = new QWidget(); dialogUI->setupUi(dialogWidget); mplayerConfigUI->setupUi(mplayerConfigUIWidget); addPage( dialogWidget, i18n("General"), "general" ); addPage( mplayerConfigUIWidget, i18n("MPlayer Backend"), "mplayer" ); connect( dialogUI->clean_cache, SIGNAL(clicked() ), this, SLOT(cleanCache() ) ); // setFaceType(Plain); if(!config->mplayerbin().length() ) QTimer::singleShot( 100, this, SLOT(autoFindPath())); dialogUI->kcfg_backend->addItem(i18n("MPlayer"), VideoBackendIFace::MPlayer ); dialogUI->kcfg_backend->addItem(i18n("Phonon"), VideoBackendIFace::Phonon ); } MPlayerThumbsConfig::~MPlayerThumbsConfig() { } #include "mplayerthumbscfg.moc" /*! \fn MPlayerThumbsConfig::autoFindPath() */ void MPlayerThumbsConfig::autoFindPath() { QString playerPath=KStandardDirs::findExe("mplayer-bin"); if(playerPath.isNull() ) playerPath=KStandardDirs::findExe("mplayer"); kDebug() << "Trying to set player path to " << playerPath << endl; mplayerConfigUI->kcfg_mplayerbin->setPath( playerPath ); } void MPlayerThumbsConfig::cleanCache() { int doClean = KMessageBox::warningContinueCancel(this, i18n("Cleaning the cache will delete all the previously generated thumbnails.\nNote that as there is a single common thumbnail cache, the thumbnails for all other file types will also be deleted.\nDo you really want to clean up the cache?") ); if (doClean!= KMessageBox::Continue ) return; kDebug() << "Cleaning cache from " << thumbnailsDir << endl; KIO::del( thumbnailsDir ); } <commit_msg>Fix mem leak<commit_after>/*************************************************************************** Copyright (C) 2006-2008 by Marco Gulino <marco@kmobiletools.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.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 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. ***************************************************************************/ #include "mplayerthumbscfg.h" #include "videobackendiface.h" #include <klineedit.h> #include <kpushbutton.h> #include <qlabel.h> #include <klocale.h> #include <kstandarddirs.h> #include <kdebug.h> #include <qtimer.h> #include <keditlistbox.h> #include <kmessagebox.h> #include <kio/deletejob.h> #include <QDir> const QString MPlayerThumbsConfig::thumbnailsDir( QDir::homePath() + "/.thumbnails/" ); MPlayerThumbsConfig::MPlayerThumbsConfig(QWidget *parent, const QString &name, MPlayerThumbsCfg *config) : KConfigDialog(parent, name, config) { dialogUI=new Ui::configDialog(); mplayerConfigUI=new Ui::mplayerConfig(); QWidget *dialogWidget=new QWidget(); QWidget *mplayerConfigUIWidget = new QWidget(); dialogUI->setupUi(dialogWidget); mplayerConfigUI->setupUi(mplayerConfigUIWidget); addPage( dialogWidget, i18n("General"), "general" ); addPage( mplayerConfigUIWidget, i18n("MPlayer Backend"), "mplayer" ); connect( dialogUI->clean_cache, SIGNAL(clicked() ), this, SLOT(cleanCache() ) ); // setFaceType(Plain); if(!config->mplayerbin().length() ) QTimer::singleShot( 100, this, SLOT(autoFindPath())); dialogUI->kcfg_backend->addItem(i18n("MPlayer"), VideoBackendIFace::MPlayer ); dialogUI->kcfg_backend->addItem(i18n("Phonon"), VideoBackendIFace::Phonon ); } MPlayerThumbsConfig::~MPlayerThumbsConfig() { delete dialogUI; delete mplayerConfigUI; } #include "mplayerthumbscfg.moc" /*! \fn MPlayerThumbsConfig::autoFindPath() */ void MPlayerThumbsConfig::autoFindPath() { QString playerPath=KStandardDirs::findExe("mplayer-bin"); if(playerPath.isNull() ) playerPath=KStandardDirs::findExe("mplayer"); kDebug() << "Trying to set player path to " << playerPath << endl; mplayerConfigUI->kcfg_mplayerbin->setPath( playerPath ); } void MPlayerThumbsConfig::cleanCache() { int doClean = KMessageBox::warningContinueCancel(this, i18n("Cleaning the cache will delete all the previously generated thumbnails.\nNote that as there is a single common thumbnail cache, the thumbnails for all other file types will also be deleted.\nDo you really want to clean up the cache?") ); if (doClean!= KMessageBox::Continue ) return; kDebug() << "Cleaning cache from " << thumbnailsDir << endl; KIO::del( thumbnailsDir ); } <|endoftext|>
<commit_before>#include <iostream> #include <QDir> #include <QTextStream> //============================================================================== // Computer engine class //============================================================================== #include "computerengine.h" #include "computermath.h" //============================================================================== #include <QApplication> //============================================================================== #include "llvm/LLVMContext.h" #ifdef Q_WS_WIN // To include llvm/Module.h results in some indirect warnings from MSVC, but // it's LLVM's task to address them not ours, so... #pragma warning(disable: 4146) #endif #include "llvm/Module.h" #ifdef Q_WS_WIN #pragma warning(default: 4146) #endif #include "llvm/ADT/OwningPtr.h" #include "llvm/ADT/SmallString.h" #include "llvm/Assembly/Parser.h" #include "llvm/ExecutionEngine/ExecutionEngine.h" #include "llvm/Support/SourceMgr.h" #include "llvm/Support/TargetSelect.h" #include "llvm/Support/DynamicLibrary.h" #include "llvm/Support/Host.h" #include "llvm/Support/ManagedStatic.h" #include "llvm/Support/Path.h" #include "llvm/Support/raw_ostream.h" #include "clang/CodeGen/CodeGenAction.h" #include "clang/Driver/Compilation.h" #include "clang/Driver/Driver.h" #include "clang/Driver/Tool.h" #include "clang/Frontend/CompilerInvocation.h" #include "clang/Frontend/CompilerInstance.h" #include "clang/Frontend/DiagnosticOptions.h" #include "clang/Frontend/FrontendDiagnostic.h" #include "clang/Frontend/TextDiagnosticPrinter.h" //============================================================================== namespace OpenCOR { namespace Computer { //============================================================================== ComputerEngine::ComputerEngine() : mError(ComputerError()) { // Create a module static int counter = 0; mModule = new llvm::Module(qPrintable(QString("Module #%1").arg(QString::number(++counter))), llvm::getGlobalContext()); // Initialise the native target, so not only can we then create a JIT // execution engine, but more importantly its data layout will match that of // our target platform... llvm::InitializeNativeTarget(); // Create a JIT execution engine mExecutionEngine = llvm::ExecutionEngine::createJIT(mModule); } //============================================================================== ComputerEngine::~ComputerEngine() { // Delete some internal objects delete mExecutionEngine; // Note: we must NOT delete mModule, since it gets deleted when deleting // mExecutionEngine... } //============================================================================== llvm::Module * ComputerEngine::module() { // Return the computer engine's module return mModule; } //============================================================================== llvm::ExecutionEngine * ComputerEngine::executionEngine() { // Return the computer engine's execution engine return mExecutionEngine; } //============================================================================== ComputerError ComputerEngine::error() { // Return the computer engine's error return mError; } //============================================================================== llvm::sys::Path getExecutablePath(const char *pArg) { return llvm::sys::Path::GetMainExecutable(pArg, (void *) (intptr_t) getExecutablePath); } //============================================================================== llvm::Function * ComputerEngine::addFunction(const QString &pFunctionName, const QString &pFunctionBody, const bool &pOutputErrors) { // Check whether we want to compute a definite integral or not if (pFunctionBody.contains("defint(func")) { mError = ComputerError(tr("definite integrals are not yet supported")); return 0; } // Save the function in a temporary file, after having prepended it with // all possible external functions which it may, or not, need // Note: indeed, we cannot include header files since we don't (and don't // want to avoid complications) deploy them with OpenCOR. So, instead, // we must declare as external functions all the functions which we // would normally use through header files... QByteArray appByteArray = qApp->applicationFilePath().toLatin1(); const char *appFileName = appByteArray.constData(); QByteArray tempFileByteArray = QString(QDir::tempPath()+QDir::separator()+QFileInfo(appFileName).baseName()+".c").toLatin1(); const char *tempFileName = tempFileByteArray.constData(); QFile tempFile = tempFileName; if (!tempFile.open(QIODevice::WriteOnly | QIODevice::Text)) { // The temporary file can't be opened, so... mError = ComputerError(tr("the '%1' temporary file could not be created").arg(tempFileName)); tempFile.remove(); return 0; } QTextStream out(&tempFile); out << "extern double fabs(double);\n" << "\n" << "extern double exp(double);\n" << "extern double log(double);\n" << "\n" << "extern double ceil(double);\n" << "extern double floor(double);\n" << "\n" << "extern double factorial(double);\n" << "\n" << "extern double sin(double);\n" << "extern double cos(double);\n" << "extern double tan(double);\n" << "extern double sinh(double);\n" << "extern double cosh(double);\n" << "extern double tanh(double);\n" << "extern double asin(double);\n" << "extern double acos(double);\n" << "extern double atan(double);\n" << "extern double asinh(double);\n" << "extern double acosh(double);\n" << "extern double atanh(double);\n" << "\n" << "extern double arbitrary_log(double, double);\n" << "\n" << "extern double pow(double, double);\n" << "\n" << "extern double gcd_multi(int, ...);\n" << "extern double lcm_multi(int, ...);\n" << "extern double multi_max(int, ...);\n" << "extern double multi_min(int, ...);\n" << "\n" << pFunctionBody; tempFile.close(); // Get a driver to compile our function llvm::raw_ostream &outputStream = pOutputErrors?llvm::errs():llvm::nulls(); clang::DiagnosticsEngine diagnosticsEngine(llvm::IntrusiveRefCntPtr<clang::DiagnosticIDs>(new clang::DiagnosticIDs()), new clang::TextDiagnosticPrinter(outputStream, clang::DiagnosticOptions())); clang::driver::Driver driver(getExecutablePath(appFileName).str(), llvm::sys::getDefaultTargetTriple(), "a.out", true, diagnosticsEngine); // Get a compilation object to which we pass some arguments llvm::SmallVector<const char *, 16> compilationArguments; compilationArguments.push_back(appFileName); compilationArguments.push_back("-fsyntax-only"); compilationArguments.push_back("-O2"); compilationArguments.push_back("-Werror"); compilationArguments.push_back(tempFileName); llvm::OwningPtr<clang::driver::Compilation> compilation(driver.BuildCompilation(compilationArguments)); if (!compilation) { // We couldn't get a compilation object, so... mError = ComputerError(tr("the compilation object could not be created")); tempFile.remove(); return 0; } // The compilation object should have only one command, so if it doesn't // then something went wrong const clang::driver::JobList &jobList = compilation->getJobs(); if ( (jobList.size() != 1) || !llvm::isa<clang::driver::Command>(*jobList.begin())) { mError = ComputerError(tr("the compilation object must contain only one command")); tempFile.remove(); return 0; } // Retrieve the command job const clang::driver::Command *command = llvm::cast<clang::driver::Command>(*jobList.begin()); QString commandName = command->getCreator().getName(); if (commandName.compare("clang")) { mError = ComputerError(tr("a 'clang' command was expected, but a '%1' command was found instead").arg(commandName)); tempFile.remove(); return 0; } // Create a compiler invocation using our command's arguments const clang::driver::ArgStringList &commandArguments = command->getArguments(); llvm::OwningPtr<clang::CompilerInvocation> compilerInvocation(new clang::CompilerInvocation()); clang::CompilerInvocation::CreateFromArgs(*compilerInvocation, const_cast<const char **>(commandArguments.data()), const_cast<const char **>(commandArguments.data())+commandArguments.size(), diagnosticsEngine); // Create a compiler instance to handle the actual work clang::CompilerInstance compilerInstance; compilerInstance.setInvocation(compilerInvocation.take()); // Create the compiler instance's diagnostics engine compilerInstance.createDiagnostics(int(commandArguments.size()), const_cast<char **>(commandArguments.data()), new clang::TextDiagnosticPrinter(outputStream, compilerInstance.getDiagnosticOpts())); if (!compilerInstance.hasDiagnostics()) { mError = ComputerError(tr("the diagnostics engine could not be created")); tempFile.remove(); return 0; } // Create and execute the frontend to generate the LLVM assembly code, // making sure that all added functions end up in the same module llvm::OwningPtr<clang::CodeGenAction> codeGenerationAction(new clang::EmitLLVMOnlyAction(&mModule->getContext())); codeGenerationAction->setLinkModule(mModule); if (!compilerInstance.ExecuteAction(*codeGenerationAction, outputStream)) { mError = ComputerError(tr("the '%1' function could not be compiled").arg(pFunctionName)); tempFile.remove(); return 0; } // The LLVM assembly code was generated, so we can update our module and // delete our temporary file mModule = codeGenerationAction->takeModule(); tempFile.remove(); // Try to retrieve the function we have just added llvm::Function *res = mModule->getFunction(qPrintable(pFunctionName)); if (!res) { mError = ComputerError(tr("the '%1' function could not be found").arg(pFunctionName)); return 0; } // Everything went fine, so reset the engine's error and return the function // we have just added mError = ComputerError(); return res; } //============================================================================== } // namespace Computer } // namespace OpenCOR //============================================================================== // End of file //============================================================================== <commit_msg>Minor fix as part of our LLVM+Clang work.<commit_after>#include <iostream> #include <QDir> #include <QTextStream> //============================================================================== // Computer engine class //============================================================================== #include "computerengine.h" #include "computermath.h" //============================================================================== #include <QApplication> //============================================================================== #include "llvm/LLVMContext.h" #ifdef Q_WS_WIN // To include llvm/Module.h results in some indirect warnings from MSVC, but // it's LLVM's task to address them not ours, so... #pragma warning(disable: 4146) #endif #include "llvm/Module.h" #ifdef Q_WS_WIN #pragma warning(default: 4146) #endif #include "llvm/ADT/OwningPtr.h" #include "llvm/ADT/SmallString.h" #include "llvm/Assembly/Parser.h" #include "llvm/ExecutionEngine/ExecutionEngine.h" #include "llvm/Support/SourceMgr.h" #include "llvm/Support/TargetSelect.h" #include "llvm/Support/DynamicLibrary.h" #include "llvm/Support/Host.h" #include "llvm/Support/ManagedStatic.h" #include "llvm/Support/Path.h" #include "llvm/Support/raw_ostream.h" #include "clang/CodeGen/CodeGenAction.h" #include "clang/Driver/Compilation.h" #include "clang/Driver/Driver.h" #include "clang/Driver/Tool.h" #include "clang/Frontend/CompilerInvocation.h" #include "clang/Frontend/CompilerInstance.h" #include "clang/Frontend/DiagnosticOptions.h" #include "clang/Frontend/FrontendDiagnostic.h" #include "clang/Frontend/TextDiagnosticPrinter.h" //============================================================================== namespace OpenCOR { namespace Computer { //============================================================================== ComputerEngine::ComputerEngine() : mError(ComputerError()) { // Create a module static int counter = 0; mModule = new llvm::Module(qPrintable(QString("Module #%1").arg(QString::number(++counter))), llvm::getGlobalContext()); // Initialise the native target, so not only can we then create a JIT // execution engine, but more importantly its data layout will match that of // our target platform... llvm::InitializeNativeTarget(); // Create a JIT execution engine mExecutionEngine = llvm::ExecutionEngine::createJIT(mModule); } //============================================================================== ComputerEngine::~ComputerEngine() { // Delete some internal objects delete mExecutionEngine; // Note: we must NOT delete mModule, since it gets deleted when deleting // mExecutionEngine... } //============================================================================== llvm::Module * ComputerEngine::module() { // Return the computer engine's module return mModule; } //============================================================================== llvm::ExecutionEngine * ComputerEngine::executionEngine() { // Return the computer engine's execution engine return mExecutionEngine; } //============================================================================== ComputerError ComputerEngine::error() { // Return the computer engine's error return mError; } //============================================================================== llvm::sys::Path getExecutablePath(const char *pArg) { return llvm::sys::Path::GetMainExecutable(pArg, (void *) (intptr_t) getExecutablePath); } //============================================================================== llvm::Function * ComputerEngine::addFunction(const QString &pFunctionName, const QString &pFunctionBody, const bool &pOutputErrors) { // Check whether we want to compute a definite integral or not if (pFunctionBody.contains("defint(func")) { mError = ComputerError(tr("definite integrals are not yet supported")); return 0; } // Save the function in a temporary file, after having prepended it with // all possible external functions which it may, or not, need // Note: indeed, we cannot include header files since we don't (and don't // want to avoid complications) deploy them with OpenCOR. So, instead, // we must declare as external functions all the functions which we // would normally use through header files... QByteArray appByteArray = qApp->applicationFilePath().toLatin1(); const char *appFileName = appByteArray.constData(); QByteArray tempFileByteArray = QString(QDir::tempPath()+QDir::separator()+QFileInfo(appFileName).baseName()+".c").toLatin1(); const char *tempFileName = tempFileByteArray.constData(); QFile tempFile(tempFileName); if (!tempFile.open(QIODevice::WriteOnly | QIODevice::Text)) { // The temporary file can't be opened, so... mError = ComputerError(tr("the '%1' temporary file could not be created").arg(tempFileName)); tempFile.remove(); return 0; } QTextStream out(&tempFile); out << "extern double fabs(double);\n" << "\n" << "extern double exp(double);\n" << "extern double log(double);\n" << "\n" << "extern double ceil(double);\n" << "extern double floor(double);\n" << "\n" << "extern double factorial(double);\n" << "\n" << "extern double sin(double);\n" << "extern double cos(double);\n" << "extern double tan(double);\n" << "extern double sinh(double);\n" << "extern double cosh(double);\n" << "extern double tanh(double);\n" << "extern double asin(double);\n" << "extern double acos(double);\n" << "extern double atan(double);\n" << "extern double asinh(double);\n" << "extern double acosh(double);\n" << "extern double atanh(double);\n" << "\n" << "extern double arbitrary_log(double, double);\n" << "\n" << "extern double pow(double, double);\n" << "\n" << "extern double gcd_multi(int, ...);\n" << "extern double lcm_multi(int, ...);\n" << "extern double multi_max(int, ...);\n" << "extern double multi_min(int, ...);\n" << "\n" << pFunctionBody; tempFile.close(); // Get a driver to compile our function llvm::raw_ostream &outputStream = pOutputErrors?llvm::errs():llvm::nulls(); clang::DiagnosticsEngine diagnosticsEngine(llvm::IntrusiveRefCntPtr<clang::DiagnosticIDs>(new clang::DiagnosticIDs()), new clang::TextDiagnosticPrinter(outputStream, clang::DiagnosticOptions())); clang::driver::Driver driver(getExecutablePath(appFileName).str(), llvm::sys::getDefaultTargetTriple(), "a.out", true, diagnosticsEngine); // Get a compilation object to which we pass some arguments llvm::SmallVector<const char *, 16> compilationArguments; compilationArguments.push_back(appFileName); compilationArguments.push_back("-fsyntax-only"); compilationArguments.push_back("-O2"); compilationArguments.push_back("-Werror"); compilationArguments.push_back(tempFileName); llvm::OwningPtr<clang::driver::Compilation> compilation(driver.BuildCompilation(compilationArguments)); if (!compilation) { // We couldn't get a compilation object, so... mError = ComputerError(tr("the compilation object could not be created")); tempFile.remove(); return 0; } // The compilation object should have only one command, so if it doesn't // then something went wrong const clang::driver::JobList &jobList = compilation->getJobs(); if ( (jobList.size() != 1) || !llvm::isa<clang::driver::Command>(*jobList.begin())) { mError = ComputerError(tr("the compilation object must contain only one command")); tempFile.remove(); return 0; } // Retrieve the command job const clang::driver::Command *command = llvm::cast<clang::driver::Command>(*jobList.begin()); QString commandName = command->getCreator().getName(); if (commandName.compare("clang")) { mError = ComputerError(tr("a 'clang' command was expected, but a '%1' command was found instead").arg(commandName)); tempFile.remove(); return 0; } // Create a compiler invocation using our command's arguments const clang::driver::ArgStringList &commandArguments = command->getArguments(); llvm::OwningPtr<clang::CompilerInvocation> compilerInvocation(new clang::CompilerInvocation()); clang::CompilerInvocation::CreateFromArgs(*compilerInvocation, const_cast<const char **>(commandArguments.data()), const_cast<const char **>(commandArguments.data())+commandArguments.size(), diagnosticsEngine); // Create a compiler instance to handle the actual work clang::CompilerInstance compilerInstance; compilerInstance.setInvocation(compilerInvocation.take()); // Create the compiler instance's diagnostics engine compilerInstance.createDiagnostics(int(commandArguments.size()), const_cast<char **>(commandArguments.data()), new clang::TextDiagnosticPrinter(outputStream, compilerInstance.getDiagnosticOpts())); if (!compilerInstance.hasDiagnostics()) { mError = ComputerError(tr("the diagnostics engine could not be created")); tempFile.remove(); return 0; } // Create and execute the frontend to generate the LLVM assembly code, // making sure that all added functions end up in the same module llvm::OwningPtr<clang::CodeGenAction> codeGenerationAction(new clang::EmitLLVMOnlyAction(&mModule->getContext())); codeGenerationAction->setLinkModule(mModule); if (!compilerInstance.ExecuteAction(*codeGenerationAction, outputStream)) { mError = ComputerError(tr("the '%1' function could not be compiled").arg(pFunctionName)); tempFile.remove(); return 0; } // The LLVM assembly code was generated, so we can update our module and // delete our temporary file mModule = codeGenerationAction->takeModule(); tempFile.remove(); // Try to retrieve the function we have just added llvm::Function *res = mModule->getFunction(qPrintable(pFunctionName)); if (!res) { mError = ComputerError(tr("the '%1' function could not be found").arg(pFunctionName)); return 0; } // Everything went fine, so reset the engine's error and return the function // we have just added mError = ComputerError(); return res; } //============================================================================== } // namespace Computer } // namespace OpenCOR //============================================================================== // End of file //============================================================================== <|endoftext|>
<commit_before>#include "mdlearn.hpp" #include <cstdlib> #include <cstring> #include <boost/array.hpp> #include <algorithm> TilesMDLearn::TilesMDLearn(FILE *in) : TilesMdist(in) { initops(10); } void TilesMDLearn::initops(unsigned int dmax) { unsigned int oldsz = ops.size(); ops.resize(dmax+1); for (unsigned int d = 0; d < oldsz; d++) initdests(d); for (unsigned int d = oldsz; d <= dmax; d++) { for (unsigned int i = 0; i < Ntiles; i++) { memset(&ops[d][i], 0, sizeof(ops[d][i])); if (i >= Width) ops[d][i].mvs[ops[d][i].n++].b = i - Width; if (i % Width > 0) ops[d][i].mvs[ops[d][i].n++].b = i - 1; if (i % Width < Width - 1) ops[d][i].mvs[ops[d][i].n++].b = i + 1; if (i < Ntiles - Width) ops[d][i].mvs[ops[d][i].n++].b = i + Width; } initdests(d); } } void TilesMDLearn::initdests(unsigned int d) { for (unsigned int i = 0; i < Ntiles; i++) { for (unsigned int j = 0; j < ops[d][i].n; j++) { Pos b = ops[d][i].mvs[j].b; ops[d][i].dests[b] = &ops[d][i].mvs[j]; } } } void TilesMDLearn::resetprobs(void) { for (unsigned int d = 0; d < ops.size(); d++) { for (unsigned int i = 0; i < Ntiles; i++) { for (unsigned int j = 0; j < ops[d][i].n; j++) { ops[d][i].mvs[j].nother = 0; ops[d][i].mvs[j].ndec = 0; } } } } int cmpmv(const void *_a, const void *_b) { const TilesMDLearn::Opinfo *a = (const TilesMDLearn::Opinfo *) _a; const TilesMDLearn::Opinfo *b = (const TilesMDLearn::Opinfo *) _b; double aprob = (double) a->ndec / (double) (a->nother + a->ndec); double bprob = (double) b->ndec / (double) (b->nother + b->ndec); if (aprob > bprob) return -1; return 1; } void TilesMDLearn::sortops(void) { for (unsigned int d = 0; d < ops.size(); d++) { for (unsigned int i = 0; i < Ntiles; i++) std::sort(ops[d][i].mvs.begin(), ops[d][i].mvs.begin() + ops[d][i].n); initdests(d); } } <commit_msg>Ensure the vector capacity grows geometrically.<commit_after>#include "mdlearn.hpp" #include <cstdlib> #include <cstring> #include <boost/array.hpp> #include <algorithm> TilesMDLearn::TilesMDLearn(FILE *in) : TilesMdist(in) { initops(10); } void TilesMDLearn::initops(unsigned int dmax) { unsigned int oldsz = ops.size(); if (dmax+1 > ops.capacity()) ops.reserve((dmax+1) * 2); ops.resize(dmax+1); for (unsigned int d = 0; d < oldsz; d++) initdests(d); for (unsigned int d = oldsz; d <= dmax; d++) { for (unsigned int i = 0; i < Ntiles; i++) { memset(&ops[d][i], 0, sizeof(ops[d][i])); if (i >= Width) ops[d][i].mvs[ops[d][i].n++].b = i - Width; if (i % Width > 0) ops[d][i].mvs[ops[d][i].n++].b = i - 1; if (i % Width < Width - 1) ops[d][i].mvs[ops[d][i].n++].b = i + 1; if (i < Ntiles - Width) ops[d][i].mvs[ops[d][i].n++].b = i + Width; } initdests(d); } } void TilesMDLearn::initdests(unsigned int d) { for (unsigned int i = 0; i < Ntiles; i++) { for (unsigned int j = 0; j < ops[d][i].n; j++) { Pos b = ops[d][i].mvs[j].b; ops[d][i].dests[b] = &ops[d][i].mvs[j]; } } } void TilesMDLearn::resetprobs(void) { for (unsigned int d = 0; d < ops.size(); d++) { for (unsigned int i = 0; i < Ntiles; i++) { for (unsigned int j = 0; j < ops[d][i].n; j++) { ops[d][i].mvs[j].nother = 0; ops[d][i].mvs[j].ndec = 0; } } } } int cmpmv(const void *_a, const void *_b) { const TilesMDLearn::Opinfo *a = (const TilesMDLearn::Opinfo *) _a; const TilesMDLearn::Opinfo *b = (const TilesMDLearn::Opinfo *) _b; double aprob = (double) a->ndec / (double) (a->nother + a->ndec); double bprob = (double) b->ndec / (double) (b->nother + b->ndec); if (aprob > bprob) return -1; return 1; } void TilesMDLearn::sortops(void) { for (unsigned int d = 0; d < ops.size(); d++) { for (unsigned int i = 0; i < Ntiles; i++) std::sort(ops[d][i].mvs.begin(), ops[d][i].mvs.begin() + ops[d][i].n); initdests(d); } } <|endoftext|>
<commit_before>//======================================================================= // Copyright Baptiste Wicht 2011. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) //======================================================================= #include <memory> #include <unordered_map> #include <boost/variant.hpp> #include "tac/IntelX86CodeGenerator.hpp" #include "AssemblyFileWriter.hpp" #include "FunctionContext.hpp" #include "il/Labels.hpp" using namespace eddic; tac::IntelX86CodeGenerator::IntelX86CodeGenerator(AssemblyFileWriter& w) : writer(w) {} namespace eddic { namespace tac { enum Register { EAX, EBX, ECX, EDX, ESP, //Extended stack pointer EBP, //Extended base pointer ESI, //Extended source index EDI, //Extended destination index REGISTER_COUNT }; std::string regToString(Register reg){ switch(reg){ case EAX: return "%eax"; case EBX: return "%ebx"; case ECX: return "%ecx"; case EDX: return "%edx"; case ESP: return "%esp"; case EBP: return "%ebp"; case ESI: return "%esi"; case EDI: return "%edi"; default: assert(false); //Not a register } } struct StatementCompiler : public boost::static_visitor<> { AssemblyFileWriter& writer; std::shared_ptr<tac::Function> function; std::unordered_map<std::shared_ptr<BasicBlock>, std::string> labels; std::shared_ptr<Variable> descriptors[Register::REGISTER_COUNT]; std::unordered_map<std::shared_ptr<Variable>, Register> variables; StatementCompiler(AssemblyFileWriter& w, std::shared_ptr<tac::Function> f) : writer(w), function(f) {} std::string arg(tac::Argument argument){ if(auto* ptr = boost::get<int>(&argument)){ return "$" + toString(*ptr); } else if(auto* ptr = boost::get<std::string>(&argument)){ return "$" + *ptr; } else if(auto* ptr = boost::get<std::shared_ptr<Variable>>(&argument)){ if(variables.find(*ptr) != variables.end()){ //The variables is already in a register return regToString(variables[*ptr]); } else { //The variable is not in a register return ""; } } assert(false); } void spills(Register reg){ //TODO Spills the content of the reg with the valid content } void operator()(std::shared_ptr<tac::Goto>& goto_){ writer.stream() << "goto " << labels[goto_->block] << std::endl; } void operator()(std::shared_ptr<tac::Param>& param){ writer.stream() << "pushl " << arg(param->arg) << std::endl; } void operator()(std::shared_ptr<tac::Call>& call){ writer.stream() << "call " << call->function << std::endl; if(call->params > 0){ writer.stream() << "addl " << call->params << ", %esp" << std::endl; } if(call->return_){ descriptors[Register::EAX] = call->return_; variables[call->return_] = Register::EAX; } if(call->return2_){ descriptors[Register::EBX] = call->return2_; variables[call->return2_] = Register::EBX; } } void operator()(std::shared_ptr<tac::Return>& return_){ //A return without args is the same as exiting from the function if(return_->arg1){ if(descriptors[Register::EAX]){ spills(Register::EAX); } writer.stream() << "movl " << arg(*return_->arg1) << ", %eax" << std::endl; if(return_->arg2){ if(descriptors[Register::EBX]){ spills(Register::EBX); } writer.stream() << "movl " << arg(*return_->arg2) << ", %ebx" << std::endl; } } if(function->context->size() > 0){ writer.stream() << "addl $" << function->context->size() << " , %esp" << std::endl; } writer.stream() << "leave" << std::endl; writer.stream() << "ret" << std::endl; } void operator()(std::shared_ptr<tac::Quadruple>& quadruple){ //TODO } void operator()(std::shared_ptr<tac::IfFalse>& ifFalse){ writer.stream() << "cmpl " << arg(ifFalse->arg1) << ", " << arg(ifFalse->arg2) << std::endl; switch(ifFalse->op){ case BinaryOperator::EQUALS: writer.stream() << "jne " << labels[ifFalse->block] << std::endl; break; case BinaryOperator::NOT_EQUALS: writer.stream() << "je " << labels[ifFalse->block] << std::endl; break; case BinaryOperator::LESS: writer.stream() << "jge " << labels[ifFalse->block] << std::endl; break; case BinaryOperator::LESS_EQUALS: writer.stream() << "jg " << labels[ifFalse->block] << std::endl; break; case BinaryOperator::GREATER: writer.stream() << "jle " << labels[ifFalse->block] << std::endl; break; case BinaryOperator::GREATER_EQUALS: writer.stream() << "jl " << labels[ifFalse->block] << std::endl; break; } } void operator()(std::string&){ assert(false); //There is no more label after the basic blocks have been extracted } }; }} void tac::IntelX86CodeGenerator::compile(std::shared_ptr<tac::BasicBlock> block, StatementCompiler& compiler){ std::string label = newLabel(); compiler.labels[block] = label; writer.stream() << label << ":" << std::endl; for(auto& statement : block->statements){ boost::apply_visitor(compiler, statement); } } bool updateLiveness(std::unordered_map<std::shared_ptr<Variable>, bool>& liveness, tac::Argument arg){ if(auto* variable = boost::get<std::shared_ptr<Variable>>(&arg)){ if(liveness.find(*variable) != liveness.end()){ if((*variable)->position().isGlobal()){ liveness[*variable] = true; } else { liveness[*variable] = false; } } bool live = liveness[*variable]; //variable is live liveness[*variable] = true; return live; } return false; } void tac::IntelX86CodeGenerator::computeLiveness(std::shared_ptr<tac::Function> function){ std::vector<std::shared_ptr<BasicBlock>>::reverse_iterator bit = function->getBasicBlocks().rbegin(); std::vector<std::shared_ptr<BasicBlock>>::reverse_iterator bend = function->getBasicBlocks().rend(); std::unordered_map<std::shared_ptr<Variable>, bool> liveness; while(bit != bend){ std::vector<tac::Statement>::reverse_iterator sit = (*bit)->statements.rbegin(); std::vector<tac::Statement>::reverse_iterator send = (*bit)->statements.rend(); while(sit != send){ auto statement = *sit; if(auto* ptr = boost::get<std::shared_ptr<tac::Param>>(&statement)){ (*ptr)->liveVariable = updateLiveness(liveness, (*ptr)->arg); } else if(auto* ptr = boost::get<std::shared_ptr<tac::Return>>(&statement)){ if((*ptr)->arg1){ (*ptr)->liveVariable1 = updateLiveness(liveness, (*(*ptr)->arg1)); } if((*ptr)->arg2){ (*ptr)->liveVariable2 = updateLiveness(liveness, (*(*ptr)->arg2)); } } else if(auto* ptr = boost::get<std::shared_ptr<tac::IfFalse>>(&statement)){ (*ptr)->liveVariable1 = updateLiveness(liveness, (*ptr)->arg1); (*ptr)->liveVariable2 = updateLiveness(liveness, (*ptr)->arg2); } else if(auto* ptr = boost::get<std::shared_ptr<tac::Quadruple>>(&statement)){ (*ptr)->liveVariable1 = updateLiveness(liveness, (*ptr)->arg1); if((*ptr)->arg2){ (*ptr)->liveVariable2 = updateLiveness(liveness, (*(*ptr)->arg2)); } (*ptr)->liveResult = liveness[(*ptr)->result]; liveness[(*ptr)->result] = false; } sit++; } bit++; } } void tac::IntelX86CodeGenerator::compile(std::shared_ptr<tac::Function> function){ computeLiveness(function); writer.stream() << std::endl << function->getName() << ":" << std::endl; writer.stream() << "pushl %ebp" << std::endl; writer.stream() << "movl %esp, %ebp" << std::endl; auto size = function->context->size(); //Only if necessary, allocates size on the stack for the local variables if(size > 0){ writer.stream() << "subl $" << size << " , %esp" << std::endl; } StatementCompiler compiler(writer, function); for(auto& block : function->getBasicBlocks()){ compile(block, compiler); } //Only if necessary, deallocates size on the stack for the local variables if(size > 0){ writer.stream() << "addl $" << size << " , %esp" << std::endl; } writer.stream() << "leave" << std::endl; writer.stream() << "ret" << std::endl; } void tac::IntelX86CodeGenerator::generate(tac::Program& program){ resetNumbering(); for(auto& function : program.functions){ compile(function); } } <commit_msg>Start implementing register allocation<commit_after>//======================================================================= // Copyright Baptiste Wicht 2011. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) //======================================================================= #include <memory> #include <unordered_map> #include <boost/variant.hpp> #include "tac/IntelX86CodeGenerator.hpp" #include "AssemblyFileWriter.hpp" #include "FunctionContext.hpp" #include "il/Labels.hpp" using namespace eddic; tac::IntelX86CodeGenerator::IntelX86CodeGenerator(AssemblyFileWriter& w) : writer(w) {} namespace eddic { namespace tac { enum Register { EAX, EBX, ECX, EDX, ESP, //Extended stack pointer EBP, //Extended base pointer ESI, //Extended source index EDI, //Extended destination index REGISTER_COUNT }; std::string regToString(Register reg){ switch(reg){ case EAX: return "%eax"; case EBX: return "%ebx"; case ECX: return "%ecx"; case EDX: return "%edx"; case ESP: return "%esp"; case EBP: return "%ebp"; case ESI: return "%esi"; case EDI: return "%edi"; default: assert(false); //Not a register } } struct StatementCompiler : public boost::static_visitor<> { AssemblyFileWriter& writer; std::shared_ptr<tac::Function> function; std::unordered_map<std::shared_ptr<BasicBlock>, std::string> labels; std::vector<Register> registers; std::shared_ptr<Variable> descriptors[Register::REGISTER_COUNT]; std::unordered_map<std::shared_ptr<Variable>, Register> variables; StatementCompiler(AssemblyFileWriter& w, std::shared_ptr<tac::Function> f) : writer(w), function(f) { registers = {EDI, ESI, ECX, EDX, EBX, EAX}; } void move(std::shared_ptr<Variable> variable, Register reg){ //TODO } std::string arg(tac::Argument argument){ if(auto* ptr = boost::get<int>(&argument)){ return "$" + toString(*ptr); } else if(auto* ptr = boost::get<std::string>(&argument)){ return "$" + *ptr; } else if(auto* ptr = boost::get<std::shared_ptr<Variable>>(&argument)){ if(variables.find(*ptr) != variables.end()){ //The variables is already in a register return regToString(variables[*ptr]); } else { //The variable is not in a register for(auto reg : registers){ //If the register is free if(!descriptors[reg]){ move(*ptr, reg); descriptors[reg] = *ptr; variables[*ptr] = reg; return regToString(reg); } } //There are no free register, take one auto reg = registers[0]; spills(reg); move(*ptr, reg); descriptors[reg] = *ptr; variables[*ptr] = reg; return regToString(reg); } } assert(false); } void spills(Register reg){ //TODO Spills the content of the reg with the valid content } void operator()(std::shared_ptr<tac::Goto>& goto_){ writer.stream() << "goto " << labels[goto_->block] << std::endl; } void operator()(std::shared_ptr<tac::Param>& param){ writer.stream() << "pushl " << arg(param->arg) << std::endl; } void operator()(std::shared_ptr<tac::Call>& call){ writer.stream() << "call " << call->function << std::endl; if(call->params > 0){ writer.stream() << "addl " << call->params << ", %esp" << std::endl; } if(call->return_){ descriptors[Register::EAX] = call->return_; variables[call->return_] = Register::EAX; } if(call->return2_){ descriptors[Register::EBX] = call->return2_; variables[call->return2_] = Register::EBX; } } void operator()(std::shared_ptr<tac::Return>& return_){ //A return without args is the same as exiting from the function if(return_->arg1){ if(descriptors[Register::EAX]){ spills(Register::EAX); } writer.stream() << "movl " << arg(*return_->arg1) << ", %eax" << std::endl; if(return_->arg2){ if(descriptors[Register::EBX]){ spills(Register::EBX); } writer.stream() << "movl " << arg(*return_->arg2) << ", %ebx" << std::endl; } } if(function->context->size() > 0){ writer.stream() << "addl $" << function->context->size() << " , %esp" << std::endl; } writer.stream() << "leave" << std::endl; writer.stream() << "ret" << std::endl; } void operator()(std::shared_ptr<tac::Quadruple>& quadruple){ //TODO } void operator()(std::shared_ptr<tac::IfFalse>& ifFalse){ writer.stream() << "cmpl " << arg(ifFalse->arg1) << ", " << arg(ifFalse->arg2) << std::endl; switch(ifFalse->op){ case BinaryOperator::EQUALS: writer.stream() << "jne " << labels[ifFalse->block] << std::endl; break; case BinaryOperator::NOT_EQUALS: writer.stream() << "je " << labels[ifFalse->block] << std::endl; break; case BinaryOperator::LESS: writer.stream() << "jge " << labels[ifFalse->block] << std::endl; break; case BinaryOperator::LESS_EQUALS: writer.stream() << "jg " << labels[ifFalse->block] << std::endl; break; case BinaryOperator::GREATER: writer.stream() << "jle " << labels[ifFalse->block] << std::endl; break; case BinaryOperator::GREATER_EQUALS: writer.stream() << "jl " << labels[ifFalse->block] << std::endl; break; } } void operator()(std::string&){ assert(false); //There is no more label after the basic blocks have been extracted } }; }} void tac::IntelX86CodeGenerator::compile(std::shared_ptr<tac::BasicBlock> block, StatementCompiler& compiler){ std::string label = newLabel(); compiler.labels[block] = label; writer.stream() << label << ":" << std::endl; for(auto& statement : block->statements){ boost::apply_visitor(compiler, statement); } //TODO End the basic block } bool updateLiveness(std::unordered_map<std::shared_ptr<Variable>, bool>& liveness, tac::Argument arg){ if(auto* variable = boost::get<std::shared_ptr<Variable>>(&arg)){ if(liveness.find(*variable) != liveness.end()){ if((*variable)->position().isGlobal()){ liveness[*variable] = true; } else { liveness[*variable] = false; } } bool live = liveness[*variable]; //variable is live liveness[*variable] = true; return live; } return false; } void tac::IntelX86CodeGenerator::computeLiveness(std::shared_ptr<tac::Function> function){ std::vector<std::shared_ptr<BasicBlock>>::reverse_iterator bit = function->getBasicBlocks().rbegin(); std::vector<std::shared_ptr<BasicBlock>>::reverse_iterator bend = function->getBasicBlocks().rend(); std::unordered_map<std::shared_ptr<Variable>, bool> liveness; while(bit != bend){ std::vector<tac::Statement>::reverse_iterator sit = (*bit)->statements.rbegin(); std::vector<tac::Statement>::reverse_iterator send = (*bit)->statements.rend(); while(sit != send){ auto statement = *sit; if(auto* ptr = boost::get<std::shared_ptr<tac::Param>>(&statement)){ (*ptr)->liveVariable = updateLiveness(liveness, (*ptr)->arg); } else if(auto* ptr = boost::get<std::shared_ptr<tac::Return>>(&statement)){ if((*ptr)->arg1){ (*ptr)->liveVariable1 = updateLiveness(liveness, (*(*ptr)->arg1)); } if((*ptr)->arg2){ (*ptr)->liveVariable2 = updateLiveness(liveness, (*(*ptr)->arg2)); } } else if(auto* ptr = boost::get<std::shared_ptr<tac::IfFalse>>(&statement)){ (*ptr)->liveVariable1 = updateLiveness(liveness, (*ptr)->arg1); (*ptr)->liveVariable2 = updateLiveness(liveness, (*ptr)->arg2); } else if(auto* ptr = boost::get<std::shared_ptr<tac::Quadruple>>(&statement)){ (*ptr)->liveVariable1 = updateLiveness(liveness, (*ptr)->arg1); if((*ptr)->arg2){ (*ptr)->liveVariable2 = updateLiveness(liveness, (*(*ptr)->arg2)); } (*ptr)->liveResult = liveness[(*ptr)->result]; liveness[(*ptr)->result] = false; } sit++; } bit++; } } void tac::IntelX86CodeGenerator::compile(std::shared_ptr<tac::Function> function){ computeLiveness(function); writer.stream() << std::endl << function->getName() << ":" << std::endl; writer.stream() << "pushl %ebp" << std::endl; writer.stream() << "movl %esp, %ebp" << std::endl; auto size = function->context->size(); //Only if necessary, allocates size on the stack for the local variables if(size > 0){ writer.stream() << "subl $" << size << " , %esp" << std::endl; } StatementCompiler compiler(writer, function); for(auto& block : function->getBasicBlocks()){ compile(block, compiler); } //Only if necessary, deallocates size on the stack for the local variables if(size > 0){ writer.stream() << "addl $" << size << " , %esp" << std::endl; } writer.stream() << "leave" << std::endl; writer.stream() << "ret" << std::endl; } void tac::IntelX86CodeGenerator::generate(tac::Program& program){ resetNumbering(); for(auto& function : program.functions){ compile(function); } } <|endoftext|>
<commit_before>#include "metatype_p.h" #include "metatype.h" #include <ostream> #include <mutex> #include <vector> #include <array> #include <unordered_map> namespace rtti { namespace { #define DEFINE_STATIC_TYPE_INFO(NAME, TYPEID) \ TypeInfo{CString{#NAME}, sizeof(NAME), MetaType_ID{TYPEID}, MetaType_ID{TYPEID}, type_flags<NAME>::value}, static constexpr std::array<TypeInfo, 41> fundamentalTypes = { TypeInfo{CString{"void"}, 0, MetaType_ID{0}, MetaType_ID{0}, type_flags<void>::value}, FOR_EACH_FUNDAMENTAL_TYPE(DEFINE_STATIC_TYPE_INFO) }; #undef DEFINE_STATIC_TYPE_INFO class DLL_LOCAL CustomTypes { public: CustomTypes(); CustomTypes(const CustomTypes &) = delete; CustomTypes& operator=(const CustomTypes &) = delete; CustomTypes(CustomTypes &&) = delete; CustomTypes& operator=(CustomTypes &&) = delete; ~CustomTypes() noexcept; const TypeInfo* getTypeInfo(MetaType_ID typeId) const; const TypeInfo* getTypeInfo(const char *name) const; MetaType_ID addTypeInfo(const char *name, unsigned int size, MetaType_ID decay, MetaType::TypeFlags flags); private: mutable std::mutex m_lock; std::vector<TypeInfo> m_items; std::unordered_map<CString, std::size_t> m_names; }; #define DEFINE_STATIC_TYPE_MAP(NAME, INDEX) \ {CString{#NAME}, INDEX}, CustomTypes::CustomTypes() : m_names { {CString{"void"}, 0}, FOR_EACH_FUNDAMENTAL_TYPE(DEFINE_STATIC_TYPE_MAP) } {} #undef DEFINE_STATIC_TYPE_MAP CustomTypes::~CustomTypes() noexcept { std::lock_guard<std::mutex> lock{m_lock}; m_items.clear(); m_names.clear(); } const TypeInfo* CustomTypes::getTypeInfo(MetaType_ID typeId) const { auto type = typeId.value(); if (type == MetaType::InvalidTypeId) return nullptr; if (type < fundamentalTypes.size()) return &fundamentalTypes[type]; type -= fundamentalTypes.size(); std::lock_guard<std::mutex> lock{m_lock}; if (type < m_items.size()) return &m_items[type]; return nullptr; } const TypeInfo* CustomTypes::getTypeInfo(const char *name) const { if (!name) return nullptr; auto temp = CString{name}; std::lock_guard<std::mutex> lock{m_lock}; auto search = m_names.find(temp); if (search != std::end(m_names)) { auto index = search->second; if (index < fundamentalTypes.size()) return &fundamentalTypes[index]; index -= fundamentalTypes.size(); if (index < m_items.size()) return &m_items[index]; } return nullptr; } inline MetaType_ID CustomTypes::addTypeInfo(const char *name, unsigned int size, MetaType_ID decay, MetaType::TypeFlags flags) { std::lock_guard<std::mutex> lock{m_lock}; MetaType_ID::type result = fundamentalTypes.size() + m_items.size(); // this means that decay_t<type> = type if (decay.value() == MetaType::InvalidTypeId) decay = MetaType_ID{result}; auto temp = CString{name}; m_items.emplace_back(temp, size, MetaType_ID{result}, decay, flags); m_names.emplace(std::move(temp), result); return MetaType_ID{result}; } static inline CustomTypes& customTypes() { static CustomTypes result; return result; } } // namespace //-------------------------------------------------------------------------------------------------------------------------------- // MetaType //-------------------------------------------------------------------------------------------------------------------------------- MetaType::MetaType(MetaType_ID typeId) : m_typeInfo(customTypes().getTypeInfo(typeId)) {} rtti::MetaType::MetaType(const char *name) : m_typeInfo(customTypes().getTypeInfo(name)) {} MetaType_ID MetaType::typeId() const noexcept { if (m_typeInfo) return m_typeInfo->type; return MetaType_ID{}; } MetaType_ID MetaType::decayId() const noexcept { if (m_typeInfo) return m_typeInfo->decay; return MetaType_ID{}; } void MetaType::setTypeId(MetaType_ID typeId) { *this = MetaType{typeId}; } const char* MetaType::typeName() const noexcept { if (m_typeInfo) return m_typeInfo->name.data(); return nullptr; } std::size_t MetaType::typeSize() const noexcept { if (m_typeInfo) return m_typeInfo->size; return 0; } MetaType::TypeFlags MetaType::typeFlags() const noexcept { MetaType::TypeFlags result = TypeFlags::None; if (m_typeInfo) result = m_typeInfo->flags; return result; } MetaType_ID MetaType::registerMetaType(const char *name, unsigned int size, MetaType_ID decay, MetaType::TypeFlags flags) { return customTypes().addTypeInfo(name, size, decay, flags); } //-------------------------------------------------------------------------------------------------------------------------------- // Converter //-------------------------------------------------------------------------------------------------------------------------------- namespace { template<typename F> class MetaTypeFunctionList { public: using key_t = std::pair<MetaType_ID, MetaType_ID>; ~MetaTypeFunctionList() noexcept { std::lock_guard<std::mutex> lock{m_lock}; m_items.clear(); Destroyed = true; } bool find(const key_t &key) const { std::lock_guard<std::mutex> lock{m_lock}; return (m_items.find(key) != std::end(m_items)); } bool add(key_t key, const F *func) { if (!func) return false; std::lock_guard<std::mutex> lock{m_lock}; auto search = m_items.find(key); if (search != std::end(m_items)) return false; m_items.emplace(key, func); return true; } const F* get(const key_t &key) const { std::lock_guard<std::mutex> lock{m_lock}; auto search = m_items.find(key); if (search != std::end(m_items)) return search->second; return nullptr; } void remove(const key_t &key) { std::lock_guard<std::mutex> lock{m_lock}; m_items.erase(key); } private: struct hash_key { using result_type = std::size_t; using argument_type = key_t; result_type operator()(const argument_type &key) const { return std::_Hash_impl::__hash_combine(key.first.value(), std::_Hash_impl::hash(key.second.value())); } }; mutable std::mutex m_lock; std::unordered_map<key_t, const F*, hash_key> m_items; static bool Destroyed; friend MetaTypeFunctionList<internal::ConvertFunctionBase>* customConverters(); }; template<typename F> bool MetaTypeFunctionList<F>::Destroyed = false; static inline MetaTypeFunctionList<internal::ConvertFunctionBase>* customConverters() { if (MetaTypeFunctionList<internal::ConvertFunctionBase>::Destroyed) return nullptr; static MetaTypeFunctionList<internal::ConvertFunctionBase> result; return &result; } } //namespace bool MetaType::hasConverter(MetaType_ID fromTypeId, MetaType_ID toTypeId) { if (fromTypeId.value() == InvalidTypeId || toTypeId.value() == InvalidTypeId) return false; auto fromType = MetaType{fromTypeId}; auto toType = MetaType{toTypeId}; if (fromType.valid() && toType.valid()) { auto list = customConverters(); if (list) return list->find({fromType.m_typeInfo->decay, toType.m_typeInfo->decay}); } return false; } bool MetaType::registerConverter(MetaType_ID fromTypeId, MetaType_ID toTypeId, const internal::ConvertFunctionBase &converter) { if (fromTypeId.value() == InvalidTypeId || toTypeId.value() == InvalidTypeId) return false; auto fromType = MetaType{fromTypeId}; auto toType = MetaType{toTypeId}; if (fromType.valid() && toType.valid()) { auto list = customConverters(); if (list) return list->add({fromType.m_typeInfo->decay, toType.m_typeInfo->decay}, &converter); } return false; } bool MetaType::convert(const void *from, MetaType_ID fromTypeId, void *to, MetaType_ID toTypeId) { if (fromTypeId.value() == InvalidTypeId || toTypeId.value() == InvalidTypeId) return false; auto fromType = MetaType{fromTypeId}; auto toType = MetaType{toTypeId}; if (fromType.valid() && toType.valid()) { auto list = customConverters(); if (list) { auto converter = list->get({fromType.m_typeInfo->decay, toType.m_typeInfo->decay}); if (converter) return converter->invoke(from, to); } } return false; } void MetaType::unregisterConverter(MetaType_ID fromTypeId, MetaType_ID toTypeId) { if (fromTypeId.value() == InvalidTypeId || toTypeId.value() == InvalidTypeId) return; auto fromType = MetaType{fromTypeId}; auto toType = MetaType{toTypeId}; if (fromType.valid() && toType.valid()) { auto list = customConverters(); if (list) list->remove({fromType.m_typeInfo->decay, toType.m_typeInfo->decay}); } } } //namespace rtti std::ostream& operator<<(std::ostream &stream, const rtti::MetaType &value) { return stream << value.typeId().value() << ":" << value.typeName() << ":" << value.typeFlags(); } <commit_msg>remove unnecessary checks<commit_after>#include "metatype_p.h" #include "metatype.h" #include <ostream> #include <mutex> #include <vector> #include <array> #include <unordered_map> namespace rtti { namespace { #define DEFINE_STATIC_TYPE_INFO(NAME, TYPEID) \ TypeInfo{CString{#NAME}, sizeof(NAME), MetaType_ID{TYPEID}, MetaType_ID{TYPEID}, type_flags<NAME>::value}, static constexpr std::array<TypeInfo, 41> fundamentalTypes = { TypeInfo{CString{"void"}, 0, MetaType_ID{0}, MetaType_ID{0}, type_flags<void>::value}, FOR_EACH_FUNDAMENTAL_TYPE(DEFINE_STATIC_TYPE_INFO) }; #undef DEFINE_STATIC_TYPE_INFO class DLL_LOCAL CustomTypes { public: CustomTypes(); CustomTypes(const CustomTypes &) = delete; CustomTypes& operator=(const CustomTypes &) = delete; CustomTypes(CustomTypes &&) = delete; CustomTypes& operator=(CustomTypes &&) = delete; ~CustomTypes() noexcept; const TypeInfo* getTypeInfo(MetaType_ID typeId) const; const TypeInfo* getTypeInfo(const char *name) const; MetaType_ID addTypeInfo(const char *name, unsigned int size, MetaType_ID decay, MetaType::TypeFlags flags); private: mutable std::mutex m_lock; std::vector<TypeInfo> m_items; std::unordered_map<CString, std::size_t> m_names; }; #define DEFINE_STATIC_TYPE_MAP(NAME, INDEX) \ {CString{#NAME}, INDEX}, CustomTypes::CustomTypes() : m_names { {CString{"void"}, 0}, FOR_EACH_FUNDAMENTAL_TYPE(DEFINE_STATIC_TYPE_MAP) } {} #undef DEFINE_STATIC_TYPE_MAP CustomTypes::~CustomTypes() noexcept { std::lock_guard<std::mutex> lock{m_lock}; m_items.clear(); m_names.clear(); } const TypeInfo* CustomTypes::getTypeInfo(MetaType_ID typeId) const { auto type = typeId.value(); if (type == MetaType::InvalidTypeId) return nullptr; if (type < fundamentalTypes.size()) return &fundamentalTypes[type]; type -= fundamentalTypes.size(); std::lock_guard<std::mutex> lock{m_lock}; if (type < m_items.size()) return &m_items[type]; return nullptr; } const TypeInfo* CustomTypes::getTypeInfo(const char *name) const { if (!name) return nullptr; auto temp = CString{name}; std::lock_guard<std::mutex> lock{m_lock}; auto search = m_names.find(temp); if (search != std::end(m_names)) { auto index = search->second; if (index < fundamentalTypes.size()) return &fundamentalTypes[index]; index -= fundamentalTypes.size(); if (index < m_items.size()) return &m_items[index]; } return nullptr; } inline MetaType_ID CustomTypes::addTypeInfo(const char *name, unsigned int size, MetaType_ID decay, MetaType::TypeFlags flags) { std::lock_guard<std::mutex> lock{m_lock}; MetaType_ID::type result = fundamentalTypes.size() + m_items.size(); // this means that decay_t<type> = type if (decay.value() == MetaType::InvalidTypeId) decay = MetaType_ID{result}; auto temp = CString{name}; m_items.emplace_back(temp, size, MetaType_ID{result}, decay, flags); m_names.emplace(std::move(temp), result); return MetaType_ID{result}; } static inline CustomTypes& customTypes() { static CustomTypes result; return result; } } // namespace //-------------------------------------------------------------------------------------------------------------------------------- // MetaType //-------------------------------------------------------------------------------------------------------------------------------- MetaType::MetaType(MetaType_ID typeId) : m_typeInfo(customTypes().getTypeInfo(typeId)) {} rtti::MetaType::MetaType(const char *name) : m_typeInfo(customTypes().getTypeInfo(name)) {} MetaType_ID MetaType::typeId() const noexcept { if (m_typeInfo) return m_typeInfo->type; return MetaType_ID{}; } MetaType_ID MetaType::decayId() const noexcept { if (m_typeInfo) return m_typeInfo->decay; return MetaType_ID{}; } void MetaType::setTypeId(MetaType_ID typeId) { *this = MetaType{typeId}; } const char* MetaType::typeName() const noexcept { if (m_typeInfo) return m_typeInfo->name.data(); return nullptr; } std::size_t MetaType::typeSize() const noexcept { if (m_typeInfo) return m_typeInfo->size; return 0; } MetaType::TypeFlags MetaType::typeFlags() const noexcept { MetaType::TypeFlags result = TypeFlags::None; if (m_typeInfo) result = m_typeInfo->flags; return result; } MetaType_ID MetaType::registerMetaType(const char *name, unsigned int size, MetaType_ID decay, MetaType::TypeFlags flags) { return customTypes().addTypeInfo(name, size, decay, flags); } //-------------------------------------------------------------------------------------------------------------------------------- // Converter //-------------------------------------------------------------------------------------------------------------------------------- namespace { template<typename F> class MetaTypeFunctionList { public: using key_t = std::pair<MetaType_ID, MetaType_ID>; ~MetaTypeFunctionList() noexcept { std::lock_guard<std::mutex> lock{m_lock}; m_items.clear(); Destroyed = true; } bool find(const key_t &key) const { std::lock_guard<std::mutex> lock{m_lock}; return (m_items.find(key) != std::end(m_items)); } bool add(key_t key, const F *func) { if (!func) return false; std::lock_guard<std::mutex> lock{m_lock}; auto search = m_items.find(key); if (search != std::end(m_items)) return false; m_items.emplace(key, func); return true; } const F* get(const key_t &key) const { std::lock_guard<std::mutex> lock{m_lock}; auto search = m_items.find(key); if (search != std::end(m_items)) return search->second; return nullptr; } void remove(const key_t &key) { std::lock_guard<std::mutex> lock{m_lock}; m_items.erase(key); } private: struct hash_key { using result_type = std::size_t; using argument_type = key_t; result_type operator()(const argument_type &key) const { return std::_Hash_impl::__hash_combine(key.first.value(), std::_Hash_impl::hash(key.second.value())); } }; mutable std::mutex m_lock; std::unordered_map<key_t, const F*, hash_key> m_items; static bool Destroyed; friend MetaTypeFunctionList<internal::ConvertFunctionBase>* customConverters(); }; template<typename F> bool MetaTypeFunctionList<F>::Destroyed = false; static inline MetaTypeFunctionList<internal::ConvertFunctionBase>* customConverters() { if (MetaTypeFunctionList<internal::ConvertFunctionBase>::Destroyed) return nullptr; static MetaTypeFunctionList<internal::ConvertFunctionBase> result; return &result; } } //namespace bool MetaType::hasConverter(MetaType_ID fromTypeId, MetaType_ID toTypeId) { auto fromType = MetaType{fromTypeId}; auto toType = MetaType{toTypeId}; if (fromType.valid() && toType.valid()) { auto list = customConverters(); if (list) return list->find({fromType.m_typeInfo->decay, toType.m_typeInfo->decay}); } return false; } bool MetaType::registerConverter(MetaType_ID fromTypeId, MetaType_ID toTypeId, const internal::ConvertFunctionBase &converter) { auto fromType = MetaType{fromTypeId}; auto toType = MetaType{toTypeId}; if (fromType.valid() && toType.valid()) { auto list = customConverters(); if (list) return list->add({fromType.m_typeInfo->decay, toType.m_typeInfo->decay}, &converter); } return false; } bool MetaType::convert(const void *from, MetaType_ID fromTypeId, void *to, MetaType_ID toTypeId) { auto fromType = MetaType{fromTypeId}; auto toType = MetaType{toTypeId}; if (fromType.valid() && toType.valid()) { auto list = customConverters(); if (list) { auto converter = list->get({fromType.m_typeInfo->decay, toType.m_typeInfo->decay}); if (converter) return converter->invoke(from, to); } } return false; } void MetaType::unregisterConverter(MetaType_ID fromTypeId, MetaType_ID toTypeId) { auto fromType = MetaType{fromTypeId}; auto toType = MetaType{toTypeId}; if (fromType.valid() && toType.valid()) { auto list = customConverters(); if (list) list->remove({fromType.m_typeInfo->decay, toType.m_typeInfo->decay}); } } } //namespace rtti std::ostream& operator<<(std::ostream &stream, const rtti::MetaType &value) { return stream << value.typeId().value() << ":" << value.typeName() << ":" << value.typeFlags(); } <|endoftext|>
<commit_before>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation (info@qt.nokia.com) ** ** ** GNU Lesser General Public License Usage ** ** 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. ** ** Other Usage ** ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** If you have questions regarding the use of this file, please contact ** Nokia at info@qt.nokia.com. ** **************************************************************************/ #include "toolchainmanager.h" #include "toolchain.h" #include <coreplugin/icore.h> #include <projectexplorer/persistentsettings.h> #include <extensionsystem/pluginmanager.h> #include <QtCore/QCoreApplication> #include <QtCore/QDir> #include <QtCore/QSettings> #include <QtGui/QMainWindow> static const char TOOLCHAIN_DATA_KEY[] = "ToolChain."; static const char TOOLCHAIN_COUNT_KEY[] = "ToolChain.Count"; static const char TOOLCHAIN_FILE_VERSION_KEY[] = "Version"; static const char DEFAULT_DEBUGGER_COUNT_KEY[] = "DefaultDebugger.Count"; static const char DEFAULT_DEBUGGER_ABI_KEY[] = "DefaultDebugger.Abi."; static const char DEFAULT_DEBUGGER_PATH_KEY[] = "DefaultDebugger.Path."; static const char TOOLCHAIN_FILENAME[] = "/toolChains.xml"; static QString settingsFileName() { ExtensionSystem::PluginManager *pm = ExtensionSystem::PluginManager::instance(); QFileInfo settingsLocation(pm->settings()->fileName()); return settingsLocation.absolutePath() + QLatin1String(TOOLCHAIN_FILENAME); } namespace ProjectExplorer { ToolChainManager *ToolChainManager::m_instance = 0; namespace Internal { // -------------------------------------------------------------------------- // ToolChainManagerPrivate // -------------------------------------------------------------------------- class ToolChainManagerPrivate { public: QList<ToolChain *> m_toolChains; QMap<QString, QString> m_abiToDebugger; }; } // namespace Internal // -------------------------------------------------------------------------- // ToolChainManager // -------------------------------------------------------------------------- ToolChainManager *ToolChainManager::instance() { Q_ASSERT(m_instance); return m_instance; } ToolChainManager::ToolChainManager(QObject *parent) : QObject(parent), m_d(new Internal::ToolChainManagerPrivate) { Q_ASSERT(!m_instance); m_instance = this; connect(Core::ICore::instance(), SIGNAL(saveSettingsRequested()), this, SLOT(saveToolChains())); connect(this, SIGNAL(toolChainAdded(ProjectExplorer::ToolChain*)), this, SIGNAL(toolChainsChanged())); connect(this, SIGNAL(toolChainRemoved(ProjectExplorer::ToolChain*)), this, SIGNAL(toolChainsChanged())); connect(this, SIGNAL(toolChainUpdated(ProjectExplorer::ToolChain*)), this, SIGNAL(toolChainsChanged())); } void ToolChainManager::restoreToolChains() { // Restore SDK settings first restoreToolChains(Core::ICore::instance()->resourcePath() + QLatin1String("/Nokia") + QLatin1String(TOOLCHAIN_FILENAME), true); // Then auto detect ExtensionSystem::PluginManager *pm = ExtensionSystem::PluginManager::instance(); QList<ToolChainFactory *> factories = pm->getObjects<ToolChainFactory>(); // Autodetect tool chains: foreach (ToolChainFactory *f, factories) { QList<ToolChain *> tcs = f->autoDetect(); foreach (ToolChain *tc, tcs) registerToolChain(tc); } // Then restore user settings restoreToolChains(settingsFileName(), false); } ToolChainManager::~ToolChainManager() { // Deregister tool chains QList<ToolChain *> copy = m_d->m_toolChains; foreach (ToolChain *tc, copy) deregisterToolChain(tc); delete m_d; m_instance = 0; } void ToolChainManager::saveToolChains() { PersistentSettingsWriter writer; writer.saveValue(QLatin1String(TOOLCHAIN_FILE_VERSION_KEY), 1); int count = 0; foreach (ToolChain *tc, m_d->m_toolChains) { if (!tc->isAutoDetected() && tc->isValid()) { QVariantMap tmp = tc->toMap(); if (tmp.isEmpty()) continue; writer.saveValue(QString::fromLatin1(TOOLCHAIN_DATA_KEY) + QString::number(count), tmp); ++count; } } writer.saveValue(QLatin1String(TOOLCHAIN_COUNT_KEY), count); writer.save(settingsFileName(), "QtCreatorToolChains", Core::ICore::instance()->mainWindow()); // Do not save default debuggers! Those are set by the SDK! } void ToolChainManager::restoreToolChains(const QString &fileName, bool autoDetected) { PersistentSettingsReader reader; if (!reader.load(fileName)) return; QVariantMap data = reader.restoreValues(); // Check version: int version = data.value(QLatin1String(TOOLCHAIN_FILE_VERSION_KEY), 0).toInt(); if (version < 1) return; // Read default debugger settings (if any) int count = data.value(QLatin1String(DEFAULT_DEBUGGER_COUNT_KEY)).toInt(); for (int i = 0; i < count; ++i) { const QString abiKey = QString::fromLatin1(DEFAULT_DEBUGGER_ABI_KEY) + QString::number(i); if (!data.contains(abiKey)) continue; const QString pathKey = QString::fromLatin1(DEFAULT_DEBUGGER_PATH_KEY) + QString::number(i); if (!data.contains(abiKey)) continue; m_d->m_abiToDebugger.insert(data.value(abiKey).toString(), data.value(pathKey).toString()); } ExtensionSystem::PluginManager *pm = ExtensionSystem::PluginManager::instance(); QList<ToolChainFactory *> factories = pm->getObjects<ToolChainFactory>(); count = data.value(QLatin1String(TOOLCHAIN_COUNT_KEY), 0).toInt(); for (int i = 0; i < count; ++i) { const QString key = QString::fromLatin1(TOOLCHAIN_DATA_KEY) + QString::number(i); if (!data.contains(key)) break; const QVariantMap tcMap = data.value(key).toMap(); bool restored = false; foreach (ToolChainFactory *f, factories) { if (f->canRestore(tcMap)) { if (ToolChain *tc = f->restore(tcMap)) { tc->setAutoDetected(autoDetected); registerToolChain(tc); restored = true; break; } } } if (!restored) qWarning("Warning: Unable to restore manual tool chain '%s' stored in %s.", qPrintable(ToolChainFactory::idFromMap(tcMap)), qPrintable(QDir::toNativeSeparators(fileName))); } } QList<ToolChain *> ToolChainManager::toolChains() const { return m_d->m_toolChains; } QList<ToolChain *> ToolChainManager::findToolChains(const Abi &abi) const { QList<ToolChain *> result; foreach (ToolChain *tc, m_d->m_toolChains) { Abi targetAbi = tc->targetAbi(); if (targetAbi.isCompatibleWith(abi)) result.append(tc); } return result; } ToolChain *ToolChainManager::findToolChain(const QString &id) const { foreach (ToolChain *tc, m_d->m_toolChains) { if (tc->id() == id) return tc; } return 0; } QString ToolChainManager::defaultDebugger(const Abi &abi) const { return m_d->m_abiToDebugger.value(abi.toString()); } void ToolChainManager::notifyAboutUpdate(ProjectExplorer::ToolChain *tc) { if (!tc || !m_d->m_toolChains.contains(tc)) return; emit toolChainUpdated(tc); } bool ToolChainManager::registerToolChain(ToolChain *tc) { if (!tc || m_d->m_toolChains.contains(tc)) return true; foreach (ToolChain *current, m_d->m_toolChains) { if (*tc == *current) return false; } m_d->m_toolChains.append(tc); emit toolChainAdded(tc); return true; } void ToolChainManager::deregisterToolChain(ToolChain *tc) { if (!tc || !m_d->m_toolChains.contains(tc)) return; m_d->m_toolChains.removeOne(tc); emit toolChainRemoved(tc); delete tc; } } // namespace ProjectExplorer <commit_msg>Fix copy and paste error<commit_after>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation (info@qt.nokia.com) ** ** ** GNU Lesser General Public License Usage ** ** 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. ** ** Other Usage ** ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** If you have questions regarding the use of this file, please contact ** Nokia at info@qt.nokia.com. ** **************************************************************************/ #include "toolchainmanager.h" #include "toolchain.h" #include <coreplugin/icore.h> #include <projectexplorer/persistentsettings.h> #include <extensionsystem/pluginmanager.h> #include <QtCore/QCoreApplication> #include <QtCore/QDir> #include <QtCore/QSettings> #include <QtGui/QMainWindow> static const char TOOLCHAIN_DATA_KEY[] = "ToolChain."; static const char TOOLCHAIN_COUNT_KEY[] = "ToolChain.Count"; static const char TOOLCHAIN_FILE_VERSION_KEY[] = "Version"; static const char DEFAULT_DEBUGGER_COUNT_KEY[] = "DefaultDebugger.Count"; static const char DEFAULT_DEBUGGER_ABI_KEY[] = "DefaultDebugger.Abi."; static const char DEFAULT_DEBUGGER_PATH_KEY[] = "DefaultDebugger.Path."; static const char TOOLCHAIN_FILENAME[] = "/toolChains.xml"; static QString settingsFileName() { ExtensionSystem::PluginManager *pm = ExtensionSystem::PluginManager::instance(); QFileInfo settingsLocation(pm->settings()->fileName()); return settingsLocation.absolutePath() + QLatin1String(TOOLCHAIN_FILENAME); } namespace ProjectExplorer { ToolChainManager *ToolChainManager::m_instance = 0; namespace Internal { // -------------------------------------------------------------------------- // ToolChainManagerPrivate // -------------------------------------------------------------------------- class ToolChainManagerPrivate { public: QList<ToolChain *> m_toolChains; QMap<QString, QString> m_abiToDebugger; }; } // namespace Internal // -------------------------------------------------------------------------- // ToolChainManager // -------------------------------------------------------------------------- ToolChainManager *ToolChainManager::instance() { Q_ASSERT(m_instance); return m_instance; } ToolChainManager::ToolChainManager(QObject *parent) : QObject(parent), m_d(new Internal::ToolChainManagerPrivate) { Q_ASSERT(!m_instance); m_instance = this; connect(Core::ICore::instance(), SIGNAL(saveSettingsRequested()), this, SLOT(saveToolChains())); connect(this, SIGNAL(toolChainAdded(ProjectExplorer::ToolChain*)), this, SIGNAL(toolChainsChanged())); connect(this, SIGNAL(toolChainRemoved(ProjectExplorer::ToolChain*)), this, SIGNAL(toolChainsChanged())); connect(this, SIGNAL(toolChainUpdated(ProjectExplorer::ToolChain*)), this, SIGNAL(toolChainsChanged())); } void ToolChainManager::restoreToolChains() { // Restore SDK settings first restoreToolChains(Core::ICore::instance()->resourcePath() + QLatin1String("/Nokia") + QLatin1String(TOOLCHAIN_FILENAME), true); // Then auto detect ExtensionSystem::PluginManager *pm = ExtensionSystem::PluginManager::instance(); QList<ToolChainFactory *> factories = pm->getObjects<ToolChainFactory>(); // Autodetect tool chains: foreach (ToolChainFactory *f, factories) { QList<ToolChain *> tcs = f->autoDetect(); foreach (ToolChain *tc, tcs) registerToolChain(tc); } // Then restore user settings restoreToolChains(settingsFileName(), false); } ToolChainManager::~ToolChainManager() { // Deregister tool chains QList<ToolChain *> copy = m_d->m_toolChains; foreach (ToolChain *tc, copy) deregisterToolChain(tc); delete m_d; m_instance = 0; } void ToolChainManager::saveToolChains() { PersistentSettingsWriter writer; writer.saveValue(QLatin1String(TOOLCHAIN_FILE_VERSION_KEY), 1); int count = 0; foreach (ToolChain *tc, m_d->m_toolChains) { if (!tc->isAutoDetected() && tc->isValid()) { QVariantMap tmp = tc->toMap(); if (tmp.isEmpty()) continue; writer.saveValue(QString::fromLatin1(TOOLCHAIN_DATA_KEY) + QString::number(count), tmp); ++count; } } writer.saveValue(QLatin1String(TOOLCHAIN_COUNT_KEY), count); writer.save(settingsFileName(), "QtCreatorToolChains", Core::ICore::instance()->mainWindow()); // Do not save default debuggers! Those are set by the SDK! } void ToolChainManager::restoreToolChains(const QString &fileName, bool autoDetected) { PersistentSettingsReader reader; if (!reader.load(fileName)) return; QVariantMap data = reader.restoreValues(); // Check version: int version = data.value(QLatin1String(TOOLCHAIN_FILE_VERSION_KEY), 0).toInt(); if (version < 1) return; // Read default debugger settings (if any) int count = data.value(QLatin1String(DEFAULT_DEBUGGER_COUNT_KEY)).toInt(); for (int i = 0; i < count; ++i) { const QString abiKey = QString::fromLatin1(DEFAULT_DEBUGGER_ABI_KEY) + QString::number(i); if (!data.contains(abiKey)) continue; const QString pathKey = QString::fromLatin1(DEFAULT_DEBUGGER_PATH_KEY) + QString::number(i); if (!data.contains(pathKey)) continue; m_d->m_abiToDebugger.insert(data.value(abiKey).toString(), data.value(pathKey).toString()); } ExtensionSystem::PluginManager *pm = ExtensionSystem::PluginManager::instance(); QList<ToolChainFactory *> factories = pm->getObjects<ToolChainFactory>(); count = data.value(QLatin1String(TOOLCHAIN_COUNT_KEY), 0).toInt(); for (int i = 0; i < count; ++i) { const QString key = QString::fromLatin1(TOOLCHAIN_DATA_KEY) + QString::number(i); if (!data.contains(key)) break; const QVariantMap tcMap = data.value(key).toMap(); bool restored = false; foreach (ToolChainFactory *f, factories) { if (f->canRestore(tcMap)) { if (ToolChain *tc = f->restore(tcMap)) { tc->setAutoDetected(autoDetected); registerToolChain(tc); restored = true; break; } } } if (!restored) qWarning("Warning: Unable to restore manual tool chain '%s' stored in %s.", qPrintable(ToolChainFactory::idFromMap(tcMap)), qPrintable(QDir::toNativeSeparators(fileName))); } } QList<ToolChain *> ToolChainManager::toolChains() const { return m_d->m_toolChains; } QList<ToolChain *> ToolChainManager::findToolChains(const Abi &abi) const { QList<ToolChain *> result; foreach (ToolChain *tc, m_d->m_toolChains) { Abi targetAbi = tc->targetAbi(); if (targetAbi.isCompatibleWith(abi)) result.append(tc); } return result; } ToolChain *ToolChainManager::findToolChain(const QString &id) const { foreach (ToolChain *tc, m_d->m_toolChains) { if (tc->id() == id) return tc; } return 0; } QString ToolChainManager::defaultDebugger(const Abi &abi) const { return m_d->m_abiToDebugger.value(abi.toString()); } void ToolChainManager::notifyAboutUpdate(ProjectExplorer::ToolChain *tc) { if (!tc || !m_d->m_toolChains.contains(tc)) return; emit toolChainUpdated(tc); } bool ToolChainManager::registerToolChain(ToolChain *tc) { if (!tc || m_d->m_toolChains.contains(tc)) return true; foreach (ToolChain *current, m_d->m_toolChains) { if (*tc == *current) return false; } m_d->m_toolChains.append(tc); emit toolChainAdded(tc); return true; } void ToolChainManager::deregisterToolChain(ToolChain *tc) { if (!tc || !m_d->m_toolChains.contains(tc)) return; m_d->m_toolChains.removeOne(tc); emit toolChainRemoved(tc); delete tc; } } // namespace ProjectExplorer <|endoftext|>
<commit_before>// Copyright (c) 2020 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 <banman.h> #include <chainparams.h> #include <consensus/consensus.h> #include <net.h> #include <net_processing.h> #include <protocol.h> #include <scheduler.h> #include <script/script.h> #include <streams.h> #include <test/fuzz/FuzzedDataProvider.h> #include <test/fuzz/fuzz.h> #include <test/fuzz/util.h> #include <test/util/mining.h> #include <test/util/net.h> #include <test/util/setup_common.h> #include <test/util/validation.h> #include <util/memory.h> #include <validationinterface.h> #include <version.h> #include <atomic> #include <cassert> #include <chrono> #include <cstdint> #include <iosfwd> #include <iostream> #include <memory> #include <string> namespace { const TestingSetup* g_setup; } // namespace size_t& GetNumMsgTypes() { static size_t g_num_msg_types{0}; return g_num_msg_types; } #define FUZZ_TARGET_MSG(msg_type) \ struct msg_type##_Count_Before_Main { \ msg_type##_Count_Before_Main() \ { \ ++GetNumMsgTypes(); \ } \ } const static g_##msg_type##_count_before_main; \ FUZZ_TARGET_INIT(process_message_##msg_type, initialize_process_message) \ { \ fuzz_target(buffer, #msg_type); \ } void initialize_process_message() { Assert(GetNumMsgTypes() == getAllNetMessageTypes().size()); // If this fails, add or remove the message type below static const auto testing_setup = MakeFuzzingContext<const TestingSetup>(); g_setup = testing_setup.get(); for (int i = 0; i < 2 * COINBASE_MATURITY; i++) { MineBlock(g_setup->m_node, CScript() << OP_TRUE); } SyncWithValidationInterfaceQueue(); } void fuzz_target(FuzzBufferType buffer, const std::string& LIMIT_TO_MESSAGE_TYPE) { FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size()); ConnmanTestMsg& connman = *(ConnmanTestMsg*)g_setup->m_node.connman.get(); TestChainState& chainstate = *(TestChainState*)&g_setup->m_node.chainman->ActiveChainstate(); SetMockTime(1610000000); // any time to successfully reset ibd chainstate.ResetIbd(); const std::string random_message_type{fuzzed_data_provider.ConsumeBytesAsString(CMessageHeader::COMMAND_SIZE).c_str()}; if (!LIMIT_TO_MESSAGE_TYPE.empty() && random_message_type != LIMIT_TO_MESSAGE_TYPE) { return; } CNode& p2p_node = *ConsumeNodeAsUniquePtr(fuzzed_data_provider).release(); const bool successfully_connected{fuzzed_data_provider.ConsumeBool()}; p2p_node.fSuccessfullyConnected = successfully_connected; connman.AddTestNode(p2p_node); g_setup->m_node.peerman->InitializeNode(&p2p_node); FillNode(fuzzed_data_provider, p2p_node, /* init_version */ successfully_connected); const auto mock_time = ConsumeTime(fuzzed_data_provider); SetMockTime(mock_time); // fuzzed_data_provider is fully consumed after this call, don't use it CDataStream random_bytes_data_stream{fuzzed_data_provider.ConsumeRemainingBytes<unsigned char>(), SER_NETWORK, PROTOCOL_VERSION}; try { g_setup->m_node.peerman->ProcessMessage(p2p_node, random_message_type, random_bytes_data_stream, GetTime<std::chrono::microseconds>(), std::atomic<bool>{false}); } catch (const std::ios_base::failure&) { } { LOCK(p2p_node.cs_sendProcessing); g_setup->m_node.peerman->SendMessages(&p2p_node); } SyncWithValidationInterfaceQueue(); LOCK2(::cs_main, g_cs_orphans); // See init.cpp for rationale for implicit locking order requirement g_setup->m_node.connman->StopNodes(); } FUZZ_TARGET_INIT(process_message, initialize_process_message) { fuzz_target(buffer, ""); } FUZZ_TARGET_MSG(addr); FUZZ_TARGET_MSG(addrv2); FUZZ_TARGET_MSG(block); FUZZ_TARGET_MSG(blocktxn); FUZZ_TARGET_MSG(cfcheckpt); FUZZ_TARGET_MSG(cfheaders); FUZZ_TARGET_MSG(cfilter); FUZZ_TARGET_MSG(cmpctblock); FUZZ_TARGET_MSG(feefilter); FUZZ_TARGET_MSG(filteradd); FUZZ_TARGET_MSG(filterclear); FUZZ_TARGET_MSG(filterload); FUZZ_TARGET_MSG(getaddr); FUZZ_TARGET_MSG(getblocks); FUZZ_TARGET_MSG(getblocktxn); FUZZ_TARGET_MSG(getcfcheckpt); FUZZ_TARGET_MSG(getcfheaders); FUZZ_TARGET_MSG(getcfilters); FUZZ_TARGET_MSG(getdata); FUZZ_TARGET_MSG(getheaders); FUZZ_TARGET_MSG(headers); FUZZ_TARGET_MSG(inv); FUZZ_TARGET_MSG(mempool); FUZZ_TARGET_MSG(merkleblock); FUZZ_TARGET_MSG(notfound); FUZZ_TARGET_MSG(ping); FUZZ_TARGET_MSG(pong); FUZZ_TARGET_MSG(sendaddrv2); FUZZ_TARGET_MSG(sendcmpct); FUZZ_TARGET_MSG(sendheaders); FUZZ_TARGET_MSG(tx); FUZZ_TARGET_MSG(verack); FUZZ_TARGET_MSG(version); FUZZ_TARGET_MSG(wtxidrelay); <commit_msg>add mn fuzz target msgs<commit_after>// Copyright (c) 2020 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 <banman.h> #include <chainparams.h> #include <consensus/consensus.h> #include <net.h> #include <net_processing.h> #include <protocol.h> #include <scheduler.h> #include <script/script.h> #include <streams.h> #include <test/fuzz/FuzzedDataProvider.h> #include <test/fuzz/fuzz.h> #include <test/fuzz/util.h> #include <test/util/mining.h> #include <test/util/net.h> #include <test/util/setup_common.h> #include <test/util/validation.h> #include <util/memory.h> #include <validationinterface.h> #include <version.h> #include <atomic> #include <cassert> #include <chrono> #include <cstdint> #include <iosfwd> #include <iostream> #include <memory> #include <string> namespace { const TestingSetup* g_setup; } // namespace size_t& GetNumMsgTypes() { static size_t g_num_msg_types{0}; return g_num_msg_types; } #define FUZZ_TARGET_MSG(msg_type) \ struct msg_type##_Count_Before_Main { \ msg_type##_Count_Before_Main() \ { \ ++GetNumMsgTypes(); \ } \ } const static g_##msg_type##_count_before_main; \ FUZZ_TARGET_INIT(process_message_##msg_type, initialize_process_message) \ { \ fuzz_target(buffer, #msg_type); \ } void initialize_process_message() { Assert(GetNumMsgTypes() == getAllNetMessageTypes().size()); // If this fails, add or remove the message type below static const auto testing_setup = MakeFuzzingContext<const TestingSetup>(); g_setup = testing_setup.get(); for (int i = 0; i < 2 * COINBASE_MATURITY; i++) { MineBlock(g_setup->m_node, CScript() << OP_TRUE); } SyncWithValidationInterfaceQueue(); } void fuzz_target(FuzzBufferType buffer, const std::string& LIMIT_TO_MESSAGE_TYPE) { FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size()); ConnmanTestMsg& connman = *(ConnmanTestMsg*)g_setup->m_node.connman.get(); TestChainState& chainstate = *(TestChainState*)&g_setup->m_node.chainman->ActiveChainstate(); SetMockTime(1610000000); // any time to successfully reset ibd chainstate.ResetIbd(); const std::string random_message_type{fuzzed_data_provider.ConsumeBytesAsString(CMessageHeader::COMMAND_SIZE).c_str()}; if (!LIMIT_TO_MESSAGE_TYPE.empty() && random_message_type != LIMIT_TO_MESSAGE_TYPE) { return; } CNode& p2p_node = *ConsumeNodeAsUniquePtr(fuzzed_data_provider).release(); const bool successfully_connected{fuzzed_data_provider.ConsumeBool()}; p2p_node.fSuccessfullyConnected = successfully_connected; connman.AddTestNode(p2p_node); g_setup->m_node.peerman->InitializeNode(&p2p_node); FillNode(fuzzed_data_provider, p2p_node, /* init_version */ successfully_connected); const auto mock_time = ConsumeTime(fuzzed_data_provider); SetMockTime(mock_time); // fuzzed_data_provider is fully consumed after this call, don't use it CDataStream random_bytes_data_stream{fuzzed_data_provider.ConsumeRemainingBytes<unsigned char>(), SER_NETWORK, PROTOCOL_VERSION}; try { g_setup->m_node.peerman->ProcessMessage(p2p_node, random_message_type, random_bytes_data_stream, GetTime<std::chrono::microseconds>(), std::atomic<bool>{false}); } catch (const std::ios_base::failure&) { } { LOCK(p2p_node.cs_sendProcessing); g_setup->m_node.peerman->SendMessages(&p2p_node); } SyncWithValidationInterfaceQueue(); LOCK2(::cs_main, g_cs_orphans); // See init.cpp for rationale for implicit locking order requirement g_setup->m_node.connman->StopNodes(); } FUZZ_TARGET_INIT(process_message, initialize_process_message) { fuzz_target(buffer, ""); } FUZZ_TARGET_MSG(addr); FUZZ_TARGET_MSG(addrv2); FUZZ_TARGET_MSG(block); FUZZ_TARGET_MSG(blocktxn); FUZZ_TARGET_MSG(cfcheckpt); FUZZ_TARGET_MSG(cfheaders); FUZZ_TARGET_MSG(cfilter); FUZZ_TARGET_MSG(cmpctblock); FUZZ_TARGET_MSG(feefilter); FUZZ_TARGET_MSG(filteradd); FUZZ_TARGET_MSG(filterclear); FUZZ_TARGET_MSG(filterload); FUZZ_TARGET_MSG(getaddr); FUZZ_TARGET_MSG(getblocks); FUZZ_TARGET_MSG(getblocktxn); FUZZ_TARGET_MSG(getcfcheckpt); FUZZ_TARGET_MSG(getcfheaders); FUZZ_TARGET_MSG(getcfilters); FUZZ_TARGET_MSG(getdata); FUZZ_TARGET_MSG(getheaders); FUZZ_TARGET_MSG(headers); FUZZ_TARGET_MSG(inv); FUZZ_TARGET_MSG(mempool); FUZZ_TARGET_MSG(merkleblock); FUZZ_TARGET_MSG(notfound); FUZZ_TARGET_MSG(ping); FUZZ_TARGET_MSG(pong); FUZZ_TARGET_MSG(sendaddrv2); FUZZ_TARGET_MSG(sendcmpct); FUZZ_TARGET_MSG(sendheaders); FUZZ_TARGET_MSG(tx); FUZZ_TARGET_MSG(verack); FUZZ_TARGET_MSG(version); FUZZ_TARGET_MSG(wtxidrelay); // SYSCOIN FUZZ_TARGET_MSG(spork); FUZZ_TARGET_MSG(getsporks); FUZZ_TARGET_MSG(ssc); FUZZ_TARGET_MSG(govsync); FUZZ_TARGET_MSG(govobj); FUZZ_TARGET_MSG(govobjvote); FUZZ_TARGET_MSG(getmnlistd); FUZZ_TARGET_MSG(mnlistdiff); FUZZ_TARGET_MSG(qsendrecsigs); FUZZ_TARGET_MSG(qfcommit); FUZZ_TARGET_MSG(qcontrib); FUZZ_TARGET_MSG(qcompliant); FUZZ_TARGET_MSG(qjustify); FUZZ_TARGET_MSG(qpcommit); FUZZ_TARGET_MSG(qwatch); FUZZ_TARGET_MSG(qsigsesann); FUZZ_TARGET_MSG(qsigsinv); FUZZ_TARGET_MSG(qgetsigs); FUZZ_TARGET_MSG(qbsigs); FUZZ_TARGET_MSG(qsigrec); FUZZ_TARGET_MSG(qsigshare); FUZZ_TARGET_MSG(clsig); FUZZ_TARGET_MSG(mnauth);<|endoftext|>
<commit_before>#include "ScrollableWidget.hpp" #include <iostream> gsf::ScrollableWidget::ScrollableWidget(float width, float height) : ChildWidget(width, height) , m_totalWidth{ width } , m_totalHeight{ height } , m_scrollOffsetX{ 0.f } , m_scrollOffsetY{ 0.f } , m_scrollSpeed{ 6.0f } , m_isVerticalScrollEnabled{ true } , m_isHorizontalScrollEnabled{ false } , m_scrollbarHorizontal{ 30.f, 0.f } , m_scrollbarMoveActive{ false } , SCROLLBAR_PAD_HOR{ 6.f } { //m_scrollbarHorizontal.setPosition(getRight() - m_scrollbarHorizontal.getWidth() / 2.f - 3.f, m_scrollbarHorizontal.getHeight() / 2.f + 3.f ); calculateScrollbarSize(); } gsf::ScrollableWidget::~ScrollableWidget() { } void gsf::ScrollableWidget::calculateScrollbarSize() { if (m_children.size() > 0) { // get first element Widget *widget = m_children.at(0).get(); float childrenHeight = widget->getHeight(); // Get proportion between the scrollable widget and its child float proportion = getHeight() / childrenHeight; // Calculate the scrollbar size float scrollbarHeight = (getHeight() - 2 * SCROLLBAR_PAD_HOR) * proportion; m_scrollbarHorizontal.setHeight(scrollbarHeight); m_scrollbarHorizontal.setPosition(getWidth() - m_scrollbarHorizontal.getWidth() / 2.f - 3.f, 0.f + m_scrollbarHorizontal.getHeight() / 2.f + SCROLLBAR_PAD_HOR); } } void gsf::ScrollableWidget::setIsVerticalScrollEnabled(bool isEnabled) { m_isVerticalScrollEnabled = isEnabled; } bool gsf::ScrollableWidget::isVerticalScrollEnabled() const { return m_isVerticalScrollEnabled; } void gsf::ScrollableWidget::setIsHorizontalScrollEnabled(bool isEnabled) { m_isHorizontalScrollEnabled = isEnabled; } bool gsf::ScrollableWidget::isHorizontalScrollEnabled() const { return m_isHorizontalScrollEnabled; } float gsf::ScrollableWidget::getTotalWidth() const { return m_totalWidth; } float gsf::ScrollableWidget::getTotalHeight() const { return m_totalHeight; } sf::View gsf::ScrollableWidget::getShownAreaView(sf::RenderTarget &target) const { sf::View view; // The view should have the same size as the layout, so the shown area of the widget is never bigger than the size of the widget, // although when the children widgets of the layout are bigger. view.setSize(getWidth(), getHeight()); /* float scrollOffsetX = m_scrollOffsetX; float scrollOffsetY = m_scrollOffsetY; view.setCenter(getWorldPosition().x - getOrigin().x + (getWidth() / 2.f) + scrollOffsetX, getWorldPosition().y - getOrigin().y + (getHeight() / 2.f) + scrollOffsetY ); */ view.setCenter(getWorldPosition().x - getOrigin().x + (getWidth() / 2.f), getWorldPosition().y - getOrigin().y + (getHeight() / 2.f) ); float startX = ( getWorldPosition().x - getOrigin().x ) / target.getSize().x; float startY = ( getWorldPosition().y - getOrigin().y ) / target.getSize().y; float viewWidth = getWidth() / target.getSize().x; float viewHeight = getHeight() / target.getSize().y; // The viewport is the area where the widget is on screen view.setViewport(sf::FloatRect(startX , startY , viewWidth, viewHeight)); return view; } void gsf::ScrollableWidget::draw(sf::RenderTarget &target, sf::RenderStates states) const { states.transform *= getTransform(); drawCurrent(target, states); // We change the view of the target, so that only the area of the widget and its child // which are in its shown area are drawn on the RenderTarget sf::View defaultView = target.getView(); sf::View view = { getShownAreaView(target) }; target.setView(view); drawChildren(target, states); //Widget::draw(target, states); target.setView(defaultView); // Draw Scroll Elements // Do to for later: impelemnt draw method for drawing in MoveableBlock class sf::RectangleShape scrollYShape({ m_scrollbarHorizontal.getWidth(), m_scrollbarHorizontal.getHeight() }); scrollYShape.setFillColor(sf::Color::White); scrollYShape.setPosition(m_scrollbarHorizontal.getPosition()); scrollYShape.setOrigin(m_scrollbarHorizontal.getWidth() / 2.f, m_scrollbarHorizontal.getHeight() / 2.f); target.draw(scrollYShape, states); } void gsf::ScrollableWidget::drawCurrent(sf::RenderTarget &target, sf::RenderStates states) const { // Draw background sf::RectangleShape bgShape({ getWidth(), getHeight() }); bgShape.setFillColor(m_bgColor); target.draw(bgShape, states); } bool gsf::ScrollableWidget::handleEventCurrent(sf::Event &event) { if (event.type == sf::Event::MouseWheelMoved && isIntersecting(sf::Vector2f(event.mouseButton.x , event.mouseButton.y))) { m_scrollOffsetY = { event.mouseWheel.delta * m_scrollSpeed }; return true; } else if (event.type == sf::Event::MouseButtonPressed) { // We need the mouse pos as local position in the ScrollWidget sf::Vector2f localMousePos = { event.mouseButton.x - getWorldLeft() , event.mouseButton.y - getWorldTop() }; std::cout << "ScrollableWidget: Local Mouse pos x: " << localMousePos.x << " y: " << localMousePos.y << " Is intersecting: " << m_scrollbarHorizontal.isPointIntersecting({ localMousePos.x , localMousePos.y }) << std::endl; if (event.mouseButton.button == sf::Mouse::Left && m_scrollbarHorizontal.isPointIntersecting({ localMousePos.x , localMousePos.y })) { std::cout << "ScrollableWidget: Left mouse button clicked in scrollbar" << std::endl; m_scrollbarMoveActive = true; m_scrollbarMoveModeRelPos.x = localMousePos.x - m_scrollbarHorizontal.getPosition().x; m_scrollbarMoveModeRelPos.y = localMousePos.y - m_scrollbarHorizontal.getPosition().y; return true; } } else if (event.type == sf::Event::MouseButtonReleased) { if (event.mouseButton.button == sf::Mouse::Left) { std::cout << "WindowWidget: Left mouse button released" << std::endl; m_scrollbarMoveActive = false; return true; } } else if (event.type == sf::Event::MouseMoved) { if (m_scrollbarMoveActive) { sf::Vector2f localMousePos = { event.mouseMove.x - getWorldLeft() , event.mouseMove.y - getWorldTop() }; m_scrollbarHorizontal.setPositionAndStoreOld(m_scrollbarHorizontal.getPosition().x, localMousePos.y - m_scrollbarMoveModeRelPos.y); // If scrollbar is out of widget, correct its position if (m_scrollbarHorizontal.getTop() < 0.f) { m_scrollbarHorizontal.setPosition(m_scrollbarHorizontal.getPosition().x, 0.f + m_scrollbarHorizontal.getHeight() / 2.f + SCROLLBAR_PAD_HOR); } else if (m_scrollbarHorizontal.getBottom() > getHeight()) { m_scrollbarHorizontal.setPosition(m_scrollbarHorizontal.getPosition().x, getHeight() - m_scrollbarHorizontal.getHeight() / 2.f - SCROLLBAR_PAD_HOR); } std::cout << "MouseMoveEvent mouseMove x: " << event.mouseMove.x << " y: " << event.mouseMove.y << std::endl; } } return false; } void gsf::ScrollableWidget::updateCurrent(float dt) { for (const Ptr &child : m_children) { child->move(0.f, m_scrollOffsetY); // Correct the position of the childs when there are out of the bounds if (child->getBottom() <= getHeight()) { child->move(0.f, getHeight() - child->getBottom() ); } else if (child->getTop() > 0.f) { child->move(0.f, 0.f - child->getTop() ); } } // Scrolling handled m_scrollOffsetY = 0.f; } void gsf::ScrollableWidget::childAdded() { calculateScrollbarSize(); } void gsf::ScrollableWidget::childRemoved() { calculateScrollbarSize(); } <commit_msg>Scroll content when scrollbar is moved<commit_after>#include "ScrollableWidget.hpp" #include <iostream> gsf::ScrollableWidget::ScrollableWidget(float width, float height) : ChildWidget(width, height) , m_totalWidth{ width } , m_totalHeight{ height } , m_scrollOffsetX{ 0.f } , m_scrollOffsetY{ 0.f } , m_scrollSpeed{ 6.0f } , m_isVerticalScrollEnabled{ true } , m_isHorizontalScrollEnabled{ false } , m_scrollbarHorizontal{ 30.f, 0.f } , m_scrollbarMoveActive{ false } , SCROLLBAR_PAD_HOR{ 6.f } { //m_scrollbarHorizontal.setPosition(getRight() - m_scrollbarHorizontal.getWidth() / 2.f - 3.f, m_scrollbarHorizontal.getHeight() / 2.f + 3.f ); calculateScrollbarSize(); } gsf::ScrollableWidget::~ScrollableWidget() { } void gsf::ScrollableWidget::calculateScrollbarSize() { if (m_children.size() > 0) { // get first element Widget *widget = m_children.at(0).get(); float childrenHeight = widget->getHeight(); // Get proportion between the scrollable widget and its child float proportion = getHeight() / childrenHeight; // Calculate the scrollbar size float scrollbarHeight = (getHeight() - 2 * SCROLLBAR_PAD_HOR) * proportion; m_scrollbarHorizontal.setHeight(scrollbarHeight); m_scrollbarHorizontal.setPosition(getWidth() - m_scrollbarHorizontal.getWidth() / 2.f - 3.f, 0.f + m_scrollbarHorizontal.getHeight() / 2.f + SCROLLBAR_PAD_HOR); } } void gsf::ScrollableWidget::setIsVerticalScrollEnabled(bool isEnabled) { m_isVerticalScrollEnabled = isEnabled; } bool gsf::ScrollableWidget::isVerticalScrollEnabled() const { return m_isVerticalScrollEnabled; } void gsf::ScrollableWidget::setIsHorizontalScrollEnabled(bool isEnabled) { m_isHorizontalScrollEnabled = isEnabled; } bool gsf::ScrollableWidget::isHorizontalScrollEnabled() const { return m_isHorizontalScrollEnabled; } float gsf::ScrollableWidget::getTotalWidth() const { return m_totalWidth; } float gsf::ScrollableWidget::getTotalHeight() const { return m_totalHeight; } sf::View gsf::ScrollableWidget::getShownAreaView(sf::RenderTarget &target) const { sf::View view; // The view should have the same size as the layout, so the shown area of the widget is never bigger than the size of the widget, // although when the children widgets of the layout are bigger. view.setSize(getWidth(), getHeight()); /* float scrollOffsetX = m_scrollOffsetX; float scrollOffsetY = m_scrollOffsetY; view.setCenter(getWorldPosition().x - getOrigin().x + (getWidth() / 2.f) + scrollOffsetX, getWorldPosition().y - getOrigin().y + (getHeight() / 2.f) + scrollOffsetY ); */ view.setCenter(getWorldPosition().x - getOrigin().x + (getWidth() / 2.f), getWorldPosition().y - getOrigin().y + (getHeight() / 2.f) ); float startX = ( getWorldPosition().x - getOrigin().x ) / target.getSize().x; float startY = ( getWorldPosition().y - getOrigin().y ) / target.getSize().y; float viewWidth = getWidth() / target.getSize().x; float viewHeight = getHeight() / target.getSize().y; // The viewport is the area where the widget is on screen view.setViewport(sf::FloatRect(startX , startY , viewWidth, viewHeight)); return view; } void gsf::ScrollableWidget::draw(sf::RenderTarget &target, sf::RenderStates states) const { states.transform *= getTransform(); drawCurrent(target, states); // We change the view of the target, so that only the area of the widget and its child // which are in its shown area are drawn on the RenderTarget sf::View defaultView = target.getView(); sf::View view = { getShownAreaView(target) }; target.setView(view); drawChildren(target, states); //Widget::draw(target, states); target.setView(defaultView); // Draw Scroll Elements // Do to for later: impelemnt draw method for drawing in MoveableBlock class sf::RectangleShape scrollYShape({ m_scrollbarHorizontal.getWidth(), m_scrollbarHorizontal.getHeight() }); scrollYShape.setFillColor(sf::Color::White); scrollYShape.setPosition(m_scrollbarHorizontal.getPosition()); scrollYShape.setOrigin(m_scrollbarHorizontal.getWidth() / 2.f, m_scrollbarHorizontal.getHeight() / 2.f); target.draw(scrollYShape, states); } void gsf::ScrollableWidget::drawCurrent(sf::RenderTarget &target, sf::RenderStates states) const { // Draw background sf::RectangleShape bgShape({ getWidth(), getHeight() }); bgShape.setFillColor(m_bgColor); target.draw(bgShape, states); } bool gsf::ScrollableWidget::handleEventCurrent(sf::Event &event) { if (event.type == sf::Event::MouseWheelMoved && isIntersecting(sf::Vector2f(event.mouseButton.x , event.mouseButton.y))) { m_scrollOffsetY = { event.mouseWheel.delta * m_scrollSpeed }; return true; } else if (event.type == sf::Event::MouseButtonPressed) { // We need the mouse pos as local position in the ScrollWidget sf::Vector2f localMousePos = { event.mouseButton.x - getWorldLeft() , event.mouseButton.y - getWorldTop() }; std::cout << "ScrollableWidget: Local Mouse pos x: " << localMousePos.x << " y: " << localMousePos.y << " Is intersecting: " << m_scrollbarHorizontal.isPointIntersecting({ localMousePos.x , localMousePos.y }) << std::endl; if (event.mouseButton.button == sf::Mouse::Left && m_scrollbarHorizontal.isPointIntersecting({ localMousePos.x , localMousePos.y })) { std::cout << "ScrollableWidget: Left mouse button clicked in scrollbar" << std::endl; m_scrollbarMoveActive = true; m_scrollbarMoveModeRelPos.x = localMousePos.x - m_scrollbarHorizontal.getPosition().x; m_scrollbarMoveModeRelPos.y = localMousePos.y - m_scrollbarHorizontal.getPosition().y; return true; } } else if (event.type == sf::Event::MouseButtonReleased) { if (event.mouseButton.button == sf::Mouse::Left) { std::cout << "WindowWidget: Left mouse button released" << std::endl; m_scrollbarMoveActive = false; return true; } } else if (event.type == sf::Event::MouseMoved) { if (m_scrollbarMoveActive) { sf::Vector2f localMousePos = { event.mouseMove.x - getWorldLeft() , event.mouseMove.y - getWorldTop() }; m_scrollbarHorizontal.setPositionAndStoreOld(m_scrollbarHorizontal.getPosition().x, localMousePos.y - m_scrollbarMoveModeRelPos.y); // If scrollbar is out of widget, correct its position if (m_scrollbarHorizontal.getTop() < 0.f + SCROLLBAR_PAD_HOR) { m_scrollbarHorizontal.setPosition(m_scrollbarHorizontal.getPosition().x, 0.f + m_scrollbarHorizontal.getHeight() / 2.f + SCROLLBAR_PAD_HOR); } else if (m_scrollbarHorizontal.getBottom() > getHeight() - SCROLLBAR_PAD_HOR) { m_scrollbarHorizontal.setPosition(m_scrollbarHorizontal.getPosition().x, getHeight() - m_scrollbarHorizontal.getHeight() / 2.f - SCROLLBAR_PAD_HOR); } // Only ste a offset when there is a child to move if (m_children.size() > 0) { // get first element Widget *widget = m_children.at(0).get(); float childrenHeight = widget->getHeight(); // Calculate the offset m_scrollOffsetY = ( (m_scrollbarHorizontal.getLastPosition().y - m_scrollbarHorizontal.getPosition().y) / (getHeight() - 2 * SCROLLBAR_PAD_HOR ) ) * childrenHeight; } std::cout << "MouseMoveEvent mouseMove x: " << event.mouseMove.x << " y: " << event.mouseMove.y << std::endl; } } return false; } void gsf::ScrollableWidget::updateCurrent(float dt) { for (const Ptr &child : m_children) { child->move(0.f, m_scrollOffsetY); // Correct the position of the childs when there are out of the bounds if (child->getBottom() <= getHeight()) { child->move(0.f, getHeight() - child->getBottom() ); } else if (child->getTop() > 0.f) { child->move(0.f, 0.f - child->getTop() ); } } // Scrolling handled m_scrollOffsetY = 0.f; } void gsf::ScrollableWidget::childAdded() { calculateScrollbarSize(); } void gsf::ScrollableWidget::childRemoved() { calculateScrollbarSize(); } <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////////// /// DISCLAIMER /// /// Copyright 2018 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 Tobias Gödderz //////////////////////////////////////////////////////////////////////////////// #include "DependencyProxy.h" #include "Aql/BlocksWithClients.h" #include "Aql/types.h" #include "Basics/Exceptions.h" #include "Basics/voc-errors.h" using namespace arangodb; using namespace arangodb::aql; template <BlockPassthrough blockPassthrough> ExecutionState DependencyProxy<blockPassthrough>::prefetchBlock(size_t atMost) { TRI_ASSERT(atMost > 0); ExecutionState state; SharedAqlItemBlockPtr block; do { // Note: upstreamBlock will return next dependency // if we need to loop here if (_distributeId.empty()) { std::tie(state, block) = upstreamBlock().getSome(atMost); } else { auto upstreamWithClient = dynamic_cast<BlocksWithClients*>(&upstreamBlock()); std::tie(state, block) = upstreamWithClient->getSomeForShard(atMost, _distributeId); } TRI_IF_FAILURE("ExecutionBlock::getBlock") { THROW_ARANGO_EXCEPTION(TRI_ERROR_DEBUG); } if (state == ExecutionState::WAITING) { TRI_ASSERT(block == nullptr); return state; } if (block == nullptr) { // We're not waiting and didn't get a block, so we have to be done. TRI_ASSERT(state == ExecutionState::DONE); if (!advanceDependency()) { return state; } } } while (block == nullptr); // Now we definitely have a block. TRI_ASSERT(block != nullptr); if (state == ExecutionState::DONE) { // We need to modify the state here s.t. on next call we fetch from // next dependency and do not return DONE on first dependency if (advanceDependency()) { state = ExecutionState::HASMORE; } } if /* constexpr */ (blockPassthrough == BlockPassthrough::Enable) { // Reposit block for pass-through executors. _blockPassThroughQueue.push_back({state, block}); } _blockQueue.push_back({state, std::move(block)}); return ExecutionState::HASMORE; } template <BlockPassthrough blockPassthrough> std::pair<ExecutionState, SharedAqlItemBlockPtr> // NOLINTNEXTLINE google-default-arguments DependencyProxy<blockPassthrough>::fetchBlock(size_t atMost) { if (_blockQueue.empty()) { ExecutionState state = prefetchBlock(atMost); // prefetchBlock returns HASMORE iff it pushed a block onto _blockQueue. // If it didn't, it got either WAITING from upstream, or DONE + nullptr. if (state == ExecutionState::WAITING || state == ExecutionState::DONE) { return {state, nullptr}; } TRI_ASSERT(state == ExecutionState::HASMORE); } TRI_ASSERT(!_blockQueue.empty()); ExecutionState state; SharedAqlItemBlockPtr block; std::tie(state, block) = _blockQueue.front(); _blockQueue.pop_front(); return {state, std::move(block)}; } template <BlockPassthrough blockPassthrough> std::pair<ExecutionState, SharedAqlItemBlockPtr> // NOLINTNEXTLINE google-default-arguments DependencyProxy<blockPassthrough>::fetchBlockForDependency(size_t dependency, size_t atMost) { TRI_ASSERT(blockPassthrough == BlockPassthrough::Disable); ExecutionBlock& upstream = upstreamBlockForDependency(dependency); TRI_ASSERT(atMost > 0); ExecutionState state; SharedAqlItemBlockPtr block; if (_distributeId.empty()) { std::tie(state, block) = upstream.getSome(atMost); } else { auto upstreamWithClient = dynamic_cast<BlocksWithClients*>(&upstream); std::tie(state, block) = upstreamWithClient->getSomeForShard(atMost, _distributeId); } TRI_IF_FAILURE("ExecutionBlock::getBlock") { THROW_ARANGO_EXCEPTION(TRI_ERROR_DEBUG); } if (state == ExecutionState::WAITING) { TRI_ASSERT(block == nullptr); return {state, nullptr}; } if (block == nullptr) { // We're not waiting and didn't get a block, so we have to be done. TRI_ASSERT(state == ExecutionState::DONE); return {state, nullptr}; } // Now we definitely have a block. TRI_ASSERT(block != nullptr); return {state, block}; } template <BlockPassthrough blockPassthrough> std::pair<ExecutionState, size_t> DependencyProxy<blockPassthrough>::skipSomeForDependency( size_t const dependency, size_t const atMost) { TRI_ASSERT(blockPassthrough == BlockPassthrough::Disable); TRI_ASSERT(_blockPassThroughQueue.empty()); TRI_ASSERT(_blockQueue.empty()); TRI_ASSERT(atMost > 0); TRI_ASSERT(_skipped <= atMost); ExecutionBlock& upstream = upstreamBlockForDependency(dependency); ExecutionState state = ExecutionState::HASMORE; while (state == ExecutionState::HASMORE && _skipped < atMost) { size_t skippedNow; TRI_ASSERT(_skipped <= atMost); std::tie(state, skippedNow) = upstream.skipSome(atMost - _skipped); if (state == ExecutionState::WAITING) { TRI_ASSERT(skippedNow == 0); return {state, 0}; } _skipped += skippedNow; TRI_ASSERT(_skipped <= atMost); } TRI_ASSERT(state != ExecutionState::WAITING); size_t skipped = _skipped; _skipped = 0; TRI_ASSERT(skipped <= atMost); return {state, skipped}; } template <BlockPassthrough blockPassthrough> std::pair<ExecutionState, size_t> DependencyProxy<blockPassthrough>::skipSome(size_t const toSkip) { TRI_ASSERT(_blockPassThroughQueue.empty()); TRI_ASSERT(_blockQueue.empty()); TRI_ASSERT(toSkip > 0); TRI_ASSERT(_skipped <= toSkip); ExecutionState state = ExecutionState::HASMORE; while (_skipped < toSkip) { size_t skippedNow; // Note: upstreamBlock will return next dependency // if we need to loop here TRI_ASSERT(_skipped <= toSkip); if (_distributeId.empty()) { std::tie(state, skippedNow) = upstreamBlock().skipSome(toSkip - _skipped); } else { auto upstreamWithClient = dynamic_cast<BlocksWithClients*>(&upstreamBlock()); std::tie(state, skippedNow) = upstreamWithClient->skipSomeForShard(toSkip - _skipped, _distributeId); } TRI_ASSERT(skippedNow <= toSkip - _skipped); if (state == ExecutionState::WAITING) { TRI_ASSERT(skippedNow == 0); return {state, 0}; } _skipped += skippedNow; // When the current dependency is done, advance. if (state == ExecutionState::DONE && !advanceDependency()) { size_t skipped = _skipped; _skipped = 0; TRI_ASSERT(skipped <= toSkip); return {state, skipped}; } } size_t skipped = _skipped; _skipped = 0; TRI_ASSERT(skipped <= toSkip); return {state, skipped}; } template <BlockPassthrough blockPassthrough> std::pair<ExecutionState, SharedAqlItemBlockPtr> DependencyProxy<blockPassthrough>::fetchBlockForPassthrough( size_t atMost) { TRI_ASSERT(blockPassthrough == BlockPassthrough::Enable); // TODO check this with enable_if in the header already if (_blockPassThroughQueue.empty()) { ExecutionState state = prefetchBlock(atMost); // prefetchBlock returns HASMORE iff it pushed a block onto _blockPassThroughQueue. // If it didn't, it got either WAITING from upstream, or DONE + nullptr. if (state == ExecutionState::WAITING || state == ExecutionState::DONE) { return {state, nullptr}; } TRI_ASSERT(state == ExecutionState::HASMORE); } TRI_ASSERT(!_blockPassThroughQueue.empty()); ExecutionState state; SharedAqlItemBlockPtr block; std::tie(state, block) = _blockPassThroughQueue.front(); _blockPassThroughQueue.pop_front(); return {state, std::move(block)}; } template <BlockPassthrough blockPassthrough> DependencyProxy<blockPassthrough>::DependencyProxy( std::vector<ExecutionBlock*> const& dependencies, AqlItemBlockManager& itemBlockManager, std::shared_ptr<std::unordered_set<RegisterId> const> inputRegisters, RegisterId nrInputRegisters) : _dependencies(dependencies), _itemBlockManager(itemBlockManager), _inputRegisters(std::move(inputRegisters)), _nrInputRegisters(nrInputRegisters), _distributeId(), _blockQueue(), _blockPassThroughQueue(), _currentDependency(0), _skipped(0) {} template <BlockPassthrough blockPassthrough> RegisterId DependencyProxy<blockPassthrough>::getNrInputRegisters() const { return _nrInputRegisters; } template <BlockPassthrough blockPassthrough> size_t DependencyProxy<blockPassthrough>::numberDependencies() const { return _dependencies.size(); } template <BlockPassthrough blockPassthrough> void DependencyProxy<blockPassthrough>::reset() { _blockQueue.clear(); _blockPassThroughQueue.clear(); _currentDependency = 0; // We shouldn't be in a half-skipped state when reset is called TRI_ASSERT(_skipped == 0); _skipped = 0; } template <BlockPassthrough blockPassthrough> AqlItemBlockManager& DependencyProxy<blockPassthrough>::itemBlockManager() { return _itemBlockManager; } template <BlockPassthrough blockPassthrough> AqlItemBlockManager const& DependencyProxy<blockPassthrough>::itemBlockManager() const { return _itemBlockManager; } template <BlockPassthrough blockPassthrough> ExecutionBlock& DependencyProxy<blockPassthrough>::upstreamBlock() { return upstreamBlockForDependency(_currentDependency); } template <BlockPassthrough blockPassthrough> ExecutionBlock& DependencyProxy<blockPassthrough>::upstreamBlockForDependency(size_t index) { TRI_ASSERT(_dependencies.size() > index); return *_dependencies[index]; } template <BlockPassthrough blockPassthrough> bool DependencyProxy<blockPassthrough>::advanceDependency() { if (_currentDependency + 1 >= _dependencies.size()) { return false; } _currentDependency++; return true; } template class ::arangodb::aql::DependencyProxy<BlockPassthrough::Enable>; template class ::arangodb::aql::DependencyProxy<BlockPassthrough::Disable>; <commit_msg>Bugfix for recurring Jenkins error in api-simple-modify-example-cluster-spec.rb (#10190)<commit_after>//////////////////////////////////////////////////////////////////////////////// /// DISCLAIMER /// /// Copyright 2018 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 Tobias Gödderz //////////////////////////////////////////////////////////////////////////////// #include "DependencyProxy.h" #include "Aql/BlocksWithClients.h" #include "Aql/types.h" #include "Basics/Exceptions.h" #include "Basics/voc-errors.h" using namespace arangodb; using namespace arangodb::aql; template <BlockPassthrough blockPassthrough> ExecutionState DependencyProxy<blockPassthrough>::prefetchBlock(size_t atMost) { TRI_ASSERT(atMost > 0); ExecutionState state; SharedAqlItemBlockPtr block; do { // Note: upstreamBlock will return next dependency // if we need to loop here if (_distributeId.empty()) { std::tie(state, block) = upstreamBlock().getSome(atMost); } else { auto upstreamWithClient = dynamic_cast<BlocksWithClients*>(&upstreamBlock()); std::tie(state, block) = upstreamWithClient->getSomeForShard(atMost, _distributeId); } TRI_IF_FAILURE("ExecutionBlock::getBlock") { THROW_ARANGO_EXCEPTION(TRI_ERROR_DEBUG); } if (state == ExecutionState::WAITING) { TRI_ASSERT(block == nullptr); return state; } if (block == nullptr) { // We're not waiting and didn't get a block, so we have to be done. TRI_ASSERT(state == ExecutionState::DONE); if (!advanceDependency()) { return state; } } } while (block == nullptr); // Now we definitely have a block. TRI_ASSERT(block != nullptr); if (state == ExecutionState::DONE) { // We need to modify the state here s.t. on next call we fetch from // next dependency and do not return DONE on first dependency if (advanceDependency()) { state = ExecutionState::HASMORE; } } if /* constexpr */ (blockPassthrough == BlockPassthrough::Enable) { // Reposit block for pass-through executors. _blockPassThroughQueue.push_back({state, block}); } _blockQueue.push_back({state, std::move(block)}); return ExecutionState::HASMORE; } template <BlockPassthrough blockPassthrough> std::pair<ExecutionState, SharedAqlItemBlockPtr> // NOLINTNEXTLINE google-default-arguments DependencyProxy<blockPassthrough>::fetchBlock(size_t atMost) { if (_blockQueue.empty()) { ExecutionState state = prefetchBlock(atMost); // prefetchBlock returns HASMORE iff it pushed a block onto _blockQueue. // If it didn't, it got either WAITING from upstream, or DONE + nullptr. if (state == ExecutionState::WAITING || state == ExecutionState::DONE) { return {state, nullptr}; } TRI_ASSERT(state == ExecutionState::HASMORE); } TRI_ASSERT(!_blockQueue.empty()); ExecutionState state; SharedAqlItemBlockPtr block; std::tie(state, block) = _blockQueue.front(); _blockQueue.pop_front(); return {state, std::move(block)}; } template <BlockPassthrough blockPassthrough> std::pair<ExecutionState, SharedAqlItemBlockPtr> // NOLINTNEXTLINE google-default-arguments DependencyProxy<blockPassthrough>::fetchBlockForDependency(size_t dependency, size_t atMost) { TRI_ASSERT(blockPassthrough == BlockPassthrough::Disable); ExecutionBlock& upstream = upstreamBlockForDependency(dependency); TRI_ASSERT(atMost > 0); ExecutionState state; SharedAqlItemBlockPtr block; if (_distributeId.empty()) { std::tie(state, block) = upstream.getSome(atMost); } else { auto upstreamWithClient = dynamic_cast<BlocksWithClients*>(&upstream); std::tie(state, block) = upstreamWithClient->getSomeForShard(atMost, _distributeId); } TRI_IF_FAILURE("ExecutionBlock::getBlock") { THROW_ARANGO_EXCEPTION(TRI_ERROR_DEBUG); } if (state == ExecutionState::WAITING) { TRI_ASSERT(block == nullptr); return {state, nullptr}; } if (block == nullptr) { // We're not waiting and didn't get a block, so we have to be done. TRI_ASSERT(state == ExecutionState::DONE); return {state, nullptr}; } // Now we definitely have a block. TRI_ASSERT(block != nullptr); return {state, block}; } template <BlockPassthrough blockPassthrough> std::pair<ExecutionState, size_t> DependencyProxy<blockPassthrough>::skipSomeForDependency( size_t const dependency, size_t const atMost) { TRI_ASSERT(blockPassthrough == BlockPassthrough::Disable); TRI_ASSERT(_blockPassThroughQueue.empty()); TRI_ASSERT(_blockQueue.empty()); TRI_ASSERT(atMost > 0); TRI_ASSERT(_skipped <= atMost); ExecutionBlock& upstream = upstreamBlockForDependency(dependency); ExecutionState state = ExecutionState::HASMORE; while (state == ExecutionState::HASMORE && _skipped < atMost) { size_t skippedNow; TRI_ASSERT(_skipped <= atMost); std::tie(state, skippedNow) = upstream.skipSome(atMost - _skipped); if (state == ExecutionState::WAITING) { TRI_ASSERT(skippedNow == 0); return {state, 0}; } _skipped += skippedNow; TRI_ASSERT(_skipped <= atMost); } TRI_ASSERT(state != ExecutionState::WAITING); size_t skipped = _skipped; _skipped = 0; TRI_ASSERT(skipped <= atMost); return {state, skipped}; } template <BlockPassthrough blockPassthrough> std::pair<ExecutionState, size_t> DependencyProxy<blockPassthrough>::skipSome(size_t const toSkip) { TRI_ASSERT(_blockPassThroughQueue.empty()); TRI_ASSERT(_blockQueue.empty()); TRI_ASSERT(toSkip > 0); TRI_ASSERT(_skipped <= toSkip); ExecutionState state = ExecutionState::HASMORE; while (_skipped < toSkip) { size_t skippedNow; // Note: upstreamBlock will return next dependency // if we need to loop here TRI_ASSERT(_skipped <= toSkip); if (_distributeId.empty()) { std::tie(state, skippedNow) = upstreamBlock().skipSome(toSkip - _skipped); } else { auto upstreamWithClient = dynamic_cast<BlocksWithClients*>(&upstreamBlock()); std::tie(state, skippedNow) = upstreamWithClient->skipSomeForShard(toSkip - _skipped, _distributeId); } TRI_ASSERT(skippedNow <= toSkip - _skipped); if (state == ExecutionState::WAITING) { TRI_ASSERT(skippedNow == 0); return {state, 0}; } _skipped += skippedNow; // When the current dependency is done, advance. if (state == ExecutionState::DONE) { if (!advanceDependency()) { break; } else { state = ExecutionState::HASMORE; } } } size_t skipped = _skipped; _skipped = 0; TRI_ASSERT(skipped <= toSkip); return {state, skipped}; } template <BlockPassthrough blockPassthrough> std::pair<ExecutionState, SharedAqlItemBlockPtr> DependencyProxy<blockPassthrough>::fetchBlockForPassthrough( size_t atMost) { TRI_ASSERT(blockPassthrough == BlockPassthrough::Enable); // TODO check this with enable_if in the header already if (_blockPassThroughQueue.empty()) { ExecutionState state = prefetchBlock(atMost); // prefetchBlock returns HASMORE iff it pushed a block onto _blockPassThroughQueue. // If it didn't, it got either WAITING from upstream, or DONE + nullptr. if (state == ExecutionState::WAITING || state == ExecutionState::DONE) { return {state, nullptr}; } TRI_ASSERT(state == ExecutionState::HASMORE); } TRI_ASSERT(!_blockPassThroughQueue.empty()); ExecutionState state; SharedAqlItemBlockPtr block; std::tie(state, block) = _blockPassThroughQueue.front(); _blockPassThroughQueue.pop_front(); return {state, std::move(block)}; } template <BlockPassthrough blockPassthrough> DependencyProxy<blockPassthrough>::DependencyProxy( std::vector<ExecutionBlock*> const& dependencies, AqlItemBlockManager& itemBlockManager, std::shared_ptr<std::unordered_set<RegisterId> const> inputRegisters, RegisterId nrInputRegisters) : _dependencies(dependencies), _itemBlockManager(itemBlockManager), _inputRegisters(std::move(inputRegisters)), _nrInputRegisters(nrInputRegisters), _distributeId(), _blockQueue(), _blockPassThroughQueue(), _currentDependency(0), _skipped(0) {} template <BlockPassthrough blockPassthrough> RegisterId DependencyProxy<blockPassthrough>::getNrInputRegisters() const { return _nrInputRegisters; } template <BlockPassthrough blockPassthrough> size_t DependencyProxy<blockPassthrough>::numberDependencies() const { return _dependencies.size(); } template <BlockPassthrough blockPassthrough> void DependencyProxy<blockPassthrough>::reset() { _blockQueue.clear(); _blockPassThroughQueue.clear(); _currentDependency = 0; // We shouldn't be in a half-skipped state when reset is called TRI_ASSERT(_skipped == 0); _skipped = 0; } template <BlockPassthrough blockPassthrough> AqlItemBlockManager& DependencyProxy<blockPassthrough>::itemBlockManager() { return _itemBlockManager; } template <BlockPassthrough blockPassthrough> AqlItemBlockManager const& DependencyProxy<blockPassthrough>::itemBlockManager() const { return _itemBlockManager; } template <BlockPassthrough blockPassthrough> ExecutionBlock& DependencyProxy<blockPassthrough>::upstreamBlock() { return upstreamBlockForDependency(_currentDependency); } template <BlockPassthrough blockPassthrough> ExecutionBlock& DependencyProxy<blockPassthrough>::upstreamBlockForDependency(size_t index) { TRI_ASSERT(_dependencies.size() > index); return *_dependencies[index]; } template <BlockPassthrough blockPassthrough> bool DependencyProxy<blockPassthrough>::advanceDependency() { if (_currentDependency + 1 >= _dependencies.size()) { return false; } _currentDependency++; return true; } template class ::arangodb::aql::DependencyProxy<BlockPassthrough::Enable>; template class ::arangodb::aql::DependencyProxy<BlockPassthrough::Disable>; <|endoftext|>
<commit_before>/* * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "modules/video_coding/utility/ivf_file_writer.h" #include <utility> #include "api/video_codecs/video_codec.h" #include "modules/rtp_rtcp/source/byte_io.h" #include "rtc_base/checks.h" #include "rtc_base/logging.h" // TODO(palmkvist): make logging more informative in the absence of a file name // (or get one) namespace webrtc { const size_t kIvfHeaderSize = 32; IvfFileWriter::IvfFileWriter(FileWrapper file, size_t byte_limit) : codec_type_(kVideoCodecGeneric), bytes_written_(0), byte_limit_(byte_limit), num_frames_(0), width_(0), height_(0), last_timestamp_(-1), using_capture_timestamps_(false), file_(std::move(file)) { RTC_DCHECK(byte_limit == 0 || kIvfHeaderSize <= byte_limit) << "The byte_limit is too low, not even the header will fit."; } IvfFileWriter::~IvfFileWriter() { Close(); } std::unique_ptr<IvfFileWriter> IvfFileWriter::Wrap(FileWrapper file, size_t byte_limit) { return std::unique_ptr<IvfFileWriter>( new IvfFileWriter(std::move(file), byte_limit)); } bool IvfFileWriter::WriteHeader() { if (!file_.Rewind()) { RTC_LOG(LS_WARNING) << "Unable to rewind ivf output file."; return false; } uint8_t ivf_header[kIvfHeaderSize] = {0}; ivf_header[0] = 'D'; ivf_header[1] = 'K'; ivf_header[2] = 'I'; ivf_header[3] = 'F'; ByteWriter<uint16_t>::WriteLittleEndian(&ivf_header[4], 0); // Version. ByteWriter<uint16_t>::WriteLittleEndian(&ivf_header[6], 32); // Header size. switch (codec_type_) { case kVideoCodecVP8: ivf_header[8] = 'V'; ivf_header[9] = 'P'; ivf_header[10] = '8'; ivf_header[11] = '0'; break; case kVideoCodecVP9: ivf_header[8] = 'V'; ivf_header[9] = 'P'; ivf_header[10] = '9'; ivf_header[11] = '0'; break; case kVideoCodecH264: ivf_header[8] = 'H'; ivf_header[9] = '2'; ivf_header[10] = '6'; ivf_header[11] = '4'; break; default: RTC_LOG(LS_ERROR) << "Unknown CODEC type: " << codec_type_; return false; } ByteWriter<uint16_t>::WriteLittleEndian(&ivf_header[12], width_); ByteWriter<uint16_t>::WriteLittleEndian(&ivf_header[14], height_); // Render timestamps are in ms (1/1000 scale), while RTP timestamps use a // 90kHz clock. ByteWriter<uint32_t>::WriteLittleEndian( &ivf_header[16], using_capture_timestamps_ ? 1000 : 90000); ByteWriter<uint32_t>::WriteLittleEndian(&ivf_header[20], 1); ByteWriter<uint32_t>::WriteLittleEndian(&ivf_header[24], static_cast<uint32_t>(num_frames_)); ByteWriter<uint32_t>::WriteLittleEndian(&ivf_header[28], 0); // Reserved. if (!file_.Write(ivf_header, kIvfHeaderSize)) { RTC_LOG(LS_ERROR) << "Unable to write IVF header for ivf output file."; return false; } if (bytes_written_ < kIvfHeaderSize) { bytes_written_ = kIvfHeaderSize; } return true; } bool IvfFileWriter::InitFromFirstFrame(const EncodedImage& encoded_image, VideoCodecType codec_type) { width_ = encoded_image._encodedWidth; height_ = encoded_image._encodedHeight; RTC_CHECK_GT(width_, 0); RTC_CHECK_GT(height_, 0); using_capture_timestamps_ = encoded_image.Timestamp() == 0; codec_type_ = codec_type; if (!WriteHeader()) return false; const char* codec_name = CodecTypeToPayloadString(codec_type_); RTC_LOG(LS_WARNING) << "Created IVF file for codec data of type " << codec_name << " at resolution " << width_ << " x " << height_ << ", using " << (using_capture_timestamps_ ? "1" : "90") << "kHz clock resolution."; return true; } bool IvfFileWriter::WriteFrame(const EncodedImage& encoded_image, VideoCodecType codec_type) { if (!file_.is_open()) return false; if (num_frames_ == 0 && !InitFromFirstFrame(encoded_image, codec_type)) return false; RTC_DCHECK_EQ(codec_type_, codec_type); if ((encoded_image._encodedWidth > 0 || encoded_image._encodedHeight > 0) && (encoded_image._encodedHeight != height_ || encoded_image._encodedWidth != width_)) { RTC_LOG(LS_WARNING) << "Incomig frame has diffferent resolution then previous: (" << width_ << "x" << height_ << ") -> (" << encoded_image._encodedWidth << "x" << encoded_image._encodedHeight << ")"; } int64_t timestamp = using_capture_timestamps_ ? encoded_image.capture_time_ms_ : wrap_handler_.Unwrap(encoded_image.Timestamp()); if (last_timestamp_ != -1 && timestamp <= last_timestamp_) { RTC_LOG(LS_WARNING) << "Timestamp no increasing: " << last_timestamp_ << " -> " << timestamp; } last_timestamp_ = timestamp; const size_t kFrameHeaderSize = 12; if (byte_limit_ != 0 && bytes_written_ + kFrameHeaderSize + encoded_image.size() > byte_limit_) { RTC_LOG(LS_WARNING) << "Closing IVF file due to reaching size limit: " << byte_limit_ << " bytes."; Close(); return false; } uint8_t frame_header[kFrameHeaderSize] = {}; ByteWriter<uint32_t>::WriteLittleEndian( &frame_header[0], static_cast<uint32_t>(encoded_image.size())); ByteWriter<uint64_t>::WriteLittleEndian(&frame_header[4], timestamp); if (!file_.Write(frame_header, kFrameHeaderSize) || !file_.Write(encoded_image.data(), encoded_image.size())) { RTC_LOG(LS_ERROR) << "Unable to write frame to file."; return false; } bytes_written_ += kFrameHeaderSize + encoded_image.size(); ++num_frames_; return true; } bool IvfFileWriter::Close() { if (!file_.is_open()) return false; if (num_frames_ == 0) { file_.Close(); return true; } bool ret = WriteHeader(); file_.Close(); return ret; } } // namespace webrtc <commit_msg>Fix some typos found in ivf_file_writer.cc<commit_after>/* * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "modules/video_coding/utility/ivf_file_writer.h" #include <utility> #include "api/video_codecs/video_codec.h" #include "modules/rtp_rtcp/source/byte_io.h" #include "rtc_base/checks.h" #include "rtc_base/logging.h" // TODO(palmkvist): make logging more informative in the absence of a file name // (or get one) namespace webrtc { const size_t kIvfHeaderSize = 32; IvfFileWriter::IvfFileWriter(FileWrapper file, size_t byte_limit) : codec_type_(kVideoCodecGeneric), bytes_written_(0), byte_limit_(byte_limit), num_frames_(0), width_(0), height_(0), last_timestamp_(-1), using_capture_timestamps_(false), file_(std::move(file)) { RTC_DCHECK(byte_limit == 0 || kIvfHeaderSize <= byte_limit) << "The byte_limit is too low, not even the header will fit."; } IvfFileWriter::~IvfFileWriter() { Close(); } std::unique_ptr<IvfFileWriter> IvfFileWriter::Wrap(FileWrapper file, size_t byte_limit) { return std::unique_ptr<IvfFileWriter>( new IvfFileWriter(std::move(file), byte_limit)); } bool IvfFileWriter::WriteHeader() { if (!file_.Rewind()) { RTC_LOG(LS_WARNING) << "Unable to rewind ivf output file."; return false; } uint8_t ivf_header[kIvfHeaderSize] = {0}; ivf_header[0] = 'D'; ivf_header[1] = 'K'; ivf_header[2] = 'I'; ivf_header[3] = 'F'; ByteWriter<uint16_t>::WriteLittleEndian(&ivf_header[4], 0); // Version. ByteWriter<uint16_t>::WriteLittleEndian(&ivf_header[6], 32); // Header size. switch (codec_type_) { case kVideoCodecVP8: ivf_header[8] = 'V'; ivf_header[9] = 'P'; ivf_header[10] = '8'; ivf_header[11] = '0'; break; case kVideoCodecVP9: ivf_header[8] = 'V'; ivf_header[9] = 'P'; ivf_header[10] = '9'; ivf_header[11] = '0'; break; case kVideoCodecH264: ivf_header[8] = 'H'; ivf_header[9] = '2'; ivf_header[10] = '6'; ivf_header[11] = '4'; break; default: RTC_LOG(LS_ERROR) << "Unknown CODEC type: " << codec_type_; return false; } ByteWriter<uint16_t>::WriteLittleEndian(&ivf_header[12], width_); ByteWriter<uint16_t>::WriteLittleEndian(&ivf_header[14], height_); // Render timestamps are in ms (1/1000 scale), while RTP timestamps use a // 90kHz clock. ByteWriter<uint32_t>::WriteLittleEndian( &ivf_header[16], using_capture_timestamps_ ? 1000 : 90000); ByteWriter<uint32_t>::WriteLittleEndian(&ivf_header[20], 1); ByteWriter<uint32_t>::WriteLittleEndian(&ivf_header[24], static_cast<uint32_t>(num_frames_)); ByteWriter<uint32_t>::WriteLittleEndian(&ivf_header[28], 0); // Reserved. if (!file_.Write(ivf_header, kIvfHeaderSize)) { RTC_LOG(LS_ERROR) << "Unable to write IVF header for ivf output file."; return false; } if (bytes_written_ < kIvfHeaderSize) { bytes_written_ = kIvfHeaderSize; } return true; } bool IvfFileWriter::InitFromFirstFrame(const EncodedImage& encoded_image, VideoCodecType codec_type) { width_ = encoded_image._encodedWidth; height_ = encoded_image._encodedHeight; RTC_CHECK_GT(width_, 0); RTC_CHECK_GT(height_, 0); using_capture_timestamps_ = encoded_image.Timestamp() == 0; codec_type_ = codec_type; if (!WriteHeader()) return false; const char* codec_name = CodecTypeToPayloadString(codec_type_); RTC_LOG(LS_WARNING) << "Created IVF file for codec data of type " << codec_name << " at resolution " << width_ << " x " << height_ << ", using " << (using_capture_timestamps_ ? "1" : "90") << "kHz clock resolution."; return true; } bool IvfFileWriter::WriteFrame(const EncodedImage& encoded_image, VideoCodecType codec_type) { if (!file_.is_open()) return false; if (num_frames_ == 0 && !InitFromFirstFrame(encoded_image, codec_type)) return false; RTC_DCHECK_EQ(codec_type_, codec_type); if ((encoded_image._encodedWidth > 0 || encoded_image._encodedHeight > 0) && (encoded_image._encodedHeight != height_ || encoded_image._encodedWidth != width_)) { RTC_LOG(LS_WARNING) << "Incoming frame has resolution different from previous: (" << width_ << "x" << height_ << ") -> (" << encoded_image._encodedWidth << "x" << encoded_image._encodedHeight << ")"; } int64_t timestamp = using_capture_timestamps_ ? encoded_image.capture_time_ms_ : wrap_handler_.Unwrap(encoded_image.Timestamp()); if (last_timestamp_ != -1 && timestamp <= last_timestamp_) { RTC_LOG(LS_WARNING) << "Timestamp no increasing: " << last_timestamp_ << " -> " << timestamp; } last_timestamp_ = timestamp; const size_t kFrameHeaderSize = 12; if (byte_limit_ != 0 && bytes_written_ + kFrameHeaderSize + encoded_image.size() > byte_limit_) { RTC_LOG(LS_WARNING) << "Closing IVF file due to reaching size limit: " << byte_limit_ << " bytes."; Close(); return false; } uint8_t frame_header[kFrameHeaderSize] = {}; ByteWriter<uint32_t>::WriteLittleEndian( &frame_header[0], static_cast<uint32_t>(encoded_image.size())); ByteWriter<uint64_t>::WriteLittleEndian(&frame_header[4], timestamp); if (!file_.Write(frame_header, kFrameHeaderSize) || !file_.Write(encoded_image.data(), encoded_image.size())) { RTC_LOG(LS_ERROR) << "Unable to write frame to file."; return false; } bytes_written_ += kFrameHeaderSize + encoded_image.size(); ++num_frames_; return true; } bool IvfFileWriter::Close() { if (!file_.is_open()) return false; if (num_frames_ == 0) { file_.Close(); return true; } bool ret = WriteHeader(); file_.Close(); return ret; } } // namespace webrtc <|endoftext|>
<commit_before>// Copyright (C) 2015 Jérôme Leclercq // This file is part of the "Nazara Engine - Core module" // For conditions of distribution and use, see copyright notice in Config.hpp #include <Nazara/Core/MemoryManager.hpp> #include <cstdio> #include <cstdlib> #include <ctime> #include <stdexcept> #if defined(NAZARA_PLATFORM_WINDOWS) #include <windows.h> #elif defined(NAZARA_PLATFORM_POSIX) #include <pthread.h> #endif // Le seul fichier n'ayant pas à inclure Debug.hpp namespace { struct Block { std::size_t size; const char* file; Block* prev; Block* next; bool array; unsigned int line; unsigned int magic; }; bool s_allocationLogging = false; bool s_initialized = false; const unsigned int s_magic = 0x51429EE; const char* s_MLTFileName = "NazaraLeaks.log"; const char* s_nextFreeFile = "(Internal error)"; unsigned int s_nextFreeLine = 0; Block s_list = { 0, nullptr, &s_list, &s_list, false, 0, s_magic }; unsigned int s_allocationCount = 0; unsigned int s_allocatedBlock = 0; std::size_t s_allocatedSize = 0; #if defined(NAZARA_PLATFORM_WINDOWS) CRITICAL_SECTION s_mutex; #elif defined(NAZARA_PLATFORM_POSIX) pthread_mutex_t s_mutex = PTHREAD_MUTEX_INITIALIZER; #endif } NzMemoryManager::NzMemoryManager() { } NzMemoryManager::~NzMemoryManager() { Uninitialize(); } void* NzMemoryManager::Allocate(std::size_t size, bool multi, const char* file, unsigned int line) { if (!s_initialized) Initialize(); #if defined(NAZARA_PLATFORM_WINDOWS) EnterCriticalSection(&s_mutex); #elif defined(NAZARA_PLATFORM_POSIX) pthread_mutex_lock(&s_mutex); #endif Block* ptr = reinterpret_cast<Block*>(std::malloc(size+sizeof(Block))); if (!ptr) { char timeStr[23]; TimeInfo(timeStr); FILE* log = std::fopen(s_MLTFileName, "a"); if (file) std::fprintf(log, "%s Failed to allocate %zu bytes at %s:%u\n", timeStr, size, file, line); else std::fprintf(log, "%s Failed to allocate %zu bytes at unknown position\n", timeStr, size); std::fclose(log); throw std::bad_alloc(); return nullptr; // Ça me rassure d'avoir un return, aussi inutile soit-il } ptr->array = multi; ptr->file = file; ptr->line = line; ptr->size = size; ptr->magic = s_magic; ptr->prev = s_list.prev; ptr->next = &s_list; s_list.prev->next = ptr; s_list.prev = ptr; s_allocatedBlock++; s_allocatedSize += size; s_allocationCount++; if (s_allocationLogging) { char timeStr[23]; TimeInfo(timeStr); FILE* log = std::fopen(s_MLTFileName, "a"); if (file) std::fprintf(log, "%s Allocated %zu bytes at %s:%u\n", timeStr, size, file, line); else std::fprintf(log, "%s Allocated %zu bytes at unknown position\n", timeStr, size); std::fclose(log); } #if defined(NAZARA_PLATFORM_WINDOWS) LeaveCriticalSection(&s_mutex); #elif defined(NAZARA_PLATFORM_POSIX) pthread_mutex_unlock(&s_mutex); #endif return reinterpret_cast<nzUInt8*>(ptr) + sizeof(Block); } void NzMemoryManager::EnableAllocationLogging(bool logAllocations) { s_allocationLogging = logAllocations; } void NzMemoryManager::Free(void* pointer, bool multi) { if (!pointer) return; Block* ptr = reinterpret_cast<Block*>(reinterpret_cast<nzUInt8*>(pointer) - sizeof(Block)); if (ptr->magic != s_magic) return; #if defined(NAZARA_PLATFORM_WINDOWS) EnterCriticalSection(&s_mutex); #elif defined(NAZARA_PLATFORM_POSIX) pthread_mutex_lock(&s_mutex); #endif if (ptr->array != multi) { char timeStr[23]; TimeInfo(timeStr); FILE* log = std::fopen(s_MLTFileName, "a"); const char* error = (multi) ? "delete[] after new" : "delete after new[]"; if (s_nextFreeFile) std::fprintf(log, "%s Warning: %s at %s:%u\n", timeStr, error, s_nextFreeFile, s_nextFreeLine); else std::fprintf(log, "%s Warning: %s at unknown position\n", error, timeStr); std::fclose(log); } ptr->magic = 0; // Évitons des problèmes ptr->prev->next = ptr->next; ptr->next->prev = ptr->prev; s_allocatedBlock--; s_allocatedSize -= ptr->size; std::free(ptr); s_nextFreeFile = nullptr; s_nextFreeLine = 0; #if defined(NAZARA_PLATFORM_WINDOWS) LeaveCriticalSection(&s_mutex); #elif defined(NAZARA_PLATFORM_POSIX) pthread_mutex_unlock(&s_mutex); #endif } unsigned int NzMemoryManager::GetAllocatedBlockCount() { return s_allocatedBlock; } std::size_t NzMemoryManager::GetAllocatedSize() { return s_allocatedSize; } unsigned int NzMemoryManager::GetAllocationCount() { return s_allocationCount; } bool NzMemoryManager::IsAllocationLoggingEnabled() { return s_allocationLogging; } void NzMemoryManager::NextFree(const char* file, unsigned int line) { s_nextFreeFile = file; s_nextFreeLine = line; } void NzMemoryManager::Initialize() { char timeStr[23]; TimeInfo(timeStr); FILE* file = std::fopen(s_MLTFileName, "w"); std::fprintf(file, "%s ==============================\n", timeStr); std::fprintf(file, "%s Nazara Memory Leak Tracker \n", timeStr); std::fprintf(file, "%s ==============================\n", timeStr); std::fclose(file); if (std::atexit(Uninitialize) != 0) { static NzMemoryManager manager; } #ifdef NAZARA_PLATFORM_WINDOWS InitializeCriticalSection(&s_mutex); #endif s_initialized = true; } void NzMemoryManager::TimeInfo(char buffer[23]) { time_t currentTime = std::time(nullptr); std::strftime(buffer, 23, "%d/%m/%Y - %H:%M:%S:", std::localtime(&currentTime)); } void NzMemoryManager::Uninitialize() { #ifdef NAZARA_PLATFORM_WINDOWS DeleteCriticalSection(&s_mutex); #endif FILE* log = std::fopen(s_MLTFileName, "a"); char timeStr[23]; TimeInfo(timeStr); std::fprintf(log, "%s Application finished, checking leaks...\n", timeStr); if (s_allocatedBlock == 0) { std::fprintf(log, "%s ==============================\n", timeStr); std::fprintf(log, "%s No leak detected \n", timeStr); std::fprintf(log, "%s ==============================", timeStr); } else { std::fprintf(log, "%s ==============================\n", timeStr); std::fprintf(log, "%s Leaks have been detected \n", timeStr); std::fprintf(log, "%s ==============================\n\n", timeStr); std::fputs("Leak list:\n", log); Block* ptr = s_list.next; while (ptr != &s_list) { if (ptr->file) std::fprintf(log, "-0x%p -> %zu bytes allocated at %s:%u\n", reinterpret_cast<nzUInt8*>(ptr) + sizeof(Block), ptr->size, ptr->file, ptr->line); else std::fprintf(log, "-0x%p -> %zu bytes allocated at unknown position\n", reinterpret_cast<nzUInt8*>(ptr) + sizeof(Block), ptr->size); void* pointer = ptr; ptr = ptr->next; std::free(pointer); } std::fprintf(log, "\n%u blocks leaked (%zu bytes)", s_allocatedBlock, s_allocatedSize); } std::fclose(log); } <commit_msg>(MemoryManager) changed log file name<commit_after>// Copyright (C) 2015 Jérôme Leclercq // This file is part of the "Nazara Engine - Core module" // For conditions of distribution and use, see copyright notice in Config.hpp #include <Nazara/Core/MemoryManager.hpp> #include <cstdio> #include <cstdlib> #include <ctime> #include <stdexcept> #if defined(NAZARA_PLATFORM_WINDOWS) #include <windows.h> #elif defined(NAZARA_PLATFORM_POSIX) #include <pthread.h> #endif // Le seul fichier n'ayant pas à inclure Debug.hpp namespace { struct Block { std::size_t size; const char* file; Block* prev; Block* next; bool array; unsigned int line; unsigned int magic; }; bool s_allocationLogging = false; bool s_initialized = false; const unsigned int s_magic = 0xDEADB33FUL; const char* s_logFileName = "NazaraMemory.log"; const char* s_nextFreeFile = "(Internal error)"; unsigned int s_nextFreeLine = 0; Block s_list = { 0, nullptr, &s_list, &s_list, false, 0, s_magic }; unsigned int s_allocationCount = 0; unsigned int s_allocatedBlock = 0; std::size_t s_allocatedSize = 0; #if defined(NAZARA_PLATFORM_WINDOWS) CRITICAL_SECTION s_mutex; #elif defined(NAZARA_PLATFORM_POSIX) pthread_mutex_t s_mutex = PTHREAD_MUTEX_INITIALIZER; #endif } NzMemoryManager::NzMemoryManager() { } NzMemoryManager::~NzMemoryManager() { Uninitialize(); } void* NzMemoryManager::Allocate(std::size_t size, bool multi, const char* file, unsigned int line) { if (!s_initialized) Initialize(); #if defined(NAZARA_PLATFORM_WINDOWS) EnterCriticalSection(&s_mutex); #elif defined(NAZARA_PLATFORM_POSIX) pthread_mutex_lock(&s_mutex); #endif Block* ptr = reinterpret_cast<Block*>(std::malloc(size+sizeof(Block))); if (!ptr) { char timeStr[23]; TimeInfo(timeStr); FILE* log = std::fopen(s_logFileName, "a"); if (file) std::fprintf(log, "%s Failed to allocate %zu bytes at %s:%u\n", timeStr, size, file, line); else std::fprintf(log, "%s Failed to allocate %zu bytes at unknown position\n", timeStr, size); std::fclose(log); throw std::bad_alloc(); return nullptr; // Ça me rassure d'avoir un return, aussi inutile soit-il } ptr->array = multi; ptr->file = file; ptr->line = line; ptr->size = size; ptr->magic = s_magic; ptr->prev = s_list.prev; ptr->next = &s_list; s_list.prev->next = ptr; s_list.prev = ptr; s_allocatedBlock++; s_allocatedSize += size; s_allocationCount++; if (s_allocationLogging) { char timeStr[23]; TimeInfo(timeStr); FILE* log = std::fopen(s_logFileName, "a"); if (file) std::fprintf(log, "%s Allocated %zu bytes at %s:%u\n", timeStr, size, file, line); else std::fprintf(log, "%s Allocated %zu bytes at unknown position\n", timeStr, size); std::fclose(log); } #if defined(NAZARA_PLATFORM_WINDOWS) LeaveCriticalSection(&s_mutex); #elif defined(NAZARA_PLATFORM_POSIX) pthread_mutex_unlock(&s_mutex); #endif return reinterpret_cast<nzUInt8*>(ptr) + sizeof(Block); } void NzMemoryManager::EnableAllocationLogging(bool logAllocations) { s_allocationLogging = logAllocations; } void NzMemoryManager::Free(void* pointer, bool multi) { if (!pointer) return; Block* ptr = reinterpret_cast<Block*>(reinterpret_cast<nzUInt8*>(pointer) - sizeof(Block)); if (ptr->magic != s_magic) return; #if defined(NAZARA_PLATFORM_WINDOWS) EnterCriticalSection(&s_mutex); #elif defined(NAZARA_PLATFORM_POSIX) pthread_mutex_lock(&s_mutex); #endif if (ptr->array != multi) { char timeStr[23]; TimeInfo(timeStr); FILE* log = std::fopen(s_logFileName, "a"); const char* error = (multi) ? "delete[] after new" : "delete after new[]"; if (s_nextFreeFile) std::fprintf(log, "%s Warning: %s at %s:%u\n", timeStr, error, s_nextFreeFile, s_nextFreeLine); else std::fprintf(log, "%s Warning: %s at unknown position\n", error, timeStr); std::fclose(log); } ptr->magic = 0; // Évitons des problèmes ptr->prev->next = ptr->next; ptr->next->prev = ptr->prev; s_allocatedBlock--; s_allocatedSize -= ptr->size; std::free(ptr); s_nextFreeFile = nullptr; s_nextFreeLine = 0; #if defined(NAZARA_PLATFORM_WINDOWS) LeaveCriticalSection(&s_mutex); #elif defined(NAZARA_PLATFORM_POSIX) pthread_mutex_unlock(&s_mutex); #endif } unsigned int NzMemoryManager::GetAllocatedBlockCount() { return s_allocatedBlock; } std::size_t NzMemoryManager::GetAllocatedSize() { return s_allocatedSize; } unsigned int NzMemoryManager::GetAllocationCount() { return s_allocationCount; } bool NzMemoryManager::IsAllocationLoggingEnabled() { return s_allocationLogging; } void NzMemoryManager::NextFree(const char* file, unsigned int line) { s_nextFreeFile = file; s_nextFreeLine = line; } void NzMemoryManager::Initialize() { char timeStr[23]; TimeInfo(timeStr); FILE* file = std::fopen(s_logFileName, "w"); std::fprintf(file, "%s ==============================\n", timeStr); std::fprintf(file, "%s Nazara Memory Leak Tracker \n", timeStr); std::fprintf(file, "%s ==============================\n", timeStr); std::fclose(file); if (std::atexit(Uninitialize) != 0) { static NzMemoryManager manager; } #ifdef NAZARA_PLATFORM_WINDOWS InitializeCriticalSection(&s_mutex); #endif s_initialized = true; } void NzMemoryManager::TimeInfo(char buffer[23]) { time_t currentTime = std::time(nullptr); std::strftime(buffer, 23, "%d/%m/%Y - %H:%M:%S:", std::localtime(&currentTime)); } void NzMemoryManager::Uninitialize() { #ifdef NAZARA_PLATFORM_WINDOWS DeleteCriticalSection(&s_mutex); #endif FILE* log = std::fopen(s_logFileName, "a"); char timeStr[23]; TimeInfo(timeStr); std::fprintf(log, "%s Application finished, checking leaks...\n", timeStr); if (s_allocatedBlock == 0) { std::fprintf(log, "%s ==============================\n", timeStr); std::fprintf(log, "%s No leak detected \n", timeStr); std::fprintf(log, "%s ==============================", timeStr); } else { std::fprintf(log, "%s ==============================\n", timeStr); std::fprintf(log, "%s Leaks have been detected \n", timeStr); std::fprintf(log, "%s ==============================\n\n", timeStr); std::fputs("Leak list:\n", log); Block* ptr = s_list.next; while (ptr != &s_list) { if (ptr->file) std::fprintf(log, "-0x%p -> %zu bytes allocated at %s:%u\n", reinterpret_cast<nzUInt8*>(ptr) + sizeof(Block), ptr->size, ptr->file, ptr->line); else std::fprintf(log, "-0x%p -> %zu bytes allocated at unknown position\n", reinterpret_cast<nzUInt8*>(ptr) + sizeof(Block), ptr->size); void* pointer = ptr; ptr = ptr->next; std::free(pointer); } std::fprintf(log, "\n%u blocks leaked (%zu bytes)", s_allocatedBlock, s_allocatedSize); } std::fclose(log); } <|endoftext|>
<commit_before>//===-- MessageObjects.cpp --------------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "MessageObjects.h" #include "lldb/Utility/StructuredData.h" #include "llvm/ADT/StringExtras.h" #include "gtest/gtest.h" using namespace lldb_private; using namespace llvm; using namespace llvm::support; namespace llgs_tests { Expected<ProcessInfo> ProcessInfo::Create(StringRef response) { ProcessInfo process_info; auto elements_or_error = SplitUniquePairList("ProcessInfo", response); if (!elements_or_error) return elements_or_error.takeError(); auto &elements = *elements_or_error; if (elements["pid"].getAsInteger(16, process_info.m_pid)) return make_parsing_error("ProcessInfo: pid"); if (elements["parent-pid"].getAsInteger(16, process_info.m_parent_pid)) return make_parsing_error("ProcessInfo: parent-pid"); if (elements["real-uid"].getAsInteger(16, process_info.m_real_uid)) return make_parsing_error("ProcessInfo: real-uid"); if (elements["real-gid"].getAsInteger(16, process_info.m_real_gid)) return make_parsing_error("ProcessInfo: real-uid"); if (elements["effective-uid"].getAsInteger(16, process_info.m_effective_uid)) return make_parsing_error("ProcessInfo: effective-uid"); if (elements["effective-gid"].getAsInteger(16, process_info.m_effective_gid)) return make_parsing_error("ProcessInfo: effective-gid"); if (elements["ptrsize"].getAsInteger(10, process_info.m_ptrsize)) return make_parsing_error("ProcessInfo: ptrsize"); process_info.m_triple = fromHex(elements["triple"]); StringRef endian_str = elements["endian"]; if (endian_str == "little") process_info.m_endian = support::little; else if (endian_str == "big") process_info.m_endian = support::big; else return make_parsing_error("ProcessInfo: endian"); return process_info; } lldb::pid_t ProcessInfo::GetPid() const { return m_pid; } endianness ProcessInfo::GetEndian() const { return m_endian; } //====== ThreadInfo ============================================================ ThreadInfo::ThreadInfo(StringRef name, StringRef reason, const RegisterMap &registers, unsigned int signal) : m_name(name.str()), m_reason(reason.str()), m_registers(registers), m_signal(signal) {} StringRef ThreadInfo::ReadRegister(unsigned int register_id) const { return m_registers.lookup(register_id); } bool ThreadInfo::ReadRegisterAsUint64(unsigned int register_id, uint64_t &value) const { StringRef value_str(m_registers.lookup(register_id)); if (value_str.getAsInteger(16, value)) { GTEST_LOG_(ERROR) << formatv("ThreadInfo: Unable to parse register value at {0}.", register_id) .str(); return false; } sys::swapByteOrder(value); return true; } //====== JThreadsInfo ========================================================== Expected<JThreadsInfo> JThreadsInfo::Create(StringRef response, endianness endian) { JThreadsInfo jthreads_info; StructuredData::ObjectSP json = StructuredData::ParseJSON(response); StructuredData::Array *array = json->GetAsArray(); if (!array) return make_parsing_error("JThreadsInfo: JSON array"); for (size_t i = 0; i < array->GetSize(); i++) { StructuredData::Dictionary *thread_info; array->GetItemAtIndexAsDictionary(i, thread_info); if (!thread_info) return make_parsing_error("JThreadsInfo: JSON obj at {0}", i); StringRef name, reason; thread_info->GetValueForKeyAsString("name", name); thread_info->GetValueForKeyAsString("reason", reason); uint64_t signal; thread_info->GetValueForKeyAsInteger("signal", signal); uint64_t tid; thread_info->GetValueForKeyAsInteger("tid", tid); StructuredData::Dictionary *register_dict; thread_info->GetValueForKeyAsDictionary("registers", register_dict); if (!register_dict) return make_parsing_error("JThreadsInfo: registers JSON obj"); RegisterMap registers; auto keys_obj = register_dict->GetKeys(); auto keys = keys_obj->GetAsArray(); for (size_t i = 0; i < keys->GetSize(); i++) { StringRef key_str, value_str; keys->GetItemAtIndexAsString(i, key_str); register_dict->GetValueForKeyAsString(key_str, value_str); unsigned int register_id; if (key_str.getAsInteger(10, register_id)) return make_parsing_error("JThreadsInfo: register key[{0}]", i); registers[register_id] = value_str.str(); } jthreads_info.m_thread_infos[tid] = ThreadInfo(name, reason, registers, signal); } return jthreads_info; } const ThreadInfoMap &JThreadsInfo::GetThreadInfos() const { return m_thread_infos; } //====== StopReply ============================================================= const U64Map &StopReply::GetThreadPcs() const { return m_thread_pcs; } Expected<StopReply> StopReply::Create(StringRef response, llvm::support::endianness endian) { if (response.size() < 3 || !response.consume_front("T")) return make_parsing_error("StopReply: Invalid packet"); StopReply stop_reply; StringRef signal = response.take_front(2); response = response.drop_front(2); if (!llvm::to_integer(signal, stop_reply.m_signal, 16)) return make_parsing_error("StopReply: stop signal"); auto elements = SplitPairList(response); for (StringRef field : {"name", "reason", "thread", "threads", "thread-pcs"}) { // This will insert an empty field if there is none. In the future, we // should probably differentiate between these fields not being present and // them being empty, but right now no tests depends on this. if (elements.insert({field, {""}}).first->second.size() != 1) return make_parsing_error( "StopReply: got multiple responses for the {0} field", field); } stop_reply.m_name = elements["name"][0]; stop_reply.m_reason = elements["reason"][0]; if (!llvm::to_integer(elements["thread"][0], stop_reply.m_thread, 16)) return make_parsing_error("StopReply: thread"); SmallVector<StringRef, 20> threads; SmallVector<StringRef, 20> pcs; elements["threads"][0].split(threads, ','); elements["thread-pcs"][0].split(pcs, ','); if (threads.size() != pcs.size()) return make_parsing_error("StopReply: thread/PC count mismatch"); for (size_t i = 0; i < threads.size(); i++) { lldb::tid_t thread_id; uint64_t pc; if (threads[i].getAsInteger(16, thread_id)) return make_parsing_error("StopReply: thread ID at [{0}].", i); if (pcs[i].getAsInteger(16, pc)) return make_parsing_error("StopReply: thread PC at [{0}].", i); stop_reply.m_thread_pcs[thread_id] = pc; } for (auto i = elements.begin(); i != elements.end(); i++) { StringRef key = i->getKey(); const auto &val = i->getValue(); if (key.size() == 2) { unsigned int reg; if (key.getAsInteger(16, reg)) continue; if (val.size() != 1) return make_parsing_error( "StopReply: multiple entries for register field [{0:x}]", reg); stop_reply.m_registers[reg] = val[0].str(); } } return stop_reply; } //====== Globals =============================================================== Expected<StringMap<StringRef>> SplitUniquePairList(StringRef caller, StringRef str) { SmallVector<StringRef, 20> elements; str.split(elements, ';'); StringMap<StringRef> pairs; for (StringRef s : elements) { std::pair<StringRef, StringRef> pair = s.split(':'); if (pairs.count(pair.first)) return make_parsing_error("{0}: Duplicate Key: {1}", caller, pair.first); pairs.insert(pair); } return pairs; } StringMap<SmallVector<StringRef, 2>> SplitPairList(StringRef str) { SmallVector<StringRef, 20> elements; str.split(elements, ';'); StringMap<SmallVector<StringRef, 2>> pairs; for (StringRef s : elements) { std::pair<StringRef, StringRef> pair = s.split(':'); pairs[pair.first].push_back(pair.second); } return pairs; } } // namespace llgs_tests <commit_msg>lldb-server tests: Fix undefined behavior<commit_after>//===-- MessageObjects.cpp --------------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "MessageObjects.h" #include "lldb/Utility/StructuredData.h" #include "llvm/ADT/StringExtras.h" #include "gtest/gtest.h" using namespace lldb_private; using namespace llvm; using namespace llvm::support; namespace llgs_tests { Expected<ProcessInfo> ProcessInfo::Create(StringRef response) { ProcessInfo process_info; auto elements_or_error = SplitUniquePairList("ProcessInfo", response); if (!elements_or_error) return elements_or_error.takeError(); auto &elements = *elements_or_error; if (elements["pid"].getAsInteger(16, process_info.m_pid)) return make_parsing_error("ProcessInfo: pid"); if (elements["parent-pid"].getAsInteger(16, process_info.m_parent_pid)) return make_parsing_error("ProcessInfo: parent-pid"); if (elements["real-uid"].getAsInteger(16, process_info.m_real_uid)) return make_parsing_error("ProcessInfo: real-uid"); if (elements["real-gid"].getAsInteger(16, process_info.m_real_gid)) return make_parsing_error("ProcessInfo: real-uid"); if (elements["effective-uid"].getAsInteger(16, process_info.m_effective_uid)) return make_parsing_error("ProcessInfo: effective-uid"); if (elements["effective-gid"].getAsInteger(16, process_info.m_effective_gid)) return make_parsing_error("ProcessInfo: effective-gid"); if (elements["ptrsize"].getAsInteger(10, process_info.m_ptrsize)) return make_parsing_error("ProcessInfo: ptrsize"); process_info.m_triple = fromHex(elements["triple"]); StringRef endian_str = elements["endian"]; if (endian_str == "little") process_info.m_endian = support::little; else if (endian_str == "big") process_info.m_endian = support::big; else return make_parsing_error("ProcessInfo: endian"); return process_info; } lldb::pid_t ProcessInfo::GetPid() const { return m_pid; } endianness ProcessInfo::GetEndian() const { return m_endian; } //====== ThreadInfo ============================================================ ThreadInfo::ThreadInfo(StringRef name, StringRef reason, const RegisterMap &registers, unsigned int signal) : m_name(name.str()), m_reason(reason.str()), m_registers(registers), m_signal(signal) {} StringRef ThreadInfo::ReadRegister(unsigned int register_id) const { return m_registers.lookup(register_id); } bool ThreadInfo::ReadRegisterAsUint64(unsigned int register_id, uint64_t &value) const { std::string value_str(m_registers.lookup(register_id)); if (!llvm::to_integer(value_str, value, 16)) { GTEST_LOG_(ERROR) << formatv("ThreadInfo: Unable to parse register value at {0}.", register_id) .str(); return false; } sys::swapByteOrder(value); return true; } //====== JThreadsInfo ========================================================== Expected<JThreadsInfo> JThreadsInfo::Create(StringRef response, endianness endian) { JThreadsInfo jthreads_info; StructuredData::ObjectSP json = StructuredData::ParseJSON(response); StructuredData::Array *array = json->GetAsArray(); if (!array) return make_parsing_error("JThreadsInfo: JSON array"); for (size_t i = 0; i < array->GetSize(); i++) { StructuredData::Dictionary *thread_info; array->GetItemAtIndexAsDictionary(i, thread_info); if (!thread_info) return make_parsing_error("JThreadsInfo: JSON obj at {0}", i); StringRef name, reason; thread_info->GetValueForKeyAsString("name", name); thread_info->GetValueForKeyAsString("reason", reason); uint64_t signal; thread_info->GetValueForKeyAsInteger("signal", signal); uint64_t tid; thread_info->GetValueForKeyAsInteger("tid", tid); StructuredData::Dictionary *register_dict; thread_info->GetValueForKeyAsDictionary("registers", register_dict); if (!register_dict) return make_parsing_error("JThreadsInfo: registers JSON obj"); RegisterMap registers; auto keys_obj = register_dict->GetKeys(); auto keys = keys_obj->GetAsArray(); for (size_t i = 0; i < keys->GetSize(); i++) { StringRef key_str, value_str; keys->GetItemAtIndexAsString(i, key_str); register_dict->GetValueForKeyAsString(key_str, value_str); unsigned int register_id; if (key_str.getAsInteger(10, register_id)) return make_parsing_error("JThreadsInfo: register key[{0}]", i); registers[register_id] = value_str.str(); } jthreads_info.m_thread_infos[tid] = ThreadInfo(name, reason, registers, signal); } return jthreads_info; } const ThreadInfoMap &JThreadsInfo::GetThreadInfos() const { return m_thread_infos; } //====== StopReply ============================================================= const U64Map &StopReply::GetThreadPcs() const { return m_thread_pcs; } Expected<StopReply> StopReply::Create(StringRef response, llvm::support::endianness endian) { if (response.size() < 3 || !response.consume_front("T")) return make_parsing_error("StopReply: Invalid packet"); StopReply stop_reply; StringRef signal = response.take_front(2); response = response.drop_front(2); if (!llvm::to_integer(signal, stop_reply.m_signal, 16)) return make_parsing_error("StopReply: stop signal"); auto elements = SplitPairList(response); for (StringRef field : {"name", "reason", "thread", "threads", "thread-pcs"}) { // This will insert an empty field if there is none. In the future, we // should probably differentiate between these fields not being present and // them being empty, but right now no tests depends on this. if (elements.insert({field, {""}}).first->second.size() != 1) return make_parsing_error( "StopReply: got multiple responses for the {0} field", field); } stop_reply.m_name = elements["name"][0]; stop_reply.m_reason = elements["reason"][0]; if (!llvm::to_integer(elements["thread"][0], stop_reply.m_thread, 16)) return make_parsing_error("StopReply: thread"); SmallVector<StringRef, 20> threads; SmallVector<StringRef, 20> pcs; elements["threads"][0].split(threads, ','); elements["thread-pcs"][0].split(pcs, ','); if (threads.size() != pcs.size()) return make_parsing_error("StopReply: thread/PC count mismatch"); for (size_t i = 0; i < threads.size(); i++) { lldb::tid_t thread_id; uint64_t pc; if (threads[i].getAsInteger(16, thread_id)) return make_parsing_error("StopReply: thread ID at [{0}].", i); if (pcs[i].getAsInteger(16, pc)) return make_parsing_error("StopReply: thread PC at [{0}].", i); stop_reply.m_thread_pcs[thread_id] = pc; } for (auto i = elements.begin(); i != elements.end(); i++) { StringRef key = i->getKey(); const auto &val = i->getValue(); if (key.size() == 2) { unsigned int reg; if (key.getAsInteger(16, reg)) continue; if (val.size() != 1) return make_parsing_error( "StopReply: multiple entries for register field [{0:x}]", reg); stop_reply.m_registers[reg] = val[0].str(); } } return stop_reply; } //====== Globals =============================================================== Expected<StringMap<StringRef>> SplitUniquePairList(StringRef caller, StringRef str) { SmallVector<StringRef, 20> elements; str.split(elements, ';'); StringMap<StringRef> pairs; for (StringRef s : elements) { std::pair<StringRef, StringRef> pair = s.split(':'); if (pairs.count(pair.first)) return make_parsing_error("{0}: Duplicate Key: {1}", caller, pair.first); pairs.insert(pair); } return pairs; } StringMap<SmallVector<StringRef, 2>> SplitPairList(StringRef str) { SmallVector<StringRef, 20> elements; str.split(elements, ';'); StringMap<SmallVector<StringRef, 2>> pairs; for (StringRef s : elements) { std::pair<StringRef, StringRef> pair = s.split(':'); pairs[pair.first].push_back(pair.second); } return pairs; } } // namespace llgs_tests <|endoftext|>
<commit_before>/* * Jamoma DSP Soundfile Player * Copyright © 2010, Tim Place * * License: This code is licensed under the terms of the "New BSD License" * http://creativecommons.org/licenses/BSD/ */ #include "TTSoundfilePlayer.h" #define thisTTClass TTSoundfilePlayer #define thisTTClassName "soundfile.player" #define thisTTClassTags "audio, soundfile, playback" TT_AUDIO_CONSTRUCTOR, mFilePath(kTTSymEmpty), mSoundFile(NULL), mPlay(false), mLoop(false), mContinue(false), mSeek(0), mNumChannels(0), mNumBufferFrames(0) { addAttributeWithSetter( FilePath, kTypeSymbol); addAttributeWithSetter( Play, kTypeBoolean); addAttributeWithSetter( Seek, kTypeFloat64); addAttribute( Loop, kTypeBoolean); addAttribute( NumChannels, kTypeUInt16); addAttributeProperty( NumChannels, readOnly, kTTBoolYes); addMessage(Pause); addMessage(Resume); setProcessMethod(processAudio); //setAttributeValue(TT("MaxNumChannels"), arguments); // This attribute is inherited } TTSoundfilePlayer::~TTSoundfilePlayer() { setAttributeValue(TT("Play"), kTTBoolNo); if (mSoundFile) sf_close(mSoundFile); } // takes a POSIX path, e.g. /Users/tim/Music/Demos/whiteandnerdy.aif TTErr TTSoundfilePlayer::setFilePath(const TTValue& newValue) { TTSymbolPtr potentialFilePath = newValue; SNDFILE* soundfile; #ifdef TT_PLATFORM_WIN // There is a bug in libsndfile on Windows where upon return from this function a runtime check fails // because the stack is corrupted around soundfileInfo when sf_open() is called. // We work around this by allocating some extra memory to absorb the overrun. [tap] SF_INFO soundfileInfo[2]; #else SF_INFO soundfileInfo[1]; #endif memset(&soundfileInfo, 0, sizeof(SF_INFO)); //soundfileInfo.format = 0; soundfile = sf_open(potentialFilePath->getCString(), SFM_READ, soundfileInfo); if (soundfile) { SNDFILE* oldSoundFile = mSoundFile; mSoundFile = soundfile; if (oldSoundFile) sf_close(oldSoundFile); memcpy(&mSoundFileInfo, soundfileInfo, sizeof(SF_INFO)); mFilePath = potentialFilePath; mPlay = 0; mContinue = 1; //eliminating previous pause state // TODO: fill in things like the NumChannels attr here return kTTErrNone; } else return kTTErrGeneric; } TTErr TTSoundfilePlayer::setPlay(const TTValue& newValue) { mPlay = newValue; mContinue = 1; //eliminating previous pause state if (mPlay == 0){ if (mSoundFile){ mSeek = 0; sf_seek(mSoundFile, 0, SEEK_SET); } } return kTTErrNone; } TTErr TTSoundfilePlayer::setSeek(const TTValue& newValue) { if (mSoundFile) { mSeek = newValue; mSeek = mSeek * sr/1000.0; mContinue = 1; //eliminating previous pause state sf_seek(mSoundFile, mSeek, SEEK_SET); mPlay = 1; return kTTErrNone; } else return kTTErrGeneric; } TTErr TTSoundfilePlayer::Pause() { mContinue = 0; return kTTErrNone; } TTErr TTSoundfilePlayer::Resume() { mContinue = 1; return kTTErrNone; } TTErr TTSoundfilePlayer::processAudio(TTAudioSignalArrayPtr inputs, TTAudioSignalArrayPtr outputs) { TTAudioSignal& out = outputs->getSignal(0); TTUInt16 outChannelCount = out.getMaxNumChannelsAsInt(); TTUInt16 numFrames = out.getVectorSizeAsInt(); TTBoolean bufferNeedsResize = NO; sf_count_t numSamplesRead; TTUInt16 n; TTSampleValuePtr outSample; TTUInt16 channel; if (mSoundFile) { // resize of the number of output channels, if needed if (outChannelCount != mSoundFileInfo.channels || !mNumChannels) { mNumChannels = mSoundFileInfo.channels; out.setMaxNumChannels(mNumChannels); bufferNeedsResize = YES; out.setNumChannelsWithInt(mNumChannels); } if (mNumBufferFrames != numFrames) { mNumBufferFrames = numFrames; bufferNeedsResize = YES; } if (bufferNeedsResize) mBuffer.resize(mNumBufferFrames * mNumChannels); if (!mNumChannels) return TTAudioObject::muteProcess(inputs, outputs); // if there is an input, we want to treat it as a sample-accurate on/off switch for playback //if (inputs->numAudioSignals) { // ; // TODO: implement this //} //else { mBuffer.assign(mBuffer.size(), 0.0); if (mPlay && mContinue) { numSamplesRead = sf_read_double(mSoundFile, &mBuffer[0], numFrames*mNumChannels); if (numSamplesRead < numFrames*mNumChannels) { sf_seek(mSoundFile, mSeek, SEEK_SET); mPlay = mLoop; } } for (channel=0; channel<mNumChannels; channel++) { outSample = out.mSampleVectors[channel]; for (n=0; n<numFrames; n++) outSample[n] = mBuffer[n * mNumChannels + channel]; } } else { //no soundfile selected, we send out a zero signal on one channel out.setMaxNumChannels(1); out.setNumChannelsWithInt(1); for (n=0; n<numFrames; n++) out.mSampleVectors[0][n] = 0.0; } return kTTErrNone; } <commit_msg>attempt to add a playHead position signal<commit_after>/* * Jamoma DSP Soundfile Player * Copyright © 2010, Tim Place * * License: This code is licensed under the terms of the "New BSD License" * http://creativecommons.org/licenses/BSD/ */ #include "TTSoundfilePlayer.h" #define thisTTClass TTSoundfilePlayer #define thisTTClassName "soundfile.player" #define thisTTClassTags "audio, soundfile, playback" TT_AUDIO_CONSTRUCTOR, mFilePath(kTTSymEmpty), mSoundFile(NULL), mPlay(false), mLoop(false), mContinue(false), mSeek(0), mNumChannels(0), mNumBufferFrames(0) { addAttributeWithSetter( FilePath, kTypeSymbol); addAttributeWithSetter( Play, kTypeBoolean); addAttributeWithSetter( Seek, kTypeFloat64); addAttribute( Loop, kTypeBoolean); addAttribute( NumChannels, kTypeUInt16); addAttributeProperty( NumChannels, readOnly, kTTBoolYes); addMessage(Pause); addMessage(Resume); setProcessMethod(processAudio); //setAttributeValue(TT("MaxNumChannels"), arguments); // This attribute is inherited } TTSoundfilePlayer::~TTSoundfilePlayer() { setAttributeValue(TT("Play"), kTTBoolNo); if (mSoundFile) sf_close(mSoundFile); } // takes a POSIX path, e.g. /Users/tim/Music/Demos/whiteandnerdy.aif TTErr TTSoundfilePlayer::setFilePath(const TTValue& newValue) { TTSymbolPtr potentialFilePath = newValue; SNDFILE* soundfile; #ifdef TT_PLATFORM_WIN // There is a bug in libsndfile on Windows where upon return from this function a runtime check fails // because the stack is corrupted around soundfileInfo when sf_open() is called. // We work around this by allocating some extra memory to absorb the overrun. [tap] SF_INFO soundfileInfo[2]; #else SF_INFO soundfileInfo[1]; #endif memset(&soundfileInfo, 0, sizeof(SF_INFO)); //soundfileInfo.format = 0; soundfile = sf_open(potentialFilePath->getCString(), SFM_READ, soundfileInfo); if (soundfile) { SNDFILE* oldSoundFile = mSoundFile; mSoundFile = soundfile; if (oldSoundFile) sf_close(oldSoundFile); memcpy(&mSoundFileInfo, soundfileInfo, sizeof(SF_INFO)); mFilePath = potentialFilePath; mPlay = 0; mContinue = 1; //eliminating previous pause state // TODO: fill in things like the NumChannels attr here return kTTErrNone; } else return kTTErrGeneric; } TTErr TTSoundfilePlayer::setPlay(const TTValue& newValue) { mPlay = newValue; mContinue = 1; //eliminating previous pause state if (mPlay == 0){ if (mSoundFile){ mSeek = 0; sf_seek(mSoundFile, 0, SEEK_SET); } } return kTTErrNone; } TTErr TTSoundfilePlayer::setSeek(const TTValue& newValue) { if (mSoundFile) { mSeek = newValue; mSeek = mSeek * sr/1000.0; mContinue = 1; //eliminating previous pause state sf_seek(mSoundFile, mSeek, SEEK_SET); mPlay = 1; return kTTErrNone; } else return kTTErrGeneric; } TTErr TTSoundfilePlayer::Pause() { mContinue = 0; return kTTErrNone; } TTErr TTSoundfilePlayer::Resume() { mContinue = 1; return kTTErrNone; } TTErr TTSoundfilePlayer::processAudio(TTAudioSignalArrayPtr inputs, TTAudioSignalArrayPtr outputs) { TTAudioSignal& out = outputs->getSignal(0); TTAudioSignal& outPlayhead = outputs->getSignal(1); TTUInt16 outChannelCount = out.getMaxNumChannelsAsInt(); TTUInt16 numFrames = out.getVectorSizeAsInt(); TTBoolean bufferNeedsResize = NO; sf_count_t numSamplesRead; TTUInt16 n; TTSampleValuePtr outSample;// outSamplePlayhead; TTUInt16 channel; if (mSoundFile) { // resize of the number of output channels, if needed if (outChannelCount != mSoundFileInfo.channels || !mNumChannels) { mNumChannels = mSoundFileInfo.channels; out.setMaxNumChannels(mNumChannels); bufferNeedsResize = YES; out.setNumChannelsWithInt(mNumChannels); outPlayhead.setMaxNumChannels(1); outPlayhead.setNumChannelsWithInt(1); } if (mNumBufferFrames != numFrames) { mNumBufferFrames = numFrames; bufferNeedsResize = YES; } if (bufferNeedsResize) mBuffer.resize(mNumBufferFrames * mNumChannels); if (!mNumChannels) return TTAudioObject::muteProcess(inputs, outputs); // if there is an input, we want to treat it as a sample-accurate on/off switch for playback //if (inputs->numAudioSignals) { // ; // TODO: implement this //} //else { mBuffer.assign(mBuffer.size(), 0.0); if (mPlay && mContinue) { numSamplesRead = sf_read_double(mSoundFile, &mBuffer[0], numFrames*mNumChannels); if (numSamplesRead < numFrames*mNumChannels) { sf_seek(mSoundFile, mSeek, SEEK_SET); mPlay = mLoop; } } for (channel=0; channel<mNumChannels; channel++) { outSample = out.mSampleVectors[channel]; for (n=0; n<numFrames; n++) outSample[n] = mBuffer[n * mNumChannels + channel]; } for (n=0; n<numFrames; n++) outPlayhead.mSampleVectors[0][n] = n; // FIXME: this is a dummy value, replace with a proper playhead position } else { //no soundfile selected, we send out a zero signal on one channel out.setMaxNumChannels(1); out.setNumChannelsWithInt(1); for (n=0; n<numFrames; n++) out.mSampleVectors[0][n] = 0.0; } return kTTErrNone; } <|endoftext|>
<commit_before>#include "SynchronousCameraQueue.hpp" #include <ros/console.h> #include "../../matlab/profiling.hpp" SynchronousCameraQueue::SynchronousCameraQueue(long int arrivalDelay, long int maxDelay, long maxGroupInterval, bool ensureCam0) { this->maxDelay = maxDelay; this->arrivalDelay = arrivalDelay; this->maxGroupInterval = maxGroupInterval; this->ensureCam0 = ensureCam0; lastArrivalTime = 0; minimumPictureTime = 0; ROS_INFO("SynchronousCameraQueue(): arrivalDelay = %.2fms, maxDelay = %.2fms, maxGroupInterval = %.2fms, ensureCam0 = %s", arrivalDelay / 1e6, maxDelay / 1e6, maxGroupInterval / 1e6, ensureCam0 ? "true" : "false"); } size_t SynchronousCameraQueue::getSize() { return queue.size(); } bool SynchronousCameraQueue::dataAvailable() { long int currentTime = getNanoTime(); if (queue.size() == 0) { return false; } if (queue.size() >= camNos.size()) { return true; } for (std::list<Bucket>::reverse_iterator it = queue.rbegin(); it != queue.rend(); it++) { if (currentTime - it->arrivalTime > maxDelay) { return true; } if (currentTime - it->arrivalTime > arrivalDelay && queue.size() > 2) { return true; } } return false; } void SynchronousCameraQueue::enqueueInternal(CameraData data) { // Make it impossible to insert data for a time earlier than the last dequeue() result if (data.time <= minimumPictureTime) { ROS_DEBUG("Dropped data from cam %d, copter %d because it was too old (time: %ld)", data.camNo, data.quadcopterId, data.time); return; } else { // ROS_DEBUG("Inserting data from cam %d, copter %d (time: %ld)", data.camNo, data.quadcopterId, data.time); } Bucket b; b.data = data; b.arrivalTime = getNanoTime(); if (b.arrivalTime <= lastArrivalTime) { lastArrivalTime++; b.arrivalTime = lastArrivalTime; } std::list<Bucket> tmp; tmp.push_back(b); queue.merge(tmp); camNos.insert(data.camNo); } std::vector<CameraData> SynchronousCameraQueue::dequeue() { long int currentTime = getNanoTime(); Group result; for (std::list<Bucket>::iterator it = queue.begin(); it != queue.end(); it++) { Group tmp = searchGroup(it, currentTime, queue.begin(), --queue.end()); if (tmp.isValid() && (!result.isValid() || tmp.getValue() > result.getValue())) { result = tmp; } } if (result.isValid()) { //printQueue(); cutOffQueue(result.getYoungest()); if (result.getData().size() < camNos.size()) { ROS_WARN("Quadcopter %d is only seen by %ld cameras, but there are %ld entries in the queue", result.getData()[0].quadcopterId, result.getData().size(), queue.size()); } return result.getData(); } else { // Search for element which is older than maxDelay for (std::list<Bucket>::iterator it = queue.begin(); it != queue.end(); it++) { if (currentTime - it->arrivalTime > maxDelay) { ROS_WARN("Strange things are happening! The only thing to return is old and lonely (and probably invalid, but better than nothing so we return it anyways)."); // element is overdue and nothing else was found, so return group, even if it's invalid. result = searchGroup(it, currentTime, queue.begin(), --queue.end()); //printQueue(); cutOffQueue(result.getYoungest()); return result.getData(); } } return std::vector<CameraData>(); } } SynchronousCameraQueue::Group SynchronousCameraQueue::searchGroup(std::list<Bucket>::iterator it, long int currentTime, std::list<Bucket>::iterator begin, std::list<Bucket>::iterator end) { Group result(it, currentTime, arrivalDelay, maxDelay, maxGroupInterval, camNos.size(), ensureCam0); std::set<int> usedCamNos; usedCamNos.insert(it->data.camNo); // The current rand of the search area std::list<Bucket>::iterator left = it; std::list<Bucket>::iterator right = it; // Temp iterator to reduce the amount of if/else std::list<Bucket>::iterator current = it; // Which side of the rand to go int direction = 0; // -1 left, 1 right, 0 terminate do { direction = 0; // Choose direction if (left != begin && right != end) { // Both directions are possible left--; right++; // Prioritize the values that'd result in a smaller range if (result.getMinTime() - left->data.time > right->data.time - result.getMaxTime()) { left++; direction = 1; current = right; } else { right--; direction = -1; current = left; } // Not both directions are possible // Go to the direction that is possible } else if (left != begin) { direction = -1; current = --left; } else if (right != end) { direction = 1; current = ++right; } // Check if the interval size would still be below maxGroupInterval if the next element would be added // Abort if the interval size cannot be enlarged if (result.wouldInvalidateGroup(current)) { direction = 0; } if (direction != 0 && usedCamNos.count(current->data.camNo) == 0) { // Mark camNo as used and add to result usedCamNos.insert(current->data.camNo); result.add(current); // If no more other cameras available, abort if (result.getData().size() == camNos.size()) { direction = 0; } } } while (direction != 0); result.calculateValue(); return result; } void SynchronousCameraQueue::cutOffQueue(std::list<Bucket>::iterator it) { minimumPictureTime = it->data.time; std::list<Bucket> toDelete; toDelete.splice(toDelete.begin(), queue, queue.begin(), it); queue.pop_front(); } void SynchronousCameraQueue::printQueue() { ROS_DEBUG("Printing list"); for (std::list<Bucket>::iterator it = queue.begin(); it != queue.end(); it++) { ROS_DEBUG("Cam %d, Copter %d: arrival %ld, snaptime %ld", it->data.camNo, it->data.quadcopterId, it->arrivalTime, it->data.time); } } <commit_msg>Shortened output<commit_after>#include "SynchronousCameraQueue.hpp" #include <ros/console.h> #include "../../matlab/profiling.hpp" SynchronousCameraQueue::SynchronousCameraQueue(long int arrivalDelay, long int maxDelay, long maxGroupInterval, bool ensureCam0) { this->maxDelay = maxDelay; this->arrivalDelay = arrivalDelay; this->maxGroupInterval = maxGroupInterval; this->ensureCam0 = ensureCam0; lastArrivalTime = 0; minimumPictureTime = 0; ROS_INFO("SynchronousCameraQueue(): arrivalDelay = %.2fms, maxDelay = %.2fms, maxGroupInterval = %.2fms, ensureCam0 = %s", arrivalDelay / 1e6, maxDelay / 1e6, maxGroupInterval / 1e6, ensureCam0 ? "true" : "false"); } size_t SynchronousCameraQueue::getSize() { return queue.size(); } bool SynchronousCameraQueue::dataAvailable() { long int currentTime = getNanoTime(); if (queue.size() == 0) { return false; } if (queue.size() >= camNos.size()) { return true; } for (std::list<Bucket>::reverse_iterator it = queue.rbegin(); it != queue.rend(); it++) { if (currentTime - it->arrivalTime > maxDelay) { return true; } if (currentTime - it->arrivalTime > arrivalDelay && queue.size() > 2) { return true; } } return false; } void SynchronousCameraQueue::enqueueInternal(CameraData data) { // Make it impossible to insert data for a time earlier than the last dequeue() result if (data.time <= minimumPictureTime) { ROS_DEBUG("Dropped data from cam %d, copter %d because it was too old (time: %ld)", data.camNo, data.quadcopterId, data.time); return; } else { // ROS_DEBUG("Inserting data from cam %d, copter %d (time: %ld)", data.camNo, data.quadcopterId, data.time); } Bucket b; b.data = data; b.arrivalTime = getNanoTime(); if (b.arrivalTime <= lastArrivalTime) { lastArrivalTime++; b.arrivalTime = lastArrivalTime; } std::list<Bucket> tmp; tmp.push_back(b); queue.merge(tmp); camNos.insert(data.camNo); } std::vector<CameraData> SynchronousCameraQueue::dequeue() { long int currentTime = getNanoTime(); Group result; for (std::list<Bucket>::iterator it = queue.begin(); it != queue.end(); it++) { Group tmp = searchGroup(it, currentTime, queue.begin(), --queue.end()); if (tmp.isValid() && (!result.isValid() || tmp.getValue() > result.getValue())) { result = tmp; } } if (result.isValid()) { //printQueue(); cutOffQueue(result.getYoungest()); if (result.getData().size() < camNos.size()) { ROS_WARN("Quadcopter %d is only seen by %ld cameras, but there are %ld entries in the queue", result.getData()[0].quadcopterId, result.getData().size(), queue.size()); } return result.getData(); } else { // Search for element which is older than maxDelay for (std::list<Bucket>::iterator it = queue.begin(); it != queue.end(); it++) { if (currentTime - it->arrivalTime > maxDelay) { ROS_WARN("The only thing to return is old and probably invalid, but better than nothing so we return it anyways."); // element is overdue and nothing else was found, so return group, even if it's invalid. result = searchGroup(it, currentTime, queue.begin(), --queue.end()); //printQueue(); cutOffQueue(result.getYoungest()); return result.getData(); } } return std::vector<CameraData>(); } } SynchronousCameraQueue::Group SynchronousCameraQueue::searchGroup(std::list<Bucket>::iterator it, long int currentTime, std::list<Bucket>::iterator begin, std::list<Bucket>::iterator end) { Group result(it, currentTime, arrivalDelay, maxDelay, maxGroupInterval, camNos.size(), ensureCam0); std::set<int> usedCamNos; usedCamNos.insert(it->data.camNo); // The current rand of the search area std::list<Bucket>::iterator left = it; std::list<Bucket>::iterator right = it; // Temp iterator to reduce the amount of if/else std::list<Bucket>::iterator current = it; // Which side of the rand to go int direction = 0; // -1 left, 1 right, 0 terminate do { direction = 0; // Choose direction if (left != begin && right != end) { // Both directions are possible left--; right++; // Prioritize the values that'd result in a smaller range if (result.getMinTime() - left->data.time > right->data.time - result.getMaxTime()) { left++; direction = 1; current = right; } else { right--; direction = -1; current = left; } // Not both directions are possible // Go to the direction that is possible } else if (left != begin) { direction = -1; current = --left; } else if (right != end) { direction = 1; current = ++right; } // Check if the interval size would still be below maxGroupInterval if the next element would be added // Abort if the interval size cannot be enlarged if (result.wouldInvalidateGroup(current)) { direction = 0; } if (direction != 0 && usedCamNos.count(current->data.camNo) == 0) { // Mark camNo as used and add to result usedCamNos.insert(current->data.camNo); result.add(current); // If no more other cameras available, abort if (result.getData().size() == camNos.size()) { direction = 0; } } } while (direction != 0); result.calculateValue(); return result; } void SynchronousCameraQueue::cutOffQueue(std::list<Bucket>::iterator it) { minimumPictureTime = it->data.time; std::list<Bucket> toDelete; toDelete.splice(toDelete.begin(), queue, queue.begin(), it); queue.pop_front(); } void SynchronousCameraQueue::printQueue() { ROS_DEBUG("Printing list"); for (std::list<Bucket>::iterator it = queue.begin(); it != queue.end(); it++) { ROS_DEBUG("Cam %d, Copter %d: arrival %ld, snaptime %ld", it->data.camNo, it->data.quadcopterId, it->arrivalTime, it->data.time); } } <|endoftext|>
<commit_before>/* Copyright (c) 2016 Bastien Durix 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. */ /** * \brief Draw shape test * \author Bastien Durix */ #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <shape/DiscreteShape.h> #include <boundary/DiscreteBoundary.h> #include <skeleton/Skeletons.h> #include <userinput/DrawShape.h> #include <algorithm/extractboundary/MarchingSquares.h> #include <algorithm/skeletonization/VoronoiSkeleton2D.h> #include <displayopencv/DisplayShapeOCV.h> int main() { shape::DiscreteShape<2>::Ptr dissh = userinput::DrawShape(640,480); //boundary::DiscreteBoundary<2>::Ptr disbnd = algorithm::extractboundary::MarchingSquare(dissh,4); //skeleton::GraphSkel2d::Ptr grskel = algorithm::skeletonization::VoronoiSkeleton2d(disbnd); cv::Mat image(480,640,CV_8UC3,cv::Scalar(0,0,0)); displayopencv::DisplayDiscreteShape(dissh,image,dissh->getFrame(),cv::Scalar(255,255,255)); cv::imwrite("res.png",image); return 0; } <commit_msg>Test display boundary function<commit_after>/* Copyright (c) 2016 Bastien Durix 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. */ /** * \brief Draw shape test * \author Bastien Durix */ #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <shape/DiscreteShape.h> #include <boundary/DiscreteBoundary.h> #include <skeleton/Skeletons.h> #include <userinput/DrawShape.h> #include <algorithm/extractboundary/MarchingSquares.h> #include <algorithm/skeletonization/VoronoiSkeleton2D.h> #include <displayopencv/DisplayShapeOCV.h> #include <displayopencv/DisplayBoundaryOCV.h> int main() { shape::DiscreteShape<2>::Ptr dissh = userinput::DrawShape(640,480); boundary::DiscreteBoundary<2>::Ptr disbnd = algorithm::extractboundary::MarchingSquare(dissh,2); //skeleton::GraphSkel2d::Ptr grskel = algorithm::skeletonization::VoronoiSkeleton2d(disbnd); cv::Mat image(480,640,CV_8UC3,cv::Scalar(0,0,0)); displayopencv::DisplayDiscreteShape(dissh,image,dissh->getFrame(),cv::Scalar(255,255,255)); displayopencv::DisplayDiscreteBoundary(disbnd,image,dissh->getFrame(),cv::Scalar(0,0,255)); cv::imwrite("res.png",image); return 0; } <|endoftext|>
<commit_before><commit_msg>Fix custom types in node list search<commit_after><|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: addresssettings.hxx,v $ * * $Revision: 1.5 $ * * last change: $Author: rt $ $Date: 2005-09-08 19:04:54 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef EXTENSIONS_ABP_ADDRESSSETTINGS_HXX #define EXTENSIONS_ABP_ADDRESSSETTINGS_HXX #ifndef _RTL_USTRING_HXX_ #include <rtl/ustring.hxx> #endif #ifndef EXTENSIONS_ABP_ABPTYPES_HXX #include "abptypes.hxx" #endif //......................................................................... namespace abp { //......................................................................... //===================================================================== //= AddressSourceType //===================================================================== enum AddressSourceType { AST_MORK, AST_EVOLUTION, AST_LDAP, AST_OUTLOOK, AST_OE, AST_OTHER, AST_INVALID }; //===================================================================== //= AddressSettings //===================================================================== struct AddressSettings { AddressSourceType eType; ::rtl::OUString sDataSourceName; ::rtl::OUString sRegisteredDataSourceName; ::rtl::OUString sSelectedTable; MapString2String aFieldMapping; sal_Bool bRegisterDataSource; }; //......................................................................... } // namespace abp //......................................................................... #endif // EXTENSIONS_ABP_ADDRESSSETTINGS_HXX <commit_msg>INTEGRATION: CWS tbab (1.4.160); FILE MERGED 2005/09/26 10:04:29 fs 1.4.160.2: RESYNC: (1.4-1.5); FILE MERGED 2005/05/31 11:27:26 fs 1.4.160.1: #i46390# Thunderbird support<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: addresssettings.hxx,v $ * * $Revision: 1.6 $ * * last change: $Author: hr $ $Date: 2005-09-29 10:39:58 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef EXTENSIONS_ABP_ADDRESSSETTINGS_HXX #define EXTENSIONS_ABP_ADDRESSSETTINGS_HXX #ifndef _RTL_USTRING_HXX_ #include <rtl/ustring.hxx> #endif #ifndef EXTENSIONS_ABP_ABPTYPES_HXX #include "abptypes.hxx" #endif //......................................................................... namespace abp { //......................................................................... //===================================================================== //= AddressSourceType //===================================================================== enum AddressSourceType { AST_MORK, AST_THUNDERBIRD, AST_EVOLUTION, AST_LDAP, AST_OUTLOOK, AST_OE, AST_OTHER, AST_INVALID }; //===================================================================== //= AddressSettings //===================================================================== struct AddressSettings { AddressSourceType eType; ::rtl::OUString sDataSourceName; ::rtl::OUString sRegisteredDataSourceName; ::rtl::OUString sSelectedTable; MapString2String aFieldMapping; sal_Bool bRegisterDataSource; }; //......................................................................... } // namespace abp //......................................................................... #endif // EXTENSIONS_ABP_ADDRESSSETTINGS_HXX <|endoftext|>
<commit_before>#include "USBDevice.h" #include <sstream> #include <stdexcept> #include <libusb-1.0/libusb.h> USBDevice::USBDevice( uint16_t idVendor, uint16_t idProduct) : m_ctx(NULL) , m_handle(NULL) , m_version(0.0) , m_idVendor(idVendor) , m_idProduct(idProduct) { int result = libusb_init(&m_ctx); if (result != LIBUSB_SUCCESS) { throw std::runtime_error(libusb_error_name(result)); } } USBDevice::~USBDevice() { if (m_handle) { // ignore the error (we don't want to throw in dtor) libusb_release_interface(m_handle, 0); // function returns void => no error checking libusb_close(m_handle); } // function returns void => no error checking libusb_exit(m_ctx); } uint32_t USBDevice::numDevices( uint16_t idVendor, uint16_t idProduct) { libusb_context* ctx; int result = libusb_init(&ctx); if (result != LIBUSB_SUCCESS) { throw std::runtime_error(libusb_error_name(result)); } // discover devices libusb_device **list; ssize_t cnt = libusb_get_device_list(NULL, &list); ssize_t i = 0; uint32_t num = 0; int err = 0; if (cnt < 0) { throw std::runtime_error("Error during get_device_list"); } for (i = 0; i < cnt; i++) { libusb_device *device = list[i]; libusb_device_descriptor deviceDescriptor; err = libusb_get_device_descriptor(device, &deviceDescriptor); if (err != LIBUSB_SUCCESS) { libusb_free_device_list(list, 1); throw std::runtime_error(libusb_error_name(err)); } else if (deviceDescriptor.idVendor == idVendor && deviceDescriptor.idProduct == idProduct) { ++num; } } libusb_free_device_list(list, 1); // function returns void => no error checking libusb_exit(ctx); return num; } void USBDevice::open( uint32_t devid) { // discover devices libusb_device **list; libusb_device *found = NULL; ssize_t cnt = libusb_get_device_list(NULL, &list); ssize_t i = 0; uint32_t foundid = 0; int err = 0; if (cnt < 0) { throw std::runtime_error("Error during get_device_list"); } for (i = 0; i < cnt; i++) { libusb_device *device = list[i]; libusb_device_descriptor deviceDescriptor; err = libusb_get_device_descriptor(device, &deviceDescriptor); if (err != LIBUSB_SUCCESS) { libusb_free_device_list(list, 1); throw std::runtime_error(libusb_error_name(err)); } else if (deviceDescriptor.idVendor == m_idVendor && deviceDescriptor.idProduct == m_idProduct) { if (foundid == devid) { found = device; break; } ++foundid; } } if (found) { err = libusb_open(found, &m_handle); if (err != LIBUSB_SUCCESS) { libusb_free_device_list(list, 1); throw std::runtime_error(libusb_error_name(err)); } libusb_device_descriptor deviceDescriptor; err = libusb_get_device_descriptor(found, &deviceDescriptor); if (err != LIBUSB_SUCCESS) { throw std::runtime_error(libusb_error_name(err)); } std::stringstream sstr; sstr << std::hex << (deviceDescriptor.bcdDevice >> 8) << "." << (deviceDescriptor.bcdDevice & 0xFF); sstr >> m_version; } libusb_free_device_list(list, 1); // configure if (m_handle) { err = libusb_set_configuration(m_handle, 1); if (err != LIBUSB_SUCCESS) { throw std::runtime_error(libusb_error_name(err)); } err = libusb_claim_interface(m_handle, 0); if (err != LIBUSB_SUCCESS) { throw std::runtime_error(libusb_error_name(err)); } } else { throw std::runtime_error("No matching USB Device found!"); } } void USBDevice::sendVendorSetup( uint8_t request, uint16_t value, uint16_t index, const unsigned char* data, uint16_t length) { if (!m_handle) { throw std::runtime_error("No valid device handle!"); } int status = libusb_control_transfer( m_handle, LIBUSB_REQUEST_TYPE_VENDOR, request, value, index, (unsigned char*)data, length, /*timeout*/ 1000); if (status != LIBUSB_SUCCESS) { throw std::runtime_error(libusb_error_name(status)); } } <commit_msg>USB-Support: improved error reporting [from crazyswarm]<commit_after>#include "USBDevice.h" #include <sstream> #include <stdexcept> #include <libusb-1.0/libusb.h> USBDevice::USBDevice( uint16_t idVendor, uint16_t idProduct) : m_ctx(NULL) , m_handle(NULL) , m_version(0.0) , m_idVendor(idVendor) , m_idProduct(idProduct) { int result = libusb_init(&m_ctx); if (result != LIBUSB_SUCCESS) { throw std::runtime_error(libusb_error_name(result)); } } USBDevice::~USBDevice() { if (m_handle) { // ignore the error (we don't want to throw in dtor) libusb_release_interface(m_handle, 0); // function returns void => no error checking libusb_close(m_handle); } // function returns void => no error checking libusb_exit(m_ctx); } uint32_t USBDevice::numDevices( uint16_t idVendor, uint16_t idProduct) { libusb_context* ctx; int result = libusb_init(&ctx); if (result != LIBUSB_SUCCESS) { throw std::runtime_error(libusb_error_name(result)); } // discover devices libusb_device **list; ssize_t cnt = libusb_get_device_list(NULL, &list); ssize_t i = 0; uint32_t num = 0; int err = 0; if (cnt < 0) { throw std::runtime_error("Error during get_device_list"); } for (i = 0; i < cnt; i++) { libusb_device *device = list[i]; libusb_device_descriptor deviceDescriptor; err = libusb_get_device_descriptor(device, &deviceDescriptor); if (err != LIBUSB_SUCCESS) { libusb_free_device_list(list, 1); throw std::runtime_error(libusb_error_name(err)); } else if (deviceDescriptor.idVendor == idVendor && deviceDescriptor.idProduct == idProduct) { ++num; } } libusb_free_device_list(list, 1); // function returns void => no error checking libusb_exit(ctx); return num; } void USBDevice::open( uint32_t devid) { // discover devices libusb_device **list; libusb_device *found = NULL; ssize_t cnt = libusb_get_device_list(NULL, &list); ssize_t i = 0; uint32_t foundid = 0; int err = 0; if (cnt < 0) { throw std::runtime_error("Error during get_device_list"); } for (i = 0; i < cnt; i++) { libusb_device *device = list[i]; libusb_device_descriptor deviceDescriptor; err = libusb_get_device_descriptor(device, &deviceDescriptor); if (err != LIBUSB_SUCCESS) { libusb_free_device_list(list, 1); throw std::runtime_error(libusb_error_name(err)); } else if (deviceDescriptor.idVendor == m_idVendor && deviceDescriptor.idProduct == m_idProduct) { if (foundid == devid) { found = device; break; } ++foundid; } } if (found) { err = libusb_open(found, &m_handle); if (err != LIBUSB_SUCCESS) { libusb_free_device_list(list, 1); throw std::runtime_error(libusb_error_name(err)); } libusb_device_descriptor deviceDescriptor; err = libusb_get_device_descriptor(found, &deviceDescriptor); if (err != LIBUSB_SUCCESS) { throw std::runtime_error(libusb_error_name(err)); } std::stringstream sstr; sstr << std::hex << (deviceDescriptor.bcdDevice >> 8) << "." << (deviceDescriptor.bcdDevice & 0xFF); sstr >> m_version; } libusb_free_device_list(list, 1); // configure if (m_handle) { err = libusb_set_configuration(m_handle, 1); if (err != LIBUSB_SUCCESS) { throw std::runtime_error(libusb_error_name(err)); } err = libusb_claim_interface(m_handle, 0); if (err != LIBUSB_SUCCESS) { throw std::runtime_error(libusb_error_name(err)); } } else { std::stringstream sstr; sstr << "No matching USB Device with devid = " << devid << " found!"; throw std::runtime_error(sstr.str()); } } void USBDevice::sendVendorSetup( uint8_t request, uint16_t value, uint16_t index, const unsigned char* data, uint16_t length) { if (!m_handle) { throw std::runtime_error("No valid device handle!"); } int status = libusb_control_transfer( m_handle, LIBUSB_REQUEST_TYPE_VENDOR, request, value, index, (unsigned char*)data, length, /*timeout*/ 1000); if (status != LIBUSB_SUCCESS) { throw std::runtime_error(libusb_error_name(status)); } } <|endoftext|>
<commit_before>/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <geode/geode_globals.hpp> #include <geode/DistributedSystem.hpp> #include "statistics/StatisticsManager.hpp" #include <geode/SystemProperties.hpp> #include <CppCacheLibrary.hpp> #include <Utils.hpp> #include <geode/Log.hpp> #include <geode/CacheFactory.hpp> #include <ace/OS.h> #include <ExpiryTaskManager.hpp> #include <CacheImpl.hpp> #include <ace/Guard_T.h> #include <ace/Recursive_Thread_Mutex.h> #include <geode/DataOutput.hpp> #include <TcrMessage.hpp> #include <DistributedSystemImpl.hpp> #include <RegionStats.hpp> #include <PoolStatistics.hpp> #include <DiffieHellman.hpp> #include "version.h" using namespace apache::geode::client; using namespace apache::geode::statistics; DistributedSystemPtr* DistributedSystem::m_instance_ptr = nullptr; bool DistributedSystem::m_connected = false; DistributedSystemImpl* DistributedSystem::m_impl = nullptr; ACE_Recursive_Thread_Mutex* g_disconnectLock = new ACE_Recursive_Thread_Mutex(); namespace { StatisticsManager* g_statMngr = nullptr; SystemProperties* g_sysProps = nullptr; } // namespace namespace apache { namespace geode { namespace client { void setLFH() { #ifdef _WIN32 static HINSTANCE kernelMod = nullptr; if (kernelMod == nullptr) { kernelMod = GetModuleHandle("kernel32"); if (kernelMod != nullptr) { typedef BOOL(WINAPI * PHSI)( HANDLE HeapHandle, HEAP_INFORMATION_CLASS HeapInformationClass, PVOID HeapInformation, SIZE_T HeapInformationLength); typedef HANDLE(WINAPI * PGPH)(); PHSI pHSI = nullptr; PGPH pGPH = nullptr; if ((pHSI = (PHSI)GetProcAddress(kernelMod, "HeapSetInformation")) != nullptr) { // The LFH API is available /* Only set LFH for process heap; causes problems in C++ framework if set for all heaps HANDLE hProcessHeapHandles[1024]; DWORD dwRet; ULONG heapFragValue = 2; dwRet= GetProcessHeaps( 1024, hProcessHeapHandles ); for (DWORD i = 0; i < dwRet; i++) { HeapSetInformation( hProcessHeapHandles[i], HeapCompatibilityInformation, &heapFragValue, sizeof(heapFragValue) ); } */ HANDLE hProcessHeapHandle; ULONG heapFragValue = 2; if ((pGPH = (PGPH)GetProcAddress(kernelMod, "GetProcessHeap")) != nullptr) { hProcessHeapHandle = pGPH(); LOGCONFIG( "Setting Microsoft Windows' low-fragmentation heap for use as " "the main process heap."); pHSI(hProcessHeapHandle, HeapCompatibilityInformation, &heapFragValue, sizeof(heapFragValue)); } } } } #endif } } // namespace client } // namespace geode } // namespace apache DistributedSystem::DistributedSystem(const char* name) : m_name(nullptr) { LOGDEBUG("DistributedSystem::DistributedSystem"); if (name != nullptr) { size_t len = strlen(name) + 1; m_name = new char[len]; ACE_OS::strncpy(m_name, name, len); } if (strlen(g_sysProps->securityClientDhAlgo()) > 0) { DiffieHellman::initOpenSSLFuncPtrs(); } } DistributedSystem::~DistributedSystem() { GF_SAFE_DELETE_ARRAY(m_name); } DistributedSystemPtr DistributedSystem::connect( const char* name, const PropertiesPtr& configPtr) { ACE_Guard<ACE_Recursive_Thread_Mutex> disconnectGuard(*g_disconnectLock); setLFH(); if (m_connected == true) { throw AlreadyConnectedException( "DistributedSystem::connect: already connected, call getInstance to " "get it"); } // make sure statics are initialized. if (m_instance_ptr == nullptr) { m_instance_ptr = new DistributedSystemPtr(); } if (g_sysProps == nullptr) { g_sysProps = new SystemProperties(configPtr, nullptr); } Exception::setStackTraces(g_sysProps->debugStackTraceEnabled()); if (name == nullptr) { delete g_sysProps; g_sysProps = nullptr; throw IllegalArgumentException( "DistributedSystem::connect: " "name cannot be nullptr"); } if (name[0] == '\0') { name = "NativeDS"; } // Fix for Ticket#866 on NC OR SR#13306117704 // Set client name via native client API const char* propName = g_sysProps->name(); if (propName != nullptr && strlen(propName) > 0) { name = propName; } // Trigger other library initialization. CppCacheLibrary::initLib(); if (!TcrMessage::init()) { TcrMessage::cleanup(); throw IllegalArgumentException( "DistributedSystem::connect: preallocate message buffer failed!"); } const char* logFilename = g_sysProps->logFilename(); if (logFilename != nullptr) { try { Log::close(); Log::init(g_sysProps->logLevel(), logFilename, g_sysProps->logFileSizeLimit(), g_sysProps->logDiskSpaceLimit()); } catch (const GeodeIOException&) { Log::close(); TcrMessage::cleanup(); CppCacheLibrary::closeLib(); delete g_sysProps; g_sysProps = nullptr; *m_instance_ptr = nullptr; // delete g_disconnectLock; throw; } } else { Log::setLogLevel(g_sysProps->logLevel()); } try { std::string gfcpp = CppCacheLibrary::getProductDir(); LOGCONFIG("Using Geode Native Client Product Directory: %s", gfcpp.c_str()); } catch (const Exception&) { LOGERROR( "Unable to determine Product Directory. Please set the " "GFCPP environment variable."); throw; } // Add version information, source revision, current directory etc. LOGCONFIG("Product version: %s", CacheFactory::getProductDescription()); LOGCONFIG("Source revision: %s", PRODUCT_SOURCE_REVISION); LOGCONFIG("Source repository: %s", PRODUCT_SOURCE_REPOSITORY); ACE_utsname u; ACE_OS::uname(&u); LOGCONFIG( "Running on: SystemName=%s Machine=%s Host=%s Release=%s Version=%s", u.sysname, u.machine, u.nodename, u.release, u.version); #ifdef _WIN32 const uint32_t pathMax = _MAX_PATH; #else const uint32_t pathMax = PATH_MAX; #endif ACE_TCHAR cwd[pathMax + 1]; (void)ACE_OS::getcwd(cwd, pathMax); LOGCONFIG("Current directory: %s", cwd); LOGCONFIG("Current value of PATH: %s", ACE_OS::getenv("PATH")); #ifndef _WIN32 const char* ld_libpath = ACE_OS::getenv("LD_LIBRARY_PATH"); LOGCONFIG("Current library path: %s", ld_libpath == nullptr ? "nullptr" : ld_libpath); #endif // Log the Geode system properties g_sysProps->logSettings(); /* if (strlen(g_sysProps->securityClientDhAlgo())>0) { DiffieHellman::initDhKeys(g_sysProps->getSecurityProperties()); }*/ DistributedSystemPtr dptr; try { g_statMngr = StatisticsManager::initInstance( g_sysProps->statisticsArchiveFile(), g_sysProps->statisticsSampleInterval(), g_sysProps->statisticsEnabled(), g_sysProps->statsFileSizeLimit(), g_sysProps->statsDiskSpaceLimit()); } catch (const NullPointerException&) { // close all open handles, delete whatever was newed. g_statMngr = nullptr; //:Merge issue /*if (strlen(g_sysProps->securityClientDhAlgo())>0) { DiffieHellman::clearDhKeys(); }*/ Log::close(); TcrMessage::cleanup(); CppCacheLibrary::closeLib(); delete g_sysProps; g_sysProps = nullptr; *m_instance_ptr = nullptr; // delete g_disconnectLock; throw; } GF_D_ASSERT(g_statMngr != nullptr); CacheImpl::expiryTaskManager = new ExpiryTaskManager(); CacheImpl::expiryTaskManager->begin(); DistributedSystem* dp = new DistributedSystem(name); if (!dp) { throw NullPointerException("DistributedSystem::connect: new failed"); } m_impl = new DistributedSystemImpl(name, dp); try { m_impl->connect(); } catch (const apache::geode::client::Exception& e) { LOGERROR("Exception caught during client initialization: %s", e.getMessage()); std::string msg = "DistributedSystem::connect: caught exception: "; msg.append(e.getMessage()); throw NotConnectedException(msg.c_str()); } catch (const std::exception& e) { LOGERROR("Exception caught during client initialization: %s", e.what()); std::string msg = "DistributedSystem::connect: caught exception: "; msg.append(e.what()); throw NotConnectedException(msg.c_str()); } catch (...) { LOGERROR("Unknown exception caught during client initialization"); throw NotConnectedException( "DistributedSystem::connect: caught unknown exception"); } m_connected = true; dptr.reset(dp); *m_instance_ptr = dptr; LOGCONFIG("Starting the Geode Native Client"); return dptr; } /** *@brief disconnect from the distributed system */ void DistributedSystem::disconnect() { ACE_Guard<ACE_Recursive_Thread_Mutex> disconnectGuard(*g_disconnectLock); if (!m_connected) { throw NotConnectedException( "DistributedSystem::disconnect: connect " "not called"); } try { CachePtr cache = CacheFactory::getAnyInstance(); if (cache != nullptr && !cache->isClosed()) { cache->close(); } } catch (const apache::geode::client::Exception& e) { LOGWARN("Exception while closing: %s: %s", e.getName(), e.getMessage()); } if (CacheImpl::expiryTaskManager != nullptr) { CacheImpl::expiryTaskManager->stopExpiryTaskManager(); } if (m_impl) { m_impl->disconnect(); delete m_impl; m_impl = nullptr; } LOGFINEST("Deleted DistributedSystemImpl"); if (strlen(g_sysProps->securityClientDhAlgo()) > 0) { // DistributedSystem::getInstance()->m_dh->clearDhKeys(); } // Clear DH Keys /* if (strlen(g_sysProps->securityClientDhAlgo())>0) { DiffieHellman::clearDhKeys(); }*/ GF_D_ASSERT(!!g_sysProps); delete g_sysProps; g_sysProps = nullptr; LOGFINEST("Deleted SystemProperties"); if (CacheImpl::expiryTaskManager != nullptr) { delete CacheImpl::expiryTaskManager; CacheImpl::expiryTaskManager = nullptr; } LOGFINEST("Deleted ExpiryTaskManager"); TcrMessage::cleanup(); LOGFINEST("Cleaned TcrMessage"); GF_D_ASSERT(!!g_statMngr); g_statMngr->clean(); g_statMngr = nullptr; LOGFINEST("Cleaned StatisticsManager"); RegionStatType::clean(); LOGFINEST("Cleaned RegionStatType"); PoolStatType::clean(); LOGFINEST("Cleaned PoolStatType"); *m_instance_ptr = nullptr; // Free up library resources CppCacheLibrary::closeLib(); LOGCONFIG("Stopped the Geode Native Client"); Log::close(); m_connected = false; } SystemProperties* DistributedSystem::getSystemProperties() { return g_sysProps; } const char* DistributedSystem::getName() const { return m_name; } bool DistributedSystem::isConnected() { CppCacheLibrary::initLib(); return m_connected; } DistributedSystemPtr DistributedSystem::getInstance() { CppCacheLibrary::initLib(); if (m_instance_ptr == nullptr) { return nullptr; } return *m_instance_ptr; } <commit_msg>GEODE-3058: Removes Windows LFH enablement.<commit_after>/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <geode/geode_globals.hpp> #include <geode/DistributedSystem.hpp> #include "statistics/StatisticsManager.hpp" #include <geode/SystemProperties.hpp> #include <CppCacheLibrary.hpp> #include <Utils.hpp> #include <geode/Log.hpp> #include <geode/CacheFactory.hpp> #include <ace/OS.h> #include <ExpiryTaskManager.hpp> #include <CacheImpl.hpp> #include <ace/Guard_T.h> #include <ace/Recursive_Thread_Mutex.h> #include <geode/DataOutput.hpp> #include <TcrMessage.hpp> #include <DistributedSystemImpl.hpp> #include <RegionStats.hpp> #include <PoolStatistics.hpp> #include <DiffieHellman.hpp> #include "version.h" using namespace apache::geode::client; using namespace apache::geode::statistics; DistributedSystemPtr* DistributedSystem::m_instance_ptr = nullptr; bool DistributedSystem::m_connected = false; DistributedSystemImpl* DistributedSystem::m_impl = nullptr; ACE_Recursive_Thread_Mutex* g_disconnectLock = new ACE_Recursive_Thread_Mutex(); namespace { StatisticsManager* g_statMngr = nullptr; SystemProperties* g_sysProps = nullptr; } // namespace DistributedSystem::DistributedSystem(const char* name) : m_name(nullptr) { LOGDEBUG("DistributedSystem::DistributedSystem"); if (name != nullptr) { size_t len = strlen(name) + 1; m_name = new char[len]; ACE_OS::strncpy(m_name, name, len); } if (strlen(g_sysProps->securityClientDhAlgo()) > 0) { DiffieHellman::initOpenSSLFuncPtrs(); } } DistributedSystem::~DistributedSystem() { GF_SAFE_DELETE_ARRAY(m_name); } DistributedSystemPtr DistributedSystem::connect( const char* name, const PropertiesPtr& configPtr) { ACE_Guard<ACE_Recursive_Thread_Mutex> disconnectGuard(*g_disconnectLock); if (m_connected == true) { throw AlreadyConnectedException( "DistributedSystem::connect: already connected, call getInstance to " "get it"); } // make sure statics are initialized. if (m_instance_ptr == nullptr) { m_instance_ptr = new DistributedSystemPtr(); } if (g_sysProps == nullptr) { g_sysProps = new SystemProperties(configPtr, nullptr); } Exception::setStackTraces(g_sysProps->debugStackTraceEnabled()); if (name == nullptr) { delete g_sysProps; g_sysProps = nullptr; throw IllegalArgumentException( "DistributedSystem::connect: " "name cannot be nullptr"); } if (name[0] == '\0') { name = "NativeDS"; } // Fix for Ticket#866 on NC OR SR#13306117704 // Set client name via native client API const char* propName = g_sysProps->name(); if (propName != nullptr && strlen(propName) > 0) { name = propName; } // Trigger other library initialization. CppCacheLibrary::initLib(); if (!TcrMessage::init()) { TcrMessage::cleanup(); throw IllegalArgumentException( "DistributedSystem::connect: preallocate message buffer failed!"); } const char* logFilename = g_sysProps->logFilename(); if (logFilename != nullptr) { try { Log::close(); Log::init(g_sysProps->logLevel(), logFilename, g_sysProps->logFileSizeLimit(), g_sysProps->logDiskSpaceLimit()); } catch (const GeodeIOException&) { Log::close(); TcrMessage::cleanup(); CppCacheLibrary::closeLib(); delete g_sysProps; g_sysProps = nullptr; *m_instance_ptr = nullptr; // delete g_disconnectLock; throw; } } else { Log::setLogLevel(g_sysProps->logLevel()); } try { std::string gfcpp = CppCacheLibrary::getProductDir(); LOGCONFIG("Using Geode Native Client Product Directory: %s", gfcpp.c_str()); } catch (const Exception&) { LOGERROR( "Unable to determine Product Directory. Please set the " "GFCPP environment variable."); throw; } // Add version information, source revision, current directory etc. LOGCONFIG("Product version: %s", CacheFactory::getProductDescription()); LOGCONFIG("Source revision: %s", PRODUCT_SOURCE_REVISION); LOGCONFIG("Source repository: %s", PRODUCT_SOURCE_REPOSITORY); ACE_utsname u; ACE_OS::uname(&u); LOGCONFIG( "Running on: SystemName=%s Machine=%s Host=%s Release=%s Version=%s", u.sysname, u.machine, u.nodename, u.release, u.version); #ifdef _WIN32 const uint32_t pathMax = _MAX_PATH; #else const uint32_t pathMax = PATH_MAX; #endif ACE_TCHAR cwd[pathMax + 1]; (void)ACE_OS::getcwd(cwd, pathMax); LOGCONFIG("Current directory: %s", cwd); LOGCONFIG("Current value of PATH: %s", ACE_OS::getenv("PATH")); #ifndef _WIN32 const char* ld_libpath = ACE_OS::getenv("LD_LIBRARY_PATH"); LOGCONFIG("Current library path: %s", ld_libpath == nullptr ? "nullptr" : ld_libpath); #endif // Log the Geode system properties g_sysProps->logSettings(); /* if (strlen(g_sysProps->securityClientDhAlgo())>0) { DiffieHellman::initDhKeys(g_sysProps->getSecurityProperties()); }*/ DistributedSystemPtr dptr; try { g_statMngr = StatisticsManager::initInstance( g_sysProps->statisticsArchiveFile(), g_sysProps->statisticsSampleInterval(), g_sysProps->statisticsEnabled(), g_sysProps->statsFileSizeLimit(), g_sysProps->statsDiskSpaceLimit()); } catch (const NullPointerException&) { // close all open handles, delete whatever was newed. g_statMngr = nullptr; //:Merge issue /*if (strlen(g_sysProps->securityClientDhAlgo())>0) { DiffieHellman::clearDhKeys(); }*/ Log::close(); TcrMessage::cleanup(); CppCacheLibrary::closeLib(); delete g_sysProps; g_sysProps = nullptr; *m_instance_ptr = nullptr; // delete g_disconnectLock; throw; } GF_D_ASSERT(g_statMngr != nullptr); CacheImpl::expiryTaskManager = new ExpiryTaskManager(); CacheImpl::expiryTaskManager->begin(); DistributedSystem* dp = new DistributedSystem(name); if (!dp) { throw NullPointerException("DistributedSystem::connect: new failed"); } m_impl = new DistributedSystemImpl(name, dp); try { m_impl->connect(); } catch (const apache::geode::client::Exception& e) { LOGERROR("Exception caught during client initialization: %s", e.getMessage()); std::string msg = "DistributedSystem::connect: caught exception: "; msg.append(e.getMessage()); throw NotConnectedException(msg.c_str()); } catch (const std::exception& e) { LOGERROR("Exception caught during client initialization: %s", e.what()); std::string msg = "DistributedSystem::connect: caught exception: "; msg.append(e.what()); throw NotConnectedException(msg.c_str()); } catch (...) { LOGERROR("Unknown exception caught during client initialization"); throw NotConnectedException( "DistributedSystem::connect: caught unknown exception"); } m_connected = true; dptr.reset(dp); *m_instance_ptr = dptr; LOGCONFIG("Starting the Geode Native Client"); return dptr; } /** *@brief disconnect from the distributed system */ void DistributedSystem::disconnect() { ACE_Guard<ACE_Recursive_Thread_Mutex> disconnectGuard(*g_disconnectLock); if (!m_connected) { throw NotConnectedException( "DistributedSystem::disconnect: connect " "not called"); } try { CachePtr cache = CacheFactory::getAnyInstance(); if (cache != nullptr && !cache->isClosed()) { cache->close(); } } catch (const apache::geode::client::Exception& e) { LOGWARN("Exception while closing: %s: %s", e.getName(), e.getMessage()); } if (CacheImpl::expiryTaskManager != nullptr) { CacheImpl::expiryTaskManager->stopExpiryTaskManager(); } if (m_impl) { m_impl->disconnect(); delete m_impl; m_impl = nullptr; } LOGFINEST("Deleted DistributedSystemImpl"); if (strlen(g_sysProps->securityClientDhAlgo()) > 0) { // DistributedSystem::getInstance()->m_dh->clearDhKeys(); } // Clear DH Keys /* if (strlen(g_sysProps->securityClientDhAlgo())>0) { DiffieHellman::clearDhKeys(); }*/ GF_D_ASSERT(!!g_sysProps); delete g_sysProps; g_sysProps = nullptr; LOGFINEST("Deleted SystemProperties"); if (CacheImpl::expiryTaskManager != nullptr) { delete CacheImpl::expiryTaskManager; CacheImpl::expiryTaskManager = nullptr; } LOGFINEST("Deleted ExpiryTaskManager"); TcrMessage::cleanup(); LOGFINEST("Cleaned TcrMessage"); GF_D_ASSERT(!!g_statMngr); g_statMngr->clean(); g_statMngr = nullptr; LOGFINEST("Cleaned StatisticsManager"); RegionStatType::clean(); LOGFINEST("Cleaned RegionStatType"); PoolStatType::clean(); LOGFINEST("Cleaned PoolStatType"); *m_instance_ptr = nullptr; // Free up library resources CppCacheLibrary::closeLib(); LOGCONFIG("Stopped the Geode Native Client"); Log::close(); m_connected = false; } SystemProperties* DistributedSystem::getSystemProperties() { return g_sysProps; } const char* DistributedSystem::getName() const { return m_name; } bool DistributedSystem::isConnected() { CppCacheLibrary::initLib(); return m_connected; } DistributedSystemPtr DistributedSystem::getInstance() { CppCacheLibrary::initLib(); if (m_instance_ptr == nullptr) { return nullptr; } return *m_instance_ptr; } <|endoftext|>
<commit_before>#include "LiveMediaExtPch.h" #include <Media/RtspService.h> #include <LiveMediaExt/LiveSourceTaskScheduler.h> #include <LiveMediaExt/LiveRtspServer.h> namespace lme { RtspService::RtspService(ChannelManager& channelManager) :m_channelManager(channelManager), m_cEventloop(0), m_pRtspServer(NULL), m_pScheduler(NULL), m_pEnv(NULL), m_bEventLoopRunning(false) { } boost::system::error_code RtspService::start() { VLOG(2) << "Starting RTSP service"; // init live555 environment // Setup the liveMedia environment m_pScheduler = LiveSourceTaskScheduler::createNew(m_channelManager); // live media env m_pEnv = BasicUsageEnvironment::createNew(*m_pScheduler); VLOG(2) << "Creating RTSP server"; m_pRtspServer = LiveRtspServer::createNew(*m_pEnv); if (m_pRtspServer == NULL) { *m_pEnv << "Failed to create RTSP server: " << m_pEnv->getResultMsg() << "\n"; LOG(WARNING) << "Failed to create RTSP server"; // TODO: add custom error codes!!! return boost::system::error_code(boost::system::errc::bad_file_descriptor, boost::system::get_generic_category()); } // Add task that checks if there's new data in the queue checkSessionsTask(this); checkChannelsTask(this); // start live 555 in new thread m_pLive555Thread = std::unique_ptr<boost::thread>(new boost::thread(boost::bind(&RtspService::live555EventLoop, this))); return boost::system::error_code(); } boost::system::error_code RtspService::stop() { VLOG(2) << "Stopping RTSP service"; // stop live555 thread if (m_pLive555Thread) { m_cEventloop = 1; m_pLive555Thread->join(); } VLOG(2) << "End of RTSP service"; return boost::system::error_code(); } void RtspService::live555EventLoop() { m_bEventLoopRunning = true; VLOG(2) << "Entering LiveMedia event loop"; m_pEnv->taskScheduler().doEventLoop(&m_cEventloop); // does not return m_bEventLoopRunning = false; VLOG(2) << "LiveMedia event loop complete"; cleanupLiveMediaEnvironment(); } void RtspService::cleanupLiveMediaEnvironment() { if (m_pEnv) { m_pEnv->taskScheduler().unscheduleDelayedTask(m_pCheckSessionsTask); } if (m_pRtspServer) { // Shutdown the server VLOG(2) << "Shutting down RTSP Server"; Medium::close(m_pRtspServer); m_pRtspServer = NULL; } VLOG(2) << "Cleaning up"; // clean up live555 environment m_pEnv->reclaim(); if (m_pScheduler) delete m_pScheduler; m_pScheduler = NULL; } void RtspService::checkSessionsTask(void* clientData) { RtspService* pRtspService = (RtspService*)clientData; pRtspService->doCheckSessionsTask(); } void RtspService::doCheckSessionsTask() { // TODO: process RTCP reports and update RTCP rate control module VLOG(10) << "doCheckSessionsTask"; // Call this again, after a brief delay: int uSecsToDelay = 50000; // 50 ms m_pCheckSessionsTask = m_pEnv->taskScheduler().scheduleDelayedTask(uSecsToDelay, (TaskFunc*)&RtspService::checkSessionsTask, this); } void RtspService::checkChannelsTask(void* clientData) { RtspService* pRtspService = (RtspService*)clientData; pRtspService->doCheckChannelsTask(); } void RtspService::doCheckChannelsTask() { boost::mutex::scoped_lock l(m_channelLock); // Remove old sessions: while (!m_qChannelsToBeRemoved.empty()) { Channel channel = m_qChannelsToBeRemoved.front(); m_qChannelsToBeRemoved.pop_front(); assert(m_mChannels.find(channel.ChannelId) != m_mChannels.end()); m_mChannels.erase(channel.ChannelId); LOG(INFO) << "Removing RTSP media session from RTSP server - Channel: " << channel.ChannelId << " Name: " << channel.ChannelName; m_pRtspServer->removeRtspMediaSession(channel); } // Add new sessions: while (!m_qChannelsToBeAdded.empty()) { Channel newChannel = m_qChannelsToBeAdded.front(); m_qChannelsToBeAdded.pop_front(); m_mChannels[newChannel.ChannelId] = newChannel; LOG(INFO) << "Adding RTSP media session to RTSP server - Channel: " << newChannel.ChannelId << " Name: " << newChannel.ChannelName; m_pRtspServer->addRtspMediaSession(newChannel); } // Call this again, after a brief delay: int uSecsToDelay = 50000; // 50 ms m_pCheckSessionsTask = m_pEnv->taskScheduler().scheduleDelayedTask(uSecsToDelay, (TaskFunc*)&RtspService::checkChannelsTask, this); } boost::system::error_code RtspService::createChannel(uint32_t uiChannelId, const std::string& sChannelName, const VideoChannelDescriptor& videoDescriptor, const AudioChannelDescriptor& audioDescriptor) { VLOG(2) << "createChannel: " << uiChannelId; boost::mutex::scoped_lock l(m_channelLock); ChannelMap_t::iterator it = m_mChannels.find(uiChannelId); if (it != m_mChannels.end()) { return boost::system::error_code(boost::system::errc::file_exists, boost::system::get_generic_category()); } else { m_qChannelsToBeAdded.push_back(Channel(uiChannelId, sChannelName, videoDescriptor, audioDescriptor)); return boost::system::error_code(); } } boost::system::error_code RtspService::createChannel(uint32_t uiChannelId, const std::string& sChannelName, const VideoChannelDescriptor& videoDescriptor) { VLOG(2) << "createChannel: " << uiChannelId; boost::mutex::scoped_lock l(m_channelLock); ChannelMap_t::iterator it = m_mChannels.find(uiChannelId); if (it != m_mChannels.end()) { return boost::system::error_code(boost::system::errc::file_exists, boost::system::get_generic_category()); } else { m_qChannelsToBeAdded.push_back(Channel(uiChannelId, sChannelName, videoDescriptor)); VLOG(2) << "createChannel: " << uiChannelId << " channel added"; return boost::system::error_code(); } return boost::system::error_code(); } boost::system::error_code RtspService::createChannel(uint32_t uiChannelId, const std::string& sChannelName, const AudioChannelDescriptor& audioDescriptor) { VLOG(2) << "createChannel: " << uiChannelId; boost::mutex::scoped_lock l(m_channelLock); ChannelMap_t::iterator it = m_mChannels.find(uiChannelId); if (it != m_mChannels.end()) { return boost::system::error_code(boost::system::errc::file_exists, boost::system::get_generic_category()); } else { m_qChannelsToBeAdded.push_back(Channel(uiChannelId, sChannelName, audioDescriptor)); return boost::system::error_code(); } return boost::system::error_code(); } boost::system::error_code RtspService::removeChannel(uint32_t uiChannelId) { VLOG(2) << "removeChannel: " << uiChannelId; boost::mutex::scoped_lock l(m_channelLock); ChannelMap_t::iterator it = m_mChannels.find(uiChannelId); if (it != m_mChannels.end()) { m_qChannelsToBeRemoved.push_back(m_mChannels[uiChannelId]); return boost::system::error_code(); } else { return boost::system::error_code(boost::system::errc::no_such_file_or_directory, boost::system::get_generic_category()); } return boost::system::error_code(); } } //lme <commit_msg>disable TCP streaming prepro<commit_after>#include "LiveMediaExtPch.h" #include <Media/RtspService.h> #include <LiveMediaExt/LiveSourceTaskScheduler.h> #include <LiveMediaExt/LiveRtspServer.h> namespace lme { RtspService::RtspService(ChannelManager& channelManager) :m_channelManager(channelManager), m_cEventloop(0), m_pRtspServer(NULL), m_pScheduler(NULL), m_pEnv(NULL), m_bEventLoopRunning(false) { } boost::system::error_code RtspService::start() { VLOG(2) << "Starting RTSP service"; // init live555 environment // Setup the liveMedia environment m_pScheduler = LiveSourceTaskScheduler::createNew(m_channelManager); // live media env m_pEnv = BasicUsageEnvironment::createNew(*m_pScheduler); VLOG(2) << "Creating RTSP server"; m_pRtspServer = LiveRtspServer::createNew(*m_pEnv); if (m_pRtspServer == NULL) { *m_pEnv << "Failed to create RTSP server: " << m_pEnv->getResultMsg() << "\n"; LOG(WARNING) << "Failed to create RTSP server"; // TODO: add custom error codes!!! return boost::system::error_code(boost::system::errc::bad_file_descriptor, boost::system::get_generic_category()); } #if 0 // disable TCP streaming for testing m_pRtspServer->disableStreamingRTPOverTCP(); #endif // Add task that checks if there's new data in the queue checkSessionsTask(this); checkChannelsTask(this); // start live 555 in new thread m_pLive555Thread = std::unique_ptr<boost::thread>(new boost::thread(boost::bind(&RtspService::live555EventLoop, this))); return boost::system::error_code(); } boost::system::error_code RtspService::stop() { VLOG(2) << "Stopping RTSP service"; // stop live555 thread if (m_pLive555Thread) { m_cEventloop = 1; m_pLive555Thread->join(); } VLOG(2) << "End of RTSP service"; return boost::system::error_code(); } void RtspService::live555EventLoop() { m_bEventLoopRunning = true; VLOG(2) << "Entering LiveMedia event loop"; m_pEnv->taskScheduler().doEventLoop(&m_cEventloop); // does not return m_bEventLoopRunning = false; VLOG(2) << "LiveMedia event loop complete"; cleanupLiveMediaEnvironment(); } void RtspService::cleanupLiveMediaEnvironment() { if (m_pEnv) { m_pEnv->taskScheduler().unscheduleDelayedTask(m_pCheckSessionsTask); } if (m_pRtspServer) { // Shutdown the server VLOG(2) << "Shutting down RTSP Server"; Medium::close(m_pRtspServer); m_pRtspServer = NULL; } VLOG(2) << "Cleaning up"; // clean up live555 environment m_pEnv->reclaim(); if (m_pScheduler) delete m_pScheduler; m_pScheduler = NULL; } void RtspService::checkSessionsTask(void* clientData) { RtspService* pRtspService = (RtspService*)clientData; pRtspService->doCheckSessionsTask(); } void RtspService::doCheckSessionsTask() { // TODO: process RTCP reports and update RTCP rate control module VLOG(10) << "doCheckSessionsTask"; // Call this again, after a brief delay: int uSecsToDelay = 50000; // 50 ms m_pCheckSessionsTask = m_pEnv->taskScheduler().scheduleDelayedTask(uSecsToDelay, (TaskFunc*)&RtspService::checkSessionsTask, this); } void RtspService::checkChannelsTask(void* clientData) { RtspService* pRtspService = (RtspService*)clientData; pRtspService->doCheckChannelsTask(); } void RtspService::doCheckChannelsTask() { boost::mutex::scoped_lock l(m_channelLock); // Remove old sessions: while (!m_qChannelsToBeRemoved.empty()) { Channel channel = m_qChannelsToBeRemoved.front(); m_qChannelsToBeRemoved.pop_front(); assert(m_mChannels.find(channel.ChannelId) != m_mChannels.end()); m_mChannels.erase(channel.ChannelId); LOG(INFO) << "Removing RTSP media session from RTSP server - Channel: " << channel.ChannelId << " Name: " << channel.ChannelName; m_pRtspServer->removeRtspMediaSession(channel); } // Add new sessions: while (!m_qChannelsToBeAdded.empty()) { Channel newChannel = m_qChannelsToBeAdded.front(); m_qChannelsToBeAdded.pop_front(); m_mChannels[newChannel.ChannelId] = newChannel; LOG(INFO) << "Adding RTSP media session to RTSP server - Channel: " << newChannel.ChannelId << " Name: " << newChannel.ChannelName; m_pRtspServer->addRtspMediaSession(newChannel); } // Call this again, after a brief delay: int uSecsToDelay = 50000; // 50 ms m_pCheckSessionsTask = m_pEnv->taskScheduler().scheduleDelayedTask(uSecsToDelay, (TaskFunc*)&RtspService::checkChannelsTask, this); } boost::system::error_code RtspService::createChannel(uint32_t uiChannelId, const std::string& sChannelName, const VideoChannelDescriptor& videoDescriptor, const AudioChannelDescriptor& audioDescriptor) { VLOG(2) << "createChannel: " << uiChannelId; boost::mutex::scoped_lock l(m_channelLock); ChannelMap_t::iterator it = m_mChannels.find(uiChannelId); if (it != m_mChannels.end()) { return boost::system::error_code(boost::system::errc::file_exists, boost::system::get_generic_category()); } else { m_qChannelsToBeAdded.push_back(Channel(uiChannelId, sChannelName, videoDescriptor, audioDescriptor)); return boost::system::error_code(); } } boost::system::error_code RtspService::createChannel(uint32_t uiChannelId, const std::string& sChannelName, const VideoChannelDescriptor& videoDescriptor) { VLOG(2) << "createChannel: " << uiChannelId; boost::mutex::scoped_lock l(m_channelLock); ChannelMap_t::iterator it = m_mChannels.find(uiChannelId); if (it != m_mChannels.end()) { return boost::system::error_code(boost::system::errc::file_exists, boost::system::get_generic_category()); } else { m_qChannelsToBeAdded.push_back(Channel(uiChannelId, sChannelName, videoDescriptor)); VLOG(2) << "createChannel: " << uiChannelId << " channel added"; return boost::system::error_code(); } return boost::system::error_code(); } boost::system::error_code RtspService::createChannel(uint32_t uiChannelId, const std::string& sChannelName, const AudioChannelDescriptor& audioDescriptor) { VLOG(2) << "createChannel: " << uiChannelId; boost::mutex::scoped_lock l(m_channelLock); ChannelMap_t::iterator it = m_mChannels.find(uiChannelId); if (it != m_mChannels.end()) { return boost::system::error_code(boost::system::errc::file_exists, boost::system::get_generic_category()); } else { m_qChannelsToBeAdded.push_back(Channel(uiChannelId, sChannelName, audioDescriptor)); return boost::system::error_code(); } return boost::system::error_code(); } boost::system::error_code RtspService::removeChannel(uint32_t uiChannelId) { VLOG(2) << "removeChannel: " << uiChannelId; boost::mutex::scoped_lock l(m_channelLock); ChannelMap_t::iterator it = m_mChannels.find(uiChannelId); if (it != m_mChannels.end()) { m_qChannelsToBeRemoved.push_back(m_mChannels[uiChannelId]); return boost::system::error_code(); } else { return boost::system::error_code(boost::system::errc::no_such_file_or_directory, boost::system::get_generic_category()); } return boost::system::error_code(); } } //lme <|endoftext|>
<commit_before>// Copyright 2015-2018 Elviss Strazdins. All rights reserved. #ifdef _WIN32 # define WIN32_LEAN_AND_MEAN # define NOMINMAX # include <WinSock2.h> # include <WS2tcpip.h> # undef WIN32_LEAN_AND_MEAN # undef NOMINMAX #else # include <sys/socket.h> # include <netinet/in.h> # include <errno.h> # include <unistd.h> #endif #include "Socket.hpp" namespace ouzel { namespace network { Socket::Socket(): endpoint(socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) { } #ifdef _WIN32 Socket::Socket(SOCKET s): endpoint(s) { } #else Socket::Socket(int s): endpoint(s) { } #endif Socket::~Socket() { #ifdef _WIN32 if (endpoint != INVALID_SOCKET) closesocket(endpoint); #else if (endpoint != -1) close(endpoint); #endif } Socket::Socket(Socket&& other) { endpoint = other.endpoint; #ifdef _WIN32 other.endpoint = INVALID_SOCKET; #else other.endpoint = -1; #endif } Socket& Socket::operator=(Socket&& other) { if (&other != this) { #ifdef _WIN32 if (endpoint != INVALID_SOCKET) closesocket(endpoint); #else if (endpoint != -1) close(endpoint); #endif endpoint = other.endpoint; #ifdef _WIN32 other.endpoint = INVALID_SOCKET; #else other.endpoint = -1; #endif } return *this; } } // namespace network } // namespace ouzel <commit_msg>Initialize the endpoint in the constructor's member init list<commit_after>// Copyright 2015-2018 Elviss Strazdins. All rights reserved. #ifdef _WIN32 # define WIN32_LEAN_AND_MEAN # define NOMINMAX # include <WinSock2.h> # include <WS2tcpip.h> # undef WIN32_LEAN_AND_MEAN # undef NOMINMAX #else # include <sys/socket.h> # include <netinet/in.h> # include <errno.h> # include <unistd.h> #endif #include "Socket.hpp" namespace ouzel { namespace network { Socket::Socket(): endpoint(socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) { } #ifdef _WIN32 Socket::Socket(SOCKET s): endpoint(s) { } #else Socket::Socket(int s): endpoint(s) { } #endif Socket::~Socket() { #ifdef _WIN32 if (endpoint != INVALID_SOCKET) closesocket(endpoint); #else if (endpoint != -1) close(endpoint); #endif } Socket::Socket(Socket&& other): endpoint(other.endpoint) { #ifdef _WIN32 other.endpoint = INVALID_SOCKET; #else other.endpoint = -1; #endif } Socket& Socket::operator=(Socket&& other) { if (&other != this) { #ifdef _WIN32 if (endpoint != INVALID_SOCKET) closesocket(endpoint); #else if (endpoint != -1) close(endpoint); #endif endpoint = other.endpoint; #ifdef _WIN32 other.endpoint = INVALID_SOCKET; #else other.endpoint = -1; #endif } return *this; } } // namespace network } // namespace ouzel <|endoftext|>
<commit_before>/* * Drive.cpp * * Created on: Feb 1, 2016 * Author: Edward */ #include "Drive.h" #include <cmath> #include <memory> #include <string> namespace subsystems { std::string Drive::ModeToString(Mode_t mode) { switch(mode) { case Mode_t::VBus: return "VBus"; case Mode_t::Position: return "Position"; case Mode_t::Velocity: return "Velocity"; } } Drive::Drive(): dman::WPISystem("Drive"), talons_(nullptr), mode_(Mode_t::VBus), ticks_per_rev_(761), wheel_diameter_(0.3048), max_velocity_(120.0), wheel_revs_per_base_rev_(5000), allowable_error_(0.05) // 5 cm of wheel rotation { } void Drive::initTalons() { if(!is_initialized()) { auto& ports = GetPortSpace("CAN"); int left = ports("left"); int left_slave = ports("left_slave"); int right = ports("right"); int right_slave = ports("right_slave"); talons_ = std::make_unique<Talons>(left, left_slave, right, right_slave); Log(dman::MessageData::INFO, "", "Subsystem") << "Port Config: left: " << left << ", " << "left_slave: " << left_slave << ", right: " << right << ", right_slave: " << right_slave; } } bool Drive::configureMaster(CANTalon& master) { std::cout << "Configuring a side" << std::endl; master.ConfigLimitMode(CANTalon::LimitMode::kLimitMode_SrxDisableSwitchInputs); master.ConfigNeutralMode(CANTalon::NeutralMode::kNeutralMode_Brake); master.SetFeedbackDevice(CANTalon::FeedbackDevice::QuadEncoder); SetTicksPerRev(get_ticks_per_rev()); master.SetPosition(0.0); master.SetVoltageRampRate(50.0); if(GetSettings()["closed_loop_settings"]("use").GetValueOrDefault()) { auto& settings = GetSettings()["closed_loop_settings"]; if(!settings("P").is_empty()) master.SetP(settings("P").get_value()); if(!settings("I").is_empty()) master.SetI(settings("I").get_value()); if(!settings("D").is_empty()) master.SetD(settings("D").get_value()); if(!settings("F").is_empty()) master.SetF(settings("F").get_value()); if(!settings("I_Zone").is_empty()) master.SetIzone(settings("I_Zone").get_value()); if(!settings("ramp_rate").is_empty()) master.SetCloseLoopRampRate(settings("ramp_rate").get_value()); } return true; } bool Drive::configureBoth() { if(is_initialized()) { std::cout << "Configuring Drive" << std::endl; auto& settings = GetSettings(); auto& ports = GetPortSpace("CAN"); bool left_ret = configureMaster(talons_->left_); talons_->left_slave_.SetControlMode(CANTalon::ControlMode::kFollower); talons_->left_slave_.Set(ports("left")); talons_->left_.SetInverted(settings["left"]("invert_output").GetValueOrDefault()); talons_->left_.SetSensorDirection(settings["left"]("invert_sensor").GetValueOrDefault()); bool right_ret = configureMaster(talons_->right_); talons_->right_slave_.SetControlMode(CANTalon::ControlMode::kFollower); talons_->right_slave_.Set(ports("right")); talons_->right_.SetInverted(settings["right"]("invert_output").GetValueOrDefault()); talons_->right_.SetSensorDirection(settings["right"]("invert_sensor").GetValueOrDefault()); return left_ret && right_ret; } return false; } void Drive::doRegister() { auto& can_ports = GetPortSpace("CAN"); can_ports("right").SetDefault(1); can_ports("right_slave").SetDefault(2); can_ports("left").SetDefault(3); can_ports("left_slave").SetDefault(4); auto& settings = GetSettings(); settings("ticks_per_revolution").SetDefault(get_ticks_per_rev()); settings("wheel_diameter").SetDefault(get_wheel_diameter()); settings("max_velocity").SetDefault(get_velocity_scale()); settings("wheel_revolutions_per_chassis_pivot_revolution").SetDefault(get_wheel_revs_per_base_rev()); settings("allowable_error").SetDefault(get_allowable_error()); auto& closed_loop_settings = settings["closed_loop_settings"]; closed_loop_settings("use").SetDefault(false); closed_loop_settings("P").SetDefault(.1); closed_loop_settings("I").SetDefault(0.0); closed_loop_settings("D").SetDefault(0.0); closed_loop_settings("F").SetDefault(1.0); closed_loop_settings("I_Zone").SetDefault(2.5); closed_loop_settings("ramp_rate").SetDefault(10); settings["left"]("invert_output").SetDefault(false); settings["left"]("invert_sensor").SetDefault(false); settings["right"]("invert_output").SetDefault(true); settings["right"]("invert_sensor").SetDefault(true); } bool Drive::doConfigure() { if(!is_initialized()) initTalons(); auto& settings = GetSettings(); SetTicksPerRev(settings("ticks_per_revolution").GetValueOrDefault()); SetWheelDiameter(settings("wheel_diameter").GetValueOrDefault()); SetVelocityScale(settings("max_velocity").GetValueOrDefault()); SetWheelRevsPerBaseRev(settings("wheel_revolutions_per_chassis_pivot_revolution").GetValueOrDefault()); SetAllowableError(settings("allowable_error").GetValueOrDefault()); return configureBoth(); } void Drive::SetMode(Mode_t m) { if(!is_initialized()) return; if(m == mode_) return; else { mode_ = m; std::cout << "Setting mode to " << ModeToString(mode_) << std::endl; setModeMaster(talons_->left_); setModeMaster(talons_->right_); } } void Drive::setModeMaster(CANTalon &master) { if(get_mode() == Mode_t::Position) { master.SetControlMode(CANTalon::ControlMode::kPosition); master.SelectProfileSlot(ModePIDSlot_t::PositionPID); } else if(get_mode() == Mode_t::Velocity) { master.SetControlMode(CANTalon::ControlMode::kSpeed); master.SelectProfileSlot(ModePIDSlot_t::VelocityPID); } else if(get_mode() == Mode_t::VBus) { master.SetControlMode(CANTalon::ControlMode::kPercentVbus); } } void Drive::SetTicksPerRev(Ticks_t val) { ticks_per_rev_ = val; if(is_initialized()) { talons_->left_.ConfigEncoderCodesPerRev(ticks_per_rev_); talons_->right_.ConfigEncoderCodesPerRev(ticks_per_rev_); } } void Drive::SetWheelDiameter(Meters_t val) { wheel_diameter_ = val; } void Drive::SetVelocityScale(MetersPerSecond_t max_velocity) { max_velocity_ = max_velocity; } void Drive::SetWheelRevsPerBaseRev(double rate) { wheel_revs_per_base_rev_= rate; } void Drive::SetAllowableError(double allow) { allowable_error_ = allow; } Drive::Meters_t Drive::GetDistance() const { return (GetLeftRevs() + GetRightRevs()) / 2.0 * get_wheel_circumference(); } double Drive::GetRotation() const { return (GetLeftRevs() - GetRightRevs()) / 2.0 * get_wheel_revs_per_base_rev(); } double Drive::GetLeftRevs() const { if(is_initialized()) return talons_->left_.GetPosition(); //< Current understanding is that this returns revs else return 0.0; } double Drive::GetRightRevs() const { if(is_initialized()) return talons_->right_.GetPosition(); //< See GetLeftRevs else return 0.0; } double Drive::GetLeftRPM() const { if(is_initialized()) return talons_->left_.GetSpeed(); else return 0.0; } double Drive::GetRightRPM() const { if(is_initialized()) return talons_->right_.GetSpeed(); else return 0.0; } double Drive::GetLeftSetPointRPM() const { if(is_initialized()) return talons_->left_.GetSetpoint(); else return 0.0; } double Drive::GetRightSetPointRPM() const { if(is_initialized()) return talons_->right_.GetSetpoint(); else return 0.0; } Drive::MetersPerSecond_t Drive::GetVelocity() const { return (GetLeftRPM() + GetRightRPM()) / 2.0 * get_wheel_circumference(); } double Drive::GetBaseRPM() const { return (GetLeftRPM() - GetRightRPM()) / 2.0 * get_wheel_revs_per_base_rev(); } void Drive::ResetPosition() { if(is_initialized()) { talons_->left_.SetPosition(0.0); talons_->right_.SetPosition(0.0); } } bool Drive::GoToPosition(Meters_t pos) { SetMode(Mode_t::Position); if(is_initialized()) { talons_->left_.Set(pos * get_wheel_circumference(), 3); talons_->right_.Set(pos * get_wheel_circumference(), 3); CANJaguar::UpdateSyncGroup(3); if(fabs(GetDistance() - pos) < get_allowable_error()) { return true; } else { return false; } } else { return false; } } bool Drive::TurnToRotation(double revolutions) { SetMode(Mode_t::Position); if(is_initialized()) { talons_->left_.Set(revolutions * get_wheel_revs_per_base_rev(), 3); talons_->right_.Set(revolutions * get_wheel_revs_per_base_rev(), 3); CANJaguar::UpdateSyncGroup(3); if(fabs(GetRotation() - revolutions) * get_wheel_revs_per_base_rev() < get_allowable_error() / get_wheel_diameter()) { return true; } else { return false; } } else { return false; } } void Drive::TankDrive(double left, double right) { if(get_mode() == Mode_t::Position) return; if(is_initialized()) { if(left > 1.0) left = 1.0; if(left < -1.0) left = -1.0; if(right > 1.0) right = 1.0; if(right < -1.0) right = -1.0; if(get_mode() == Mode_t::Velocity) { left *= get_velocity_scale(); right *= get_velocity_scale(); } talons_->left_.Set(left, 3); talons_->right_.Set(right, 3); CANJaguar::UpdateSyncGroup(3); } } void Drive::Stop() { TankDrive(0.0, 0.0); } void Drive::ArcadeDrive(double y, double rotation) { if(y > 1.0) y = 1.0; if(y < -1.0) y = -1.0; if(rotation > 1.0) rotation = 1.0; if(rotation < -1.0) rotation = -1.0; TankDrive(y - rotation, y + rotation); } } <commit_msg>Drive: Adds dynamic runtime values<commit_after>/* * Drive.cpp * * Created on: Feb 1, 2016 * Author: Edward */ #include "Drive.h" #include "Utility/FunkyGet.h" #include <cmath> #include <memory> #include <string> namespace subsystems { std::string Drive::ModeToString(Mode_t mode) { switch(mode) { case Mode_t::VBus: return "VBus"; case Mode_t::Position: return "Position"; case Mode_t::Velocity: return "Velocity"; } } Drive::Drive(): dman::WPISystem("Drive"), talons_(nullptr), mode_(Mode_t::VBus), ticks_per_rev_(761), wheel_diameter_(0.3048), max_velocity_(120.0), wheel_revs_per_base_rev_(5000), allowable_error_(0.05) // 5 cm of wheel rotation { } void Drive::initTalons() { if(!is_initialized()) { auto& ports = GetPortSpace("CAN"); int left = ports("left"); int left_slave = ports("left_slave"); int right = ports("right"); int right_slave = ports("right_slave"); talons_ = std::make_unique<Talons>(left, left_slave, right, right_slave); Log(dman::MessageData::INFO, "", "Subsystem") << "Port Config: left: " << left << ", " << "left_slave: " << left_slave << ", right: " << right << ", right_slave: " << right_slave; } } bool Drive::configureMaster(CANTalon& master) { std::cout << "Configuring a side" << std::endl; master.ConfigLimitMode(CANTalon::LimitMode::kLimitMode_SrxDisableSwitchInputs); master.ConfigNeutralMode(CANTalon::NeutralMode::kNeutralMode_Brake); master.SetFeedbackDevice(CANTalon::FeedbackDevice::QuadEncoder); SetTicksPerRev(get_ticks_per_rev()); master.SetPosition(0.0); master.SetVoltageRampRate(50.0); if(GetSettings()["closed_loop_settings"]("use").GetValueOrDefault()) { auto& settings = GetSettings()["closed_loop_settings"]; if(!settings("P").is_empty()) master.SetP(settings("P").get_value()); if(!settings("I").is_empty()) master.SetI(settings("I").get_value()); if(!settings("D").is_empty()) master.SetD(settings("D").get_value()); if(!settings("F").is_empty()) master.SetF(settings("F").get_value()); if(!settings("I_Zone").is_empty()) master.SetIzone(settings("I_Zone").get_value()); if(!settings("ramp_rate").is_empty()) master.SetCloseLoopRampRate(settings("ramp_rate").get_value()); } return true; } bool Drive::configureBoth() { if(is_initialized()) { std::cout << "Configuring Drive" << std::endl; auto& settings = GetSettings(); auto& ports = GetPortSpace("CAN"); bool left_ret = configureMaster(talons_->left_); talons_->left_slave_.SetControlMode(CANTalon::ControlMode::kFollower); talons_->left_slave_.Set(ports("left")); talons_->left_.SetInverted(settings["left"]("invert_output").GetValueOrDefault()); talons_->left_.SetSensorDirection(settings["left"]("invert_sensor").GetValueOrDefault()); bool right_ret = configureMaster(talons_->right_); talons_->right_slave_.SetControlMode(CANTalon::ControlMode::kFollower); talons_->right_slave_.Set(ports("right")); talons_->right_.SetInverted(settings["right"]("invert_output").GetValueOrDefault()); talons_->right_.SetSensorDirection(settings["right"]("invert_sensor").GetValueOrDefault()); return left_ret && right_ret; } return false; } void Drive::doRegister() { auto& can_ports = GetPortSpace("CAN"); can_ports("right").SetDefault(1); can_ports("right_slave").SetDefault(2); can_ports("left").SetDefault(3); can_ports("left_slave").SetDefault(4); auto& settings = GetSettings(); settings("ticks_per_revolution").SetDefault(get_ticks_per_rev()); settings("wheel_diameter").SetDefault(get_wheel_diameter()); settings("max_velocity").SetDefault(get_velocity_scale()); settings("wheel_revolutions_per_chassis_pivot_revolution").SetDefault(get_wheel_revs_per_base_rev()); settings("allowable_error").SetDefault(get_allowable_error()); auto& closed_loop_settings = settings["closed_loop_settings"]; closed_loop_settings("use").SetDefault(false); closed_loop_settings("P").SetDefault(.1); closed_loop_settings("I").SetDefault(0.0); closed_loop_settings("D").SetDefault(0.0); closed_loop_settings("F").SetDefault(1.0); closed_loop_settings("I_Zone").SetDefault(2.5); closed_loop_settings("ramp_rate").SetDefault(10); settings["left"]("invert_output").SetDefault(false); settings["left"]("invert_sensor").SetDefault(false); settings["right"]("invert_output").SetDefault(true); settings["right"]("invert_sensor").SetDefault(true); GetLocalValue<double>("distance").Initialize(std::make_shared<dman::FunkyGet<double> > ([this]() { if(is_initialized()) return GetDistance(); })); } bool Drive::doConfigure() { if(!is_initialized()) initTalons(); auto& settings = GetSettings(); SetTicksPerRev(settings("ticks_per_revolution").GetValueOrDefault()); SetWheelDiameter(settings("wheel_diameter").GetValueOrDefault()); SetVelocityScale(settings("max_velocity").GetValueOrDefault()); SetWheelRevsPerBaseRev(settings("wheel_revolutions_per_chassis_pivot_revolution").GetValueOrDefault()); SetAllowableError(settings("allowable_error").GetValueOrDefault()); return configureBoth(); } void Drive::SetMode(Mode_t m) { if(!is_initialized()) return; if(m == mode_) return; else { mode_ = m; std::cout << "Setting mode to " << ModeToString(mode_) << std::endl; setModeMaster(talons_->left_); setModeMaster(talons_->right_); } } void Drive::setModeMaster(CANTalon &master) { if(get_mode() == Mode_t::Position) { master.SetControlMode(CANTalon::ControlMode::kPosition); master.SelectProfileSlot(ModePIDSlot_t::PositionPID); } else if(get_mode() == Mode_t::Velocity) { master.SetControlMode(CANTalon::ControlMode::kSpeed); master.SelectProfileSlot(ModePIDSlot_t::VelocityPID); } else if(get_mode() == Mode_t::VBus) { master.SetControlMode(CANTalon::ControlMode::kPercentVbus); } } void Drive::SetTicksPerRev(Ticks_t val) { ticks_per_rev_ = val; if(is_initialized()) { talons_->left_.ConfigEncoderCodesPerRev(ticks_per_rev_); talons_->right_.ConfigEncoderCodesPerRev(ticks_per_rev_); } } void Drive::SetWheelDiameter(Meters_t val) { wheel_diameter_ = val; } void Drive::SetVelocityScale(MetersPerSecond_t max_velocity) { max_velocity_ = max_velocity; } void Drive::SetWheelRevsPerBaseRev(double rate) { wheel_revs_per_base_rev_= rate; } void Drive::SetAllowableError(double allow) { allowable_error_ = allow; } Drive::Meters_t Drive::GetDistance() const { return (GetLeftRevs())* get_wheel_circumference(); } double Drive::GetRotation() const { return (GetLeftRevs() - GetRightRevs()) / 2.0 * get_wheel_revs_per_base_rev(); } double Drive::GetLeftRevs() const { if(is_initialized()) return talons_->left_.GetPosition(); //< Current understanding is that this returns revs else return 0.0; } double Drive::GetRightRevs() const { if(is_initialized()) return talons_->right_.GetPosition(); //< See GetLeftRevs else return 0.0; } double Drive::GetLeftRPM() const { if(is_initialized()) return talons_->left_.GetSpeed(); else return 0.0; } double Drive::GetRightRPM() const { if(is_initialized()) return talons_->right_.GetSpeed(); else return 0.0; } double Drive::GetLeftSetPointRPM() const { if(is_initialized()) return talons_->left_.GetSetpoint(); else return 0.0; } double Drive::GetRightSetPointRPM() const { if(is_initialized()) return talons_->right_.GetSetpoint(); else return 0.0; } Drive::MetersPerSecond_t Drive::GetVelocity() const { return (GetLeftRPM() + GetRightRPM()) / 2.0 * get_wheel_circumference(); } double Drive::GetBaseRPM() const { return (GetLeftRPM() - GetRightRPM()) / 2.0 * get_wheel_revs_per_base_rev(); } void Drive::ResetPosition() { if(is_initialized()) { talons_->left_.SetPosition(0.0); talons_->right_.SetPosition(0.0); } } bool Drive::GoToPosition(Meters_t pos) { SetMode(Mode_t::Position); if(is_initialized()) { talons_->left_.Set(pos * get_wheel_circumference(), 3); talons_->right_.Set(pos * get_wheel_circumference(), 3); CANJaguar::UpdateSyncGroup(3); if(fabs(GetDistance() - pos) < get_allowable_error()) { return true; } else { return false; } } else { return false; } } bool Drive::TurnToRotation(double revolutions) { SetMode(Mode_t::Position); if(is_initialized()) { talons_->left_.Set(revolutions * get_wheel_revs_per_base_rev(), 3); talons_->right_.Set(revolutions * get_wheel_revs_per_base_rev(), 3); CANJaguar::UpdateSyncGroup(3); if(fabs(GetRotation() - revolutions) * get_wheel_revs_per_base_rev() < get_allowable_error() / get_wheel_diameter()) { return true; } else { return false; } } else { return false; } } void Drive::TankDrive(double left, double right) { if(get_mode() == Mode_t::Position) return; if(is_initialized()) { if(left > 1.0) left = 1.0; if(left < -1.0) left = -1.0; if(right > 1.0) right = 1.0; if(right < -1.0) right = -1.0; if(get_mode() == Mode_t::Velocity) { left *= get_velocity_scale(); right *= get_velocity_scale(); } talons_->left_.Set(left, 3); talons_->right_.Set(right, 3); CANJaguar::UpdateSyncGroup(3); } } void Drive::Stop() { TankDrive(0.0, 0.0); } void Drive::ArcadeDrive(double y, double rotation) { if(y > 1.0) y = 1.0; if(y < -1.0) y = -1.0; if(rotation > 1.0) rotation = 1.0; if(rotation < -1.0) rotation = -1.0; TankDrive(y - rotation, y + rotation); } } <|endoftext|>
<commit_before>// A work-in-progress llvm backend #include <set> #include <taichi/common/util.h> #include <taichi/io/io.h> #include "../ir.h" #include "../program.h" #include "../tlang_util.h" #include "codegen_cuda.h" #include "cuda_context.h" #if defined(TLANG_WITH_CUDA) #include "cuda_runtime.h" #endif #include "codegen_llvm.h" TLANG_NAMESPACE_BEGIN using namespace llvm; // NVVM IR Spec: // https://docs.nvidia.com/cuda/archive/10.0/pdf/NVVM_IR_Specification.pdf class CodeGenLLVMGPU : public CodeGenLLVM { public: int kernel_grid_dim; int kernel_block_dim; CodeGenLLVMGPU(CodeGenBase *codegen_base, Kernel *kernel) : CodeGenLLVM(codegen_base, kernel) {} void mark_function_as_cuda_kernel(llvm::Function *func) { /******************************************************************* Example annotation from llvm PTX doc: define void @kernel(float addrspace(1)* %A, float addrspace(1)* %B, float addrspace(1)* %C); !nvvm.annotations = !{!0} !0 = !{void (float addrspace(1)*, float addrspace(1)*, float addrspace(1)*)* @kernel, !"kernel", i32 1} *******************************************************************/ // Mark kernel function as a CUDA __global__ function // Add the nvvm annotation that it is considered a kernel function. llvm::Metadata *md_args[] = { llvm::ValueAsMetadata::get(func), MDString::get(*llvm_context, "kernel"), llvm::ValueAsMetadata::get(tlctx->get_constant(1))}; MDNode *md_node = MDNode::get(*llvm_context, md_args); module->getOrInsertNamedMetadata("nvvm.annotations")->addOperand(md_node); } FunctionType compile_module_to_executable() override { #if defined(TLANG_WITH_CUDA) auto offloaded_local = offloaded_tasks; for (auto &task : offloaded_local) { llvm::Function *func = module->getFunction(task.name); TC_ASSERT(func); mark_function_as_cuda_kernel(func); } auto ptx = compile_module_to_ptx(module); auto cuda_module = cuda_context.compile(ptx); for (auto &task : offloaded_local) { task.cuda_func = (void *)cuda_context.get_function(cuda_module, task.name); } return [offloaded_local](Context context) { for (auto task : offloaded_local) { if (get_current_program().config.verbose_kernel_launches) TC_INFO("Launching kernel {}<<<{}, {}>>>", task.name, task.grid_dim, task.block_dim); if (get_current_program().config.enable_profiler) { get_current_program().profiler_llvm->start(task.name); } cuda_context.launch((CUfunction)task.cuda_func, &context, task.grid_dim, task.block_dim); if (get_current_program().config.enable_profiler) { get_current_program().profiler_llvm->stop(); } } }; #else TC_NOT_IMPLEMENTED; return nullptr; #endif } void visit(PrintStmt *stmt) override { TC_ASSERT(stmt->width() == 1); auto value_type = tlctx->get_data_type(stmt->stmt->ret_type.data_type); std::string format; auto value = stmt->stmt->value; if (stmt->stmt->ret_type.data_type == DataType::i32) { format = "%d"; } else if (stmt->stmt->ret_type.data_type == DataType::f32) { value_type = llvm::Type::getDoubleTy(*llvm_context); value = builder->CreateFPExt(value, value_type); format = "%f"; } else if (stmt->stmt->ret_type.data_type == DataType::f64) { format = "%f"; } else { TC_NOT_IMPLEMENTED } std::vector<llvm::Type *> types{value_type}; auto stype = llvm::StructType::get(*llvm_context, types, false); auto values = builder->CreateAlloca(stype); auto value_ptr = builder->CreateGEP( values, {tlctx->get_constant(0), tlctx->get_constant(0)}); builder->CreateStore(value, value_ptr); auto format_str = "[debug] " + stmt->str + " = " + format + "\n"; stmt->value = ModuleBuilder::call( builder, "vprintf", builder->CreateGlobalStringPtr(format_str, "format_string"), builder->CreateBitCast(values, llvm::Type::getInt8PtrTy(*llvm_context))); } void emit_extra_unary(UnaryOpStmt *stmt) override { // functions from libdevice auto input = stmt->operand->value; auto input_taichi_type = stmt->operand->ret_type.data_type; auto op = stmt->op_type; #define UNARY_STD(x) \ else if (op == UnaryOpType::x) { \ if (input_taichi_type == DataType::f32) { \ stmt->value = \ builder->CreateCall(get_runtime_function("__nv_" #x "f"), input); \ } else if (input_taichi_type == DataType::f64) { \ stmt->value = \ builder->CreateCall(get_runtime_function("__nv_" #x), input); \ } else if (input_taichi_type == DataType::i32) { \ stmt->value = builder->CreateCall(get_runtime_function(#x), input); \ } else { \ TC_NOT_IMPLEMENTED \ } \ } if (op == UnaryOpType::abs) { if (input_taichi_type == DataType::f32) { stmt->value = builder->CreateCall(get_runtime_function("__nv_fabsf"), input); } else if (input_taichi_type == DataType::f64) { stmt->value = builder->CreateCall(get_runtime_function("__nv_fabs"), input); } else if (input_taichi_type == DataType::i32) { stmt->value = builder->CreateCall(get_runtime_function("__nv_abs"), input); } else { TC_NOT_IMPLEMENTED } } else if (op == UnaryOpType::logic_not) { if (input_taichi_type == DataType::i32) { stmt->value = builder->CreateCall(get_runtime_function("logic_not_i32"), input); } else { TC_NOT_IMPLEMENTED } } UNARY_STD(exp) UNARY_STD(log) UNARY_STD(tan) UNARY_STD(tanh) UNARY_STD(sgn) else { TC_P(unary_op_type_name(op)); TC_NOT_IMPLEMENTED } #undef UNARY_STD } void visit(AtomicOpStmt *stmt) override { auto mask = stmt->parent->mask(); for (int l = 0; l < stmt->width(); l++) { if (mask) { emit("if ({}[{}]) ", mask->raw_name(), l); } else { TC_ASSERT(stmt->op_type == AtomicOpType::add); if (is_integral(stmt->val->ret_type.data_type)) builder->CreateAtomicRMW( llvm::AtomicRMWInst::BinOp::Add, stmt->dest->value, stmt->val->value, llvm::AtomicOrdering::SequentiallyConsistent); else if (stmt->val->ret_type.data_type == DataType::f32) { auto dt = tlctx->get_data_type(DataType::f32); builder->CreateIntrinsic(Intrinsic::nvvm_atomic_load_add_f32, {llvm::PointerType::get(dt, 0)}, {stmt->dest->value, stmt->val->value}); } else if (stmt->val->ret_type.data_type == DataType::f64) { auto dt = tlctx->get_data_type(DataType::f64); builder->CreateIntrinsic(Intrinsic::nvvm_atomic_load_add_f64, {llvm::PointerType::get(dt, 0)}, {stmt->dest->value, stmt->val->value}); } else { TC_NOT_IMPLEMENTED } } } } void visit(RangeForStmt *for_stmt) override { create_naive_range_for(for_stmt); } void create_offload_range_for(OffloadedStmt *stmt) { auto loop_var = create_entry_block_alloca(DataType::i32); stmt->loop_vars_llvm.push_back(loop_var); auto loop_begin = stmt->begin; auto loop_end = stmt->end; auto loop_block_dim = stmt->block_dim; if (loop_block_dim == 0) { loop_block_dim = get_current_program().config.default_gpu_block_dim; } kernel_grid_dim = (loop_end - loop_begin + loop_block_dim - 1) / loop_block_dim; kernel_block_dim = loop_block_dim; BasicBlock *body = BasicBlock::Create(*llvm_context, "loop_body", func); BasicBlock *after_loop = BasicBlock::Create(*llvm_context, "block", func); auto threadIdx = builder->CreateIntrinsic(Intrinsic::nvvm_read_ptx_sreg_tid_x, {}, {}); auto blockIdx = builder->CreateIntrinsic(Intrinsic::nvvm_read_ptx_sreg_ctaid_x, {}, {}); auto blockDim = builder->CreateIntrinsic(Intrinsic::nvvm_read_ptx_sreg_ntid_x, {}, {}); auto loop_id = builder->CreateAdd( tlctx->get_constant(stmt->begin), builder->CreateAdd(threadIdx, builder->CreateMul(blockIdx, blockDim))); builder->CreateStore(loop_id, loop_var); auto cond = builder->CreateICmp(llvm::CmpInst::Predicate::ICMP_SLT, builder->CreateLoad(loop_var), tlctx->get_constant(stmt->end)); builder->CreateCondBr(cond, body, after_loop); { // body cfg builder->SetInsertPoint(body); stmt->body->accept(this); builder->CreateBr(after_loop); } builder->SetInsertPoint(after_loop); } void visit(OffloadedStmt *stmt) override { #if defined(TLANG_WITH_CUDA) using Type = OffloadedStmt::TaskType; kernel_grid_dim = 1; kernel_block_dim = 1; init_task_function(stmt); if (stmt->task_type == Type::serial) { stmt->body->accept(this); } else if (stmt->task_type == Type::range_for) { create_offload_range_for(stmt); } else if (stmt->task_type == Type::struct_for) { int num_SMs; cudaDeviceGetAttribute(&num_SMs, cudaDevAttrMultiProcessorCount, 0); int max_block_dim; cudaDeviceGetAttribute(&max_block_dim, cudaDevAttrMaxBlockDimX, 0); kernel_grid_dim = num_SMs * 32; // each SM can have 16-32 resident blocks kernel_block_dim = stmt->block_dim; if (kernel_block_dim == 0) kernel_block_dim = get_current_program().config.default_gpu_block_dim; kernel_block_dim = std::min(stmt->snode->parent->max_num_elements(), kernel_block_dim); stmt->block_dim = kernel_block_dim; create_offload_struct_for(stmt, true); } else if (stmt->task_type == Type::listgen) { emit_list_gen(stmt); } else { TC_NOT_IMPLEMENTED } finalize_task_function(); current_task->grid_dim = kernel_grid_dim; current_task->block_dim = kernel_block_dim; current_task->end(); current_task = nullptr; #else TC_NOT_IMPLEMENTED #endif } }; FunctionType GPUCodeGen::codegen_llvm() { TC_PROFILER("gpu codegen"); return CodeGenLLVMGPU(this, kernel).gen(); } TLANG_NAMESPACE_END <commit_msg>try fix cuda tests<commit_after>// A work-in-progress llvm backend #include <set> #include <taichi/common/util.h> #include <taichi/io/io.h> #include "../ir.h" #include "../program.h" #include "../tlang_util.h" #include "codegen_cuda.h" #include "cuda_context.h" #if defined(TLANG_WITH_CUDA) #include "cuda_runtime.h" #endif #include "codegen_llvm.h" TLANG_NAMESPACE_BEGIN using namespace llvm; // NVVM IR Spec: // https://docs.nvidia.com/cuda/archive/10.0/pdf/NVVM_IR_Specification.pdf class CodeGenLLVMGPU : public CodeGenLLVM { public: int kernel_grid_dim; int kernel_block_dim; CodeGenLLVMGPU(CodeGenBase *codegen_base, Kernel *kernel) : CodeGenLLVM(codegen_base, kernel) {} void mark_function_as_cuda_kernel(llvm::Function *func) { /******************************************************************* Example annotation from llvm PTX doc: define void @kernel(float addrspace(1)* %A, float addrspace(1)* %B, float addrspace(1)* %C); !nvvm.annotations = !{!0} !0 = !{void (float addrspace(1)*, float addrspace(1)*, float addrspace(1)*)* @kernel, !"kernel", i32 1} *******************************************************************/ // Mark kernel function as a CUDA __global__ function // Add the nvvm annotation that it is considered a kernel function. llvm::Metadata *md_args[] = { llvm::ValueAsMetadata::get(func), MDString::get(*llvm_context, "kernel"), llvm::ValueAsMetadata::get(tlctx->get_constant(1))}; MDNode *md_node = MDNode::get(*llvm_context, md_args); module->getOrInsertNamedMetadata("nvvm.annotations")->addOperand(md_node); } FunctionType compile_module_to_executable() override { #if defined(TLANG_WITH_CUDA) auto offloaded_local = offloaded_tasks; for (auto &task : offloaded_local) { llvm::Function *func = module->getFunction(task.name); TC_ASSERT(func); mark_function_as_cuda_kernel(func); } auto ptx = compile_module_to_ptx(module); auto cuda_module = cuda_context.compile(ptx); for (auto &task : offloaded_local) { task.cuda_func = (void *)cuda_context.get_function(cuda_module, task.name); } return [offloaded_local](Context context) { for (auto task : offloaded_local) { if (get_current_program().config.verbose_kernel_launches) TC_INFO("Launching kernel {}<<<{}, {}>>>", task.name, task.grid_dim, task.block_dim); if (get_current_program().config.enable_profiler) { get_current_program().profiler_llvm->start(task.name); } cuda_context.launch((CUfunction)task.cuda_func, &context, task.grid_dim, task.block_dim); if (get_current_program().config.enable_profiler) { get_current_program().profiler_llvm->stop(); } } }; #else TC_NOT_IMPLEMENTED; return nullptr; #endif } void visit(PrintStmt *stmt) override { TC_ASSERT(stmt->width() == 1); auto value_type = tlctx->get_data_type(stmt->stmt->ret_type.data_type); std::string format; auto value = stmt->stmt->value; if (stmt->stmt->ret_type.data_type == DataType::i32) { format = "%d"; } else if (stmt->stmt->ret_type.data_type == DataType::f32) { value_type = llvm::Type::getDoubleTy(*llvm_context); value = builder->CreateFPExt(value, value_type); format = "%f"; } else if (stmt->stmt->ret_type.data_type == DataType::f64) { format = "%f"; } else { TC_NOT_IMPLEMENTED } std::vector<llvm::Type *> types{value_type}; auto stype = llvm::StructType::get(*llvm_context, types, false); auto values = builder->CreateAlloca(stype); auto value_ptr = builder->CreateGEP( values, {tlctx->get_constant(0), tlctx->get_constant(0)}); builder->CreateStore(value, value_ptr); auto format_str = "[debug] " + stmt->str + " = " + format + "\n"; stmt->value = ModuleBuilder::call( builder, "vprintf", builder->CreateGlobalStringPtr(format_str, "format_string"), builder->CreateBitCast(values, llvm::Type::getInt8PtrTy(*llvm_context))); } void emit_extra_unary(UnaryOpStmt *stmt) override { // functions from libdevice auto input = stmt->operand->value; auto input_taichi_type = stmt->operand->ret_type.data_type; auto op = stmt->op_type; #define UNARY_STD(x) \ else if (op == UnaryOpType::x) { \ if (input_taichi_type == DataType::f32) { \ stmt->value = \ builder->CreateCall(get_runtime_function("__nv_" #x "f"), input); \ } else if (input_taichi_type == DataType::f64) { \ stmt->value = \ builder->CreateCall(get_runtime_function("__nv_" #x), input); \ } else if (input_taichi_type == DataType::i32) { \ stmt->value = builder->CreateCall(get_runtime_function(#x), input); \ } else { \ TC_NOT_IMPLEMENTED \ } \ } if (op == UnaryOpType::abs) { if (input_taichi_type == DataType::f32) { stmt->value = builder->CreateCall(get_runtime_function("__nv_fabsf"), input); } else if (input_taichi_type == DataType::f64) { stmt->value = builder->CreateCall(get_runtime_function("__nv_fabs"), input); } else if (input_taichi_type == DataType::i32) { stmt->value = builder->CreateCall(get_runtime_function("__nv_abs"), input); } else { TC_NOT_IMPLEMENTED } } else if (op == UnaryOpType::logic_not) { if (input_taichi_type == DataType::i32) { stmt->value = builder->CreateCall(get_runtime_function("logic_not_i32"), input); } else { TC_NOT_IMPLEMENTED } } UNARY_STD(exp) UNARY_STD(log) UNARY_STD(tan) UNARY_STD(tanh) UNARY_STD(sgn) else { TC_P(unary_op_type_name(op)); TC_NOT_IMPLEMENTED } #undef UNARY_STD } void visit(AtomicOpStmt *stmt) override { auto mask = stmt->parent->mask(); TC_ASSERT(stmt->width() == 1); for (int l = 0; l < stmt->width(); l++) { TC_ASSERT(stmt->op_type == AtomicOpType::add); if (is_integral(stmt->val->ret_type.data_type)) builder->CreateAtomicRMW( llvm::AtomicRMWInst::BinOp::Add, stmt->dest->value, stmt->val->value, llvm::AtomicOrdering::SequentiallyConsistent); else if (stmt->val->ret_type.data_type == DataType::f32) { auto dt = tlctx->get_data_type(DataType::f32); builder->CreateIntrinsic(Intrinsic::nvvm_atomic_load_add_f32, {llvm::PointerType::get(dt, 0)}, {stmt->dest->value, stmt->val->value}); } else if (stmt->val->ret_type.data_type == DataType::f64) { auto dt = tlctx->get_data_type(DataType::f64); builder->CreateIntrinsic(Intrinsic::nvvm_atomic_load_add_f64, {llvm::PointerType::get(dt, 0)}, {stmt->dest->value, stmt->val->value}); } else { TC_NOT_IMPLEMENTED } } } void visit(RangeForStmt *for_stmt) override { create_naive_range_for(for_stmt); } void create_offload_range_for(OffloadedStmt *stmt) { auto loop_var = create_entry_block_alloca(DataType::i32); stmt->loop_vars_llvm.push_back(loop_var); auto loop_begin = stmt->begin; auto loop_end = stmt->end; auto loop_block_dim = stmt->block_dim; if (loop_block_dim == 0) { loop_block_dim = get_current_program().config.default_gpu_block_dim; } kernel_grid_dim = (loop_end - loop_begin + loop_block_dim - 1) / loop_block_dim; kernel_block_dim = loop_block_dim; BasicBlock *body = BasicBlock::Create(*llvm_context, "loop_body", func); BasicBlock *after_loop = BasicBlock::Create(*llvm_context, "block", func); auto threadIdx = builder->CreateIntrinsic(Intrinsic::nvvm_read_ptx_sreg_tid_x, {}, {}); auto blockIdx = builder->CreateIntrinsic(Intrinsic::nvvm_read_ptx_sreg_ctaid_x, {}, {}); auto blockDim = builder->CreateIntrinsic(Intrinsic::nvvm_read_ptx_sreg_ntid_x, {}, {}); auto loop_id = builder->CreateAdd( tlctx->get_constant(stmt->begin), builder->CreateAdd(threadIdx, builder->CreateMul(blockIdx, blockDim))); builder->CreateStore(loop_id, loop_var); auto cond = builder->CreateICmp(llvm::CmpInst::Predicate::ICMP_SLT, builder->CreateLoad(loop_var), tlctx->get_constant(stmt->end)); builder->CreateCondBr(cond, body, after_loop); { // body cfg builder->SetInsertPoint(body); stmt->body->accept(this); builder->CreateBr(after_loop); } builder->SetInsertPoint(after_loop); } void visit(OffloadedStmt *stmt) override { #if defined(TLANG_WITH_CUDA) using Type = OffloadedStmt::TaskType; kernel_grid_dim = 1; kernel_block_dim = 1; init_task_function(stmt); if (stmt->task_type == Type::serial) { stmt->body->accept(this); } else if (stmt->task_type == Type::range_for) { create_offload_range_for(stmt); } else if (stmt->task_type == Type::struct_for) { int num_SMs; cudaDeviceGetAttribute(&num_SMs, cudaDevAttrMultiProcessorCount, 0); int max_block_dim; cudaDeviceGetAttribute(&max_block_dim, cudaDevAttrMaxBlockDimX, 0); kernel_grid_dim = num_SMs * 32; // each SM can have 16-32 resident blocks kernel_block_dim = stmt->block_dim; if (kernel_block_dim == 0) kernel_block_dim = get_current_program().config.default_gpu_block_dim; kernel_block_dim = std::min(stmt->snode->parent->max_num_elements(), kernel_block_dim); stmt->block_dim = kernel_block_dim; create_offload_struct_for(stmt, true); } else if (stmt->task_type == Type::listgen) { emit_list_gen(stmt); } else { TC_NOT_IMPLEMENTED } finalize_task_function(); current_task->grid_dim = kernel_grid_dim; current_task->block_dim = kernel_block_dim; current_task->end(); current_task = nullptr; #else TC_NOT_IMPLEMENTED #endif } }; FunctionType GPUCodeGen::codegen_llvm() { TC_PROFILER("gpu codegen"); return CodeGenLLVMGPU(this, kernel).gen(); } TLANG_NAMESPACE_END <|endoftext|>
<commit_before>//===-- FileCollectorTest.cpp -----------------------------------*- C++ -*-===// // // 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 // //===----------------------------------------------------------------------===// #include "gmock/gmock.h" #include "gtest/gtest.h" #include "llvm/Support/FileCollector.h" #include "llvm/Support/FileSystem.h" using namespace llvm; namespace llvm { namespace vfs { inline bool operator==(const llvm::vfs::YAMLVFSEntry &LHS, const llvm::vfs::YAMLVFSEntry &RHS) { return LHS.VPath == RHS.VPath && LHS.RPath == RHS.RPath; } } // namespace vfs } // namespace llvm namespace { class TestingFileCollector : public FileCollector { public: using FileCollector::FileCollector; using FileCollector::m_root; using FileCollector::m_seen; using FileCollector::m_symlink_map; using FileCollector::m_vfs_writer; bool HasSeen(StringRef fs) { return m_seen.find(fs) != m_seen.end(); } }; struct ScopedDir { SmallString<128> Path; ScopedDir(const Twine &Name, bool Unique = false) { std::error_code EC; if (Unique) { EC = llvm::sys::fs::createUniqueDirectory(Name, Path); } else { Path = Name.str(); EC = llvm::sys::fs::create_directory(Twine(Path)); } if (EC) Path = ""; EXPECT_FALSE(EC); // Ensure the path is the real path so tests can use it to compare against // realpath output. SmallString<128> RealPath; if (!llvm::sys::fs::real_path(Path, RealPath)) Path.swap(RealPath); } ~ScopedDir() { if (Path != "") { EXPECT_FALSE(llvm::sys::fs::remove_directories(Path.str())); } } operator StringRef() { return Path.str(); } }; struct ScopedLink { SmallString<128> Path; ScopedLink(const Twine &To, const Twine &From) { Path = From.str(); std::error_code EC = sys::fs::create_link(To, From); if (EC) Path = ""; EXPECT_FALSE(EC); } ~ScopedLink() { if (Path != "") { EXPECT_FALSE(llvm::sys::fs::remove(Path.str())); } } operator StringRef() { return Path.str(); } }; struct ScopedFile { SmallString<128> Path; ScopedFile(const Twine &Name) { std::error_code EC; EC = llvm::sys::fs::createUniqueFile(Name, Path); if (EC) Path = ""; EXPECT_FALSE(EC); } ~ScopedFile() { if (Path != "") { EXPECT_FALSE(llvm::sys::fs::remove(Path.str())); } } operator StringRef() { return Path.str(); } }; } // end anonymous namespace TEST(FileCollectorTest, AddFile) { ScopedDir root("add_file_root", true); std::string root_fs = root.Path.str(); TestingFileCollector file_collector(root_fs, root_fs); file_collector.AddFile("/path/to/a"); file_collector.AddFile("/path/to/b"); file_collector.AddFile("/path/to/c"); // Make sure the root is correct. EXPECT_EQ(file_collector.m_root, root_fs); // Make sure we've seen all the added files. EXPECT_TRUE(file_collector.HasSeen("/path/to/a")); EXPECT_TRUE(file_collector.HasSeen("/path/to/b")); EXPECT_TRUE(file_collector.HasSeen("/path/to/c")); // Make sure we've only seen the added files. EXPECT_FALSE(file_collector.HasSeen("/path/to/d")); } TEST(FileCollectorTest, CopyFiles) { ScopedDir file_root("file_root", true); ScopedFile a(file_root + "/aaa"); ScopedFile b(file_root + "/bbb"); ScopedFile c(file_root + "/ccc"); // Create file collector and add files. ScopedDir root("copy_files_root", true); std::string root_fs = root.Path.str(); TestingFileCollector file_collector(root_fs, root_fs); file_collector.AddFile(a.Path); file_collector.AddFile(b.Path); file_collector.AddFile(c.Path); // Make sure we can copy the files. std::error_code ec = file_collector.CopyFiles(true); EXPECT_FALSE(ec); // Now add a bogus file and make sure we error out. file_collector.AddFile("/some/bogus/file"); ec = file_collector.CopyFiles(true); EXPECT_TRUE(ec); // However, if stop_on_error is true the copy should still succeed. ec = file_collector.CopyFiles(false); EXPECT_FALSE(ec); } #ifndef _WIN32 TEST(FileCollectorTest, Symlinks) { // Root where the original files live. ScopedDir file_root("file_root", true); // Create some files in the file root. ScopedFile a(file_root + "/aaa"); ScopedFile b(file_root + "/bbb"); ScopedFile c(file_root + "/ccc"); // Create a directory foo with file ddd. ScopedDir foo(file_root + "/foo"); ScopedFile d(foo + "/ddd"); // Create a file eee in the foo's parent directory. ScopedFile e(foo + "/../eee"); // Create a symlink bar pointing to foo. ScopedLink symlink(file_root + "/foo", file_root + "/bar"); // Root where files are copied to. ScopedDir reproducer_root("reproducer_root", true); std::string root_fs = reproducer_root.Path.str(); TestingFileCollector file_collector(root_fs, root_fs); // Add all the files to the collector. file_collector.AddFile(a.Path); file_collector.AddFile(b.Path); file_collector.AddFile(c.Path); file_collector.AddFile(d.Path); file_collector.AddFile(e.Path); file_collector.AddFile(file_root + "/bar/ddd"); auto mapping = file_collector.m_vfs_writer.getMappings(); { // Make sure the common case works. std::string vpath = (file_root + "/aaa").str(); std::string rpath = (reproducer_root.Path + file_root.Path + "/aaa").str(); printf("%s -> %s\n", vpath.c_str(), rpath.c_str()); EXPECT_THAT(mapping, testing::Contains(vfs::YAMLVFSEntry(vpath, rpath))); } { // Make sure the virtual path points to the real source path. std::string vpath = (file_root + "/bar/ddd").str(); std::string rpath = (reproducer_root.Path + file_root.Path + "/foo/ddd").str(); printf("%s -> %s\n", vpath.c_str(), rpath.c_str()); EXPECT_THAT(mapping, testing::Contains(vfs::YAMLVFSEntry(vpath, rpath))); } { // Make sure that .. is removed from the source path. std::string vpath = (file_root + "/eee").str(); std::string rpath = (reproducer_root.Path + file_root.Path + "/eee").str(); printf("%s -> %s\n", vpath.c_str(), rpath.c_str()); EXPECT_THAT(mapping, testing::Contains(vfs::YAMLVFSEntry(vpath, rpath))); } } #endif <commit_msg>[FileCollector] Update unit test to match coding style.<commit_after>//===-- FileCollectorTest.cpp -----------------------------------*- C++ -*-===// // // 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 // //===----------------------------------------------------------------------===// #include "gmock/gmock.h" #include "gtest/gtest.h" #include "llvm/Support/FileCollector.h" #include "llvm/Support/FileSystem.h" using namespace llvm; namespace llvm { namespace vfs { inline bool operator==(const llvm::vfs::YAMLVFSEntry &LHS, const llvm::vfs::YAMLVFSEntry &RHS) { return LHS.VPath == RHS.VPath && LHS.RPath == RHS.RPath; } } // namespace vfs } // namespace llvm namespace { class TestingFileCollector : public FileCollector { public: using FileCollector::FileCollector; using FileCollector::Root; using FileCollector::Seen; using FileCollector::SymlinkMap; using FileCollector::VFSWriter; bool hasSeen(StringRef fs) { return Seen.find(fs) != Seen.end(); } }; struct ScopedDir { SmallString<128> Path; ScopedDir(const Twine &Name, bool Unique = false) { std::error_code EC; if (Unique) { EC = llvm::sys::fs::createUniqueDirectory(Name, Path); } else { Path = Name.str(); EC = llvm::sys::fs::create_directory(Twine(Path)); } if (EC) Path = ""; EXPECT_FALSE(EC); // Ensure the path is the real path so tests can use it to compare against // realpath output. SmallString<128> RealPath; if (!llvm::sys::fs::real_path(Path, RealPath)) Path.swap(RealPath); } ~ScopedDir() { if (Path != "") { EXPECT_FALSE(llvm::sys::fs::remove_directories(Path.str())); } } operator StringRef() { return Path.str(); } }; struct ScopedLink { SmallString<128> Path; ScopedLink(const Twine &To, const Twine &From) { Path = From.str(); std::error_code EC = sys::fs::create_link(To, From); if (EC) Path = ""; EXPECT_FALSE(EC); } ~ScopedLink() { if (Path != "") { EXPECT_FALSE(llvm::sys::fs::remove(Path.str())); } } operator StringRef() { return Path.str(); } }; struct ScopedFile { SmallString<128> Path; ScopedFile(const Twine &Name) { std::error_code EC; EC = llvm::sys::fs::createUniqueFile(Name, Path); if (EC) Path = ""; EXPECT_FALSE(EC); } ~ScopedFile() { if (Path != "") { EXPECT_FALSE(llvm::sys::fs::remove(Path.str())); } } operator StringRef() { return Path.str(); } }; } // end anonymous namespace TEST(FileCollectorTest, addFile) { ScopedDir root("add_file_root", true); std::string root_fs = root.Path.str(); TestingFileCollector FileCollector(root_fs, root_fs); FileCollector.addFile("/path/to/a"); FileCollector.addFile("/path/to/b"); FileCollector.addFile("/path/to/c"); // Make sure the root is correct. EXPECT_EQ(FileCollector.Root, root_fs); // Make sure we've seen all the added files. EXPECT_TRUE(FileCollector.hasSeen("/path/to/a")); EXPECT_TRUE(FileCollector.hasSeen("/path/to/b")); EXPECT_TRUE(FileCollector.hasSeen("/path/to/c")); // Make sure we've only seen the added files. EXPECT_FALSE(FileCollector.hasSeen("/path/to/d")); } TEST(FileCollectorTest, copyFiles) { ScopedDir file_root("file_root", true); ScopedFile a(file_root + "/aaa"); ScopedFile b(file_root + "/bbb"); ScopedFile c(file_root + "/ccc"); // Create file collector and add files. ScopedDir root("copy_files_root", true); std::string root_fs = root.Path.str(); TestingFileCollector FileCollector(root_fs, root_fs); FileCollector.addFile(a.Path); FileCollector.addFile(b.Path); FileCollector.addFile(c.Path); // Make sure we can copy the files. std::error_code ec = FileCollector.copyFiles(true); EXPECT_FALSE(ec); // Now add a bogus file and make sure we error out. FileCollector.addFile("/some/bogus/file"); ec = FileCollector.copyFiles(true); EXPECT_TRUE(ec); // However, if stop_on_error is true the copy should still succeed. ec = FileCollector.copyFiles(false); EXPECT_FALSE(ec); } #ifndef _WIN32 TEST(FileCollectorTest, Symlinks) { // Root where the original files live. ScopedDir file_root("file_root", true); // Create some files in the file root. ScopedFile a(file_root + "/aaa"); ScopedFile b(file_root + "/bbb"); ScopedFile c(file_root + "/ccc"); // Create a directory foo with file ddd. ScopedDir foo(file_root + "/foo"); ScopedFile d(foo + "/ddd"); // Create a file eee in the foo's parent directory. ScopedFile e(foo + "/../eee"); // Create a symlink bar pointing to foo. ScopedLink symlink(file_root + "/foo", file_root + "/bar"); // Root where files are copied to. ScopedDir reproducer_root("reproducer_root", true); std::string root_fs = reproducer_root.Path.str(); TestingFileCollector FileCollector(root_fs, root_fs); // Add all the files to the collector. FileCollector.addFile(a.Path); FileCollector.addFile(b.Path); FileCollector.addFile(c.Path); FileCollector.addFile(d.Path); FileCollector.addFile(e.Path); FileCollector.addFile(file_root + "/bar/ddd"); auto mapping = FileCollector.VFSWriter.getMappings(); { // Make sure the common case works. std::string vpath = (file_root + "/aaa").str(); std::string rpath = (reproducer_root.Path + file_root.Path + "/aaa").str(); printf("%s -> %s\n", vpath.c_str(), rpath.c_str()); EXPECT_THAT(mapping, testing::Contains(vfs::YAMLVFSEntry(vpath, rpath))); } { // Make sure the virtual path points to the real source path. std::string vpath = (file_root + "/bar/ddd").str(); std::string rpath = (reproducer_root.Path + file_root.Path + "/foo/ddd").str(); printf("%s -> %s\n", vpath.c_str(), rpath.c_str()); EXPECT_THAT(mapping, testing::Contains(vfs::YAMLVFSEntry(vpath, rpath))); } { // Make sure that .. is removed from the source path. std::string vpath = (file_root + "/eee").str(); std::string rpath = (reproducer_root.Path + file_root.Path + "/eee").str(); printf("%s -> %s\n", vpath.c_str(), rpath.c_str()); EXPECT_THAT(mapping, testing::Contains(vfs::YAMLVFSEntry(vpath, rpath))); } } #endif <|endoftext|>
<commit_before> #include "Path.h" #include "SpanningTree.h" #include <iostream> Path::Path(const size_t size) { length = size; path.reserve(length); } Path::~Path(void) { // path.clear(); } /** * Recurser function for fromTree to do the search */ static void fromTreeHelper(SpanningTree * const tree, std::vector<Vertex> * const path, std::size_t curr) { for (std::size_t i = 0; i != tree->size(); i++) { // Skip over any nodes that don't have current node as parent. // Therefore also skips previously visited nodes. // Note: tree.get gives the parent of node if (i != curr && tree->get(i) == curr) { path->push_back(i); fromTreeHelper(tree, path, i); } } } Path * Path::fromTree(SpanningTree *const tree) { Path * const newPath = new Path(tree->size()); std::size_t curr = 0; newPath->path.push_back(0); // default root of MST is 0th node fromTreeHelper(tree, &newPath->path, curr); return newPath; } Path * Path::fromPath(std::vector<Vertex> path) { Path *newPath = new Path(path.size()); newPath->path = path; return newPath; } Path * Path::fromPair(std::pair<Vertex, Vertex> path) { Path *newPath = new Path(2); newPath->path.push_back(path.first); newPath->path.push_back(path.second); return newPath; } static mbogo_weight_t getWeight(UndirectedGraph * const g, Vertex v, EdgeDescriptor e) { typename boost::property_map<UndirectedGraph, boost::edge_weight_t >::type weight = boost::get(boost::edge_weight, *g); return boost::get(weight, e); } mbogo_weight_t Path::getTotalCost(UndirectedGraph *const g) { mbogo_weight_t cost = 0; if (length == 0 || length == 1) return 0; EdgeDescriptor e; bool found; std::vector<Vertex>::iterator it = path.begin(); Vertex prevNode = *it++; for (; it != path.end(); it++) { tie(e, found) = edge(prevNode, *it, *g); // std::cout << "weight(" << prevNode << "," << *it << "):" << boost::get(weight, e) << std::endl; cost += getWeight(g, *it, e); prevNode = *it; } return cost; } void Path::getLocations(Point *locations, Point *locs) { for (size_t i = 0; i < length; i++) locs[i] = locations[path.data()[i]]; } void Path::convertPath(Vertex *path) { std::vector<Vertex> tempPath; tempPath.resize(length); for (size_t i = 0; i < length; i++) tempPath[i] = path[this->path[i]]; this->path = tempPath; } std::vector<Vertex> * Path::data(void) { return &path; } void Path::print(void) const { for (std::vector<Vertex>::const_iterator it = path.begin(); it != path.end(); it++) { std::cout << *it << std::endl; } } void Path::printWithLocations(Point *locations, UndirectedGraph *g) const { int index = 0; EdgeDescriptor e; bool found; std::vector<Vertex>::const_iterator it = path.begin(); Vertex prevNode = *it++; for (; it != path.end(); it++) { tie(e, found) = edge(prevNode, *it, *g); std::cout << *it << " : (" << locations[path.data()[index]].first << "," << locations[path.data()[index]].second << ") : " << getWeight(g, *it, e) << std::endl; index += 1; } } std::string Path::toString(void) const { std::ostringstream os; std::streambuf *coutbuf = std::cout.rdbuf(); std::cout.rdbuf(os.rdbuf()); print(); std::cout.rdbuf(coutbuf); return os.str(); } std::string Path::toStringWithLocations(Point *locations, UndirectedGraph *g) const { std::ostringstream os; std::streambuf *coutbuf = std::cout.rdbuf(); std::cout.rdbuf(os.rdbuf()); printWithLocations(locations, g); std::cout.rdbuf(coutbuf); return os.str(); } <commit_msg>Fixed skipped first vertex printout<commit_after> #include "Path.h" #include "SpanningTree.h" #include <iostream> Path::Path(const size_t size) { length = size; path.reserve(length); } Path::~Path(void) { // path.clear(); } /** * Recurser function for fromTree to do the search */ static void fromTreeHelper(SpanningTree * const tree, std::vector<Vertex> * const path, std::size_t curr) { for (std::size_t i = 0; i != tree->size(); i++) { // Skip over any nodes that don't have current node as parent. // Therefore also skips previously visited nodes. // Note: tree.get gives the parent of node if (i != curr && tree->get(i) == curr) { path->push_back(i); fromTreeHelper(tree, path, i); } } } Path * Path::fromTree(SpanningTree *const tree) { Path * const newPath = new Path(tree->size()); std::size_t curr = 0; newPath->path.push_back(0); // default root of MST is 0th node fromTreeHelper(tree, &newPath->path, curr); return newPath; } Path * Path::fromPath(std::vector<Vertex> path) { Path *newPath = new Path(path.size()); newPath->path = path; return newPath; } Path * Path::fromPair(std::pair<Vertex, Vertex> path) { Path *newPath = new Path(2); newPath->path.push_back(path.first); newPath->path.push_back(path.second); return newPath; } static mbogo_weight_t getWeight(UndirectedGraph * const g, Vertex v, EdgeDescriptor e) { typename boost::property_map<UndirectedGraph, boost::edge_weight_t >::type weight = boost::get(boost::edge_weight, *g); return boost::get(weight, e); } mbogo_weight_t Path::getTotalCost(UndirectedGraph *const g) { mbogo_weight_t cost = 0; if (length == 0 || length == 1) return 0; EdgeDescriptor e; bool found; std::vector<Vertex>::iterator it = path.begin(); Vertex prevNode = *it++; for (; it != path.end(); it++) { tie(e, found) = edge(prevNode, *it, *g); // std::cout << "weight(" << prevNode << "," << *it << "):" << boost::get(weight, e) << std::endl; cost += getWeight(g, *it, e); prevNode = *it; } return cost; } void Path::getLocations(Point *locations, Point *locs) { for (size_t i = 0; i < length; i++) locs[i] = locations[path.data()[i]]; } void Path::convertPath(Vertex *path) { std::vector<Vertex> tempPath; tempPath.resize(length); for (size_t i = 0; i < length; i++) tempPath[i] = path[this->path[i]]; this->path = tempPath; } std::vector<Vertex> * Path::data(void) { return &path; } void Path::print(void) const { for (std::vector<Vertex>::const_iterator it = path.begin(); it != path.end(); it++) { std::cout << *it << std::endl; } } void Path::printWithLocations(Point *locations, UndirectedGraph *g) const { int index = 0; EdgeDescriptor e; bool found; std::vector<Vertex>::const_iterator it = path.begin(); for (; it != path.end(); it++) { Vertex prevNode = *it; tie(e, found) = edge(prevNode, *it, *g); std::cout << *it << " : (" << locations[path.data()[index]].first << "," << locations[path.data()[index]].second << ") : " << getWeight(g, *it, e) << std::endl; index += 1; } } std::string Path::toString(void) const { std::ostringstream os; std::streambuf *coutbuf = std::cout.rdbuf(); std::cout.rdbuf(os.rdbuf()); print(); std::cout.rdbuf(coutbuf); return os.str(); } std::string Path::toStringWithLocations(Point *locations, UndirectedGraph *g) const { std::ostringstream os; std::streambuf *coutbuf = std::cout.rdbuf(); std::cout.rdbuf(os.rdbuf()); printWithLocations(locations, g); std::cout.rdbuf(coutbuf); return os.str(); } <|endoftext|>
<commit_before>/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include <stdint.h> #include "tensorflow/lite/c/common.h" #include "tensorflow/lite/kernels/internal/optimized/optimized_ops.h" #include "tensorflow/lite/kernels/internal/reference/reference_ops.h" #include "tensorflow/lite/kernels/internal/tensor.h" #include "tensorflow/lite/kernels/internal/tensor_ctypes.h" #include "tensorflow/lite/kernels/kernel_util.h" namespace tflite { namespace ops { namespace builtin { namespace gather_nd { constexpr int kParams = 0; constexpr int kIndices = 1; constexpr int kOutputTensor = 0; TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) { TF_LITE_ENSURE_EQ(context, NumInputs(node), 2); TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1); const TfLiteTensor* params; TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kParams, &params)); const TfLiteTensor* indices; TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kIndices, &indices)); TfLiteTensor* output; TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, kOutputTensor, &output)); switch (params->type) { case kTfLiteFloat32: case kTfLiteUInt8: case kTfLiteInt8: case kTfLiteInt16: case kTfLiteInt64: case kTfLiteInt32: case kTfLiteString: break; default: context->ReportError( context, "Params of type '%s' are not supported by gather_nd.", TfLiteTypeGetName(params->type)); return kTfLiteError; } switch (indices->type) { case kTfLiteInt64: case kTfLiteInt32: break; default: context->ReportError( context, "Indices of type '%s' are not supported by gather_nd.", TfLiteTypeGetName(indices->type)); return kTfLiteError; } const int params_rank = NumDimensions(params); const int indices_rank = NumDimensions(indices); const int indices_nd = SizeOfDimension(indices, indices_rank - 1); if (params_rank < 1) { context->ReportError(context, "Params must be at least a vector."); return kTfLiteError; } if (indices_rank < 1) { context->ReportError(context, "Indices must be at least a vector."); return kTfLiteError; } if (indices_nd > params_rank) { context->ReportError( context, "Index innermost dimension length must be <= params rank."); return kTfLiteError; } // Assign to output the input type. output->type = params->type; // The result shape is // indices.shape[:-1] + params.shape[indices.shape[-1]:] const int output_rank = indices_rank + params_rank - indices_nd - 1; TfLiteIntArray* output_shape = TfLiteIntArrayCreate(output_rank); int output_index = 0; for (int i = 0; i < indices_rank - 1; ++i) { output_shape->data[output_index++] = indices->dims->data[i]; } for (int i = indices_nd; i < params_rank; ++i) { output_shape->data[output_index++] = params->dims->data[i]; } return context->ResizeTensor(context, output, output_shape); } template <typename ParamsT, typename IndicesT> TfLiteStatus GatherNd(const TfLiteTensor* params, const TfLiteTensor* indices, TfLiteTensor* output) { reference_ops::GatherNd( GetTensorShape(params), GetTensorData<ParamsT>(params), GetTensorShape(indices), GetTensorData<IndicesT>(indices), GetTensorShape(output), GetTensorData<ParamsT>(output)); return kTfLiteOk; } template <typename IndicesT> TfLiteStatus GatherNdString(const TfLiteTensor* params, const TfLiteTensor* indices, TfLiteTensor* output) { reference_ops::GatherNdString( GetTensorShape(params), params, GetTensorShape(indices), GetTensorData<IndicesT>(indices), GetTensorShape(output), output); return kTfLiteOk; } template <typename IndicesT> TfLiteStatus EvalGatherNd(TfLiteContext* context, const TfLiteTensor* params, const TfLiteTensor* indices, TfLiteTensor* output) { switch (params->type) { case kTfLiteFloat32: return GatherNd<float, IndicesT>(params, indices, output); case kTfLiteUInt8: return GatherNd<uint8_t, IndicesT>(params, indices, output); case kTfLiteInt8: return GatherNd<int8_t, IndicesT>(params, indices, output); case kTfLiteInt16: return GatherNd<int16_t, IndicesT>(params, indices, output); case kTfLiteInt32: return GatherNd<int32_t, IndicesT>(params, indices, output); case kTfLiteInt64: return GatherNd<int64_t, IndicesT>(params, indices, output); case kTfLiteString: return GatherNdString<IndicesT>(params, indices, output); default: context->ReportError(context, "Params type '%s' are not supported by gather_nd.", TfLiteTypeGetName(params->type)); return kTfLiteError; } } TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) { const TfLiteTensor* params; TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kParams, &params)); const TfLiteTensor* indices; TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kIndices, &indices)); TfLiteTensor* output; TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, kOutputTensor, &output)); switch (indices->type) { case kTfLiteInt32: return EvalGatherNd<int32_t>(context, params, indices, output); case kTfLiteInt64: return EvalGatherNd<int64_t>(context, params, indices, output); default: context->ReportError( context, "Indices of type '%s' are not supported by gather_nd.", TfLiteTypeGetName(indices->type)); return kTfLiteError; } } } // namespace gather_nd TfLiteRegistration* Register_GATHER_ND() { static TfLiteRegistration r = {/*init*/ nullptr, /*free*/ nullptr, gather_nd::Prepare, gather_nd::Eval}; return &r; } } // namespace builtin } // namespace ops } // namespace tflite <commit_msg>Handle one more division by 0 in TFLite.<commit_after>/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include <stdint.h> #include "tensorflow/lite/c/common.h" #include "tensorflow/lite/kernels/internal/optimized/optimized_ops.h" #include "tensorflow/lite/kernels/internal/reference/reference_ops.h" #include "tensorflow/lite/kernels/internal/tensor.h" #include "tensorflow/lite/kernels/internal/tensor_ctypes.h" #include "tensorflow/lite/kernels/kernel_util.h" namespace tflite { namespace ops { namespace builtin { namespace gather_nd { constexpr int kParams = 0; constexpr int kIndices = 1; constexpr int kOutputTensor = 0; TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) { TF_LITE_ENSURE_EQ(context, NumInputs(node), 2); TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1); const TfLiteTensor* params; TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kParams, &params)); const TfLiteTensor* indices; TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kIndices, &indices)); TfLiteTensor* output; TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, kOutputTensor, &output)); switch (params->type) { case kTfLiteFloat32: case kTfLiteUInt8: case kTfLiteInt8: case kTfLiteInt16: case kTfLiteInt64: case kTfLiteInt32: case kTfLiteString: break; default: context->ReportError( context, "Params of type '%s' are not supported by gather_nd.", TfLiteTypeGetName(params->type)); return kTfLiteError; } switch (indices->type) { case kTfLiteInt64: case kTfLiteInt32: break; default: context->ReportError( context, "Indices of type '%s' are not supported by gather_nd.", TfLiteTypeGetName(indices->type)); return kTfLiteError; } const int params_rank = NumDimensions(params); const int indices_rank = NumDimensions(indices); const int indices_nd = SizeOfDimension(indices, indices_rank - 1); if (params_rank < 1) { context->ReportError(context, "Params must be at least a vector."); return kTfLiteError; } if (indices_rank < 1) { context->ReportError(context, "Indices must be at least a vector."); return kTfLiteError; } if (indices_nd > params_rank) { context->ReportError( context, "Index innermost dimension length must be <= params rank."); return kTfLiteError; } // Assign to output the input type. output->type = params->type; // The result shape is // indices.shape[:-1] + params.shape[indices.shape[-1]:] const int output_rank = indices_rank + params_rank - indices_nd - 1; TfLiteIntArray* output_shape = TfLiteIntArrayCreate(output_rank); int output_index = 0; for (int i = 0; i < indices_rank - 1; ++i) { output_shape->data[output_index++] = indices->dims->data[i]; } for (int i = indices_nd; i < params_rank; ++i) { output_shape->data[output_index++] = params->dims->data[i]; } return context->ResizeTensor(context, output, output_shape); } template <typename ParamsT, typename IndicesT> TfLiteStatus GatherNd(const TfLiteTensor* params, const TfLiteTensor* indices, TfLiteTensor* output) { reference_ops::GatherNd( GetTensorShape(params), GetTensorData<ParamsT>(params), GetTensorShape(indices), GetTensorData<IndicesT>(indices), GetTensorShape(output), GetTensorData<ParamsT>(output)); return kTfLiteOk; } template <typename IndicesT> TfLiteStatus GatherNdString(const TfLiteTensor* params, const TfLiteTensor* indices, TfLiteTensor* output) { reference_ops::GatherNdString( GetTensorShape(params), params, GetTensorShape(indices), GetTensorData<IndicesT>(indices), GetTensorShape(output), output); return kTfLiteOk; } template <typename IndicesT> TfLiteStatus EvalGatherNd(TfLiteContext* context, const TfLiteTensor* params, const TfLiteTensor* indices, TfLiteTensor* output) { switch (params->type) { case kTfLiteFloat32: return GatherNd<float, IndicesT>(params, indices, output); case kTfLiteUInt8: return GatherNd<uint8_t, IndicesT>(params, indices, output); case kTfLiteInt8: return GatherNd<int8_t, IndicesT>(params, indices, output); case kTfLiteInt16: return GatherNd<int16_t, IndicesT>(params, indices, output); case kTfLiteInt32: return GatherNd<int32_t, IndicesT>(params, indices, output); case kTfLiteInt64: return GatherNd<int64_t, IndicesT>(params, indices, output); case kTfLiteString: return GatherNdString<IndicesT>(params, indices, output); default: context->ReportError(context, "Params type '%s' are not supported by gather_nd.", TfLiteTypeGetName(params->type)); return kTfLiteError; } } TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) { const TfLiteTensor* params; TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kParams, &params)); const TfLiteTensor* indices; TF_LITE_ENSURE_OK(context, GetInputSafe(context, node, kIndices, &indices)); TfLiteTensor* output; TF_LITE_ENSURE_OK(context, GetOutputSafe(context, node, kOutputTensor, &output)); // Prevent division by 0 in the helper TF_LITE_ENSURE(context, NumElements(params) > 0); switch (indices->type) { case kTfLiteInt32: return EvalGatherNd<int32_t>(context, params, indices, output); case kTfLiteInt64: return EvalGatherNd<int64_t>(context, params, indices, output); default: context->ReportError( context, "Indices of type '%s' are not supported by gather_nd.", TfLiteTypeGetName(indices->type)); return kTfLiteError; } } } // namespace gather_nd TfLiteRegistration* Register_GATHER_ND() { static TfLiteRegistration r = {/*init*/ nullptr, /*free*/ nullptr, gather_nd::Prepare, gather_nd::Eval}; return &r; } } // namespace builtin } // namespace ops } // namespace tflite <|endoftext|>
<commit_before>#include <EXTERN.h> // from the Perl distribution #include <perl.h> // from the Perl distribution #ifdef WIN32 // Perl win32 specific includes, found in perl\\lib\\CORE\\win32.h // Defines the windows specific convenience RunPerl() function, // which is not available on other operating systems. #include <win32.h> #include <wchar.h> #endif #include <cstdio> #include <cstdlib> #ifdef WIN32 int main(int argc, char **argv, char **env) { SetCurrentDirectory("libexec"); // If the Slic3r is installed in a localized directory (containing non-iso // characters), spaces or semicolons, use short file names. char exe_path[MAX_PATH] = {0}; char script_path[MAX_PATH]; char gui_flag[6] = {"--gui"}; #ifdef FORCE_GUI char** command_line = (char**)malloc(sizeof(char*) * ((++ argc) + 2)); #else char** command_line = (char**)malloc(sizeof(char*) * ((++ argc) + 1)); #endif { // Unicode path. This will not be used directly, but to test, whether // there are any non-ISO characters, in which case the path is converted to a // short path (using 8.3 directory names). wchar_t exe_path_w[MAX_PATH] = {0}; char drive[_MAX_DRIVE]; char dir[_MAX_DIR]; char fname[_MAX_FNAME]; char ext[_MAX_EXT]; bool needs_short_paths = false; int len; int i; GetModuleFileNameA(NULL, exe_path, MAX_PATH-1); GetModuleFileNameW(NULL, exe_path_w, MAX_PATH-1); len = strlen(exe_path); if (len != wcslen(exe_path_w)) { needs_short_paths = true; } else { for (i = 0; i < len; ++ i) if ((wchar_t)exe_path[i] != exe_path_w[i] || exe_path[i] == ' ' || exe_path[i] == ';') { needs_short_paths = true; break; } } if (needs_short_paths) { wchar_t exe_path_short[MAX_PATH] = {0}; GetShortPathNameW(exe_path_w, exe_path_short, MAX_PATH); len = wcslen(exe_path_short); for (i = 0; i <= len; ++ i) exe_path[i] = (char)exe_path_short[i]; } _splitpath(exe_path, drive, dir, fname, ext); _makepath(script_path, drive, dir, NULL, NULL); if (needs_short_paths) printf("Slic3r installed in a loclized path. Using an 8.3 path: \"%s\"\n", script_path); SetDllDirectoryA(script_path); _makepath(script_path, drive, dir, "slic3r", "pl"); command_line[0] = exe_path; command_line[1] = script_path; memcpy(command_line + 2, argv + 1, sizeof(char*) * (argc - 2)); #ifdef FORCE_GUI command_line[argc] = gui_flag; command_line[argc+1] = NULL; #else command_line[argc] = NULL; #endif // Unset the PERL5LIB and PERLLIB environment variables. SetEnvironmentVariable("PERL5LIB", NULL); SetEnvironmentVariable("PERLLIB", NULL); #if 0 printf("Arguments: \r\n"); for (size_t i = 0; i < argc + 1; ++ i) printf(" %d: %s\r\n", i, command_line[i]); #endif } #ifdef FORCE_GUI RunPerl(argc+1, command_line, NULL); #else RunPerl(argc, command_line, NULL); #endif free(command_line); } #else int main(int argc, char **argv, char **env) { PerlInterpreter *my_perl = perl_alloc(); if (my_perl == NULL) { fprintf(stderr, "Cannot start perl interpreter. Exiting.\n"); return -1; } perl_construct(my_perl); #ifdef FORCE_GUI char* command_line[] = { "slic3r", "slic3r.pl", "--gui" }; #else char* command_line[] = { "slic3r", "slic3r.pl" }; #endif perl_parse(my_perl, NULL, 3, command_line, (char **)NULL); perl_run(my_perl); perl_destruct(my_perl); perl_free(my_perl); } #endif <commit_msg>Append libexec to the slic3r.pl path<commit_after>#include <EXTERN.h> // from the Perl distribution #include <perl.h> // from the Perl distribution #ifdef WIN32 // Perl win32 specific includes, found in perl\\lib\\CORE\\win32.h // Defines the windows specific convenience RunPerl() function, // which is not available on other operating systems. #include <win32.h> #include <wchar.h> #endif #include <cstdio> #include <cstdlib> #ifdef WIN32 int main(int argc, char **argv, char **env) { SetCurrentDirectory("libexec"); // If the Slic3r is installed in a localized directory (containing non-iso // characters), spaces or semicolons, use short file names. char exe_path[MAX_PATH] = {0}; char script_path[MAX_PATH]; char gui_flag[6] = {"--gui"}; #ifdef FORCE_GUI char** command_line = (char**)malloc(sizeof(char*) * ((++ argc) + 2)); #else char** command_line = (char**)malloc(sizeof(char*) * ((++ argc) + 1)); #endif { // Unicode path. This will not be used directly, but to test, whether // there are any non-ISO characters, in which case the path is converted to a // short path (using 8.3 directory names). wchar_t exe_path_w[MAX_PATH] = {0}; char drive[_MAX_DRIVE]; char dir[_MAX_DIR]; char fname[_MAX_FNAME]; char ext[_MAX_EXT]; bool needs_short_paths = false; int len; int i; GetModuleFileNameA(NULL, exe_path, MAX_PATH-1); GetModuleFileNameW(NULL, exe_path_w, MAX_PATH-1); len = strlen(exe_path); if (len != wcslen(exe_path_w)) { needs_short_paths = true; } else { for (i = 0; i < len; ++ i) if ((wchar_t)exe_path[i] != exe_path_w[i] || exe_path[i] == ' ' || exe_path[i] == ';') { needs_short_paths = true; break; } } if (needs_short_paths) { wchar_t exe_path_short[MAX_PATH] = {0}; GetShortPathNameW(exe_path_w, exe_path_short, MAX_PATH); len = wcslen(exe_path_short); for (i = 0; i <= len; ++ i) exe_path[i] = (char)exe_path_short[i]; } _splitpath(exe_path, drive, dir, fname, ext); _makepath(script_path, drive, dir, NULL, NULL); if (needs_short_paths) printf("Slic3r installed in a loclized path. Using an 8.3 path: \"%s\"\n", script_path); SetDllDirectoryA(script_path); strcat(dir, "libexec\\"); _makepath(script_path, drive, dir, "slic3r", "pl"); command_line[0] = exe_path; command_line[1] = script_path; memcpy(command_line + 2, argv + 1, sizeof(char*) * (argc - 2)); #ifdef FORCE_GUI command_line[argc] = gui_flag; command_line[argc+1] = NULL; #else command_line[argc] = NULL; #endif // Unset the PERL5LIB and PERLLIB environment variables. SetEnvironmentVariable("PERL5LIB", NULL); SetEnvironmentVariable("PERLLIB", NULL); #if 0 printf("Arguments: \r\n"); for (size_t i = 0; i < argc + 1; ++ i) printf(" %d: %s\r\n", i, command_line[i]); #endif } #ifdef FORCE_GUI RunPerl(argc+1, command_line, NULL); #else RunPerl(argc, command_line, NULL); #endif free(command_line); } #else int main(int argc, char **argv, char **env) { PerlInterpreter *my_perl = perl_alloc(); if (my_perl == NULL) { fprintf(stderr, "Cannot start perl interpreter. Exiting.\n"); return -1; } perl_construct(my_perl); #ifdef FORCE_GUI char* command_line[] = { "slic3r", "slic3r.pl", "--gui" }; #else char* command_line[] = { "slic3r", "slic3r.pl" }; #endif perl_parse(my_perl, NULL, 3, command_line, (char **)NULL); perl_run(my_perl); perl_destruct(my_perl); perl_free(my_perl); } #endif <|endoftext|>
<commit_before>/* * Copyright (C) 2018 The Android Open Source Project * * 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 "VulkanHandles.h" #include "VulkanConstants.h" #include "VulkanPlatform.h" #include <utils/Panic.h> using namespace bluevk; namespace filament { namespace backend { static void flipVertically(VkRect2D* rect, uint32_t framebufferHeight) { rect->offset.y = framebufferHeight - rect->offset.y - rect->extent.height; } static void flipVertically(VkViewport* rect, uint32_t framebufferHeight) { rect->y = framebufferHeight - rect->y - rect->height; } static void clampToFramebuffer(VkRect2D* rect, uint32_t fbWidth, uint32_t fbHeight) { int32_t x = std::max(rect->offset.x, 0); int32_t y = std::max(rect->offset.y, 0); int32_t right = std::min(rect->offset.x + (int32_t) rect->extent.width, (int32_t) fbWidth); int32_t top = std::min(rect->offset.y + (int32_t) rect->extent.height, (int32_t) fbHeight); rect->offset.x = std::min(x, (int32_t) fbWidth); rect->offset.y = std::min(y, (int32_t) fbHeight); rect->extent.width = std::max(right - x, 0); rect->extent.height = std::max(top - y, 0); } VulkanProgram::VulkanProgram(VulkanContext& context, const Program& builder) noexcept : HwProgram(builder.getName()), context(context) { auto const& blobs = builder.getShadersSource(); VkShaderModule* modules[2] = { &bundle.vertex, &bundle.fragment }; bool missing = false; for (size_t i = 0; i < Program::SHADER_TYPE_COUNT; i++) { const auto& blob = blobs[i]; VkShaderModule* module = modules[i]; if (blob.empty()) { missing = true; continue; } VkShaderModuleCreateInfo moduleInfo = {}; moduleInfo.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO; moduleInfo.codeSize = blob.size(); moduleInfo.pCode = (uint32_t*) blob.data(); VkResult result = vkCreateShaderModule(context.device, &moduleInfo, VKALLOC, module); ASSERT_POSTCONDITION(result == VK_SUCCESS, "Unable to create shader module."); } // Output a warning because it's okay to encounter empty blobs, but it's not okay to use // this program handle in a draw call. if (missing) { utils::slog.w << "Missing SPIR-V shader: " << builder.getName().c_str() << utils::io::endl; return; } // Make a copy of the binding map samplerGroupInfo = builder.getSamplerGroupInfo(); #if FILAMENT_VULKAN_VERBOSE utils::slog.d << "Created VulkanProgram " << builder.getName().c_str() << ", variant = (" << utils::io::hex << (int) builder.getVariant() << utils::io::dec << "), " << "shaders = (" << bundle.vertex << ", " << bundle.fragment << ")" << utils::io::endl; #endif } VulkanProgram::~VulkanProgram() { vkDestroyShaderModule(context.device, bundle.vertex, VKALLOC); vkDestroyShaderModule(context.device, bundle.fragment, VKALLOC); } static VulkanAttachment createAttachment(VulkanContext& context, VulkanAttachment spec) { if (spec.texture == nullptr) { return spec; } return { .format = spec.texture->getVkFormat(), .image = spec.texture->getVkImage(), .view = {}, .memory = {}, .texture = spec.texture, .layout = context.getTextureLayout(spec.texture->usage), .level = spec.level, .layer = spec.layer }; } // Creates a special "default" render target (i.e. associated with the swap chain) // Note that the attachment structs are unused in this case in favor of VulkanSwapChain. VulkanRenderTarget::VulkanRenderTarget(VulkanContext& context) : HwRenderTarget(0, 0), mContext(context), mOffscreen(false), mSamples(1) {} VulkanRenderTarget::VulkanRenderTarget(VulkanContext& context, uint32_t width, uint32_t height, uint8_t samples, VulkanAttachment color[MRT::MAX_SUPPORTED_RENDER_TARGET_COUNT], VulkanAttachment depthStencil[2], VulkanStagePool& stagePool) : HwRenderTarget(width, height), mContext(context), mOffscreen(true), mSamples(samples) { // For each color attachment, create (or fetch from cache) a VkImageView that selects a specific // miplevel and array layer. for (int index = 0; index < MRT::MAX_SUPPORTED_RENDER_TARGET_COUNT; index++) { const VulkanAttachment& spec = color[index]; mColor[index] = createAttachment(context, spec); VulkanTexture* texture = spec.texture; if (texture == nullptr) { continue; } mColor[index].view = texture->getImageView(spec.level, spec.layer, VK_IMAGE_ASPECT_COLOR_BIT); } // For the depth attachment, create (or fetch from cache) a VkImageView that selects a specific // miplevel and array layer. const VulkanAttachment& depthSpec = depthStencil[0]; mDepth = createAttachment(context, depthSpec); VulkanTexture* depthTexture = mDepth.texture; if (depthTexture) { mDepth.view = depthTexture->getImageView(mDepth.level, mDepth.layer, VK_IMAGE_ASPECT_DEPTH_BIT); } if (samples == 1) { return; } // The sidecar textures need to have only 1 miplevel and 1 array slice. const int level = 1; const int depth = 1; // Create sidecar MSAA textures for color attachments. for (int index = 0; index < MRT::MAX_SUPPORTED_RENDER_TARGET_COUNT; index++) { const VulkanAttachment& spec = color[index]; VulkanTexture* texture = spec.texture; if (texture && texture->samples == 1) { VulkanTexture* msTexture = new VulkanTexture(context, texture->target, level, texture->format, samples, width, height, depth, texture->usage, stagePool); mMsaaAttachments[index] = createAttachment(context, { .texture = msTexture }); mMsaaAttachments[index].view = msTexture->getImageView(0, 0, VK_IMAGE_ASPECT_COLOR_BIT); } if (texture && texture->samples > 1) { mMsaaAttachments[index] = mColor[index]; } } if (depthTexture == nullptr) { return; } // There is no need for sidecar depth if the depth texture is already MSAA. if (depthTexture->samples > 1) { mMsaaDepthAttachment = mDepth; return; } // Create sidecar MSAA texture for the depth attachment. VulkanTexture* msTexture = new VulkanTexture(context, depthTexture->target, level, depthTexture->format, samples, width, height, depth, depthTexture->usage, stagePool); mMsaaDepthAttachment = createAttachment(context, { .format = {}, .image = {}, .view = {}, .memory = {}, .texture = msTexture, .layout = {}, .level = depthSpec.level, .layer = depthSpec.layer, }); mMsaaDepthAttachment.view = msTexture->getImageView(depthSpec.level, depthSpec.layer, VK_IMAGE_ASPECT_DEPTH_BIT); } VulkanRenderTarget::~VulkanRenderTarget() { for (int index = 0; index < MRT::MAX_SUPPORTED_RENDER_TARGET_COUNT; index++) { if (mMsaaAttachments[index].texture != mColor[index].texture) { delete mMsaaAttachments[index].texture; } } if (mMsaaDepthAttachment.texture != mDepth.texture) { delete mMsaaDepthAttachment.texture; } } void VulkanRenderTarget::transformClientRectToPlatform(VkRect2D* bounds) const { const auto& extent = getExtent(); flipVertically(bounds, extent.height); clampToFramebuffer(bounds, extent.width, extent.height); } void VulkanRenderTarget::transformClientRectToPlatform(VkViewport* bounds) const { flipVertically(bounds, getExtent().height); } VkExtent2D VulkanRenderTarget::getExtent() const { if (mOffscreen) { return {width, height}; } return mContext.currentSurface->clientSize; } VulkanAttachment VulkanRenderTarget::getColor(int target) const { return (mOffscreen || target > 0) ? mColor[target] : mContext.currentSurface->getColor(); } VulkanAttachment VulkanRenderTarget::getMsaaColor(int target) const { return mMsaaAttachments[target]; } VulkanAttachment VulkanRenderTarget::getDepth() const { return mOffscreen ? mDepth : mContext.currentSurface->depth; } VulkanAttachment VulkanRenderTarget::getMsaaDepth() const { return mMsaaDepthAttachment; } int VulkanRenderTarget::getColorTargetCount(const VulkanRenderPass& pass) const { if (!mOffscreen) { return 1; } int count = 0; for (int i = 0; i < MRT::MAX_SUPPORTED_RENDER_TARGET_COUNT; i++) { if (mColor[i].format == VK_FORMAT_UNDEFINED) { continue; } // NOTE: This must be consistent with VkRenderPass construction (see VulkanFboCache). if (!(pass.subpassMask & (1 << i)) || pass.currentSubpass == 1) { count++; } } return count; } VulkanVertexBuffer::VulkanVertexBuffer(VulkanContext& context, VulkanStagePool& stagePool, uint8_t bufferCount, uint8_t attributeCount, uint32_t elementCount, AttributeArray const& attribs) : HwVertexBuffer(bufferCount, attributeCount, elementCount, attribs), buffers(bufferCount) {} VulkanUniformBuffer::VulkanUniformBuffer(VulkanContext& context, VulkanStagePool& stagePool, uint32_t numBytes, backend::BufferUsage usage) : mContext(context), mStagePool(stagePool) { // Create the VkBuffer. VkBufferCreateInfo bufferInfo { .sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, .size = numBytes, .usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT, }; VmaAllocationCreateInfo allocInfo { .usage = VMA_MEMORY_USAGE_GPU_ONLY }; vmaCreateBuffer(mContext.allocator, &bufferInfo, &allocInfo, &mGpuBuffer, &mGpuMemory, nullptr); } void VulkanUniformBuffer::loadFromCpu(const void* cpuData, uint32_t numBytes) { VulkanStage const* stage = mStagePool.acquireStage(numBytes); void* mapped; vmaMapMemory(mContext.allocator, stage->memory, &mapped); memcpy(mapped, cpuData, numBytes); vmaUnmapMemory(mContext.allocator, stage->memory); vmaFlushAllocation(mContext.allocator, stage->memory, 0, numBytes); const VkCommandBuffer cmdbuffer = mContext.commands->get().cmdbuffer; VkBufferCopy region { .size = numBytes }; vkCmdCopyBuffer(cmdbuffer, stage->buffer, mGpuBuffer, 1, &region); // First, ensure that the copy finishes before the next draw call. // Second, in case the user decides to upload another chunk (without ever using the first one) // we need to ensure that this upload completes first. // NOTE: ideally dstStageMask would include VERTEX_SHADER_BIT | FRAGMENT_SHADER_BIT, but this // seems to be insufficient on Mali devices. To work around this we are using a more // aggressive ALL_GRAPHICS_BIT barrier. VkBufferMemoryBarrier barrier { .sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER, .srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT, .dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_UNIFORM_READ_BIT, .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, .buffer = mGpuBuffer, .size = VK_WHOLE_SIZE }; vkCmdPipelineBarrier(cmdbuffer, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT | VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT, 0, 0, nullptr, 1, &barrier, 0, nullptr); } VulkanUniformBuffer::~VulkanUniformBuffer() { vmaDestroyBuffer(mContext.allocator, mGpuBuffer, mGpuMemory); } void VulkanRenderPrimitive::setPrimitiveType(backend::PrimitiveType pt) { this->type = pt; switch (pt) { case backend::PrimitiveType::NONE: case backend::PrimitiveType::POINTS: primitiveTopology = VK_PRIMITIVE_TOPOLOGY_POINT_LIST; break; case backend::PrimitiveType::LINES: primitiveTopology = VK_PRIMITIVE_TOPOLOGY_LINE_LIST; break; case backend::PrimitiveType::TRIANGLES: primitiveTopology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; break; } } void VulkanRenderPrimitive::setBuffers(VulkanVertexBuffer* vertexBuffer, VulkanIndexBuffer* indexBuffer) { this->vertexBuffer = vertexBuffer; this->indexBuffer = indexBuffer; } VulkanTimerQuery::VulkanTimerQuery(VulkanContext& context) : mContext(context) { std::unique_lock<utils::Mutex> lock(context.timestamps.mutex); utils::bitset32& bitset = context.timestamps.used; const size_t maxTimers = bitset.size(); assert_invariant(bitset.count() < maxTimers); for (size_t timerIndex = 0; timerIndex < maxTimers; ++timerIndex) { if (!bitset.test(timerIndex)) { bitset.set(timerIndex); startingQueryIndex = timerIndex * 2; stoppingQueryIndex = timerIndex * 2 + 1; return; } } utils::slog.e << "More than " << maxTimers << " timers are not supported." << utils::io::endl; startingQueryIndex = 0; stoppingQueryIndex = 1; } VulkanTimerQuery::~VulkanTimerQuery() { std::unique_lock<utils::Mutex> lock(mContext.timestamps.mutex); mContext.timestamps.used.unset(startingQueryIndex / 2); } } // namespace filament } // namespace backend <commit_msg>Vulkan: Fix uninitialized vector contents.<commit_after>/* * Copyright (C) 2018 The Android Open Source Project * * 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 "VulkanHandles.h" #include "VulkanConstants.h" #include "VulkanPlatform.h" #include <utils/Panic.h> using namespace bluevk; namespace filament { namespace backend { static void flipVertically(VkRect2D* rect, uint32_t framebufferHeight) { rect->offset.y = framebufferHeight - rect->offset.y - rect->extent.height; } static void flipVertically(VkViewport* rect, uint32_t framebufferHeight) { rect->y = framebufferHeight - rect->y - rect->height; } static void clampToFramebuffer(VkRect2D* rect, uint32_t fbWidth, uint32_t fbHeight) { int32_t x = std::max(rect->offset.x, 0); int32_t y = std::max(rect->offset.y, 0); int32_t right = std::min(rect->offset.x + (int32_t) rect->extent.width, (int32_t) fbWidth); int32_t top = std::min(rect->offset.y + (int32_t) rect->extent.height, (int32_t) fbHeight); rect->offset.x = std::min(x, (int32_t) fbWidth); rect->offset.y = std::min(y, (int32_t) fbHeight); rect->extent.width = std::max(right - x, 0); rect->extent.height = std::max(top - y, 0); } VulkanProgram::VulkanProgram(VulkanContext& context, const Program& builder) noexcept : HwProgram(builder.getName()), context(context) { auto const& blobs = builder.getShadersSource(); VkShaderModule* modules[2] = { &bundle.vertex, &bundle.fragment }; bool missing = false; for (size_t i = 0; i < Program::SHADER_TYPE_COUNT; i++) { const auto& blob = blobs[i]; VkShaderModule* module = modules[i]; if (blob.empty()) { missing = true; continue; } VkShaderModuleCreateInfo moduleInfo = {}; moduleInfo.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO; moduleInfo.codeSize = blob.size(); moduleInfo.pCode = (uint32_t*) blob.data(); VkResult result = vkCreateShaderModule(context.device, &moduleInfo, VKALLOC, module); ASSERT_POSTCONDITION(result == VK_SUCCESS, "Unable to create shader module."); } // Output a warning because it's okay to encounter empty blobs, but it's not okay to use // this program handle in a draw call. if (missing) { utils::slog.w << "Missing SPIR-V shader: " << builder.getName().c_str() << utils::io::endl; return; } // Make a copy of the binding map samplerGroupInfo = builder.getSamplerGroupInfo(); #if FILAMENT_VULKAN_VERBOSE utils::slog.d << "Created VulkanProgram " << builder.getName().c_str() << ", variant = (" << utils::io::hex << (int) builder.getVariant() << utils::io::dec << "), " << "shaders = (" << bundle.vertex << ", " << bundle.fragment << ")" << utils::io::endl; #endif } VulkanProgram::~VulkanProgram() { vkDestroyShaderModule(context.device, bundle.vertex, VKALLOC); vkDestroyShaderModule(context.device, bundle.fragment, VKALLOC); } static VulkanAttachment createAttachment(VulkanContext& context, VulkanAttachment spec) { if (spec.texture == nullptr) { return spec; } return { .format = spec.texture->getVkFormat(), .image = spec.texture->getVkImage(), .view = {}, .memory = {}, .texture = spec.texture, .layout = context.getTextureLayout(spec.texture->usage), .level = spec.level, .layer = spec.layer }; } // Creates a special "default" render target (i.e. associated with the swap chain) // Note that the attachment structs are unused in this case in favor of VulkanSwapChain. VulkanRenderTarget::VulkanRenderTarget(VulkanContext& context) : HwRenderTarget(0, 0), mContext(context), mOffscreen(false), mSamples(1) {} VulkanRenderTarget::VulkanRenderTarget(VulkanContext& context, uint32_t width, uint32_t height, uint8_t samples, VulkanAttachment color[MRT::MAX_SUPPORTED_RENDER_TARGET_COUNT], VulkanAttachment depthStencil[2], VulkanStagePool& stagePool) : HwRenderTarget(width, height), mContext(context), mOffscreen(true), mSamples(samples) { // For each color attachment, create (or fetch from cache) a VkImageView that selects a specific // miplevel and array layer. for (int index = 0; index < MRT::MAX_SUPPORTED_RENDER_TARGET_COUNT; index++) { const VulkanAttachment& spec = color[index]; mColor[index] = createAttachment(context, spec); VulkanTexture* texture = spec.texture; if (texture == nullptr) { continue; } mColor[index].view = texture->getImageView(spec.level, spec.layer, VK_IMAGE_ASPECT_COLOR_BIT); } // For the depth attachment, create (or fetch from cache) a VkImageView that selects a specific // miplevel and array layer. const VulkanAttachment& depthSpec = depthStencil[0]; mDepth = createAttachment(context, depthSpec); VulkanTexture* depthTexture = mDepth.texture; if (depthTexture) { mDepth.view = depthTexture->getImageView(mDepth.level, mDepth.layer, VK_IMAGE_ASPECT_DEPTH_BIT); } if (samples == 1) { return; } // The sidecar textures need to have only 1 miplevel and 1 array slice. const int level = 1; const int depth = 1; // Create sidecar MSAA textures for color attachments. for (int index = 0; index < MRT::MAX_SUPPORTED_RENDER_TARGET_COUNT; index++) { const VulkanAttachment& spec = color[index]; VulkanTexture* texture = spec.texture; if (texture && texture->samples == 1) { VulkanTexture* msTexture = new VulkanTexture(context, texture->target, level, texture->format, samples, width, height, depth, texture->usage, stagePool); mMsaaAttachments[index] = createAttachment(context, { .texture = msTexture }); mMsaaAttachments[index].view = msTexture->getImageView(0, 0, VK_IMAGE_ASPECT_COLOR_BIT); } if (texture && texture->samples > 1) { mMsaaAttachments[index] = mColor[index]; } } if (depthTexture == nullptr) { return; } // There is no need for sidecar depth if the depth texture is already MSAA. if (depthTexture->samples > 1) { mMsaaDepthAttachment = mDepth; return; } // Create sidecar MSAA texture for the depth attachment. VulkanTexture* msTexture = new VulkanTexture(context, depthTexture->target, level, depthTexture->format, samples, width, height, depth, depthTexture->usage, stagePool); mMsaaDepthAttachment = createAttachment(context, { .format = {}, .image = {}, .view = {}, .memory = {}, .texture = msTexture, .layout = {}, .level = depthSpec.level, .layer = depthSpec.layer, }); mMsaaDepthAttachment.view = msTexture->getImageView(depthSpec.level, depthSpec.layer, VK_IMAGE_ASPECT_DEPTH_BIT); } VulkanRenderTarget::~VulkanRenderTarget() { for (int index = 0; index < MRT::MAX_SUPPORTED_RENDER_TARGET_COUNT; index++) { if (mMsaaAttachments[index].texture != mColor[index].texture) { delete mMsaaAttachments[index].texture; } } if (mMsaaDepthAttachment.texture != mDepth.texture) { delete mMsaaDepthAttachment.texture; } } void VulkanRenderTarget::transformClientRectToPlatform(VkRect2D* bounds) const { const auto& extent = getExtent(); flipVertically(bounds, extent.height); clampToFramebuffer(bounds, extent.width, extent.height); } void VulkanRenderTarget::transformClientRectToPlatform(VkViewport* bounds) const { flipVertically(bounds, getExtent().height); } VkExtent2D VulkanRenderTarget::getExtent() const { if (mOffscreen) { return {width, height}; } return mContext.currentSurface->clientSize; } VulkanAttachment VulkanRenderTarget::getColor(int target) const { return (mOffscreen || target > 0) ? mColor[target] : mContext.currentSurface->getColor(); } VulkanAttachment VulkanRenderTarget::getMsaaColor(int target) const { return mMsaaAttachments[target]; } VulkanAttachment VulkanRenderTarget::getDepth() const { return mOffscreen ? mDepth : mContext.currentSurface->depth; } VulkanAttachment VulkanRenderTarget::getMsaaDepth() const { return mMsaaDepthAttachment; } int VulkanRenderTarget::getColorTargetCount(const VulkanRenderPass& pass) const { if (!mOffscreen) { return 1; } int count = 0; for (int i = 0; i < MRT::MAX_SUPPORTED_RENDER_TARGET_COUNT; i++) { if (mColor[i].format == VK_FORMAT_UNDEFINED) { continue; } // NOTE: This must be consistent with VkRenderPass construction (see VulkanFboCache). if (!(pass.subpassMask & (1 << i)) || pass.currentSubpass == 1) { count++; } } return count; } VulkanVertexBuffer::VulkanVertexBuffer(VulkanContext& context, VulkanStagePool& stagePool, uint8_t bufferCount, uint8_t attributeCount, uint32_t elementCount, AttributeArray const& attribs) : HwVertexBuffer(bufferCount, attributeCount, elementCount, attribs), buffers(bufferCount, nullptr) {} VulkanUniformBuffer::VulkanUniformBuffer(VulkanContext& context, VulkanStagePool& stagePool, uint32_t numBytes, backend::BufferUsage usage) : mContext(context), mStagePool(stagePool) { // Create the VkBuffer. VkBufferCreateInfo bufferInfo { .sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, .size = numBytes, .usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT, }; VmaAllocationCreateInfo allocInfo { .usage = VMA_MEMORY_USAGE_GPU_ONLY }; vmaCreateBuffer(mContext.allocator, &bufferInfo, &allocInfo, &mGpuBuffer, &mGpuMemory, nullptr); } void VulkanUniformBuffer::loadFromCpu(const void* cpuData, uint32_t numBytes) { VulkanStage const* stage = mStagePool.acquireStage(numBytes); void* mapped; vmaMapMemory(mContext.allocator, stage->memory, &mapped); memcpy(mapped, cpuData, numBytes); vmaUnmapMemory(mContext.allocator, stage->memory); vmaFlushAllocation(mContext.allocator, stage->memory, 0, numBytes); const VkCommandBuffer cmdbuffer = mContext.commands->get().cmdbuffer; VkBufferCopy region { .size = numBytes }; vkCmdCopyBuffer(cmdbuffer, stage->buffer, mGpuBuffer, 1, &region); // First, ensure that the copy finishes before the next draw call. // Second, in case the user decides to upload another chunk (without ever using the first one) // we need to ensure that this upload completes first. // NOTE: ideally dstStageMask would include VERTEX_SHADER_BIT | FRAGMENT_SHADER_BIT, but this // seems to be insufficient on Mali devices. To work around this we are using a more // aggressive ALL_GRAPHICS_BIT barrier. VkBufferMemoryBarrier barrier { .sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER, .srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT, .dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_UNIFORM_READ_BIT, .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, .buffer = mGpuBuffer, .size = VK_WHOLE_SIZE }; vkCmdPipelineBarrier(cmdbuffer, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT | VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT, 0, 0, nullptr, 1, &barrier, 0, nullptr); } VulkanUniformBuffer::~VulkanUniformBuffer() { vmaDestroyBuffer(mContext.allocator, mGpuBuffer, mGpuMemory); } void VulkanRenderPrimitive::setPrimitiveType(backend::PrimitiveType pt) { this->type = pt; switch (pt) { case backend::PrimitiveType::NONE: case backend::PrimitiveType::POINTS: primitiveTopology = VK_PRIMITIVE_TOPOLOGY_POINT_LIST; break; case backend::PrimitiveType::LINES: primitiveTopology = VK_PRIMITIVE_TOPOLOGY_LINE_LIST; break; case backend::PrimitiveType::TRIANGLES: primitiveTopology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; break; } } void VulkanRenderPrimitive::setBuffers(VulkanVertexBuffer* vertexBuffer, VulkanIndexBuffer* indexBuffer) { this->vertexBuffer = vertexBuffer; this->indexBuffer = indexBuffer; } VulkanTimerQuery::VulkanTimerQuery(VulkanContext& context) : mContext(context) { std::unique_lock<utils::Mutex> lock(context.timestamps.mutex); utils::bitset32& bitset = context.timestamps.used; const size_t maxTimers = bitset.size(); assert_invariant(bitset.count() < maxTimers); for (size_t timerIndex = 0; timerIndex < maxTimers; ++timerIndex) { if (!bitset.test(timerIndex)) { bitset.set(timerIndex); startingQueryIndex = timerIndex * 2; stoppingQueryIndex = timerIndex * 2 + 1; return; } } utils::slog.e << "More than " << maxTimers << " timers are not supported." << utils::io::endl; startingQueryIndex = 0; stoppingQueryIndex = 1; } VulkanTimerQuery::~VulkanTimerQuery() { std::unique_lock<utils::Mutex> lock(mContext.timestamps.mutex); mContext.timestamps.used.unset(startingQueryIndex / 2); } } // namespace filament } // namespace backend <|endoftext|>
<commit_before>// Copyright 2014 The Crashpad Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "util/synchronization/semaphore.h" #include <errno.h> #include <time.h> #include <cmath> #include "base/logging.h" #include "base/posix/eintr_wrapper.h" namespace crashpad { #if !defined(OS_MACOSX) namespace { void AddTimespec(const timespec& ts1, const timespec& ts2, timespec* result) { result->tv_sec = ts1.tv_sec + ts2.tv_sec; result->tv_nsec = ts1.tv_nsec + ts2.tv_nsec; if (result->tv_nsec > static_cast<long>(1E9)) { ++result->tv_sec; result->tv_nsec -= static_cast<long>(1E9); } } } // namespace Semaphore::Semaphore(int value) { PCHECK(sem_init(&semaphore_, 0, value) == 0) << "sem_init"; } Semaphore::~Semaphore() { PCHECK(sem_destroy(&semaphore_) == 0) << "sem_destroy"; } void Semaphore::Wait() { PCHECK(HANDLE_EINTR(sem_wait(&semaphore_)) == 0) << "sem_wait"; } bool Semaphore::TimedWait(double seconds) { DCHECK_GE(seconds, 0.0); if (std::isinf(seconds)) { Wait(); return true; } timespec current_time; if (clock_gettime(CLOCK_REALTIME, &current_time) != 0) { PLOG(ERROR) << "clock_gettime"; return false; } timespec timeout; timeout.tv_sec = seconds; timeout.tv_nsec = (seconds - trunc(seconds)) * 1E9; AddTimespec(current_time, timeout, &timeout); int rv = HANDLE_EINTR(sem_timedwait(&semaphore_, &timeout)); PCHECK(rv == 0 || errno == ETIMEDOUT) << "sem_timedwait"; return rv == 0; } void Semaphore::Signal() { PCHECK(sem_post(&semaphore_) == 0) << "sem_post"; } #endif } // namespace crashpad <commit_msg>posix: Use std::trunc() from <cmath> instead of trunc()<commit_after>// Copyright 2014 The Crashpad Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "util/synchronization/semaphore.h" #include <errno.h> #include <time.h> #include <cmath> #include "base/logging.h" #include "base/posix/eintr_wrapper.h" namespace crashpad { #if !defined(OS_MACOSX) namespace { void AddTimespec(const timespec& ts1, const timespec& ts2, timespec* result) { result->tv_sec = ts1.tv_sec + ts2.tv_sec; result->tv_nsec = ts1.tv_nsec + ts2.tv_nsec; if (result->tv_nsec > static_cast<long>(1E9)) { ++result->tv_sec; result->tv_nsec -= static_cast<long>(1E9); } } } // namespace Semaphore::Semaphore(int value) { PCHECK(sem_init(&semaphore_, 0, value) == 0) << "sem_init"; } Semaphore::~Semaphore() { PCHECK(sem_destroy(&semaphore_) == 0) << "sem_destroy"; } void Semaphore::Wait() { PCHECK(HANDLE_EINTR(sem_wait(&semaphore_)) == 0) << "sem_wait"; } bool Semaphore::TimedWait(double seconds) { DCHECK_GE(seconds, 0.0); if (std::isinf(seconds)) { Wait(); return true; } timespec current_time; if (clock_gettime(CLOCK_REALTIME, &current_time) != 0) { PLOG(ERROR) << "clock_gettime"; return false; } timespec timeout; timeout.tv_sec = seconds; timeout.tv_nsec = (seconds - std::trunc(seconds)) * 1E9; AddTimespec(current_time, timeout, &timeout); int rv = HANDLE_EINTR(sem_timedwait(&semaphore_, &timeout)); PCHECK(rv == 0 || errno == ETIMEDOUT) << "sem_timedwait"; return rv == 0; } void Semaphore::Signal() { PCHECK(sem_post(&semaphore_) == 0) << "sem_post"; } #endif } // namespace crashpad <|endoftext|>
<commit_before>// RUN: %clang -emit-llvm -g -S %s -o - | FileCheck %s // TAG_member is used to encode debug info for 'z' in A. // CHECK: TAG_member class A { public: int z; }; A *foo (A* x) { A *a = new A(*x); return a; } <commit_msg>Add a test to verify that -flimit-debug-info is working in some way.<commit_after>// RUN: %clang -emit-llvm -g -S %s -o - | FileCheck %s // TAG_member is used to encode debug info for 'z' in A. // CHECK: TAG_member class A { public: int z; }; A *foo (A* x) { A *a = new A(*x); return a; } // Verify that we're not emitting a full definition of B in limit debug mode. // RUN: %clang -emit-llvm -g -flimit-debug-info -S %s -o - | FileCheck %s // CHECK-NOT: TAG_member class B { public: int y; }; extern int bar(B *b); int baz(B *b) { return bar(b); } <|endoftext|>
<commit_before>// RUN: clang -fsyntax-only -verify %s class X { }; X operator+(X, X); void f(X x) { x = x + x; } struct Y; struct Z; struct Y { Y(const Z&); }; struct Z { Z(const Y&); }; Y operator+(Y, Y); bool operator-(Y, Y); // expected-note{{candidate function}} bool operator-(Z, Z); // expected-note{{candidate function}} void g(Y y, Z z) { y = y + z; bool b = y - z; // expected-error{{use of overloaded operator '-' is ambiguous; candidates are:}} } struct A { bool operator==(Z&); // expected-note{{candidate function}} }; A make_A(); bool operator==(A&, Z&); // expected-note{{candidate function}} void h(A a, const A ac, Z z) { make_A() == z; a == z; // expected-error{{use of overloaded operator '==' is ambiguous; candidates are:}} ac == z; // expected-error{{invalid operands to binary expression ('struct A const' and 'struct Z')}} } struct B { bool operator==(const B&) const; void test(Z z) { make_A() == z; } }; enum Enum1 { }; enum Enum2 { }; struct E1 { E1(Enum1) { } }; struct E2 { E2(Enum2); }; // C++ [over.match.oper]p3 - enum restriction. float& operator==(E1, E2); void enum_test(Enum1 enum1, Enum2 enum2, E1 e1, E2 e2) { float &f1 = (e1 == e2); float &f2 = (enum1 == e2); float &f3 = (e1 == enum2); float &f4 = (enum1 == enum2); // expected-error{{non-const reference to type 'float' cannot be initialized with a temporary of type '_Bool'}} } struct PostInc { PostInc operator++(int); PostInc& operator++(); }; struct PostDec { PostDec operator--(int); PostDec& operator--(); }; void incdec_test(PostInc pi, PostDec pd) { const PostInc& pi1 = pi++; const PostDec& pd1 = pd--; PostInc &pi2 = ++pi; PostDec &pd2 = --pd; } struct SmartPtr { int& operator*(); // FIXME: spurious error: long& operator*() const; }; void test_smartptr(SmartPtr ptr, const SmartPtr cptr) { int &ir = *ptr; // FIXME: reinstate long &lr = *cptr; } struct ArrayLike { int& operator[](int); }; void test_arraylike(ArrayLike a) { int& ir = a[17]; } struct SmartRef { int* operator&(); }; void test_smartref(SmartRef r) { int* ip = &r; } bool& operator,(X, Y); void test_comma(X x, Y y) { bool& b1 = (x, y); X& xr = (x, x); } struct Callable { int& operator()(int, double = 2.71828); // expected-note{{candidate function}} float& operator()(int, double, long, ...); // expected-note{{candidate function}} }; void test_callable(Callable c) { int &ir = c(1); float &fr = c(1, 3.14159, 17, 42); c(); // expected-error{{no matching function for call to object of type 'struct Callable'; candidates are:}} } typedef int& Func1(float, double); typedef float& Func2(int, double); struct ConvertToFunc { operator Func1*(); // expected-note{{conversion candidate of type 'int &(*)(float, double)'}} operator Func2&(); // expected-note{{conversion candidate of type 'float &(&)(int, double)'}} }; void test_funcptr_call(ConvertToFunc ctf) { int &i1 = ctf(1.0f, 2.0); float &f2 = ctf((short int)1, 1.0f); ctf((long int)17, 2.0); // expected-error{{error: call to object of type 'struct ConvertToFunc' is ambiguous; candidates are:}} } <commit_msg>Beef up the test for function call operators slightly<commit_after>// RUN: clang -fsyntax-only -verify %s class X { }; X operator+(X, X); void f(X x) { x = x + x; } struct Y; struct Z; struct Y { Y(const Z&); }; struct Z { Z(const Y&); }; Y operator+(Y, Y); bool operator-(Y, Y); // expected-note{{candidate function}} bool operator-(Z, Z); // expected-note{{candidate function}} void g(Y y, Z z) { y = y + z; bool b = y - z; // expected-error{{use of overloaded operator '-' is ambiguous; candidates are:}} } struct A { bool operator==(Z&); // expected-note{{candidate function}} }; A make_A(); bool operator==(A&, Z&); // expected-note{{candidate function}} void h(A a, const A ac, Z z) { make_A() == z; a == z; // expected-error{{use of overloaded operator '==' is ambiguous; candidates are:}} ac == z; // expected-error{{invalid operands to binary expression ('struct A const' and 'struct Z')}} } struct B { bool operator==(const B&) const; void test(Z z) { make_A() == z; } }; enum Enum1 { }; enum Enum2 { }; struct E1 { E1(Enum1) { } }; struct E2 { E2(Enum2); }; // C++ [over.match.oper]p3 - enum restriction. float& operator==(E1, E2); void enum_test(Enum1 enum1, Enum2 enum2, E1 e1, E2 e2) { float &f1 = (e1 == e2); float &f2 = (enum1 == e2); float &f3 = (e1 == enum2); float &f4 = (enum1 == enum2); // expected-error{{non-const reference to type 'float' cannot be initialized with a temporary of type '_Bool'}} } struct PostInc { PostInc operator++(int); PostInc& operator++(); }; struct PostDec { PostDec operator--(int); PostDec& operator--(); }; void incdec_test(PostInc pi, PostDec pd) { const PostInc& pi1 = pi++; const PostDec& pd1 = pd--; PostInc &pi2 = ++pi; PostDec &pd2 = --pd; } struct SmartPtr { int& operator*(); // FIXME: spurious error: long& operator*() const; }; void test_smartptr(SmartPtr ptr, const SmartPtr cptr) { int &ir = *ptr; // FIXME: reinstate long &lr = *cptr; } struct ArrayLike { int& operator[](int); }; void test_arraylike(ArrayLike a) { int& ir = a[17]; } struct SmartRef { int* operator&(); }; void test_smartref(SmartRef r) { int* ip = &r; } bool& operator,(X, Y); void test_comma(X x, Y y) { bool& b1 = (x, y); X& xr = (x, x); } struct Callable { int& operator()(int, double = 2.71828); // expected-note{{candidate function}} float& operator()(int, double, long, ...); // expected-note{{candidate function}} }; void test_callable(Callable c) { int &ir = c(1); float &fr = c(1, 3.14159, 17, 42); c(); // expected-error{{no matching function for call to object of type 'struct Callable'; candidates are:}} } typedef int& Func1(float, double); typedef float& Func2(int, double); struct ConvertToFunc { operator Func1*(); // expected-note{{conversion candidate of type 'int &(*)(float, double)'}} operator Func2&(); // expected-note{{conversion candidate of type 'float &(&)(int, double)'}} void operator()(); }; void test_funcptr_call(ConvertToFunc ctf) { int &i1 = ctf(1.0f, 2.0); float &f2 = ctf((short int)1, 1.0f); ctf((long int)17, 2.0); // expected-error{{error: call to object of type 'struct ConvertToFunc' is ambiguous; candidates are:}} ctf(); } <|endoftext|>
<commit_before>/* * Ultrasonic.cpp - Library for HC-SR04 Ultrasonic Ranging Module.library * * Created by ITead studio. Apr 20, 2010. * iteadstudio.com * * SVN Keywords * ---------------------------------- * $Author$ * $Date$ * $Revision$ * ---------------------------------- */ #include <stdlib.h> #include <string.h> #include <Ultrasonic.h> Ultrasonic::Ultrasonic(int tp, int ep) { pinMode(tp, OUTPUT); pinMode(ep, INPUT); _trigPin = tp; _echoPin = ep; } long Ultrasonic::timing() { digitalWrite(_trigPin, LOW); delayMicroseconds(2); digitalWrite(_trigPin, HIGH); delayMicroseconds(10); digitalWrite(_trigPin, LOW); return pulseIn(_echoPin, HIGH); } long Ultrasonic::convert(long microsec, int metric) { if(metric) return microsec / 29 / 2; // CM else return microsec / 74 / 2; // IN } #ifdef COMPILE_STD_DEV bool Ultrasonic::sampleCreate(size_t numBufs, ...) { bool result = false; va_list ap; _numBufs = numBufs; if((_pBuffers = (BufCtl *) calloc(numBufs, sizeof(BufCtl))) != NULL) { va_start(ap, numBufs); BufCtl *buf; size_t smpSize; for(size_t i = 0; i < _numBufs; i++) { buf = &_pBuffers[i]; smpSize = va_arg(ap, size_t); if((buf->pBegin = (float *) calloc(smpSize, sizeof(float))) != NULL) { buf->pIndex = buf->pBegin; buf->length = smpSize; buf->filled = false; result = true; } else { result = false; break; } } va_end(ap); } if(!result) _freeBuffers() return result; } void Ultrasonic::sampleClear() { if(_pBuffers) { BufCtl *buf; for(size_t i = 0; i < _numBufs; i++) { buf = &_pBuffers[i]; memset(buf, '\0', sizeof(float) * buf->length); buf->pIndex = buf->pBegin; buf->filled = false; } } } float Ultrasonic::unbiasedStdDev(long value, size_t bufNum) { float result = 0.0; if(_pBuffers) { BufCtl *buf = &_pBuffers[bufNum]; if(buf->length > 1) { _sampleUpdate(buf, float(value)); if(buf->filled) { float sum = 0.0, mean, tmp; for(size_t i = 0; i < buf->length; i++) sum += buf->pBegin[i]; mean = sum / buf->length; sum = 0.0; for(size_t i = 0; i < buf->length; i++) { tmp = buf->pBegin[i] - mean; sum += (tmp * tmp); } result = sqrt(sum / (buf->length - 1)); //Serial.print(bufNum); //Serial.print(" : "); //Serial.println(result); } } } return result; } void Ultrasonic::_sampleUpdate(BufCtl *buf, float msec) { if(buf->pIndex >= (buf->pBegin + buf->length)) { buf->pIndex = buf->pBegin; buf->filled = true; } *(buf->pIndex++) = msec; } void Ultrasonic::_freeBuffers() { if(_pBuffers) { BufCtl *buf; for(size_t i = 0; i < _numBufs; i++) { buf = &_pBuffers[i]; free(buf->pBegin) } free(pBuffers) } } #endif // COMPILE_STD_DEV <commit_msg>Opps forgot an underscore.<commit_after>/* * Ultrasonic.cpp - Library for HC-SR04 Ultrasonic Ranging Module.library * * Created by ITead studio. Apr 20, 2010. * iteadstudio.com * * SVN Keywords * ---------------------------------- * $Author$ * $Date$ * $Revision$ * ---------------------------------- */ #include <stdlib.h> #include <string.h> #include <Ultrasonic.h> Ultrasonic::Ultrasonic(int tp, int ep) { pinMode(tp, OUTPUT); pinMode(ep, INPUT); _trigPin = tp; _echoPin = ep; } long Ultrasonic::timing() { digitalWrite(_trigPin, LOW); delayMicroseconds(2); digitalWrite(_trigPin, HIGH); delayMicroseconds(10); digitalWrite(_trigPin, LOW); return pulseIn(_echoPin, HIGH); } long Ultrasonic::convert(long microsec, int metric) { if(metric) return microsec / 29 / 2; // CM else return microsec / 74 / 2; // IN } #ifdef COMPILE_STD_DEV bool Ultrasonic::sampleCreate(size_t numBufs, ...) { bool result = false; va_list ap; _numBufs = numBufs; if((_pBuffers = (BufCtl *) calloc(numBufs, sizeof(BufCtl))) != NULL) { va_start(ap, numBufs); BufCtl *buf; size_t smpSize; for(size_t i = 0; i < _numBufs; i++) { buf = &_pBuffers[i]; smpSize = va_arg(ap, size_t); if((buf->pBegin = (float *) calloc(smpSize, sizeof(float))) != NULL) { buf->pIndex = buf->pBegin; buf->length = smpSize; buf->filled = false; result = true; } else { result = false; break; } } va_end(ap); } if(!result) _freeBuffers() return result; } void Ultrasonic::sampleClear() { if(_pBuffers) { BufCtl *buf; for(size_t i = 0; i < _numBufs; i++) { buf = &_pBuffers[i]; memset(buf, '\0', sizeof(float) * buf->length); buf->pIndex = buf->pBegin; buf->filled = false; } } } float Ultrasonic::unbiasedStdDev(long value, size_t bufNum) { float result = 0.0; if(_pBuffers) { BufCtl *buf = &_pBuffers[bufNum]; if(buf->length > 1) { _sampleUpdate(buf, float(value)); if(buf->filled) { float sum = 0.0, mean, tmp; for(size_t i = 0; i < buf->length; i++) sum += buf->pBegin[i]; mean = sum / buf->length; sum = 0.0; for(size_t i = 0; i < buf->length; i++) { tmp = buf->pBegin[i] - mean; sum += (tmp * tmp); } result = sqrt(sum / (buf->length - 1)); //Serial.print(bufNum); //Serial.print(" : "); //Serial.println(result); } } } return result; } void Ultrasonic::_sampleUpdate(BufCtl *buf, float msec) { if(buf->pIndex >= (buf->pBegin + buf->length)) { buf->pIndex = buf->pBegin; buf->filled = true; } *(buf->pIndex++) = msec; } void Ultrasonic::_freeBuffers() { if(_pBuffers) { BufCtl *buf; for(size_t i = 0; i < _numBufs; i++) { buf = &_pBuffers[i]; free(buf->pBegin) } free(_pBuffers) } } #endif // COMPILE_STD_DEV <|endoftext|>
<commit_before><commit_msg>src/aio.cpp: Added error reporting responses<commit_after><|endoftext|>
<commit_before>// Copyright (c) 2018-2021 The Dash Core developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <llmq/commitment.h> #include <evo/deterministicmns.h> #include <evo/specialtx.h> #include <chainparams.h> #include <consensus/validation.h> #include <logging.h> #include <validation.h> namespace llmq { CFinalCommitment::CFinalCommitment(const Consensus::LLMQParams& params, const uint256& _quorumHash) : llmqType(params.type), quorumHash(_quorumHash), signers(params.size), validMembers(params.size) { } #define LogPrintfFinalCommitment(...) do { \ LogInstance().LogPrintStr(strprintf("CFinalCommitment::%s -- %s", __func__, tinyformat::format(__VA_ARGS__))); \ } while(0) bool CFinalCommitment::Verify(const CBlockIndex* pQuorumBaseBlockIndex, bool checkSigs) const { if (nVersion == 0 || nVersion != (CLLMQUtils::IsQuorumRotationEnabled(llmqType, pQuorumBaseBlockIndex) ? INDEXED_QUORUM_VERSION : CURRENT_VERSION)) { LogPrintfFinalCommitment("q[%s] invalid nVersion=%d\n", quorumHash.ToString(), nVersion); return false; } if (!Params().HasLLMQ(llmqType)) { LogPrintfFinalCommitment("q[%s] invalid llmqType=%d\n", quorumHash.ToString(), static_cast<uint8_t>(llmqType)); return false; } const auto& llmq_params = GetLLMQParams(llmqType); if (pQuorumBaseBlockIndex->GetBlockHash() != quorumHash) { LogPrintfFinalCommitment("q[%s] invalid quorumHash\n", quorumHash.ToString()); return false; } if ((pQuorumBaseBlockIndex->nHeight % llmq_params.dkgInterval) != quorumIndex) { LogPrintfFinalCommitment("q[%s] invalid quorumIndex=%d\n", quorumHash.ToString(), quorumIndex); return false; } if (!VerifySizes(llmq_params)) { return false; } if (CountValidMembers() < llmq_params.minSize) { LogPrintfFinalCommitment("q[%s] invalid validMembers count. validMembersCount=%d\n", quorumHash.ToString(), CountValidMembers()); return false; } if (CountSigners() < llmq_params.minSize) { LogPrintfFinalCommitment("q[%s] invalid signers count. signersCount=%d\n", quorumHash.ToString(), CountSigners()); return false; } if (!quorumPublicKey.IsValid()) { LogPrintfFinalCommitment("q[%s] invalid quorumPublicKey\n", quorumHash.ToString()); return false; } if (quorumVvecHash.IsNull()) { LogPrintfFinalCommitment("q[%s] invalid quorumVvecHash\n", quorumHash.ToString()); return false; } if (!membersSig.IsValid()) { LogPrintfFinalCommitment("q[%s] invalid membersSig\n", quorumHash.ToString()); return false; } if (!quorumSig.IsValid()) { LogPrintfFinalCommitment("q[%s] invalid vvecSig\n"); return false; } auto members = CLLMQUtils::GetAllQuorumMembers(llmqType, pQuorumBaseBlockIndex); std::stringstream ss; for (size_t i = 0; i < llmq_params.size; i++) { ss << "v[" << i << "]=" << validMembers[i]; } std::stringstream ss2; for (size_t i = 0; i < llmq_params.size; i++) { ss2 << "s[" << i << "]=" << signers[i]; } LogPrintf("CFinalCommitment::%s mns[%d] validMembers[%s] signers[%s]\n", __func__, members.size(), ss.str(), ss2.str()); for (size_t i = members.size(); i < size_t(llmq_params.size); i++) { if (validMembers[i]) { LogPrintfFinalCommitment("q[%s] invalid validMembers bitset. bit %d should not be set\n", quorumHash.ToString(), i); return false; } if (signers[i]) { LogPrintfFinalCommitment("q[%s] invalid signers bitset. bit %d should not be set\n", quorumHash.ToString(), i); return false; } } // sigs are only checked when the block is processed if (checkSigs) { uint256 commitmentHash = CLLMQUtils::BuildCommitmentHash(llmq_params.type, quorumHash, validMembers, quorumPublicKey, quorumVvecHash); std::stringstream ss3; for (const auto& mn : members) { ss3 << mn->proTxHash.ToString().substr(0, 4) << " | "; } LogPrintf("CFinalCommitment::%s members[%s] quorumPublicKey[%s] commitmentHash[%s]\n", __func__, ss3.str(), quorumPublicKey.ToString(), commitmentHash.ToString()); std::vector<CBLSPublicKey> memberPubKeys; for (size_t i = 0; i < members.size(); i++) { if (!signers[i]) { continue; } memberPubKeys.emplace_back(members[i]->pdmnState->pubKeyOperator.Get()); } if (!membersSig.VerifySecureAggregated(memberPubKeys, commitmentHash)) { LogPrintfFinalCommitment("q[%s] invalid aggregated members signature\n", quorumHash.ToString()); return false; } if (!quorumSig.VerifyInsecure(quorumPublicKey, commitmentHash)) { LogPrintfFinalCommitment("q[%s] invalid quorum signature\n", quorumHash.ToString()); return false; } } LogPrintfFinalCommitment("q[%s] VALID\n", quorumHash.ToString()); return true; } bool CFinalCommitment::VerifyNull() const { if (!Params().HasLLMQ(llmqType)) { LogPrintfFinalCommitment("q[%s]invalid llmqType=%d\n", quorumHash.ToString(), static_cast<uint8_t>(llmqType)); return false; } if (!IsNull() || !VerifySizes(GetLLMQParams(llmqType))) { return false; } return true; } bool CFinalCommitment::VerifySizes(const Consensus::LLMQParams& params) const { if (signers.size() != size_t(params.size)) { LogPrintfFinalCommitment("q[%s] invalid signers.size=%d\n", quorumHash.ToString(), signers.size()); return false; } if (validMembers.size() != size_t(params.size)) { LogPrintfFinalCommitment("q[%s] invalid signers.size=%d\n", quorumHash.ToString(), signers.size()); return false; } return true; } bool CheckLLMQCommitment(const CTransaction& tx, const CBlockIndex* pindexPrev, CValidationState& state) { CFinalCommitmentTxPayload qcTx; if (!GetTxPayload(tx, qcTx)) { LogPrintfFinalCommitment("h[%d] GetTxPayload failed\n", pindexPrev->nHeight); return state.DoS(100, false, REJECT_INVALID, "bad-qc-payload"); } const auto& llmq_params = GetLLMQParams(qcTx.commitment.llmqType); std::stringstream ss; for (size_t i = 0; i < llmq_params.size; i++) { ss << "v[" << i << "]=" << qcTx.commitment.validMembers[i]; } LogPrintf("%s llmqType[%d] validMembers[%s] signers[]\n", __func__, int(qcTx.commitment.llmqType), ss.str()); if (qcTx.nVersion == 0 || qcTx.nVersion > CFinalCommitmentTxPayload::CURRENT_VERSION) { LogPrintfFinalCommitment("h[%d] invalid qcTx.nVersion[%d]\n", pindexPrev->nHeight, qcTx.nVersion); return state.DoS(100, false, REJECT_INVALID, "bad-qc-version"); } if (qcTx.nHeight != uint32_t(pindexPrev->nHeight + 1)) { LogPrintfFinalCommitment("h[%d] invalid qcTx.nHeight[%d]\n", pindexPrev->nHeight, qcTx.nHeight); return state.DoS(100, false, REJECT_INVALID, "bad-qc-height"); } const CBlockIndex* pQuorumBaseBlockIndex = WITH_LOCK(cs_main, return LookupBlockIndex(qcTx.commitment.quorumHash)); if (!pQuorumBaseBlockIndex) { return state.DoS(100, false, REJECT_INVALID, "bad-qc-quorum-hash"); } if (pQuorumBaseBlockIndex != pindexPrev->GetAncestor(pQuorumBaseBlockIndex->nHeight)) { // not part of active chain return state.DoS(100, false, REJECT_INVALID, "bad-qc-quorum-hash"); } if (!Params().HasLLMQ(qcTx.commitment.llmqType)) { return state.DoS(100, false, REJECT_INVALID, "bad-qc-type"); } if (qcTx.commitment.IsNull()) { if (!qcTx.commitment.VerifyNull()) { LogPrintfFinalCommitment("h[%d] invalid qcTx.commitment[%s] VerifyNull failed\n", pindexPrev->nHeight, qcTx.commitment.quorumHash.ToString()); return state.DoS(100, false, REJECT_INVALID, "bad-qc-invalid-null"); } return true; } if (!qcTx.commitment.Verify(pQuorumBaseBlockIndex, false)) { LogPrintfFinalCommitment("h[%d] invalid qcTx.commitment[%s] Verify failed\n", pindexPrev->nHeight, qcTx.commitment.quorumHash.ToString()); return state.DoS(100, false, REJECT_INVALID, "bad-qc-invalid"); } LogPrintfFinalCommitment("h[%d] CheckLLMQCommitment VALID\n", pindexPrev->nHeight); return true; } } // namespace llmq <commit_msg>refactor: only do LogPrintfFinalCommitment if LogAccept LLMQ (#4779)<commit_after>// Copyright (c) 2018-2021 The Dash Core developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <llmq/commitment.h> #include <evo/deterministicmns.h> #include <evo/specialtx.h> #include <chainparams.h> #include <consensus/validation.h> #include <logging.h> #include <validation.h> namespace llmq { CFinalCommitment::CFinalCommitment(const Consensus::LLMQParams& params, const uint256& _quorumHash) : llmqType(params.type), quorumHash(_quorumHash), signers(params.size), validMembers(params.size) { } #define LogPrintfFinalCommitment(...) if (LogAcceptCategory(BCLog::LLMQ)) { \ LogInstance().LogPrintStr(strprintf("CFinalCommitment::%s -- %s", __func__, tinyformat::format(__VA_ARGS__))); \ } bool CFinalCommitment::Verify(const CBlockIndex* pQuorumBaseBlockIndex, bool checkSigs) const { if (nVersion == 0 || nVersion != (CLLMQUtils::IsQuorumRotationEnabled(llmqType, pQuorumBaseBlockIndex) ? INDEXED_QUORUM_VERSION : CURRENT_VERSION)) { LogPrintfFinalCommitment("q[%s] invalid nVersion=%d\n", quorumHash.ToString(), nVersion); return false; } if (!Params().HasLLMQ(llmqType)) { LogPrintfFinalCommitment("q[%s] invalid llmqType=%d\n", quorumHash.ToString(), static_cast<uint8_t>(llmqType)); return false; } const auto& llmq_params = GetLLMQParams(llmqType); if (pQuorumBaseBlockIndex->GetBlockHash() != quorumHash) { LogPrintfFinalCommitment("q[%s] invalid quorumHash\n", quorumHash.ToString()); return false; } if ((pQuorumBaseBlockIndex->nHeight % llmq_params.dkgInterval) != quorumIndex) { LogPrintfFinalCommitment("q[%s] invalid quorumIndex=%d\n", quorumHash.ToString(), quorumIndex); return false; } if (!VerifySizes(llmq_params)) { return false; } if (CountValidMembers() < llmq_params.minSize) { LogPrintfFinalCommitment("q[%s] invalid validMembers count. validMembersCount=%d\n", quorumHash.ToString(), CountValidMembers()); return false; } if (CountSigners() < llmq_params.minSize) { LogPrintfFinalCommitment("q[%s] invalid signers count. signersCount=%d\n", quorumHash.ToString(), CountSigners()); return false; } if (!quorumPublicKey.IsValid()) { LogPrintfFinalCommitment("q[%s] invalid quorumPublicKey\n", quorumHash.ToString()); return false; } if (quorumVvecHash.IsNull()) { LogPrintfFinalCommitment("q[%s] invalid quorumVvecHash\n", quorumHash.ToString()); return false; } if (!membersSig.IsValid()) { LogPrintfFinalCommitment("q[%s] invalid membersSig\n", quorumHash.ToString()); return false; } if (!quorumSig.IsValid()) { LogPrintfFinalCommitment("q[%s] invalid vvecSig\n"); return false; } auto members = CLLMQUtils::GetAllQuorumMembers(llmqType, pQuorumBaseBlockIndex); std::stringstream ss; for (size_t i = 0; i < llmq_params.size; i++) { ss << "v[" << i << "]=" << validMembers[i]; } std::stringstream ss2; for (size_t i = 0; i < llmq_params.size; i++) { ss2 << "s[" << i << "]=" << signers[i]; } LogPrintfFinalCommitment("CFinalCommitment::%s mns[%d] validMembers[%s] signers[%s]\n", __func__, members.size(), ss.str(), ss2.str()); for (size_t i = members.size(); i < size_t(llmq_params.size); i++) { if (validMembers[i]) { LogPrintfFinalCommitment("q[%s] invalid validMembers bitset. bit %d should not be set\n", quorumHash.ToString(), i); return false; } if (signers[i]) { LogPrintfFinalCommitment("q[%s] invalid signers bitset. bit %d should not be set\n", quorumHash.ToString(), i); return false; } } // sigs are only checked when the block is processed if (checkSigs) { uint256 commitmentHash = CLLMQUtils::BuildCommitmentHash(llmq_params.type, quorumHash, validMembers, quorumPublicKey, quorumVvecHash); std::stringstream ss3; for (const auto& mn : members) { ss3 << mn->proTxHash.ToString().substr(0, 4) << " | "; } LogPrintfFinalCommitment("CFinalCommitment::%s members[%s] quorumPublicKey[%s] commitmentHash[%s]\n", __func__, ss3.str(), quorumPublicKey.ToString(), commitmentHash.ToString()); std::vector<CBLSPublicKey> memberPubKeys; for (size_t i = 0; i < members.size(); i++) { if (!signers[i]) { continue; } memberPubKeys.emplace_back(members[i]->pdmnState->pubKeyOperator.Get()); } if (!membersSig.VerifySecureAggregated(memberPubKeys, commitmentHash)) { LogPrintfFinalCommitment("q[%s] invalid aggregated members signature\n", quorumHash.ToString()); return false; } if (!quorumSig.VerifyInsecure(quorumPublicKey, commitmentHash)) { LogPrintfFinalCommitment("q[%s] invalid quorum signature\n", quorumHash.ToString()); return false; } } LogPrintfFinalCommitment("q[%s] VALID\n", quorumHash.ToString()); return true; } bool CFinalCommitment::VerifyNull() const { if (!Params().HasLLMQ(llmqType)) { LogPrintfFinalCommitment("q[%s]invalid llmqType=%d\n", quorumHash.ToString(), static_cast<uint8_t>(llmqType)); return false; } if (!IsNull() || !VerifySizes(GetLLMQParams(llmqType))) { return false; } return true; } bool CFinalCommitment::VerifySizes(const Consensus::LLMQParams& params) const { if (signers.size() != size_t(params.size)) { LogPrintfFinalCommitment("q[%s] invalid signers.size=%d\n", quorumHash.ToString(), signers.size()); return false; } if (validMembers.size() != size_t(params.size)) { LogPrintfFinalCommitment("q[%s] invalid signers.size=%d\n", quorumHash.ToString(), signers.size()); return false; } return true; } bool CheckLLMQCommitment(const CTransaction& tx, const CBlockIndex* pindexPrev, CValidationState& state) { CFinalCommitmentTxPayload qcTx; if (!GetTxPayload(tx, qcTx)) { LogPrintfFinalCommitment("h[%d] GetTxPayload failed\n", pindexPrev->nHeight); return state.DoS(100, false, REJECT_INVALID, "bad-qc-payload"); } const auto& llmq_params = GetLLMQParams(qcTx.commitment.llmqType); std::stringstream ss; for (size_t i = 0; i < llmq_params.size; i++) { ss << "v[" << i << "]=" << qcTx.commitment.validMembers[i]; } LogPrintfFinalCommitment("%s llmqType[%d] validMembers[%s] signers[]\n", __func__, int(qcTx.commitment.llmqType), ss.str()); if (qcTx.nVersion == 0 || qcTx.nVersion > CFinalCommitmentTxPayload::CURRENT_VERSION) { LogPrintfFinalCommitment("h[%d] invalid qcTx.nVersion[%d]\n", pindexPrev->nHeight, qcTx.nVersion); return state.DoS(100, false, REJECT_INVALID, "bad-qc-version"); } if (qcTx.nHeight != uint32_t(pindexPrev->nHeight + 1)) { LogPrintfFinalCommitment("h[%d] invalid qcTx.nHeight[%d]\n", pindexPrev->nHeight, qcTx.nHeight); return state.DoS(100, false, REJECT_INVALID, "bad-qc-height"); } const CBlockIndex* pQuorumBaseBlockIndex = WITH_LOCK(cs_main, return LookupBlockIndex(qcTx.commitment.quorumHash)); if (!pQuorumBaseBlockIndex) { return state.DoS(100, false, REJECT_INVALID, "bad-qc-quorum-hash"); } if (pQuorumBaseBlockIndex != pindexPrev->GetAncestor(pQuorumBaseBlockIndex->nHeight)) { // not part of active chain return state.DoS(100, false, REJECT_INVALID, "bad-qc-quorum-hash"); } if (!Params().HasLLMQ(qcTx.commitment.llmqType)) { return state.DoS(100, false, REJECT_INVALID, "bad-qc-type"); } if (qcTx.commitment.IsNull()) { if (!qcTx.commitment.VerifyNull()) { LogPrintfFinalCommitment("h[%d] invalid qcTx.commitment[%s] VerifyNull failed\n", pindexPrev->nHeight, qcTx.commitment.quorumHash.ToString()); return state.DoS(100, false, REJECT_INVALID, "bad-qc-invalid-null"); } return true; } if (!qcTx.commitment.Verify(pQuorumBaseBlockIndex, false)) { LogPrintfFinalCommitment("h[%d] invalid qcTx.commitment[%s] Verify failed\n", pindexPrev->nHeight, qcTx.commitment.quorumHash.ToString()); return state.DoS(100, false, REJECT_INVALID, "bad-qc-invalid"); } LogPrintfFinalCommitment("h[%d] CheckLLMQCommitment VALID\n", pindexPrev->nHeight); return true; } } // namespace llmq <|endoftext|>
<commit_before>#include <pybind11/pybind11.h> #include <pybind11/stl.h> // for conversions between c++ and python collections #include <pybind11/numpy.h> // support for numpy arrays #include "trajectory.h" #include "raster.h" #include "visibility.h" #include "planning.h" namespace py = pybind11; /** Converts a nupy array to a vector */ template<class T> std::vector<T> as_vector(py::array_t<T, py::array::c_style | py::array::forcecast> array) { std::vector<T> data(array.size()); for(size_t x=0; x<array.shape(0); x++) { for(size_t y=0; y<array.shape(1); y++) { data[x + y*array.shape(0)] = *(array.data(x, y)); } } return data; } /** Converts a vector to a 2D numpy array. */ template<class T> py::array_t<T> as_nparray(std::vector<T> vec, size_t x_width, size_t y_height) { ASSERT(vec.size() == x_width * y_height) py::array_t<T, py::array::c_style | py::array::forcecast> array(std::vector<size_t> {x_width, y_height}); for(size_t x=0; x<x_width; x++) { for (size_t y = 0; y < y_height; y++) { *(array.mutable_data(x, y)) = vec[x + y*x_width]; } } return array; } PYBIND11_DECLARE_HOLDER_TYPE(T, std::shared_ptr<T>); PYBIND11_PLUGIN(uav_planning) { py::module m("uav_planning", "Python module for AUV trajectory planning"); srand(time(0)); srand(0); py::class_<DRaster>(m, "DRaster") .def("__init__", [](DRaster& self, py::array_t<double, py::array::c_style | py::array::forcecast> arr, double x_offset, double y_offset, double cell_width) { // create a new object and sibstitute to the given self new (&self) DRaster(as_vector<double>(arr), arr.shape(0), arr.shape(1), x_offset, y_offset, cell_width); }) .def("as_numpy", [](DRaster& self) { return as_nparray<double>(self.data, self.x_width, self.y_height); }) .def_readonly("x_offset", &DRaster::x_offset) .def_readonly("y_offset", &DRaster::y_offset) .def_readonly("cell_width", &DRaster::cell_width); py::class_<LRaster>(m, "LRaster") .def("__init__", [](LRaster& self, py::array_t<long, py::array::c_style | py::array::forcecast> arr, double x_offset, double y_offset, double cell_width) { new (&self) LRaster(as_vector<long>(arr), arr.shape(0), arr.shape(1), x_offset, y_offset, cell_width); }) .def("as_numpy", [](LRaster& self) { return as_nparray<long>(self.data, self.x_width, self.y_height); }) .def_readonly("x_offset", &LRaster::x_offset) .def_readonly("y_offset", &LRaster::y_offset) .def_readonly("cell_width", &LRaster::cell_width); py::class_<TimeWindow>(m, "TimeWindow") .def(py::init<const double, const double>(), py::arg("start"), py::arg("end")) .def_readonly("start", &TimeWindow::start) .def_readonly("end", &TimeWindow::end) .def("__repr__", [](const TimeWindow &tw) { std::stringstream repr; repr << "TimeWindow(" << tw.start << ", " << tw.end << ")"; return repr.str(); } ) .def("as_tuple", [](TimeWindow &self) { return py::make_tuple(self.start, self.end); } ); py::class_<Cell>(m, "Cell") .def(py::init<const size_t, const size_t>(), py::arg("x"), py::arg("y")) .def_readonly("x", &Cell::x) .def_readonly("y", &Cell::y) .def("__repr__", [](const Cell &c) { std::stringstream repr; repr << "Cell(" << c.x << ", " << c.y << ")"; return repr.str(); } ) .def("as_tuple", [](Cell &self) { return py::make_tuple(self.x, self.y); } ); py::class_<Position>(m, "Position") .def(py::init<double, double>(), py::arg("x"), py::arg("y")) .def_readonly("x", &Position::x) .def_readonly("y", &Position::y) .def("__repr__", [](const Position &p) { std::stringstream repr; repr << "Position(" << p.x << ", " << p.y << ")"; return repr.str(); } ) .def("as_tuple", [](Position &self) { return py::make_tuple(self.x, self.y); } ); py::class_<Position3d>(m, "Position3d") .def(py::init<double, double, double>(), py::arg("x"), py::arg("y"), py::arg("z")) .def_readonly("x", &Position3d::x) .def_readonly("y", &Position3d::y) .def_readonly("z", &Position3d::z) .def("__repr__", [](const Position3d &p) { std::stringstream repr; repr << "Position3d(" << p.x << ", " << p.y << ", " << p.z << ")"; return repr.str(); } ) .def("as_tuple", [](Position3d &self) { return py::make_tuple(self.x, self.y, self.z); } ); py::class_<PositionTime>(m, "PositionTime") .def(py::init<Position, double>(), py::arg("point"), py::arg("time")) .def_readonly("pt", &PositionTime::pt) .def_readonly("y", &PositionTime::time) .def("__repr__", [](const PositionTime &p) { std::stringstream repr; repr << "PositionTime(" << p.pt.x << ", " << p.pt.y << ", " << p.time << ")"; return repr.str(); } ) .def("as_tuple", [](PositionTime &self) { return py::make_tuple(py::make_tuple(self.pt.x, self.pt.y), self.time); } ); py::class_<Position3dTime>(m, "Position3dTime") .def(py::init<Position3d, double>(), py::arg("point"), py::arg("time")) .def_readonly("pt", &Position3dTime::pt) .def_readonly("y", &Position3dTime::time) .def("__repr__", [](const Position3dTime &p) { std::stringstream repr; repr << "Position3dTime(" << p.pt.x << ", " << p.pt.y << ", " << p.pt.z << ", " << p.time << ")"; return repr.str(); } ) .def("as_tuple", [](Position3dTime &self) { return py::make_tuple(py::make_tuple(self.pt.x, self.pt.y, self.pt.z), self.time); } ); py::class_<IsochroneCluster, shared_ptr<IsochroneCluster>>(m, "IsochroneCluster") .def("__init__", [](IsochroneCluster& self, const TimeWindow& tw, vector<Cell> cell_vector) { new (&self) IsochroneCluster(tw, cell_vector); }) .def_readonly("time_window", &IsochroneCluster::time_window) .def_readonly("cells", &IsochroneCluster::cells); py::class_<FireData>(m, "FireData") .def("__init__", [](FireData& self, DRaster& ignitions) { new (&self) FireData(ignitions); }) .def_readonly("ignitions", &FireData::ignitions) .def_readonly("traversal_end", &FireData::traversal_end) .def_readonly("propagation_directions", &FireData::propagation_directions) // .def_readonly_static("isochrone_timespan", &FireData::isochrone_timespan) .def_readonly("isochrones", &FireData::isochrones); py::class_<Waypoint3d>(m, "Waypoint") .def(py::init<const double, const double, const double, const double>(), py::arg("x"), py::arg("y"), py::arg("z"), py::arg("direction")) .def_readonly("x", &Waypoint3d::x) .def_readonly("y", &Waypoint3d::y) .def_readonly("z", &Waypoint3d::z) .def_readonly("dir", &Waypoint3d::dir) .def("__repr__", &Waypoint3d::to_string); py::class_<Segment3d>(m, "Segment") .def(py::init<const Waypoint3d, const double>()) .def(py::init<const Waypoint3d, const Waypoint3d>()) .def_readonly("start", &Segment3d::start) .def_readonly("end", &Segment3d::end) .def_readonly("length", &Segment3d::length); py::class_<UAV>(m, "UAV") .def(py::init<const double, const double, const double>()) .def_readonly("min_turn_radius", &UAV::min_turn_radius) .def_readonly("max_air_speed", &UAV::max_air_speed) .def_readonly("max_pitch_angle", &UAV::max_pitch_angle) .def("travel_distance", (double (UAV::*)(const Waypoint3d &, const Waypoint3d &) const)&UAV::travel_distance, py::arg("origin"), py::arg("destination")) .def("travel_distance", (double (UAV::*)(const Waypoint &, const Waypoint &) const)&UAV::travel_distance, py::arg("origin"), py::arg("destination")) .def("travel_time", (double (UAV::*)(const Waypoint3d &, const Waypoint3d &) const)&UAV::travel_time, py::arg("origin"), py::arg("destination")) .def("travel_time", (double (UAV::*)(const Waypoint &, const Waypoint &) const)&UAV::travel_time, py::arg("origin"), py::arg("destination")); py::class_<Trajectory>(m, "Trajectory") .def(py::init<const TrajectoryConfig&>()) .def("start_time", (double (Trajectory::*)() const)&Trajectory::start_time) .def("end_time", (double (Trajectory::*)() const)&Trajectory::end_time) .def_readonly("segments", &Trajectory::traj) .def("length", &Trajectory::length) .def("duration", &Trajectory::duration) .def("as_waypoints", &Trajectory::as_waypoints) .def("sampled", &Trajectory::sampled, py::arg("step_size") = 1) .def("with_waypoint_at_end", &Trajectory::with_waypoint_at_end) .def("__repr__", &Trajectory::to_string); py::class_<TrajectoryConfig>(m, "TrajectoryConfig") .def(py::init<UAV, Waypoint3d, Waypoint3d, double, double>()) .def_readonly("uav", &TrajectoryConfig::uav) .def_readonly("max_flight_time", &TrajectoryConfig::max_flight_time) .def_static("build", [](UAV uav, double start_time, double max_flight_time) -> TrajectoryConfig { return TrajectoryConfig(uav, start_time, max_flight_time); }, "Constructor", py::arg("uav"), py::arg("start_time") = 0, py::arg("max_flight_time") = std::numeric_limits<double>::max()); py::class_<Plan>(m, "Plan") .def_readonly("trajectories", &Plan::trajectories) .def("utility", &Plan::utility) .def("duration", &Plan::duration) .def_readonly("firedata", &Plan::firedata) .def("observations", &Plan::observations); py::class_<SearchResult>(m, "SearchResult") .def("initial_plan", &SearchResult::initial) .def("final_plan", &SearchResult::final) .def_readonly("intermediate_plans", &SearchResult::intermediate_plans) .def_readonly("planning_time", &SearchResult::planning_time) .def_readonly("preprocessing_time", &SearchResult::preprocessing_time); m.def("make_plan_vns", [](UAV uav, DRaster ignitions, double min_time, double max_time, double max_flight_time, size_t save_every, bool save_improvements) -> SearchResult { auto fire_data = make_shared<FireData>(ignitions); TrajectoryConfig conf(uav, min_time, max_flight_time); Plan p(vector<TrajectoryConfig> { conf }, fire_data, TimeWindow{min_time, max_time}); DefaultVnsSearch vns; auto res = vns.search(p, 0, save_every, save_improvements); return res; }, py::arg("uav"), py::arg("ignitions"), py::arg("min_time"), py::arg("max_time"), py::arg("max_flight_time"), py::arg("save_every") = 0, py::arg("save_improvements") = false); m.def("plan_vns", [](vector<TrajectoryConfig> configs, DRaster ignitions, double min_time, double max_time, size_t save_every, bool save_improvements=false) -> SearchResult { auto time = []() { struct timeval tp; gettimeofday(&tp, NULL); return (double) tp.tv_sec + ((double)(tp.tv_usec / 1000) /1000.); }; printf("Processing firedata data\n"); double preprocessing_start = time(); auto fire_data = make_shared<FireData>(ignitions); double preprocessing_end = time(); printf("Building initial plan\n"); Plan p(configs, fire_data, TimeWindow{min_time, max_time}); printf("Planning\n"); DefaultVnsSearch vns; const double planning_start = time(); auto res = vns.search(p, 0, save_every, save_improvements); const double planning_end = time(); printf("Plan found\n"); res.planning_time = planning_end - planning_start; res.preprocessing_time = preprocessing_end - preprocessing_start; return res; }, py::arg("trajectory_configs"), py::arg("ignitions"), py::arg("min_time"), py::arg("max_time"), py::arg("save_every") = 0, py::arg("save_improvements") = false); return m.ptr(); } <commit_msg>Fix pybind11 deprecation warnings<commit_after>#include <pybind11/pybind11.h> #include <pybind11/stl.h> // for conversions between c++ and python collections #include <pybind11/numpy.h> // support for numpy arrays #include "trajectory.h" #include "raster.h" #include "visibility.h" #include "planning.h" namespace py = pybind11; /** Converts a numpy array to a vector */ template<class T> std::vector<T> as_vector(py::array_t<T, py::array::c_style | py::array::forcecast> array) { std::vector<T> data(array.size()); for(ssize_t x=0; x<array.shape(0); x++) { for(ssize_t y=0; y<array.shape(1); y++) { data[x + y*array.shape(0)] = *(array.data(x, y)); } } return data; } /** Converts a vector to a 2D numpy array. */ template<class T> py::array_t<T> as_nparray(std::vector<T> vec, size_t x_width, size_t y_height) { ASSERT(vec.size() == x_width * y_height) py::array_t<T, py::array::c_style | py::array::forcecast> array(std::vector<size_t> {x_width, y_height}); auto s_x_width = static_cast<ssize_t>(x_width); auto s_y_height = static_cast<ssize_t>(y_height); for(ssize_t x=0; x<s_x_width; x++) { for (ssize_t y = 0; y < s_y_height; y++) { *(array.mutable_data(x, y)) = vec[x + y*x_width]; } } return array; } PYBIND11_DECLARE_HOLDER_TYPE(T, std::shared_ptr<T>); PYBIND11_MODULE(uav_planning, m) { m.doc() = "Python module for UAV trajectory planning"; srand(time(0)); srand(0); py::class_<DRaster>(m, "DRaster") .def("__init__", [](DRaster& self, py::array_t<double, py::array::c_style | py::array::forcecast> arr, double x_offset, double y_offset, double cell_width) { // create a new object and sibstitute to the given self new (&self) DRaster(as_vector<double>(arr), arr.shape(0), arr.shape(1), x_offset, y_offset, cell_width); }) .def("as_numpy", [](DRaster& self) { return as_nparray<double>(self.data, self.x_width, self.y_height); }) .def_readonly("x_offset", &DRaster::x_offset) .def_readonly("y_offset", &DRaster::y_offset) .def_readonly("cell_width", &DRaster::cell_width); py::class_<LRaster>(m, "LRaster") .def("__init__", [](LRaster& self, py::array_t<long, py::array::c_style | py::array::forcecast> arr, double x_offset, double y_offset, double cell_width) { new (&self) LRaster(as_vector<long>(arr), arr.shape(0), arr.shape(1), x_offset, y_offset, cell_width); }) .def("as_numpy", [](LRaster& self) { return as_nparray<long>(self.data, self.x_width, self.y_height); }) .def_readonly("x_offset", &LRaster::x_offset) .def_readonly("y_offset", &LRaster::y_offset) .def_readonly("cell_width", &LRaster::cell_width); py::class_<TimeWindow>(m, "TimeWindow") .def(py::init<const double, const double>(), py::arg("start"), py::arg("end")) .def_readonly("start", &TimeWindow::start) .def_readonly("end", &TimeWindow::end) .def("__repr__", [](const TimeWindow &tw) { std::stringstream repr; repr << "TimeWindow(" << tw.start << ", " << tw.end << ")"; return repr.str(); } ) .def("as_tuple", [](TimeWindow &self) { return py::make_tuple(self.start, self.end); } ); py::class_<Cell>(m, "Cell") .def(py::init<const size_t, const size_t>(), py::arg("x"), py::arg("y")) .def_readonly("x", &Cell::x) .def_readonly("y", &Cell::y) .def("__repr__", [](const Cell &c) { std::stringstream repr; repr << "Cell(" << c.x << ", " << c.y << ")"; return repr.str(); } ) .def("as_tuple", [](Cell &self) { return py::make_tuple(self.x, self.y); } ); py::class_<Position>(m, "Position") .def(py::init<double, double>(), py::arg("x"), py::arg("y")) .def_readonly("x", &Position::x) .def_readonly("y", &Position::y) .def("__repr__", [](const Position &p) { std::stringstream repr; repr << "Position(" << p.x << ", " << p.y << ")"; return repr.str(); } ) .def("as_tuple", [](Position &self) { return py::make_tuple(self.x, self.y); } ); py::class_<Position3d>(m, "Position3d") .def(py::init<double, double, double>(), py::arg("x"), py::arg("y"), py::arg("z")) .def_readonly("x", &Position3d::x) .def_readonly("y", &Position3d::y) .def_readonly("z", &Position3d::z) .def("__repr__", [](const Position3d &p) { std::stringstream repr; repr << "Position3d(" << p.x << ", " << p.y << ", " << p.z << ")"; return repr.str(); } ) .def("as_tuple", [](Position3d &self) { return py::make_tuple(self.x, self.y, self.z); } ); py::class_<PositionTime>(m, "PositionTime") .def(py::init<Position, double>(), py::arg("point"), py::arg("time")) .def_readonly("pt", &PositionTime::pt) .def_readonly("y", &PositionTime::time) .def("__repr__", [](const PositionTime &p) { std::stringstream repr; repr << "PositionTime(" << p.pt.x << ", " << p.pt.y << ", " << p.time << ")"; return repr.str(); } ) .def("as_tuple", [](PositionTime &self) { return py::make_tuple(py::make_tuple(self.pt.x, self.pt.y), self.time); } ); py::class_<Position3dTime>(m, "Position3dTime") .def(py::init<Position3d, double>(), py::arg("point"), py::arg("time")) .def_readonly("pt", &Position3dTime::pt) .def_readonly("y", &Position3dTime::time) .def("__repr__", [](const Position3dTime &p) { std::stringstream repr; repr << "Position3dTime(" << p.pt.x << ", " << p.pt.y << ", " << p.pt.z << ", " << p.time << ")"; return repr.str(); } ) .def("as_tuple", [](Position3dTime &self) { return py::make_tuple(py::make_tuple(self.pt.x, self.pt.y, self.pt.z), self.time); } ); py::class_<IsochroneCluster, shared_ptr<IsochroneCluster>>(m, "IsochroneCluster") .def("__init__", [](IsochroneCluster& self, const TimeWindow& tw, vector<Cell> cell_vector) { new (&self) IsochroneCluster(tw, cell_vector); }) .def_readonly("time_window", &IsochroneCluster::time_window) .def_readonly("cells", &IsochroneCluster::cells); py::class_<FireData>(m, "FireData") .def("__init__", [](FireData& self, DRaster& ignitions) { new (&self) FireData(ignitions); }) .def_readonly("ignitions", &FireData::ignitions) .def_readonly("traversal_end", &FireData::traversal_end) .def_readonly("propagation_directions", &FireData::propagation_directions) // .def_readonly_static("isochrone_timespan", &FireData::isochrone_timespan) .def_readonly("isochrones", &FireData::isochrones); py::class_<Waypoint3d>(m, "Waypoint") .def(py::init<const double, const double, const double, const double>(), py::arg("x"), py::arg("y"), py::arg("z"), py::arg("direction")) .def_readonly("x", &Waypoint3d::x) .def_readonly("y", &Waypoint3d::y) .def_readonly("z", &Waypoint3d::z) .def_readonly("dir", &Waypoint3d::dir) .def("__repr__", &Waypoint3d::to_string); py::class_<Segment3d>(m, "Segment") .def(py::init<const Waypoint3d, const double>()) .def(py::init<const Waypoint3d, const Waypoint3d>()) .def_readonly("start", &Segment3d::start) .def_readonly("end", &Segment3d::end) .def_readonly("length", &Segment3d::length); py::class_<UAV>(m, "UAV") .def(py::init<const double, const double, const double>()) .def_readonly("min_turn_radius", &UAV::min_turn_radius) .def_readonly("max_air_speed", &UAV::max_air_speed) .def_readonly("max_pitch_angle", &UAV::max_pitch_angle) .def("travel_distance", (double (UAV::*)(const Waypoint3d &, const Waypoint3d &) const)&UAV::travel_distance, py::arg("origin"), py::arg("destination")) .def("travel_distance", (double (UAV::*)(const Waypoint &, const Waypoint &) const)&UAV::travel_distance, py::arg("origin"), py::arg("destination")) .def("travel_time", (double (UAV::*)(const Waypoint3d &, const Waypoint3d &) const)&UAV::travel_time, py::arg("origin"), py::arg("destination")) .def("travel_time", (double (UAV::*)(const Waypoint &, const Waypoint &) const)&UAV::travel_time, py::arg("origin"), py::arg("destination")); py::class_<Trajectory>(m, "Trajectory") .def(py::init<const TrajectoryConfig&>()) .def("start_time", (double (Trajectory::*)() const)&Trajectory::start_time) .def("end_time", (double (Trajectory::*)() const)&Trajectory::end_time) .def_readonly("segments", &Trajectory::traj) .def("length", &Trajectory::length) .def("duration", &Trajectory::duration) .def("as_waypoints", &Trajectory::as_waypoints) .def("sampled", &Trajectory::sampled, py::arg("step_size") = 1) .def("with_waypoint_at_end", &Trajectory::with_waypoint_at_end) .def("__repr__", &Trajectory::to_string); py::class_<TrajectoryConfig>(m, "TrajectoryConfig") .def(py::init<UAV, Waypoint3d, Waypoint3d, double, double>()) .def_readonly("uav", &TrajectoryConfig::uav) .def_readonly("max_flight_time", &TrajectoryConfig::max_flight_time) .def_static("build", [](UAV uav, double start_time, double max_flight_time) -> TrajectoryConfig { return TrajectoryConfig(uav, start_time, max_flight_time); }, "Constructor", py::arg("uav"), py::arg("start_time") = 0, py::arg("max_flight_time") = std::numeric_limits<double>::max()); py::class_<Plan>(m, "Plan") .def_readonly("trajectories", &Plan::trajectories) .def("utility", &Plan::utility) .def("duration", &Plan::duration) .def_readonly("firedata", &Plan::firedata) .def("observations", &Plan::observations); py::class_<SearchResult>(m, "SearchResult") .def("initial_plan", &SearchResult::initial) .def("final_plan", &SearchResult::final) .def_readonly("intermediate_plans", &SearchResult::intermediate_plans) .def_readonly("planning_time", &SearchResult::planning_time) .def_readonly("preprocessing_time", &SearchResult::preprocessing_time); m.def("make_plan_vns", [](UAV uav, DRaster ignitions, double min_time, double max_time, double max_flight_time, size_t save_every, bool save_improvements) -> SearchResult { auto fire_data = make_shared<FireData>(ignitions); TrajectoryConfig conf(uav, min_time, max_flight_time); Plan p(vector<TrajectoryConfig> { conf }, fire_data, TimeWindow{min_time, max_time}); DefaultVnsSearch vns; auto res = vns.search(p, 0, save_every, save_improvements); return res; }, py::arg("uav"), py::arg("ignitions"), py::arg("min_time"), py::arg("max_time"), py::arg("max_flight_time"), py::arg("save_every") = 0, py::arg("save_improvements") = false); m.def("plan_vns", [](vector<TrajectoryConfig> configs, DRaster ignitions, double min_time, double max_time, size_t save_every, bool save_improvements=false) -> SearchResult { auto time = []() { struct timeval tp; gettimeofday(&tp, NULL); return (double) tp.tv_sec + ((double)(tp.tv_usec / 1000) /1000.); }; printf("Processing firedata data\n"); double preprocessing_start = time(); auto fire_data = make_shared<FireData>(ignitions); double preprocessing_end = time(); printf("Building initial plan\n"); Plan p(configs, fire_data, TimeWindow{min_time, max_time}); printf("Planning\n"); DefaultVnsSearch vns; const double planning_start = time(); auto res = vns.search(p, 0, save_every, save_improvements); const double planning_end = time(); printf("Plan found\n"); res.planning_time = planning_end - planning_start; res.preprocessing_time = preprocessing_end - preprocessing_start; return res; }, py::arg("trajectory_configs"), py::arg("ignitions"), py::arg("min_time"), py::arg("max_time"), py::arg("save_every") = 0, py::arg("save_improvements") = false); } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: SalGtkFilePicker.hxx,v $ * * $Revision: 1.5 $ * * last change: $Author: kz $ $Date: 2005-07-12 11:59:09 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): Anil Bhatia * * ************************************************************************/ #ifndef _SALGTKFILEPICKER_HXX_ #define _SALGTKFILEPICKER_HXX_ //_______________________________________________________________________________________________________________________ // includes of other projects //_______________________________________________________________________________________________________________________ #ifndef _CPPUHELPER_COMPBASE9_HXX_ #include <cppuhelper/compbase9.hxx> #endif #ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_ #include <com/sun/star/lang/XInitialization.hpp> #endif #ifndef _COM_SUN_STAR_UI_DIALOGS_XFILEPICKERNOTIFIER_HPP_ #include <com/sun/star/ui/dialogs/XFilePickerNotifier.hpp> #endif #ifndef _COM_SUN_STAR_UI_DIALOGS_XFILTERMANAGER_HPP_ #include <com/sun/star/ui/dialogs/XFilterManager.hpp> #endif #ifndef _COM_SUN_STAR_UI_DIALOGS_XFILTERGROUPMANAGER_HPP_ #include <com/sun/star/ui/dialogs/XFilterGroupManager.hpp> #endif #ifndef _COM_SUN_STAR_UI_DIALOGS_XFILEPICKERCONTROLACCESS_HPP_ #include <com/sun/star/ui/dialogs/XFilePickerControlAccess.hpp> #endif #ifndef _COM_SUN_STAR_UI_DIALOGS_XFILEPREVIEW_HPP_ #include <com/sun/star/ui/dialogs/XFilePreview.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_STRINGPAIR_HPP_ #include <com/sun/star/beans/StringPair.hpp> #endif #ifndef _SALGTKPICKER_HXX_ #include "SalGtkPicker.hxx" #endif #include <memory> #ifndef _RTL_USTRING_H_ #include <rtl/ustring.hxx> #endif #include <list> //---------------------------------------------------------- // Implementation class for the XFilePicker Interface //---------------------------------------------------------- //---------------------------------------------------------- // forward declarations //---------------------------------------------------------- using namespace rtl; struct FilterEntry; struct ElementEntry_Impl; typedef ::std::list < FilterEntry > FilterList; typedef ::std::list < ElementEntry_Impl > ElementList; typedef ::com::sun::star::beans::StringPair UnoFilterEntry; typedef ::com::sun::star::uno::Sequence< UnoFilterEntry > UnoFilterList; // can be transported more effectively //---------------------------------------------------------- // class declaration //---------------------------------------------------------- class SalGtkFilePicker : public SalGtkPicker, public cppu::WeakComponentImplHelper9< ::com::sun::star::ui::dialogs::XFilterManager, ::com::sun::star::ui::dialogs::XFilterGroupManager, ::com::sun::star::ui::dialogs::XFilePickerControlAccess, ::com::sun::star::ui::dialogs::XFilePickerNotifier, ::com::sun::star::ui::dialogs::XFilePreview, ::com::sun::star::lang::XInitialization, ::com::sun::star::util::XCancellable, ::com::sun::star::lang::XEventListener, ::com::sun::star::lang::XServiceInfo > { public: // constructor SalGtkFilePicker( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceMgr ); //------------------------------------------------------------------------------------ // XFilePickerNotifier //------------------------------------------------------------------------------------ virtual void SAL_CALL addFilePickerListener( const ::com::sun::star::uno::Reference< ::com::sun::star::ui::dialogs::XFilePickerListener >& xListener ) throw( ::com::sun::star::uno::RuntimeException ); virtual void SAL_CALL removeFilePickerListener( const ::com::sun::star::uno::Reference< ::com::sun::star::ui::dialogs::XFilePickerListener >& xListener ) throw( ::com::sun::star::uno::RuntimeException ); //------------------------------------------------------------------------------------ // XExecutableDialog functions //------------------------------------------------------------------------------------ virtual void SAL_CALL setTitle( const ::rtl::OUString& aTitle ) throw( ::com::sun::star::uno::RuntimeException ); virtual sal_Int16 SAL_CALL execute( ) throw( ::com::sun::star::uno::RuntimeException ); //------------------------------------------------------------------------------------ // XFilePicker functions //------------------------------------------------------------------------------------ virtual void SAL_CALL setMultiSelectionMode( sal_Bool bMode ) throw( ::com::sun::star::uno::RuntimeException ); virtual void SAL_CALL setDefaultName( const ::rtl::OUString& aName ) throw( ::com::sun::star::uno::RuntimeException ); virtual void SAL_CALL setDisplayDirectory( const ::rtl::OUString& aDirectory ) throw( com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException ); virtual ::rtl::OUString SAL_CALL getDisplayDirectory( ) throw( ::com::sun::star::uno::RuntimeException ); virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getFiles( ) throw( ::com::sun::star::uno::RuntimeException ); //------------------------------------------------------------------------------------ // XFilterManager functions //------------------------------------------------------------------------------------ virtual void SAL_CALL appendFilter( const ::rtl::OUString& aTitle, const ::rtl::OUString& aFilter ) throw( ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException ); virtual void SAL_CALL setCurrentFilter( const ::rtl::OUString& aTitle ) throw( ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException ); virtual ::rtl::OUString SAL_CALL getCurrentFilter( ) throw( ::com::sun::star::uno::RuntimeException ); //------------------------------------------------------------------------------------ // XFilterGroupManager functions //------------------------------------------------------------------------------------ virtual void SAL_CALL appendFilterGroup( const ::rtl::OUString& sGroupTitle, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::StringPair >& aFilters ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException); //------------------------------------------------------------------------------------ // XFilePickerControlAccess functions //------------------------------------------------------------------------------------ virtual void SAL_CALL setValue( sal_Int16 nControlId, sal_Int16 nControlAction, const ::com::sun::star::uno::Any& aValue ) throw (::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Any SAL_CALL getValue( sal_Int16 aControlId, sal_Int16 aControlAction ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL enableControl( sal_Int16 nControlId, sal_Bool bEnable ) throw(::com::sun::star::uno::RuntimeException ); virtual void SAL_CALL setLabel( sal_Int16 nControlId, const ::rtl::OUString& aLabel ) throw (::com::sun::star::uno::RuntimeException); virtual ::rtl::OUString SAL_CALL getLabel( sal_Int16 nControlId ) throw (::com::sun::star::uno::RuntimeException); //------------------------------------------------ // XFilePreview //------------------------------------------------ virtual ::com::sun::star::uno::Sequence< sal_Int16 > SAL_CALL getSupportedImageFormats( ) throw (::com::sun::star::uno::RuntimeException); virtual sal_Int32 SAL_CALL getTargetColorDepth( ) throw (::com::sun::star::uno::RuntimeException); virtual sal_Int32 SAL_CALL getAvailableWidth( ) throw (::com::sun::star::uno::RuntimeException); virtual sal_Int32 SAL_CALL getAvailableHeight( ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setImage( sal_Int16 aImageFormat, const ::com::sun::star::uno::Any& aImage ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL setShowState( sal_Bool bShowState ) throw (::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL getShowState( ) throw (::com::sun::star::uno::RuntimeException); //------------------------------------------------ // XInitialization //------------------------------------------------ virtual void SAL_CALL initialize( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& aArguments ) throw(::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException); //------------------------------------------------ // XCancellable //------------------------------------------------ virtual void SAL_CALL cancel( ) throw( ::com::sun::star::uno::RuntimeException ); //------------------------------------------------ // XEventListener //------------------------------------------------ virtual void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& aEvent ) throw(::com::sun::star::uno::RuntimeException); //------------------------------------------------ // XServiceInfo //------------------------------------------------ virtual ::rtl::OUString SAL_CALL getImplementationName( ) throw(::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName ) throw(::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames( ) throw(::com::sun::star::uno::RuntimeException); //------------------------------------------------------------------------------------ // FilePicker Event functions //------------------------------------------------------------------------------------ void SAL_CALL fileSelectionChanged( ::com::sun::star::ui::dialogs::FilePickerEvent aEvent ); void SAL_CALL directoryChanged( ::com::sun::star::ui::dialogs::FilePickerEvent aEvent ); rtl::OUString SAL_CALL helpRequested( ::com::sun::star::ui::dialogs::FilePickerEvent aEvent ) const; void SAL_CALL controlStateChanged( ::com::sun::star::ui::dialogs::FilePickerEvent aEvent ); void SAL_CALL dialogSizeChanged( ); private: // prevent copy and assignment SalGtkFilePicker( const SalGtkFilePicker& ); SalGtkFilePicker& operator=( const SalGtkFilePicker& ); sal_Bool FilterNameExists( const ::rtl::OUString& rTitle ); sal_Bool FilterNameExists( const UnoFilterList& _rGroupedFilters ); void ensureFilterList( const ::rtl::OUString& _rInitialCurrentFilter ); // to instanciate own services ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > m_xServiceMgr; private: ::com::sun::star::uno::Reference< ::com::sun::star::ui::dialogs::XFilePickerListener > m_xListener; FilterList *m_pFilterList; GtkWidget *m_pVBox; GtkWidget *m_pFilterExpander; GtkWidget *m_pFilterView; GtkListStore *m_pFilterStore; enum { AUTOEXTENSION, PASSWORD, FILTEROPTIONS, READONLY, LINK, PREVIEW, SELECTION, TOGGLE_LAST }; GtkWidget *m_pToggles[ TOGGLE_LAST ]; bool mbToggleVisibility[TOGGLE_LAST]; bool mbToggleChecked[TOGGLE_LAST]; static const rtl::OString m_ToggleLabels[TOGGLE_LAST]; enum { PLAY, BUTTON_LAST }; GtkWidget *m_pButtons[ BUTTON_LAST ]; enum { VERSION, TEMPLATE, IMAGE_TEMPLATE, LIST_LAST }; GtkWidget *m_pHBoxs[ LIST_LAST ]; GtkWidget *m_pAligns[ LIST_LAST ]; GtkWidget *m_pLists[ LIST_LAST ]; GtkWidget *m_pListLabels[ LIST_LAST ]; bool mbListVisibility[ LIST_LAST ]; ::rtl::OUString m_aCurrentFilter; GtkWidget *getWidget( sal_Int16 nControlId, GType *pType = NULL); void SetCurFilter( const OUString& rFilter ); void SetFilters(); void implChangeType( GtkTreeSelection *selection ); int implAddFilter( const OUString& rFilter, const OUString& rType); int implAddFilterGroup( const OUString& rFilter, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::StringPair>& _rFilters ); void updateCurrentFilterFromName(const gchar* filtername); void unselect_type(); bool bVersionWidthUnset; sal_Bool mbPreviewState; gulong mHID_Preview; GtkWidget* m_pPreview; sal_Int32 m_PreviewImageWidth; sal_Int32 m_PreviewImageHeight; void InitialMapping(); void HandleSetListValue(GtkComboBox *pWidget, sal_Int16 nControlAction, const ::com::sun::star::uno::Any& rValue); ::com::sun::star::uno::Any HandleGetListValue(GtkComboBox *pWidget, sal_Int16 nControlAction) const; static void expander_changed_cb( GtkExpander *expander, SalGtkFilePicker *pobjFP ); static void preview_toggled_cb (GtkObject *cb, SalGtkFilePicker *pobjFP); static void filter_changed_cb (GtkFileChooser *file_chooser, GParamSpec *pspec, SalGtkFilePicker *pobjFP); static void type_changed_cb( GtkTreeSelection *selection, SalGtkFilePicker *pobjFP ); static void folder_changed_cb (GtkFileChooser *file_chooser, SalGtkFilePicker *pobjFP); static void selection_changed_cb (GtkFileChooser *file_chooser, SalGtkFilePicker *pobjFP); static void update_preview_cb (GtkFileChooser *file_chooser, SalGtkFilePicker *pobjFP); static void dialog_mapped_cb(GtkWidget *widget, SalGtkFilePicker *pobjFP); public: virtual ~SalGtkFilePicker(); }; /* vi:set tabstop=4 shiftwidth=4 expandtab: */ #endif // _SALGTKFILEPICKER_HXX_ <commit_msg>INTEGRATION: CWS cmcfixes16 (1.5.18); FILE MERGED 2005/08/25 12:35:02 cmc 1.5.18.1: #i53064# getCurrentFilter shouldn't update from UI until UI is executed<commit_after>/************************************************************************* * * $RCSfile: SalGtkFilePicker.hxx,v $ * * $Revision: 1.6 $ * * last change: $Author: rt $ $Date: 2005-08-30 09:06:55 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): Anil Bhatia * * ************************************************************************/ #ifndef _SALGTKFILEPICKER_HXX_ #define _SALGTKFILEPICKER_HXX_ //_______________________________________________________________________________________________________________________ // includes of other projects //_______________________________________________________________________________________________________________________ #ifndef _CPPUHELPER_COMPBASE9_HXX_ #include <cppuhelper/compbase9.hxx> #endif #ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_ #include <com/sun/star/lang/XInitialization.hpp> #endif #ifndef _COM_SUN_STAR_UI_DIALOGS_XFILEPICKERNOTIFIER_HPP_ #include <com/sun/star/ui/dialogs/XFilePickerNotifier.hpp> #endif #ifndef _COM_SUN_STAR_UI_DIALOGS_XFILTERMANAGER_HPP_ #include <com/sun/star/ui/dialogs/XFilterManager.hpp> #endif #ifndef _COM_SUN_STAR_UI_DIALOGS_XFILTERGROUPMANAGER_HPP_ #include <com/sun/star/ui/dialogs/XFilterGroupManager.hpp> #endif #ifndef _COM_SUN_STAR_UI_DIALOGS_XFILEPICKERCONTROLACCESS_HPP_ #include <com/sun/star/ui/dialogs/XFilePickerControlAccess.hpp> #endif #ifndef _COM_SUN_STAR_UI_DIALOGS_XFILEPREVIEW_HPP_ #include <com/sun/star/ui/dialogs/XFilePreview.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_STRINGPAIR_HPP_ #include <com/sun/star/beans/StringPair.hpp> #endif #ifndef _SALGTKPICKER_HXX_ #include "SalGtkPicker.hxx" #endif #include <memory> #ifndef _RTL_USTRING_H_ #include <rtl/ustring.hxx> #endif #include <list> //---------------------------------------------------------- // Implementation class for the XFilePicker Interface //---------------------------------------------------------- //---------------------------------------------------------- // forward declarations //---------------------------------------------------------- using namespace rtl; struct FilterEntry; struct ElementEntry_Impl; typedef ::std::list < FilterEntry > FilterList; typedef ::std::list < ElementEntry_Impl > ElementList; typedef ::com::sun::star::beans::StringPair UnoFilterEntry; typedef ::com::sun::star::uno::Sequence< UnoFilterEntry > UnoFilterList; // can be transported more effectively //---------------------------------------------------------- // class declaration //---------------------------------------------------------- class SalGtkFilePicker : public SalGtkPicker, public cppu::WeakComponentImplHelper9< ::com::sun::star::ui::dialogs::XFilterManager, ::com::sun::star::ui::dialogs::XFilterGroupManager, ::com::sun::star::ui::dialogs::XFilePickerControlAccess, ::com::sun::star::ui::dialogs::XFilePickerNotifier, ::com::sun::star::ui::dialogs::XFilePreview, ::com::sun::star::lang::XInitialization, ::com::sun::star::util::XCancellable, ::com::sun::star::lang::XEventListener, ::com::sun::star::lang::XServiceInfo > { public: // constructor SalGtkFilePicker( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceMgr ); //------------------------------------------------------------------------------------ // XFilePickerNotifier //------------------------------------------------------------------------------------ virtual void SAL_CALL addFilePickerListener( const ::com::sun::star::uno::Reference< ::com::sun::star::ui::dialogs::XFilePickerListener >& xListener ) throw( ::com::sun::star::uno::RuntimeException ); virtual void SAL_CALL removeFilePickerListener( const ::com::sun::star::uno::Reference< ::com::sun::star::ui::dialogs::XFilePickerListener >& xListener ) throw( ::com::sun::star::uno::RuntimeException ); //------------------------------------------------------------------------------------ // XExecutableDialog functions //------------------------------------------------------------------------------------ virtual void SAL_CALL setTitle( const ::rtl::OUString& aTitle ) throw( ::com::sun::star::uno::RuntimeException ); virtual sal_Int16 SAL_CALL execute( ) throw( ::com::sun::star::uno::RuntimeException ); //------------------------------------------------------------------------------------ // XFilePicker functions //------------------------------------------------------------------------------------ virtual void SAL_CALL setMultiSelectionMode( sal_Bool bMode ) throw( ::com::sun::star::uno::RuntimeException ); virtual void SAL_CALL setDefaultName( const ::rtl::OUString& aName ) throw( ::com::sun::star::uno::RuntimeException ); virtual void SAL_CALL setDisplayDirectory( const ::rtl::OUString& aDirectory ) throw( com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException ); virtual ::rtl::OUString SAL_CALL getDisplayDirectory( ) throw( ::com::sun::star::uno::RuntimeException ); virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getFiles( ) throw( ::com::sun::star::uno::RuntimeException ); //------------------------------------------------------------------------------------ // XFilterManager functions //------------------------------------------------------------------------------------ virtual void SAL_CALL appendFilter( const ::rtl::OUString& aTitle, const ::rtl::OUString& aFilter ) throw( ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException ); virtual void SAL_CALL setCurrentFilter( const ::rtl::OUString& aTitle ) throw( ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException ); virtual ::rtl::OUString SAL_CALL getCurrentFilter( ) throw( ::com::sun::star::uno::RuntimeException ); //------------------------------------------------------------------------------------ // XFilterGroupManager functions //------------------------------------------------------------------------------------ virtual void SAL_CALL appendFilterGroup( const ::rtl::OUString& sGroupTitle, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::StringPair >& aFilters ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException); //------------------------------------------------------------------------------------ // XFilePickerControlAccess functions //------------------------------------------------------------------------------------ virtual void SAL_CALL setValue( sal_Int16 nControlId, sal_Int16 nControlAction, const ::com::sun::star::uno::Any& aValue ) throw (::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Any SAL_CALL getValue( sal_Int16 aControlId, sal_Int16 aControlAction ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL enableControl( sal_Int16 nControlId, sal_Bool bEnable ) throw(::com::sun::star::uno::RuntimeException ); virtual void SAL_CALL setLabel( sal_Int16 nControlId, const ::rtl::OUString& aLabel ) throw (::com::sun::star::uno::RuntimeException); virtual ::rtl::OUString SAL_CALL getLabel( sal_Int16 nControlId ) throw (::com::sun::star::uno::RuntimeException); //------------------------------------------------ // XFilePreview //------------------------------------------------ virtual ::com::sun::star::uno::Sequence< sal_Int16 > SAL_CALL getSupportedImageFormats( ) throw (::com::sun::star::uno::RuntimeException); virtual sal_Int32 SAL_CALL getTargetColorDepth( ) throw (::com::sun::star::uno::RuntimeException); virtual sal_Int32 SAL_CALL getAvailableWidth( ) throw (::com::sun::star::uno::RuntimeException); virtual sal_Int32 SAL_CALL getAvailableHeight( ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setImage( sal_Int16 aImageFormat, const ::com::sun::star::uno::Any& aImage ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL setShowState( sal_Bool bShowState ) throw (::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL getShowState( ) throw (::com::sun::star::uno::RuntimeException); //------------------------------------------------ // XInitialization //------------------------------------------------ virtual void SAL_CALL initialize( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& aArguments ) throw(::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException); //------------------------------------------------ // XCancellable //------------------------------------------------ virtual void SAL_CALL cancel( ) throw( ::com::sun::star::uno::RuntimeException ); //------------------------------------------------ // XEventListener //------------------------------------------------ virtual void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& aEvent ) throw(::com::sun::star::uno::RuntimeException); //------------------------------------------------ // XServiceInfo //------------------------------------------------ virtual ::rtl::OUString SAL_CALL getImplementationName( ) throw(::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName ) throw(::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames( ) throw(::com::sun::star::uno::RuntimeException); //------------------------------------------------------------------------------------ // FilePicker Event functions //------------------------------------------------------------------------------------ void SAL_CALL fileSelectionChanged( ::com::sun::star::ui::dialogs::FilePickerEvent aEvent ); void SAL_CALL directoryChanged( ::com::sun::star::ui::dialogs::FilePickerEvent aEvent ); rtl::OUString SAL_CALL helpRequested( ::com::sun::star::ui::dialogs::FilePickerEvent aEvent ) const; void SAL_CALL controlStateChanged( ::com::sun::star::ui::dialogs::FilePickerEvent aEvent ); void SAL_CALL dialogSizeChanged( ); private: // prevent copy and assignment SalGtkFilePicker( const SalGtkFilePicker& ); SalGtkFilePicker& operator=( const SalGtkFilePicker& ); sal_Bool FilterNameExists( const ::rtl::OUString& rTitle ); sal_Bool FilterNameExists( const UnoFilterList& _rGroupedFilters ); void ensureFilterList( const ::rtl::OUString& _rInitialCurrentFilter ); // to instanciate own services ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > m_xServiceMgr; private: ::com::sun::star::uno::Reference< ::com::sun::star::ui::dialogs::XFilePickerListener > m_xListener; FilterList *m_pFilterList; GtkWidget *m_pVBox; GtkWidget *m_pFilterExpander; GtkWidget *m_pFilterView; GtkListStore *m_pFilterStore; enum { AUTOEXTENSION, PASSWORD, FILTEROPTIONS, READONLY, LINK, PREVIEW, SELECTION, TOGGLE_LAST }; GtkWidget *m_pToggles[ TOGGLE_LAST ]; bool mbToggleVisibility[TOGGLE_LAST]; bool mbToggleChecked[TOGGLE_LAST]; static const rtl::OString m_ToggleLabels[TOGGLE_LAST]; enum { PLAY, BUTTON_LAST }; GtkWidget *m_pButtons[ BUTTON_LAST ]; enum { VERSION, TEMPLATE, IMAGE_TEMPLATE, LIST_LAST }; GtkWidget *m_pHBoxs[ LIST_LAST ]; GtkWidget *m_pAligns[ LIST_LAST ]; GtkWidget *m_pLists[ LIST_LAST ]; GtkWidget *m_pListLabels[ LIST_LAST ]; bool mbListVisibility[ LIST_LAST ]; gulong mnHID_FolderChange; gulong mnHID_SelectionChange; ::rtl::OUString m_aCurrentFilter; GtkWidget *getWidget( sal_Int16 nControlId, GType *pType = NULL); void SetCurFilter( const OUString& rFilter ); void SetFilters(); void UpdateFilterfromUI(); void implChangeType( GtkTreeSelection *selection ); int implAddFilter( const OUString& rFilter, const OUString& rType); int implAddFilterGroup( const OUString& rFilter, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::StringPair>& _rFilters ); void updateCurrentFilterFromName(const gchar* filtername); void unselect_type(); bool bVersionWidthUnset; sal_Bool mbPreviewState; gulong mHID_Preview; GtkWidget* m_pPreview; sal_Int32 m_PreviewImageWidth; sal_Int32 m_PreviewImageHeight; void InitialMapping(); void HandleSetListValue(GtkComboBox *pWidget, sal_Int16 nControlAction, const ::com::sun::star::uno::Any& rValue); ::com::sun::star::uno::Any HandleGetListValue(GtkComboBox *pWidget, sal_Int16 nControlAction) const; static void expander_changed_cb( GtkExpander *expander, SalGtkFilePicker *pobjFP ); static void preview_toggled_cb (GtkObject *cb, SalGtkFilePicker *pobjFP); static void filter_changed_cb (GtkFileChooser *file_chooser, GParamSpec *pspec, SalGtkFilePicker *pobjFP); static void type_changed_cb( GtkTreeSelection *selection, SalGtkFilePicker *pobjFP ); static void folder_changed_cb (GtkFileChooser *file_chooser, SalGtkFilePicker *pobjFP); static void selection_changed_cb (GtkFileChooser *file_chooser, SalGtkFilePicker *pobjFP); static void update_preview_cb (GtkFileChooser *file_chooser, SalGtkFilePicker *pobjFP); static void dialog_mapped_cb(GtkWidget *widget, SalGtkFilePicker *pobjFP); public: virtual ~SalGtkFilePicker(); }; /* vi:set tabstop=4 shiftwidth=4 expandtab: */ #endif // _SALGTKFILEPICKER_HXX_ <|endoftext|>
<commit_before>#include "text/table.h" #include "text/cmdline.h" #include "cortex/batch.h" #include "cortex/cortex.h" #include "cortex/logger.h" #include "thread/thread.h" #include "cortex/measure.hpp" #include "cortex/minibatch.h" #include "cortex/stochastic.h" #include "cortex/accumulator.h" #include "text/concatenate.hpp" #include "cortex/tasks/task_charset.h" #include "cortex/layers/make_layers.h" using namespace nano; template < typename tvalue > static string_t stats_to_string(const nano::stats_t<tvalue>& stats) { return nano::to_string(static_cast<tvalue>(stats.avg())) + "+/-" + nano::to_string(static_cast<tvalue>(stats.stdev())) + " [" + nano::to_string(stats.min()) + ", " + nano::to_string(stats.max()) + "]"; } template < typename ttrainer > static void test_optimizer(model_t& model, const string_t& name, const string_t& basepath, nano::table_t& table, const vectors_t& x0s, const ttrainer& trainer) { nano::stats_t<scalar_t> errors; nano::stats_t<scalar_t> speeds; nano::stats_t<scalar_t> timings; log_info() << "<<< running " << name << " ..."; for (size_t i = 0; i < x0s.size(); ++ i) { const nano::timer_t timer; model.load_params(x0s[i]); const auto result = trainer(); const auto opt_state = result.optimum_state(); const auto opt_speed = nano::convergence_speed(result.optimum_states()); errors(opt_state.m_test.m_error_avg); speeds(opt_speed); timings(static_cast<scalar_t>(timer.seconds().count())); log_info() << "<<< " << name << ": " << result << ", speed = " << opt_speed << "/s."; const auto path = basepath + "-trial" + nano::to_string(i) + ".state"; const auto opt_states = result.optimum_states(); nano::save(path, opt_states); } table.append(name) << stats_to_string(errors) << stats_to_string(speeds) << stats_to_string(timings); } static void evaluate(model_t& model, const task_t& task, const size_t fold, const loss_t& loss, const criterion_t& criterion, const vectors_t& x0s, const size_t iterations, const std::vector<batch_optimizer>& batch_optimizers, const std::vector<batch_optimizer>& minibatch_optimizers, const std::vector<stoch_optimizer>& stochastic_optimizers, const string_t& basename, const string_t& basepath, nano::table_t& table) { const scalar_t epsilon = 1e-6; const size_t n_threads = thread::concurrency(); const bool verbose = true; for (auto optimizer : batch_optimizers) { const auto optname = "batch-" + nano::to_string(optimizer); test_optimizer(model, basename + optname, basepath + optname, table, x0s, [&] () { return nano::batch_train(model, task, fold, n_threads, loss, criterion, optimizer, iterations, epsilon, verbose); }); } for (auto optimizer : minibatch_optimizers) { const auto optname = "minibatch-" + nano::to_string(optimizer); test_optimizer(model, basename + optname, basepath + optname, table, x0s, [&] () { return nano::minibatch_train(model, task, fold, n_threads, loss, criterion, optimizer, iterations, epsilon, verbose); }); } for (auto optimizer : stochastic_optimizers) { const auto optname = "stochastic-" + nano::to_string(optimizer); test_optimizer(model, basename + optname, basepath + optname, table, x0s, [&] () { return nano::stochastic_train(model, task, fold, n_threads, loss, criterion, optimizer, iterations, verbose); }); } } int main(int argc, const char* argv[]) { using namespace nano; // parse the command line nano::cmdline_t cmdline("benchmark trainers"); cmdline.add("", "mlps", "use MLPs with varying number of hidden layers"); cmdline.add("", "convnets", "use convolution networks with varying number of convolution layers"); cmdline.add("", "batch", "evaluate batch optimizers"); cmdline.add("", "batch-gd", "evaluate batch optimizer GD (gradient descent)"); cmdline.add("", "batch-cgd", "evaluate batch optimizer CGD (conjugate gradient descent)"); cmdline.add("", "batch-lbfgs", "evaluate batch optimizer LBFGS"); cmdline.add("", "minibatch", "evaluate mini-batch optimizers"); cmdline.add("", "minibatch-gd", "evaluate mini-batch optimizer GD (gradient descent)"); cmdline.add("", "minibatch-cgd", "evaluate mini-batch optimizer CGD (conjugate gradient descent)"); cmdline.add("", "minibatch-lbfgs", "evaluate mini-batch optimizer LBFGS"); cmdline.add("", "stochastic", "evaluate stochastic optimizers"); cmdline.add("", "stochastic-sg", "evaluate stochastic optimizer SG (stochastic gradient)"); cmdline.add("", "stochastic-sgm", "evaluate stochastic optimizer SGM (stochastic gradient with momentum)"); cmdline.add("", "stochastic-ag", "evaluate stochastic optimizer AG (Nesterov's accelerated gradient)"); cmdline.add("", "stochastic-agfr", "evaluate stochastic optimizer AG (AG + function value restarts)"); cmdline.add("", "stochastic-aggr", "evaluate stochastic optimizer AG (AG + gradient restarts)"); cmdline.add("", "stochastic-adam", "evaluate stochastic optimizer ADAM"); cmdline.add("", "stochastic-adagrad", "evaluate stochastic optimizer ADAGRAD"); cmdline.add("", "stochastic-adadelta", "evaluate stochastic optimizer ADADELTA"); cmdline.add("", "l2n-reg", "also evaluate the l2-norm-based regularizer"); cmdline.add("", "var-reg", "also evaluate the variance-based regularizer"); cmdline.add("", "trials", "number of models to train & evaluate", "10"); cmdline.add("", "iterations", "number of iterations/epochs", "64"); cmdline.process(argc, argv); // check arguments and options const bool use_mlps = cmdline.has("mlps"); const bool use_convnets = cmdline.has("convnets"); const bool use_reg_l2n = cmdline.has("l2n-reg"); const bool use_reg_var = cmdline.has("var-reg"); const auto trials = cmdline.get<size_t>("trials"); const auto iterations = cmdline.get<size_t>("iterations"); if ( !use_mlps && !use_convnets) { cmdline.usage(); } std::vector<batch_optimizer> batch_optimizers; if (cmdline.has("batch") || cmdline.has("batch-gd")) batch_optimizers.push_back(batch_optimizer::GD); if (cmdline.has("batch") || cmdline.has("batch-cgd")) batch_optimizers.push_back(batch_optimizer::CGD); if (cmdline.has("batch") || cmdline.has("batch-lbfgs")) batch_optimizers.push_back(batch_optimizer::LBFGS); std::vector<batch_optimizer> minibatch_optimizers; if (cmdline.has("minibatch") || cmdline.has("minibatch-gd")) minibatch_optimizers.push_back(batch_optimizer::GD); if (cmdline.has("minibatch") || cmdline.has("minibatch-cgd")) minibatch_optimizers.push_back(batch_optimizer::CGD); if (cmdline.has("minibatch") || cmdline.has("minibatch-lbfgs")) minibatch_optimizers.push_back(batch_optimizer::LBFGS); std::vector<stoch_optimizer> stochastic_optimizers; if (cmdline.has("stochastic") || cmdline.has("stochastic-sg")) stochastic_optimizers.push_back(stoch_optimizer::SG); if (cmdline.has("stochastic") || cmdline.has("stochastic-sgm")) stochastic_optimizers.push_back(stoch_optimizer::SGM); if (cmdline.has("stochastic") || cmdline.has("stochastic-ag")) stochastic_optimizers.push_back(stoch_optimizer::AG); if (cmdline.has("stochastic") || cmdline.has("stochastic-agfr")) stochastic_optimizers.push_back(stoch_optimizer::AGFR); if (cmdline.has("stochastic") || cmdline.has("stochastic-aggr")) stochastic_optimizers.push_back(stoch_optimizer::AGGR); if (cmdline.has("stochastic") || cmdline.has("stochastic-adam")) stochastic_optimizers.push_back(stoch_optimizer::ADAM); if (cmdline.has("stochastic") || cmdline.has("stochastic-adagrad")) stochastic_optimizers.push_back(stoch_optimizer::ADAGRAD); if (cmdline.has("stochastic") || cmdline.has("stochastic-adadelta")) stochastic_optimizers.push_back(stoch_optimizer::ADADELTA); if ( batch_optimizers.empty() && minibatch_optimizers.empty() && stochastic_optimizers.empty()) { cmdline.usage(); } // create task const size_t rows = 16; const size_t cols = 16; const size_t count = thread::concurrency() * 32 * 20; const color_mode color = color_mode::rgb; charset_task_t task(charset::digit, color, rows, cols, count); task.load(); const size_t fold = 0; const auto outputs = task.osize(); // construct models const auto activation = "act-snorm"; const auto pooling = "pool-full"; const auto mlp0 = string_t(); const auto mlp1 = mlp0 + make_affine_layer(16, activation); const auto mlp2 = mlp1 + make_affine_layer(16, activation); const auto mlp3 = mlp2 + make_affine_layer(16, activation); const auto convnet1 = make_conv_pool_layer(16, 7, 7, 1, activation, pooling); const auto convnet2 = make_conv_pool_layer(16, 7, 7, 1, activation, pooling) + make_conv_layer(32, 5, 5, 2); const auto convnet3 = make_conv_layer(16, 7, 7, 1, activation) + make_conv_layer(32, 5, 5, 2, activation) + make_conv_layer(64, 3, 3, 4, activation); const string_t outlayer = make_output_layer(outputs); std::vector<std::pair<string_t, string_t>> networks; if (use_mlps) { networks.emplace_back(mlp0 + outlayer, "mlp0"); networks.emplace_back(mlp1 + outlayer, "mlp1"); networks.emplace_back(mlp2 + outlayer, "mlp2"); networks.emplace_back(mlp3 + outlayer, "mlp3"); } if (use_convnets) { networks.emplace_back(convnet1 + outlayer, "convnet1"); networks.emplace_back(convnet2 + outlayer, "convnet2"); networks.emplace_back(convnet3 + outlayer, "convnet3"); } const strings_t losses = { "classnll" }; //nano::get_losses().ids(); strings_t criteria; criteria.push_back("avg"); //nano::get_criteria().ids(); if (use_reg_l2n) { criteria.push_back("l2n-reg"); } if (use_reg_var) { criteria.push_back("var-reg"); } // vary the model for (const auto& net : networks) { const auto& network = net.first; const auto& netname = net.second; log_info() << "<<< running network [" << network << "] ..."; const auto model = nano::get_models().get("forward-network", network); model->resize(task, true); // generate fixed random starting points vectors_t x0s(trials); for (vector_t& x0 : x0s) { model->random_params(); model->save_params(x0); } // vary the loss for (const string_t& iloss : losses) { log_info() << "<<< running loss [" << iloss << "] ..."; const auto loss = nano::get_losses().get(iloss); nano::table_t table(netname +"-" + iloss); table.header() << "test error" << "convergence speed" << "time [sec]"; // vary the criteria for (const string_t& icriterion : criteria) { const auto criterion = nano::get_criteria().get(icriterion); const auto basename = "[" + icriterion + "] "; const auto basepath = netname + "-" + iloss + "-" + icriterion + "-"; evaluate(*model, task, fold, *loss, *criterion, x0s, iterations, batch_optimizers, minibatch_optimizers, stochastic_optimizers, basename, basepath, table); } // show results table.print(std::cout); } log_info(); } // OK log_info() << done; return EXIT_SUCCESS; } <commit_msg>revert to using bigger task for benchmarking trainers (more stable results for stochastic methods)<commit_after>#include "text/table.h" #include "text/cmdline.h" #include "cortex/batch.h" #include "cortex/cortex.h" #include "cortex/logger.h" #include "thread/thread.h" #include "cortex/measure.hpp" #include "cortex/minibatch.h" #include "cortex/stochastic.h" #include "cortex/accumulator.h" #include "text/concatenate.hpp" #include "cortex/tasks/task_charset.h" #include "cortex/layers/make_layers.h" using namespace nano; template < typename tvalue > static string_t stats_to_string(const nano::stats_t<tvalue>& stats) { return nano::to_string(static_cast<tvalue>(stats.avg())) + "+/-" + nano::to_string(static_cast<tvalue>(stats.stdev())) + " [" + nano::to_string(stats.min()) + ", " + nano::to_string(stats.max()) + "]"; } template < typename ttrainer > static void test_optimizer(model_t& model, const string_t& name, const string_t& basepath, nano::table_t& table, const vectors_t& x0s, const ttrainer& trainer) { nano::stats_t<scalar_t> errors; nano::stats_t<scalar_t> speeds; nano::stats_t<scalar_t> timings; log_info() << "<<< running " << name << " ..."; for (size_t i = 0; i < x0s.size(); ++ i) { const nano::timer_t timer; model.load_params(x0s[i]); const auto result = trainer(); const auto opt_state = result.optimum_state(); const auto opt_speed = nano::convergence_speed(result.optimum_states()); errors(opt_state.m_test.m_error_avg); speeds(opt_speed); timings(static_cast<scalar_t>(timer.seconds().count())); log_info() << "<<< " << name << ": " << result << ", speed = " << opt_speed << "/s."; const auto path = basepath + "-trial" + nano::to_string(i) + ".state"; const auto opt_states = result.optimum_states(); nano::save(path, opt_states); } table.append(name) << stats_to_string(errors) << stats_to_string(speeds) << stats_to_string(timings); } static void evaluate(model_t& model, const task_t& task, const size_t fold, const loss_t& loss, const criterion_t& criterion, const vectors_t& x0s, const size_t iterations, const std::vector<batch_optimizer>& batch_optimizers, const std::vector<batch_optimizer>& minibatch_optimizers, const std::vector<stoch_optimizer>& stochastic_optimizers, const string_t& basename, const string_t& basepath, nano::table_t& table) { const scalar_t epsilon = 1e-6; const size_t n_threads = thread::concurrency(); const bool verbose = true; for (auto optimizer : batch_optimizers) { const auto optname = "batch-" + nano::to_string(optimizer); test_optimizer(model, basename + optname, basepath + optname, table, x0s, [&] () { return nano::batch_train(model, task, fold, n_threads, loss, criterion, optimizer, iterations, epsilon, verbose); }); } for (auto optimizer : minibatch_optimizers) { const auto optname = "minibatch-" + nano::to_string(optimizer); test_optimizer(model, basename + optname, basepath + optname, table, x0s, [&] () { return nano::minibatch_train(model, task, fold, n_threads, loss, criterion, optimizer, iterations, epsilon, verbose); }); } for (auto optimizer : stochastic_optimizers) { const auto optname = "stochastic-" + nano::to_string(optimizer); test_optimizer(model, basename + optname, basepath + optname, table, x0s, [&] () { return nano::stochastic_train(model, task, fold, n_threads, loss, criterion, optimizer, iterations, verbose); }); } } int main(int argc, const char* argv[]) { using namespace nano; // parse the command line nano::cmdline_t cmdline("benchmark trainers"); cmdline.add("", "mlps", "use MLPs with varying number of hidden layers"); cmdline.add("", "convnets", "use convolution networks with varying number of convolution layers"); cmdline.add("", "batch", "evaluate batch optimizers"); cmdline.add("", "batch-gd", "evaluate batch optimizer GD (gradient descent)"); cmdline.add("", "batch-cgd", "evaluate batch optimizer CGD (conjugate gradient descent)"); cmdline.add("", "batch-lbfgs", "evaluate batch optimizer LBFGS"); cmdline.add("", "minibatch", "evaluate mini-batch optimizers"); cmdline.add("", "minibatch-gd", "evaluate mini-batch optimizer GD (gradient descent)"); cmdline.add("", "minibatch-cgd", "evaluate mini-batch optimizer CGD (conjugate gradient descent)"); cmdline.add("", "minibatch-lbfgs", "evaluate mini-batch optimizer LBFGS"); cmdline.add("", "stochastic", "evaluate stochastic optimizers"); cmdline.add("", "stochastic-sg", "evaluate stochastic optimizer SG (stochastic gradient)"); cmdline.add("", "stochastic-sgm", "evaluate stochastic optimizer SGM (stochastic gradient with momentum)"); cmdline.add("", "stochastic-ag", "evaluate stochastic optimizer AG (Nesterov's accelerated gradient)"); cmdline.add("", "stochastic-agfr", "evaluate stochastic optimizer AG (AG + function value restarts)"); cmdline.add("", "stochastic-aggr", "evaluate stochastic optimizer AG (AG + gradient restarts)"); cmdline.add("", "stochastic-adam", "evaluate stochastic optimizer ADAM"); cmdline.add("", "stochastic-adagrad", "evaluate stochastic optimizer ADAGRAD"); cmdline.add("", "stochastic-adadelta", "evaluate stochastic optimizer ADADELTA"); cmdline.add("", "l2n-reg", "also evaluate the l2-norm-based regularizer"); cmdline.add("", "var-reg", "also evaluate the variance-based regularizer"); cmdline.add("", "trials", "number of models to train & evaluate", "10"); cmdline.add("", "iterations", "number of iterations/epochs", "64"); cmdline.process(argc, argv); // check arguments and options const bool use_mlps = cmdline.has("mlps"); const bool use_convnets = cmdline.has("convnets"); const bool use_reg_l2n = cmdline.has("l2n-reg"); const bool use_reg_var = cmdline.has("var-reg"); const auto trials = cmdline.get<size_t>("trials"); const auto iterations = cmdline.get<size_t>("iterations"); if ( !use_mlps && !use_convnets) { cmdline.usage(); } std::vector<batch_optimizer> batch_optimizers; if (cmdline.has("batch") || cmdline.has("batch-gd")) batch_optimizers.push_back(batch_optimizer::GD); if (cmdline.has("batch") || cmdline.has("batch-cgd")) batch_optimizers.push_back(batch_optimizer::CGD); if (cmdline.has("batch") || cmdline.has("batch-lbfgs")) batch_optimizers.push_back(batch_optimizer::LBFGS); std::vector<batch_optimizer> minibatch_optimizers; if (cmdline.has("minibatch") || cmdline.has("minibatch-gd")) minibatch_optimizers.push_back(batch_optimizer::GD); if (cmdline.has("minibatch") || cmdline.has("minibatch-cgd")) minibatch_optimizers.push_back(batch_optimizer::CGD); if (cmdline.has("minibatch") || cmdline.has("minibatch-lbfgs")) minibatch_optimizers.push_back(batch_optimizer::LBFGS); std::vector<stoch_optimizer> stochastic_optimizers; if (cmdline.has("stochastic") || cmdline.has("stochastic-sg")) stochastic_optimizers.push_back(stoch_optimizer::SG); if (cmdline.has("stochastic") || cmdline.has("stochastic-sgm")) stochastic_optimizers.push_back(stoch_optimizer::SGM); if (cmdline.has("stochastic") || cmdline.has("stochastic-ag")) stochastic_optimizers.push_back(stoch_optimizer::AG); if (cmdline.has("stochastic") || cmdline.has("stochastic-agfr")) stochastic_optimizers.push_back(stoch_optimizer::AGFR); if (cmdline.has("stochastic") || cmdline.has("stochastic-aggr")) stochastic_optimizers.push_back(stoch_optimizer::AGGR); if (cmdline.has("stochastic") || cmdline.has("stochastic-adam")) stochastic_optimizers.push_back(stoch_optimizer::ADAM); if (cmdline.has("stochastic") || cmdline.has("stochastic-adagrad")) stochastic_optimizers.push_back(stoch_optimizer::ADAGRAD); if (cmdline.has("stochastic") || cmdline.has("stochastic-adadelta")) stochastic_optimizers.push_back(stoch_optimizer::ADADELTA); if ( batch_optimizers.empty() && minibatch_optimizers.empty() && stochastic_optimizers.empty()) { cmdline.usage(); } // create task const size_t rows = 16; const size_t cols = 16; const size_t count = thread::concurrency() * 32 * 100; const color_mode color = color_mode::rgb; charset_task_t task(charset::digit, color, rows, cols, count); task.load(); const size_t fold = 0; const auto outputs = task.osize(); // construct models const auto activation = "act-snorm"; const auto pooling = "pool-full"; const auto mlp0 = string_t(); const auto mlp1 = mlp0 + make_affine_layer(16, activation); const auto mlp2 = mlp1 + make_affine_layer(16, activation); const auto mlp3 = mlp2 + make_affine_layer(16, activation); const auto convnet1 = make_conv_pool_layer(16, 7, 7, 1, activation, pooling); const auto convnet2 = make_conv_pool_layer(16, 7, 7, 1, activation, pooling) + make_conv_layer(32, 5, 5, 2); const auto convnet3 = make_conv_layer(16, 7, 7, 1, activation) + make_conv_layer(32, 5, 5, 2, activation) + make_conv_layer(64, 3, 3, 4, activation); const string_t outlayer = make_output_layer(outputs); std::vector<std::pair<string_t, string_t>> networks; if (use_mlps) { networks.emplace_back(mlp0 + outlayer, "mlp0"); networks.emplace_back(mlp1 + outlayer, "mlp1"); networks.emplace_back(mlp2 + outlayer, "mlp2"); networks.emplace_back(mlp3 + outlayer, "mlp3"); } if (use_convnets) { networks.emplace_back(convnet1 + outlayer, "convnet1"); networks.emplace_back(convnet2 + outlayer, "convnet2"); networks.emplace_back(convnet3 + outlayer, "convnet3"); } const strings_t losses = { "classnll" }; //nano::get_losses().ids(); strings_t criteria; criteria.push_back("avg"); //nano::get_criteria().ids(); if (use_reg_l2n) { criteria.push_back("l2n-reg"); } if (use_reg_var) { criteria.push_back("var-reg"); } // vary the model for (const auto& net : networks) { const auto& network = net.first; const auto& netname = net.second; log_info() << "<<< running network [" << network << "] ..."; const auto model = nano::get_models().get("forward-network", network); model->resize(task, true); // generate fixed random starting points vectors_t x0s(trials); for (vector_t& x0 : x0s) { model->random_params(); model->save_params(x0); } // vary the loss for (const string_t& iloss : losses) { log_info() << "<<< running loss [" << iloss << "] ..."; const auto loss = nano::get_losses().get(iloss); nano::table_t table(netname +"-" + iloss); table.header() << "test error" << "convergence speed" << "time [sec]"; // vary the criteria for (const string_t& icriterion : criteria) { const auto criterion = nano::get_criteria().get(icriterion); const auto basename = "[" + icriterion + "] "; const auto basepath = netname + "-" + iloss + "-" + icriterion + "-"; evaluate(*model, task, fold, *loss, *criterion, x0s, iterations, batch_optimizers, minibatch_optimizers, stochastic_optimizers, basename, basepath, table); } // show results table.print(std::cout); } log_info(); } // OK log_info() << done; return EXIT_SUCCESS; } <|endoftext|>
<commit_before><commit_msg>fdo#74366# Determining bMail was accidentally inverted<commit_after><|endoftext|>
<commit_before><commit_msg>coverity#703936 Unchecked return value<commit_after><|endoftext|>
<commit_before>#include "cvd/connected_components.h" #include <climits> #include <algorithm> using namespace std; namespace CVD{ static unsigned int root_of(const vector<unsigned int>& parents, unsigned int n) { while(n != parents[n]) n = parents[n]; return n; } struct CompareFistIntLessThan { bool operator()(const pair<int, int>& p1, const pair<int, int>& p2) { return p1.first < p2.first; } }; void connected_components(const vector<ImageRef>& v, vector<vector<ImageRef> >& r) { int current_label = -1; //This stores the initial labelling //of each pixel. vector<vector<ImageRef> > segments; r.clear(); if(v.size() == 0) return; //This stores the connectivity graph, where //each element stores its parent. A node storing //its own parent is a root node. vector<unsigned int> parents; //This stores the horizontal position and label of the points in the row //above. //There are several choices, map<int, int> can map a position to a label, //as can a vector<int> (using a dense representation). An ordered vector<int, int> //is equivalent to a map, but much faster, since allocation is much easier, and //points are always entered in order, so insertion is constant time. //vector<int, int> is slightly slower than vector<int> on some images, but //faster on others, especially those where objects are sparse, but rows are //not. vector<pair<int, int> > row_above, row_curent; vector<pair<int, int> >::iterator begin; int prev_row=INT_MIN, prev_x = INT_MIN; for(unsigned int i=0; i < v.size(); i++) { ImageRef pos = v[i]; if(pos.y != prev_row) { row_above.swap(row_curent); row_curent.clear(); if(pos.y-1 > prev_row) { row_above.clear(); } //Put in a sentinal value to avoid some tests. row_above.push_back(make_pair(INT_MAX, -1)); begin = row_above.begin(); } //Look to see if there is a point above (4-way connectivity) //8 way would look above above-left and above-right int above_label=-1; //Check for contiguous regions first. if(begin->first == pos.x) { above_label = begin->second; begin++; } else { vector<pair<int, int> >::iterator above; above = lower_bound(begin, row_above.end(), make_pair(pos.x, 0), CompareFistIntLessThan()); if(above->first == pos.x) { above_label = above->second; //There is no point searching from the beginning next time. We may //as well search from one past the current point. begin = above+1; } else begin = above; } //If there is nothing above or to the left, //then create a new label and corresponding segment. if(above_label == -1 && prev_x != pos.x-1) { parents.resize(parents.size()+1); current_label = parents.size()-1; parents[current_label] = current_label; segments.resize(segments.size() + 1); } else if(above_label != -1 && above_label != current_label) { //Parent is different, so take its label. //update the chain to the left if it exists. if(prev_x == pos.x - 1) current_label = parents[current_label] = root_of(parents, above_label); else current_label = root_of(parents, above_label); } segments[current_label].push_back(pos); row_curent.push_back(make_pair(pos.x, current_label)); prev_row = v[i].y; prev_x = v[i].x; } //Concatenate all the connected segments. vector<unsigned int> components; for(unsigned int i=0; i < parents.size(); i++) { //Flatten parents[i] = root_of(parents, i); //Record the roots if(i == parents[i]) components.push_back(i); else { //Or append points on to the root segment. copy(segments[i].begin(), segments[i].end(), back_inserter<vector<ImageRef> >(segments[parents[i]])); } } r.clear(); r.resize(components.size()); //Save all the root segments for(unsigned int i=0; i < components.size(); i++) r[i].swap(segments[components[i]]); } } <commit_msg>Fixed bug in connected_components where diagonal components are erroneously if position of the first point on row N is just to the right of the last point on row N-1.<commit_after>#include "cvd/connected_components.h" #include <climits> #include <algorithm> using namespace std; namespace CVD{ static unsigned int root_of(const vector<unsigned int>& parents, unsigned int n) { while(n != parents[n]) n = parents[n]; return n; } struct CompareFistIntLessThan { bool operator()(const pair<int, int>& p1, const pair<int, int>& p2) { return p1.first < p2.first; } }; void connected_components(const vector<ImageRef>& v, vector<vector<ImageRef> >& r) { int current_label = -1; //This stores the initial labelling //of each pixel. vector<vector<ImageRef> > segments; r.clear(); if(v.size() == 0) return; //This stores the connectivity graph, where //each element stores its parent. A node storing //its own parent is a root node. vector<unsigned int> parents; //This stores the horizontal position and label of the points in the row //above. //There are several choices, map<int, int> can map a position to a label, //as can a vector<int> (using a dense representation). An ordered vector<int, int> //is equivalent to a map, but much faster, since allocation is much easier, and //points are always entered in order, so insertion is constant time. //vector<int, int> is slightly slower than vector<int> on some images, but //faster on others, especially those where objects are sparse, but rows are //not. vector<pair<int, int> > row_above, row_curent; vector<pair<int, int> >::iterator begin; int prev_row=INT_MIN, prev_x = INT_MIN; for(unsigned int i=0; i < v.size(); i++) { ImageRef pos = v[i]; if(pos.y != prev_row) { prev_x=INT_MIN; row_above.swap(row_curent); row_curent.clear(); if(pos.y-1 > prev_row) { row_above.clear(); } //Put in a sentinal value to avoid some tests. row_above.push_back(make_pair(INT_MAX, -1)); begin = row_above.begin(); } //Look to see if there is a point above (4-way connectivity) //8 way would look above above-left and above-right int above_label=-1; //Check for contiguous regions first. if(begin->first == pos.x) { above_label = begin->second; begin++; } else { vector<pair<int, int> >::iterator above; above = lower_bound(begin, row_above.end(), make_pair(pos.x, 0), CompareFistIntLessThan()); if(above->first == pos.x) { above_label = above->second; //There is no point searching from the beginning next time. We may //as well search from one past the current point. begin = above+1; } else begin = above; } //If there is nothing above or to the left, //then create a new label and corresponding segment. if(above_label == -1 && prev_x != pos.x-1) { parents.resize(parents.size()+1); current_label = parents.size()-1; parents[current_label] = current_label; segments.resize(segments.size() + 1); } else if(above_label != -1 && above_label != current_label) { //Parent is different, so take its label. //update the chain to the left if it exists. if(prev_x == pos.x - 1) current_label = parents[current_label] = root_of(parents, above_label); else current_label = root_of(parents, above_label); } segments[current_label].push_back(pos); row_curent.push_back(make_pair(pos.x, current_label)); prev_row = v[i].y; prev_x = v[i].x; } //Concatenate all the connected segments. vector<unsigned int> components; for(unsigned int i=0; i < parents.size(); i++) { //Flatten parents[i] = root_of(parents, i); //Record the roots if(i == parents[i]) components.push_back(i); else { //Or append points on to the root segment. copy(segments[i].begin(), segments[i].end(), back_inserter<vector<ImageRef> >(segments[parents[i]])); } } r.clear(); r.resize(components.size()); //Save all the root segments for(unsigned int i=0; i < components.size(); i++) r[i].swap(segments[components[i]]); } } <|endoftext|>