text
stringlengths
54
60.6k
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: abpfinalpage.hxx,v $ * * $Revision: 1.5 $ * * last change: $Author: rt $ $Date: 2005-09-08 19:02: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 * ************************************************************************/ #ifndef EXTENSIONS_ABP_ABPFINALPAGE_HXX #define EXTENSIONS_ABP_ABPFINALPAGE_HXX #ifndef EXTENSIONS_ABP_ABSPAGE_HXX #include "abspage.hxx" #endif #ifndef _SV_EDIT_HXX #include <vcl/edit.hxx> #endif #ifndef EXTENSIONS_ABP_ABPTYPES_HXX #include "abptypes.hxx" #endif #ifndef SVTOOLS_URLCONTROL_HXX #include <svtools/urlcontrol.hxx> #endif //......................................................................... namespace abp { //......................................................................... //===================================================================== //= FinalPage //===================================================================== class FinalPage : public AddressBookSourcePage { protected: FixedText m_aExplanation; FixedText m_aLocationLabel; ::svt::OFileURLControl m_aLocation; PushButton m_aBrowse; CheckBox m_aRegisterName; FixedText m_aNameLabel; Edit m_aName; FixedText m_aDuplicateNameError; StringBag m_aInvalidDataSourceNames; sal_Bool m_bCheckFileName; public: FinalPage( OAddessBookSourcePilot* _pParent ); protected: // OWizardPage overridables virtual void initializePage(); virtual sal_Bool commitPage(COMMIT_REASON _eReason); // TabDialog overridables virtual void ActivatePage(); virtual void DeactivatePage(); // OImportPage overridables virtual sal_Bool determineNextButtonState(); private: DECL_LINK( OnNameModified, Edit* ); DECL_LINK( OnBrowse, PushButton* ); DECL_LINK( OnRegister, CheckBox* ); sal_Bool isValidName() const; void implCheckName(); void setFields(); }; //......................................................................... } // namespace abp //......................................................................... #endif // EXTENSIONS_ABP_ABPFINALPAGE_HXX <commit_msg>INTEGRATION: CWS odbmacros2 (1.5.424); FILE MERGED 2008/02/11 11:14:55 fs 1.5.424.3: IWizardPage is COMMIT_REASON is deprecated - replace usages with CommitPageReason, while I have an svtools-incompatible CWS 2008/01/30 13:20:59 fs 1.5.424.2: #i49133# outsourced the handling of the location of the new database to a dedicated class (::svx::DatabaseLocationInputController) 2008/01/15 09:52:42 fs 1.5.424.1: some re-factoring of OWizardMachine, RoadmapWizard and derived classes, to prepare the migration UI for #i49133#<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: abpfinalpage.hxx,v $ * * $Revision: 1.6 $ * * last change: $Author: kz $ $Date: 2008-03-06 18:35:15 $ * * 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_ABPFINALPAGE_HXX #define EXTENSIONS_ABP_ABPFINALPAGE_HXX #include "abspage.hxx" #include "abptypes.hxx" #include <svtools/urlcontrol.hxx> #include <svx/databaselocationinput.hxx> #include <vcl/edit.hxx> //......................................................................... namespace abp { //......................................................................... //===================================================================== //= FinalPage //===================================================================== class FinalPage : public AddressBookSourcePage { protected: FixedText m_aExplanation; FixedText m_aLocationLabel; ::svt::OFileURLControl m_aLocation; PushButton m_aBrowse; CheckBox m_aRegisterName; FixedText m_aNameLabel; Edit m_aName; FixedText m_aDuplicateNameError; ::svx::DatabaseLocationInputController m_aLocationController; StringBag m_aInvalidDataSourceNames; public: FinalPage( OAddessBookSourcePilot* _pParent ); protected: // OWizardPage overridables virtual void initializePage(); virtual sal_Bool commitPage( CommitPageReason _eReason ); // TabDialog overridables virtual void ActivatePage(); virtual void DeactivatePage(); // OImportPage overridables virtual bool canAdvance() const; private: DECL_LINK( OnNameModified, Edit* ); DECL_LINK( OnRegister, CheckBox* ); sal_Bool isValidName() const; void implCheckName(); void setFields(); }; //......................................................................... } // namespace abp //......................................................................... #endif // EXTENSIONS_ABP_ABPFINALPAGE_HXX <|endoftext|>
<commit_before>/************************************************************************* * Copyright (C) 2011-2016 by Paul-Louis Ageneau * * paul-louis (at) ageneau (dot) org * * * * This file is part of Plateform. * * * * Plateform 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. * * * * Plateform 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 Plateform. * * If not, see <http://www.gnu.org/licenses/>. * *************************************************************************/ #ifndef PLA_ALARM_H #define PLA_ALARM_H #include <thread> #include <mutex> #include <condition_variable> #include <future> #include <functional> #include <stdexcept> namespace pla { class Alarm { public: using clock = std::chrono::steady_clock; typedef std::chrono::duration<double> duration; typedef std::chrono::time_point<clock, duration> time_point; Alarm(void); template<class F, class... Args> Alarm(F&& f, Args&&... args); ~Alarm(void); template<class F, class... Args> auto set(F&& f, Args&&... args) -> std::future<typename std::result_of<F(Args...)>::type>; template<class F, class... Args> auto schedule(time_point time, F&& f, Args&&... args) -> std::future<typename std::result_of<F(Args...)>::type>; template<class F, class... Args> auto schedule(duration d, F&& f, Args&&... args) -> std::future<typename std::result_of<F(Args...)>::type>; void schedule(time_point time); void schedule(duration d); void cancel(void); void join(void); private: std::mutex mutex; std::condition_variable condition; std::thread thread; std::function<void()> function; time_point time; bool stop; }; inline Alarm::Alarm(void) : time(time_point::min()), stop(false) { this->thread = std::thread([this]() { while(true) { std::unique_lock<std::mutex> lock(mutex); if(this->time == time_point::min()) { if(this->stop) break; this->condition.wait(lock); } if(this->time > clock::now()) { this->condition.wait_until(lock, this->time); } else { this->time = time_point::min(); if(this->function) { std::function<void()> f = this->function; lock.unlock(); f(); } } } }); } template<class F, class... Args> Alarm::Alarm(F&& f, Args&&... args) : Alarm() { set(std::forward<F>(f), std::forward<Args>(args)...); } inline Alarm::~Alarm(void) { join(); } template<class F, class... Args> auto Alarm::set(F&& f, Args&&... args) -> std::future<typename std::result_of<F(Args...)>::type> { using type = typename std::result_of<F(Args...)>::type; auto task = std::make_shared<std::packaged_task<type()> >(std::bind(std::forward<F>(f), std::forward<Args>(args)...)); std::future<type> result = task->get_future(); { std::unique_lock<std::mutex> lock(mutex); this->function = [task]() { (*task)(); task->reset(); }; } return result; } template<class F, class... Args> auto Alarm::schedule(time_point time, F&& f, Args&&... args) -> std::future<typename std::result_of<F(Args...)>::type> { using type = typename std::result_of<F(Args...)>::type; auto task = std::make_shared<std::packaged_task<type()> >(std::bind(std::forward<F>(f), std::forward<Args>(args)...)); std::future<type> result = task->get_future(); { std::unique_lock<std::mutex> lock(mutex); if(this->stop) throw std::runtime_error("schedule on stopped Alarm"); this->time = time; this->function = [task]() { (*task)(); task->reset(); }; } condition.notify_all(); return result; } template<class F, class... Args> auto Alarm::schedule(duration d, F&& f, Args&&... args) -> std::future<typename std::result_of<F(Args...)>::type> { return schedule(clock::now() + d, std::forward<F>(f), std::forward<Args>(args)...); } inline void Alarm::schedule(time_point time) { { std::unique_lock<std::mutex> lock(mutex); if(this->stop) throw std::runtime_error("reschedule on stopped Alarm"); this->time = time; } condition.notify_all(); } inline void Alarm::schedule(duration d) { schedule(clock::now() + d); } inline void Alarm::cancel(void) { { std::unique_lock<std::mutex> lock(mutex); this->time = time_point::min(); } condition.notify_all(); } inline void Alarm::join(void) { { std::unique_lock<std::mutex> lock(mutex); this->stop = true; } condition.notify_all(); if(thread.get_id() == std::this_thread::get_id()) thread.detach(); else if(thread.joinable()) thread.join(); } } #endif <commit_msg>Properly handling Alarm autodeletion<commit_after>/************************************************************************* * Copyright (C) 2011-2016 by Paul-Louis Ageneau * * paul-louis (at) ageneau (dot) org * * * * This file is part of Plateform. * * * * Plateform 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. * * * * Plateform 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 Plateform. * * If not, see <http://www.gnu.org/licenses/>. * *************************************************************************/ #ifndef PLA_ALARM_H #define PLA_ALARM_H #include <thread> #include <mutex> #include <condition_variable> #include <future> #include <functional> #include <stdexcept> namespace pla { class Alarm { public: using clock = std::chrono::steady_clock; typedef std::chrono::duration<double> duration; typedef std::chrono::time_point<clock, duration> time_point; Alarm(void); template<class F, class... Args> Alarm(F&& f, Args&&... args); ~Alarm(void); template<class F, class... Args> auto set(F&& f, Args&&... args) -> std::future<typename std::result_of<F(Args...)>::type>; template<class F, class... Args> auto schedule(time_point time, F&& f, Args&&... args) -> std::future<typename std::result_of<F(Args...)>::type>; template<class F, class... Args> auto schedule(duration d, F&& f, Args&&... args) -> std::future<typename std::result_of<F(Args...)>::type>; void schedule(time_point time); void schedule(duration d); void cancel(void); void join(void); private: std::mutex mutex; std::condition_variable condition; std::thread thread; std::function<void()> function; time_point time; bool stop; static thread_local bool AutoDeleted; }; template<class F, class... Args> Alarm::Alarm(F&& f, Args&&... args) : Alarm() { set(std::forward<F>(f), std::forward<Args>(args)...); } template<class F, class... Args> auto Alarm::set(F&& f, Args&&... args) -> std::future<typename std::result_of<F(Args...)>::type> { using type = typename std::result_of<F(Args...)>::type; auto task = std::make_shared<std::packaged_task<type()> >(std::bind(std::forward<F>(f), std::forward<Args>(args)...)); std::future<type> result = task->get_future(); { std::unique_lock<std::mutex> lock(mutex); this->function = [task]() { (*task)(); task->reset(); }; } return result; } template<class F, class... Args> auto Alarm::schedule(time_point time, F&& f, Args&&... args) -> std::future<typename std::result_of<F(Args...)>::type> { using type = typename std::result_of<F(Args...)>::type; auto task = std::make_shared<std::packaged_task<type()> >(std::bind(std::forward<F>(f), std::forward<Args>(args)...)); std::future<type> result = task->get_future(); { std::unique_lock<std::mutex> lock(mutex); if(this->stop) throw std::runtime_error("schedule on stopped Alarm"); this->time = time; this->function = [task]() { (*task)(); task->reset(); }; } condition.notify_all(); return result; } template<class F, class... Args> auto Alarm::schedule(duration d, F&& f, Args&&... args) -> std::future<typename std::result_of<F(Args...)>::type> { return schedule(clock::now() + d, std::forward<F>(f), std::forward<Args>(args)...); } } #endif <|endoftext|>
<commit_before>#include "blackmagicsdk_video_source.h" #include "deck_link_display_mode_detector.h" #include <chrono> namespace gg { VideoSourceBlackmagicSDK::VideoSourceBlackmagicSDK() : IVideoSource() , _frame_rate(0.0) , _video_buffer(nullptr) , _video_buffer_length(0) , _cols(0) , _rows(0) , _buffer_video_frame(VideoFrame(UYVY)) , _running(false) { // nop } VideoSourceBlackmagicSDK::VideoSourceBlackmagicSDK(size_t deck_link_index, ColourSpace colour) : IVideoSource(colour) , _frame_rate(0.0) , _video_buffer(nullptr) , _video_buffer_length(0) , _cols(0) , _rows(0) , _buffer_video_frame(VideoFrame(colour, false)) // TODO manage data? , _deck_link(nullptr) , _deck_link_input(nullptr) , _video_input_flags(bmdVideoInputFlagDefault | bmdVideoInputDualStream3D) , _12_bit_rgb_to_bgra_converter(nullptr) , _bgra_frame_buffers{nullptr, nullptr} , _running(false) { // Pixel format, i.e. colour space BMDPixelFormat pixel_format; switch(_colour) { case UYVY: pixel_format = bmdFormat8BitYUV; break; case BGRA: // We currently only support BGRA with DeckLink 4K Extreme 12G, // and that card supports only this YUV format: pixel_format = bmdFormat10BitYUV; break; case I420: default: bail("BlackmagicSDK video source supports only UYVY and BGRA colour spaces"); } // Get an iterator through the available DeckLink ports IDeckLinkIterator * deck_link_iterator = CreateDeckLinkIteratorInstance(); if (deck_link_iterator == nullptr) bail("DeckLink drivers do not appear to be installed"); HRESULT res; // Get the desired DeckLink index (port) int idx = deck_link_index; while ((res = deck_link_iterator->Next(&_deck_link)) == S_OK) { if (idx == 0) break; --idx; _deck_link->Release(); } if (deck_link_iterator != nullptr) deck_link_iterator->Release(); // No glory: release everything and throw exception if (res != S_OK or _deck_link == nullptr) bail( std::string("Could not get DeckLink device ").append(std::to_string(deck_link_index)) ); // Get the input interface of connected DeckLink port res = _deck_link->QueryInterface(IID_IDeckLinkInput, reinterpret_cast<void **>(&_deck_link_input)); // No glory: release everything and throw exception if (res != S_OK) bail("Could not get the Blackmagic DeckLink input interface"); // Set the input format (i.e. display mode) BMDDisplayMode display_mode; BMDFrameFlags frame_flags; std::string error_msg = ""; size_t cols = 0, rows = 0; if (not detect_input_format(pixel_format, _video_input_flags, display_mode, _frame_rate, cols, rows, frame_flags, error_msg)) { _video_input_flags ^= bmdVideoInputDualStream3D; if (not detect_input_format(pixel_format, _video_input_flags, display_mode, _frame_rate, cols, rows, frame_flags, error_msg)) bail(error_msg); } // Get a post-capture converter if necessary if (_colour == BGRA) { _12_bit_rgb_to_bgra_converter = CreateVideoConversionInstance(); if (_12_bit_rgb_to_bgra_converter == nullptr) bail("Could not create colour converter for Blackmagic source"); } // Set this object (IDeckLinkInputCallback instance) as callback res = _deck_link_input->SetCallback(this); // No glory: release everything and throw exception if (res != S_OK) bail("Could not set the callback of Blackmagic DeckLink device"); // Enable video input res = _deck_link_input->EnableVideoInput(display_mode, pixel_format, _video_input_flags); // No glory if (res != S_OK) bail("Could not enable video input of Blackmagic DeckLink device"); // Start streaming _running = true; res = _deck_link_input->StartStreams(); // No glory: release everything and throw exception if (res != S_OK) { _running = false; bail("Could not start streaming from the Blackmagic DeckLink device"); } } VideoSourceBlackmagicSDK::~VideoSourceBlackmagicSDK() { { // Artificial scope for data lock // Make sure streamer thread not trying to access buffer std::lock_guard<std::mutex> data_lock_guard(_data_lock); _running = false; } // Stop streaming and disable enabled inputs _deck_link_input->SetCallback(nullptr); _deck_link_input->StopStreams(); _deck_link_input->DisableVideoInput(); // Release DeckLink members release_deck_link(); } bool VideoSourceBlackmagicSDK::get_frame_dimensions(int & width, int & height) { // Make sure only this thread is accessing the cols and rows members now std::lock_guard<std::mutex> data_lock_guard(_data_lock); if (_cols <= 0 or _rows <= 0) return false; width = _cols; height = _rows; return true; } bool VideoSourceBlackmagicSDK::get_frame(VideoFrame & frame) { if (frame.colour() != _colour) return false; // Make sure only this thread is accessing the video frame data now std::lock_guard<std::mutex> data_lock_guard(_data_lock); if (_video_buffer_length > 0 and _cols > 0 and _rows > 0) { frame.init_from_specs(_video_buffer, _video_buffer_length, _cols, _rows); return true; } else return false; } double VideoSourceBlackmagicSDK::get_frame_rate() { return _frame_rate; } void VideoSourceBlackmagicSDK::set_sub_frame(int x, int y, int width, int height) { // issue #147 throw VideoSourceError("Blackmagic does not support cropping yet"); } void VideoSourceBlackmagicSDK::get_full_frame() { // nop: set_sub_frame currently not implemented } HRESULT STDMETHODCALLTYPE VideoSourceBlackmagicSDK::QueryInterface(REFIID iid, LPVOID * ppv) { return E_NOINTERFACE; } ULONG STDMETHODCALLTYPE VideoSourceBlackmagicSDK::AddRef(void) { __sync_add_and_fetch(&_n_ref, 1); return _n_ref; } ULONG STDMETHODCALLTYPE VideoSourceBlackmagicSDK::Release(void) { __sync_sub_and_fetch(&_n_ref, 1); return _n_ref; } HRESULT STDMETHODCALLTYPE VideoSourceBlackmagicSDK::VideoInputFormatChanged( BMDVideoInputFormatChangedEvents events, IDeckLinkDisplayMode * display_mode, BMDDetectedVideoInputFormatFlags format_flags ) { // not supported yet: see issue #149 return S_OK; } HRESULT STDMETHODCALLTYPE VideoSourceBlackmagicSDK::VideoInputFrameArrived( IDeckLinkVideoInputFrame * video_frame, IDeckLinkAudioInputPacket * audio_packet ) { if (not _running) // nop if not running! return S_OK; // Not processing the audio packet, but only the video // frame for the time being if (video_frame == nullptr) // nop if no data return S_OK; smart_allocate_buffers( video_frame->GetWidth(), video_frame->GetHeight(), video_frame->GetFlags() ); { // Artificial scope for data lock // Make sure only this thread is accessing the buffer now std::lock_guard<std::mutex> data_lock_guard(_data_lock); if (_video_buffer == nullptr) // something's terribly wrong! // nop if something's terribly wrong! return S_OK; HRESULT res; if (need_conversion()) // convert to BGRA from capture format res = _12_bit_rgb_to_bgra_converter->ConvertFrame( video_frame, _bgra_frame_buffers[0] ); else // Get the new data into the buffer res = video_frame->GetBytes( reinterpret_cast<void **>(&_video_buffer) ); // If the last operation failed, return if (FAILED(res)) return res; if (is_stereo()) { IDeckLinkVideoFrame *right_eye_frame = nullptr; IDeckLinkVideoFrame3DExtensions *three_d_extensions = nullptr; if ((video_frame->QueryInterface( IID_IDeckLinkVideoFrame3DExtensions, (void **) &three_d_extensions) != S_OK) || (three_d_extensions->GetFrameForRightEye( &right_eye_frame) != S_OK)) { right_eye_frame = nullptr; } if (three_d_extensions != nullptr) three_d_extensions->Release(); if (right_eye_frame != nullptr) { if (need_conversion()) // convert to BGRA from capture format res = _12_bit_rgb_to_bgra_converter->ConvertFrame( right_eye_frame, _bgra_frame_buffers[1] ); else res = right_eye_frame->GetBytes( reinterpret_cast<void **>(&_video_buffer[_video_buffer_length / 2]) ); right_eye_frame->Release(); // If data could not be read into the buffer, return if (FAILED(res)) return res; } } // Propagate new video frame to observers _buffer_video_frame.init_from_specs( _video_buffer, _video_buffer_length, _cols, _rows, is_stereo() ? 2 : 1 ); } this->notify(_buffer_video_frame); // Everything went fine, return success return S_OK; } void VideoSourceBlackmagicSDK::release_deck_link() noexcept { if (_deck_link_input != nullptr) { _deck_link_input->Release(); _deck_link_input = nullptr; } if (_deck_link != nullptr) _deck_link->Release(); if (_12_bit_rgb_to_bgra_converter != nullptr) { _12_bit_rgb_to_bgra_converter->Release(); _12_bit_rgb_to_bgra_converter = nullptr; } for (size_t i = 0; i < 2; i++) if (_bgra_frame_buffers[i] != nullptr) { _bgra_frame_buffers[i]->Release(); _bgra_frame_buffers[i] = nullptr; } } inline void VideoSourceBlackmagicSDK::smart_allocate_buffers( size_t cols, size_t rows, BMDFrameFlags frame_flags ) noexcept { if (cols == _cols and rows == _rows) return; _cols = cols; _rows = rows; // Allocate pixel buffer _video_buffer_length = VideoFrame::required_data_length(_colour, _cols, _rows); if (is_stereo()) _video_buffer_length *= 2; _video_buffer = reinterpret_cast<uint8_t *>( realloc(_video_buffer, _video_buffer_length * sizeof(uint8_t)) ); // Colour converter for post-capture colour conversion if (need_conversion()) { for (size_t i = 0; i < (is_stereo() ? 2 : 1); i++) { if (_bgra_frame_buffers[i] != nullptr) { _bgra_frame_buffers[i]->Release(); delete _bgra_frame_buffers[i]; _bgra_frame_buffers[i] = nullptr; } _bgra_frame_buffers[i] = new DeckLinkBGRAVideoFrame( _cols, _rows, &_video_buffer[i * _video_buffer_length / 2], frame_flags ); } } } bool VideoSourceBlackmagicSDK::detect_input_format(BMDPixelFormat pixel_format, BMDVideoInputFlags & video_input_flags, BMDDisplayMode & display_mode, double & frame_rate, size_t & cols, size_t & rows, BMDFrameFlags & frame_flags, std::string & error_msg) noexcept { std::vector<BMDDisplayMode> display_modes = { bmdModeHD1080p6000, bmdModeHD1080p5994, bmdModeHD1080p50, bmdModeHD1080p30, bmdModeHD1080p2997, bmdModeHD1080p25, bmdModeHD1080p24, bmdModeHD1080p2398, bmdModeHD1080i6000, bmdModeHD1080i5994, bmdModeHD1080i50, bmdModeHD720p60, bmdModeHD720p5994, bmdModeHD720p50, bmdMode4K2160p60, bmdMode4K2160p5994, bmdMode4K2160p50, bmdMode4K2160p30, bmdMode4K2160p2997, bmdMode4K2160p25, bmdMode4K2160p24, bmdMode4K2160p2398, bmdMode2k25, bmdMode2k24, bmdMode2k2398, }; DeckLinkDisplayModeDetector detector( _deck_link_input, display_modes, pixel_format, video_input_flags ); BMDDisplayMode display_mode_ = detector.get_display_mode(); if (display_mode_ != bmdModeUnknown) { frame_rate = detector.get_frame_rate(); detector.get_frame_dimensions(cols, rows); frame_flags = detector.get_frame_flags(); display_mode = display_mode_; video_input_flags = detector.get_video_input_flags(); return true; } else { error_msg = detector.get_error_msg(); return false; } } } <commit_msg>Issue #30: extra dimension positivity check in smart buffer allocator method<commit_after>#include "blackmagicsdk_video_source.h" #include "deck_link_display_mode_detector.h" #include <chrono> namespace gg { VideoSourceBlackmagicSDK::VideoSourceBlackmagicSDK() : IVideoSource() , _frame_rate(0.0) , _video_buffer(nullptr) , _video_buffer_length(0) , _cols(0) , _rows(0) , _buffer_video_frame(VideoFrame(UYVY)) , _running(false) { // nop } VideoSourceBlackmagicSDK::VideoSourceBlackmagicSDK(size_t deck_link_index, ColourSpace colour) : IVideoSource(colour) , _frame_rate(0.0) , _video_buffer(nullptr) , _video_buffer_length(0) , _cols(0) , _rows(0) , _buffer_video_frame(VideoFrame(colour, false)) // TODO manage data? , _deck_link(nullptr) , _deck_link_input(nullptr) , _video_input_flags(bmdVideoInputFlagDefault | bmdVideoInputDualStream3D) , _12_bit_rgb_to_bgra_converter(nullptr) , _bgra_frame_buffers{nullptr, nullptr} , _running(false) { // Pixel format, i.e. colour space BMDPixelFormat pixel_format; switch(_colour) { case UYVY: pixel_format = bmdFormat8BitYUV; break; case BGRA: // We currently only support BGRA with DeckLink 4K Extreme 12G, // and that card supports only this YUV format: pixel_format = bmdFormat10BitYUV; break; case I420: default: bail("BlackmagicSDK video source supports only UYVY and BGRA colour spaces"); } // Get an iterator through the available DeckLink ports IDeckLinkIterator * deck_link_iterator = CreateDeckLinkIteratorInstance(); if (deck_link_iterator == nullptr) bail("DeckLink drivers do not appear to be installed"); HRESULT res; // Get the desired DeckLink index (port) int idx = deck_link_index; while ((res = deck_link_iterator->Next(&_deck_link)) == S_OK) { if (idx == 0) break; --idx; _deck_link->Release(); } if (deck_link_iterator != nullptr) deck_link_iterator->Release(); // No glory: release everything and throw exception if (res != S_OK or _deck_link == nullptr) bail( std::string("Could not get DeckLink device ").append(std::to_string(deck_link_index)) ); // Get the input interface of connected DeckLink port res = _deck_link->QueryInterface(IID_IDeckLinkInput, reinterpret_cast<void **>(&_deck_link_input)); // No glory: release everything and throw exception if (res != S_OK) bail("Could not get the Blackmagic DeckLink input interface"); // Set the input format (i.e. display mode) BMDDisplayMode display_mode; BMDFrameFlags frame_flags; std::string error_msg = ""; size_t cols = 0, rows = 0; if (not detect_input_format(pixel_format, _video_input_flags, display_mode, _frame_rate, cols, rows, frame_flags, error_msg)) { _video_input_flags ^= bmdVideoInputDualStream3D; if (not detect_input_format(pixel_format, _video_input_flags, display_mode, _frame_rate, cols, rows, frame_flags, error_msg)) bail(error_msg); } // Get a post-capture converter if necessary if (_colour == BGRA) { _12_bit_rgb_to_bgra_converter = CreateVideoConversionInstance(); if (_12_bit_rgb_to_bgra_converter == nullptr) bail("Could not create colour converter for Blackmagic source"); } // Set this object (IDeckLinkInputCallback instance) as callback res = _deck_link_input->SetCallback(this); // No glory: release everything and throw exception if (res != S_OK) bail("Could not set the callback of Blackmagic DeckLink device"); // Enable video input res = _deck_link_input->EnableVideoInput(display_mode, pixel_format, _video_input_flags); // No glory if (res != S_OK) bail("Could not enable video input of Blackmagic DeckLink device"); // Start streaming _running = true; res = _deck_link_input->StartStreams(); // No glory: release everything and throw exception if (res != S_OK) { _running = false; bail("Could not start streaming from the Blackmagic DeckLink device"); } } VideoSourceBlackmagicSDK::~VideoSourceBlackmagicSDK() { { // Artificial scope for data lock // Make sure streamer thread not trying to access buffer std::lock_guard<std::mutex> data_lock_guard(_data_lock); _running = false; } // Stop streaming and disable enabled inputs _deck_link_input->SetCallback(nullptr); _deck_link_input->StopStreams(); _deck_link_input->DisableVideoInput(); // Release DeckLink members release_deck_link(); } bool VideoSourceBlackmagicSDK::get_frame_dimensions(int & width, int & height) { // Make sure only this thread is accessing the cols and rows members now std::lock_guard<std::mutex> data_lock_guard(_data_lock); if (_cols <= 0 or _rows <= 0) return false; width = _cols; height = _rows; return true; } bool VideoSourceBlackmagicSDK::get_frame(VideoFrame & frame) { if (frame.colour() != _colour) return false; // Make sure only this thread is accessing the video frame data now std::lock_guard<std::mutex> data_lock_guard(_data_lock); if (_video_buffer_length > 0 and _cols > 0 and _rows > 0) { frame.init_from_specs(_video_buffer, _video_buffer_length, _cols, _rows); return true; } else return false; } double VideoSourceBlackmagicSDK::get_frame_rate() { return _frame_rate; } void VideoSourceBlackmagicSDK::set_sub_frame(int x, int y, int width, int height) { // issue #147 throw VideoSourceError("Blackmagic does not support cropping yet"); } void VideoSourceBlackmagicSDK::get_full_frame() { // nop: set_sub_frame currently not implemented } HRESULT STDMETHODCALLTYPE VideoSourceBlackmagicSDK::QueryInterface(REFIID iid, LPVOID * ppv) { return E_NOINTERFACE; } ULONG STDMETHODCALLTYPE VideoSourceBlackmagicSDK::AddRef(void) { __sync_add_and_fetch(&_n_ref, 1); return _n_ref; } ULONG STDMETHODCALLTYPE VideoSourceBlackmagicSDK::Release(void) { __sync_sub_and_fetch(&_n_ref, 1); return _n_ref; } HRESULT STDMETHODCALLTYPE VideoSourceBlackmagicSDK::VideoInputFormatChanged( BMDVideoInputFormatChangedEvents events, IDeckLinkDisplayMode * display_mode, BMDDetectedVideoInputFormatFlags format_flags ) { // not supported yet: see issue #149 return S_OK; } HRESULT STDMETHODCALLTYPE VideoSourceBlackmagicSDK::VideoInputFrameArrived( IDeckLinkVideoInputFrame * video_frame, IDeckLinkAudioInputPacket * audio_packet ) { if (not _running) // nop if not running! return S_OK; // Not processing the audio packet, but only the video // frame for the time being if (video_frame == nullptr) // nop if no data return S_OK; smart_allocate_buffers( video_frame->GetWidth(), video_frame->GetHeight(), video_frame->GetFlags() ); { // Artificial scope for data lock // Make sure only this thread is accessing the buffer now std::lock_guard<std::mutex> data_lock_guard(_data_lock); if (_video_buffer == nullptr) // something's terribly wrong! // nop if something's terribly wrong! return S_OK; HRESULT res; if (need_conversion()) // convert to BGRA from capture format res = _12_bit_rgb_to_bgra_converter->ConvertFrame( video_frame, _bgra_frame_buffers[0] ); else // Get the new data into the buffer res = video_frame->GetBytes( reinterpret_cast<void **>(&_video_buffer) ); // If the last operation failed, return if (FAILED(res)) return res; if (is_stereo()) { IDeckLinkVideoFrame *right_eye_frame = nullptr; IDeckLinkVideoFrame3DExtensions *three_d_extensions = nullptr; if ((video_frame->QueryInterface( IID_IDeckLinkVideoFrame3DExtensions, (void **) &three_d_extensions) != S_OK) || (three_d_extensions->GetFrameForRightEye( &right_eye_frame) != S_OK)) { right_eye_frame = nullptr; } if (three_d_extensions != nullptr) three_d_extensions->Release(); if (right_eye_frame != nullptr) { if (need_conversion()) // convert to BGRA from capture format res = _12_bit_rgb_to_bgra_converter->ConvertFrame( right_eye_frame, _bgra_frame_buffers[1] ); else res = right_eye_frame->GetBytes( reinterpret_cast<void **>(&_video_buffer[_video_buffer_length / 2]) ); right_eye_frame->Release(); // If data could not be read into the buffer, return if (FAILED(res)) return res; } } // Propagate new video frame to observers _buffer_video_frame.init_from_specs( _video_buffer, _video_buffer_length, _cols, _rows, is_stereo() ? 2 : 1 ); } this->notify(_buffer_video_frame); // Everything went fine, return success return S_OK; } void VideoSourceBlackmagicSDK::release_deck_link() noexcept { if (_deck_link_input != nullptr) { _deck_link_input->Release(); _deck_link_input = nullptr; } if (_deck_link != nullptr) _deck_link->Release(); if (_12_bit_rgb_to_bgra_converter != nullptr) { _12_bit_rgb_to_bgra_converter->Release(); _12_bit_rgb_to_bgra_converter = nullptr; } for (size_t i = 0; i < 2; i++) if (_bgra_frame_buffers[i] != nullptr) { _bgra_frame_buffers[i]->Release(); _bgra_frame_buffers[i] = nullptr; } } inline void VideoSourceBlackmagicSDK::smart_allocate_buffers( size_t cols, size_t rows, BMDFrameFlags frame_flags ) noexcept { if (cols <= 0 or rows <= 0) return; if (cols == _cols and rows == _rows) return; _cols = cols; _rows = rows; // Allocate pixel buffer _video_buffer_length = VideoFrame::required_data_length(_colour, _cols, _rows); if (is_stereo()) _video_buffer_length *= 2; _video_buffer = reinterpret_cast<uint8_t *>( realloc(_video_buffer, _video_buffer_length * sizeof(uint8_t)) ); // Colour converter for post-capture colour conversion if (need_conversion()) { for (size_t i = 0; i < (is_stereo() ? 2 : 1); i++) { if (_bgra_frame_buffers[i] != nullptr) { _bgra_frame_buffers[i]->Release(); delete _bgra_frame_buffers[i]; _bgra_frame_buffers[i] = nullptr; } _bgra_frame_buffers[i] = new DeckLinkBGRAVideoFrame( _cols, _rows, &_video_buffer[i * _video_buffer_length / 2], frame_flags ); } } } bool VideoSourceBlackmagicSDK::detect_input_format(BMDPixelFormat pixel_format, BMDVideoInputFlags & video_input_flags, BMDDisplayMode & display_mode, double & frame_rate, size_t & cols, size_t & rows, BMDFrameFlags & frame_flags, std::string & error_msg) noexcept { std::vector<BMDDisplayMode> display_modes = { bmdModeHD1080p6000, bmdModeHD1080p5994, bmdModeHD1080p50, bmdModeHD1080p30, bmdModeHD1080p2997, bmdModeHD1080p25, bmdModeHD1080p24, bmdModeHD1080p2398, bmdModeHD1080i6000, bmdModeHD1080i5994, bmdModeHD1080i50, bmdModeHD720p60, bmdModeHD720p5994, bmdModeHD720p50, bmdMode4K2160p60, bmdMode4K2160p5994, bmdMode4K2160p50, bmdMode4K2160p30, bmdMode4K2160p2997, bmdMode4K2160p25, bmdMode4K2160p24, bmdMode4K2160p2398, bmdMode2k25, bmdMode2k24, bmdMode2k2398, }; DeckLinkDisplayModeDetector detector( _deck_link_input, display_modes, pixel_format, video_input_flags ); BMDDisplayMode display_mode_ = detector.get_display_mode(); if (display_mode_ != bmdModeUnknown) { frame_rate = detector.get_frame_rate(); detector.get_frame_dimensions(cols, rows); frame_flags = detector.get_frame_flags(); display_mode = display_mode_; video_input_flags = detector.get_video_input_flags(); return true; } else { error_msg = detector.get_error_msg(); return false; } } } <|endoftext|>
<commit_before>/*************************************************************************** ** ** Copyright (C) 2010, 2011 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (directui@nokia.com) ** ** This file is part of libmeegotouch. ** ** If you have questions regarding the use of this file, please contact ** Nokia at directui@nokia.com. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation ** and appearing in the file LICENSE.LGPL included in the packaging ** of this file. ** ****************************************************************************/ #include "mtextselectionhandle.h" #include "mdebug.h" namespace { const int DefaultMovementSensitivity = 3; const qreal NormalOpacity = 1.0f; qreal distance(const QPointF &pos, const QRectF &rect) { if (rect.contains(pos)) return 0; return (pos - rect.center()).manhattanLength(); } } MTextSelectionHandle::MTextSelectionHandle() : opacityAnimation(this, "opacity"), m_pressed(false), hiddenTemporarily(false), mMovementSensitivity(DefaultMovementSensitivity), positionIsVisible(false), disabled(false) { setFocusProxy(0); setFocusPolicy(Qt::NoFocus); setOpacity(0.0f); hide(); connect(&opacityAnimation, SIGNAL(finished()), this, SLOT(onShowHideAnimationFinished())); } MTextSelectionHandle::~MTextSelectionHandle() { // Before destroying parent, detach so it doesn't try to destroy us. setParentItem(0); } void MTextSelectionHandle::appear() { if (hiddenTemporarily) { return; } const qreal targetOpacity = disabled ? style()->disableOpacity() : NormalOpacity; const bool isCompletelyVisible = (qFuzzyCompare(opacity(), targetOpacity) && opacityAnimation.state() != QAbstractAnimation::Running); const bool isShowInProgress = (qFuzzyCompare(opacityAnimation.endValue().toReal(), targetOpacity) && opacityAnimation.state() == QAbstractAnimation::Running && opacityAnimation.direction() == QAbstractAnimation::Forward); if (isVisible() && (isCompletelyVisible || isShowInProgress)) { return; } show(); opacityAnimation.setEndValue(targetOpacity); opacityAnimation.setDirection(QAbstractAnimation::Forward); if (opacityAnimation.state() != QAbstractAnimation::Running) { opacityAnimation.setStartValue(opacity()); opacityAnimation.start(); } } void MTextSelectionHandle::disappear() { if (!isVisible() || (qFuzzyIsNull(opacityAnimation.endValue().toReal()) && opacityAnimation.state() == QAbstractAnimation::Running)) { return; } opacityAnimation.setStartValue(0.0f); opacityAnimation.setDirection(QAbstractAnimation::Backward); if (opacityAnimation.state() != QAbstractAnimation::Running) { opacityAnimation.setEndValue(opacity()); opacityAnimation.start(); } } void MTextSelectionHandle::hideTemporarily() { hiddenTemporarily = true; disappear(); } void MTextSelectionHandle::restore() { if (!hiddenTemporarily) { return; } hiddenTemporarily = false; if (positionIsVisible) { appear(); } } void MTextSelectionHandle::setPositionVisibility(bool visible) { if (positionIsVisible == visible) { return; } positionIsVisible = visible; if (visible) { appear(); } else { disappear(); } } void MTextSelectionHandle::updatePosition(const QPointF &pos) { const QPointF correction(preferredWidth() / 2, style()->visualOffset()); setPos(pos - correction); } void MTextSelectionHandle::setPressed(bool press) { if (m_pressed == press) return; m_pressed = press; if (m_pressed) { emit pressed(this); } else { emit released(this); } } bool MTextSelectionHandle::isPressed() const { return m_pressed; } QPointF MTextSelectionHandle::hotSpot() const { const QPointF correction(preferredWidth() / 2, 0); return pos() + correction; } void MTextSelectionHandle::applyStyle() { mMovementSensitivity = style()->movementSensitivity(); opacityAnimation.setEasingCurve(style()->showHideEasingCurve()); opacityAnimation.setDuration(style()->showHideDuration()); prepareGeometryChange(); // in case if bounding rect will be changed due to size of graphic asset update(); } QRectF MTextSelectionHandle::boundingRect() const { return QRectF(QPointF(0.0f, 0.0f), style()->preferredSize()); } QSizeF MTextSelectionHandle::sizeHint(Qt::SizeHint which, const QSizeF &constraint) const { switch (which) { case Qt::MinimumSize: return MStylableWidget::sizeHint(which, constraint); case Qt::MaximumSize: return QSizeF(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX); case Qt::PreferredSize: return style()->preferredSize(); default: mWarning("MTextSelectionHandle") << __PRETTY_FUNCTION__ << "don't know how to handle the value of 'which':" << which; } return QSizeF(0, 0); } void MTextSelectionHandle::onShowHideAnimationFinished() { if (!opacity()) { hide(); if (!hiddenTemporarily) { m_pressed = false; emit disappeared(); } } } int MTextSelectionHandle::movementSensitivity() const { return mMovementSensitivity; } void MTextSelectionHandle::skipTransitions() { if (opacityAnimation.state() == QAbstractAnimation::Running) { opacityAnimation.stop(); if (opacityAnimation.direction() == QAbstractAnimation::Forward) { setOpacity(opacityAnimation.endValue().toReal()); } else { setOpacity(opacityAnimation.startValue().toReal()); } onShowHideAnimationFinished(); } } void MTextSelectionHandle::disable() { if (disabled) { return; } disabled = true; if (!isVisible() || isHideInProgress()) { return; } if (hiddenTemporarily || !positionIsVisible) { return; } opacityAnimation.setDirection(QAbstractAnimation::Backward); opacityAnimation.setStartValue(style()->disableOpacity()); if (opacityAnimation.state() != QAbstractAnimation::Running) { opacityAnimation.setEndValue(opacity()); opacityAnimation.start(); } } void MTextSelectionHandle::enable() { if (!disabled) { return; } disabled = false; if (!isVisible() || isHideInProgress()) { return; } if (hiddenTemporarily || !positionIsVisible) { return; } opacityAnimation.setDirection(QAbstractAnimation::Forward); opacityAnimation.setEndValue(NormalOpacity); if (opacityAnimation.state() != QAbstractAnimation::Running) { opacityAnimation.setStartValue(opacity()); opacityAnimation.start(); } } QRectF MTextSelectionHandle::region() const { return geometry().adjusted(0, 0, 0, -style()->regionPadding()); } bool MTextSelectionHandle::isReady() const { return isVisible() && !disabled && !isHideInProgress() && !m_pressed; } bool MTextSelectionHandle::isHideInProgress() const { return (qFuzzyIsNull(opacityAnimation.startValue().toReal()) && opacityAnimation.state() == QAbstractAnimation::Running && opacityAnimation.direction() == QAbstractAnimation::Backward); } <commit_msg>Fixes: NB#295983, Magnifier is still shown even if the finger is released from the text<commit_after>/*************************************************************************** ** ** Copyright (C) 2010, 2011 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (directui@nokia.com) ** ** This file is part of libmeegotouch. ** ** If you have questions regarding the use of this file, please contact ** Nokia at directui@nokia.com. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation ** and appearing in the file LICENSE.LGPL included in the packaging ** of this file. ** ****************************************************************************/ #include "mtextselectionhandle.h" #include "mdebug.h" #include "meatgesturefilter.h" namespace { const int DefaultMovementSensitivity = 3; const qreal NormalOpacity = 1.0f; qreal distance(const QPointF &pos, const QRectF &rect) { if (rect.contains(pos)) return 0; return (pos - rect.center()).manhattanLength(); } } MTextSelectionHandle::MTextSelectionHandle() : opacityAnimation(this, "opacity"), m_pressed(false), hiddenTemporarily(false), mMovementSensitivity(DefaultMovementSensitivity), positionIsVisible(false), disabled(false) { setFocusProxy(0); setFocusPolicy(Qt::NoFocus); grabGestureWithCancelPolicy(Qt::TapGesture); grabGestureWithCancelPolicy(Qt::TapAndHoldGesture); installEventFilter(new MEatGestureFilter(this)); setOpacity(0.0f); hide(); connect(&opacityAnimation, SIGNAL(finished()), this, SLOT(onShowHideAnimationFinished())); } MTextSelectionHandle::~MTextSelectionHandle() { // Before destroying parent, detach so it doesn't try to destroy us. setParentItem(0); } void MTextSelectionHandle::appear() { if (hiddenTemporarily) { return; } const qreal targetOpacity = disabled ? style()->disableOpacity() : NormalOpacity; const bool isCompletelyVisible = (qFuzzyCompare(opacity(), targetOpacity) && opacityAnimation.state() != QAbstractAnimation::Running); const bool isShowInProgress = (qFuzzyCompare(opacityAnimation.endValue().toReal(), targetOpacity) && opacityAnimation.state() == QAbstractAnimation::Running && opacityAnimation.direction() == QAbstractAnimation::Forward); if (isVisible() && (isCompletelyVisible || isShowInProgress)) { return; } show(); opacityAnimation.setEndValue(targetOpacity); opacityAnimation.setDirection(QAbstractAnimation::Forward); if (opacityAnimation.state() != QAbstractAnimation::Running) { opacityAnimation.setStartValue(opacity()); opacityAnimation.start(); } } void MTextSelectionHandle::disappear() { if (!isVisible() || (qFuzzyIsNull(opacityAnimation.endValue().toReal()) && opacityAnimation.state() == QAbstractAnimation::Running)) { return; } opacityAnimation.setStartValue(0.0f); opacityAnimation.setDirection(QAbstractAnimation::Backward); if (opacityAnimation.state() != QAbstractAnimation::Running) { opacityAnimation.setEndValue(opacity()); opacityAnimation.start(); } } void MTextSelectionHandle::hideTemporarily() { hiddenTemporarily = true; disappear(); } void MTextSelectionHandle::restore() { if (!hiddenTemporarily) { return; } hiddenTemporarily = false; if (positionIsVisible) { appear(); } } void MTextSelectionHandle::setPositionVisibility(bool visible) { if (positionIsVisible == visible) { return; } positionIsVisible = visible; if (visible) { appear(); } else { disappear(); } } void MTextSelectionHandle::updatePosition(const QPointF &pos) { const QPointF correction(preferredWidth() / 2, style()->visualOffset()); setPos(pos - correction); } void MTextSelectionHandle::setPressed(bool press) { if (m_pressed == press) return; m_pressed = press; if (m_pressed) { emit pressed(this); } else { emit released(this); } } bool MTextSelectionHandle::isPressed() const { return m_pressed; } QPointF MTextSelectionHandle::hotSpot() const { const QPointF correction(preferredWidth() / 2, 0); return pos() + correction; } void MTextSelectionHandle::applyStyle() { mMovementSensitivity = style()->movementSensitivity(); opacityAnimation.setEasingCurve(style()->showHideEasingCurve()); opacityAnimation.setDuration(style()->showHideDuration()); prepareGeometryChange(); // in case if bounding rect will be changed due to size of graphic asset update(); } QRectF MTextSelectionHandle::boundingRect() const { return QRectF(QPointF(0.0f, 0.0f), style()->preferredSize()); } QSizeF MTextSelectionHandle::sizeHint(Qt::SizeHint which, const QSizeF &constraint) const { switch (which) { case Qt::MinimumSize: return MStylableWidget::sizeHint(which, constraint); case Qt::MaximumSize: return QSizeF(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX); case Qt::PreferredSize: return style()->preferredSize(); default: mWarning("MTextSelectionHandle") << __PRETTY_FUNCTION__ << "don't know how to handle the value of 'which':" << which; } return QSizeF(0, 0); } void MTextSelectionHandle::onShowHideAnimationFinished() { if (!opacity()) { hide(); if (!hiddenTemporarily) { m_pressed = false; emit disappeared(); } } } int MTextSelectionHandle::movementSensitivity() const { return mMovementSensitivity; } void MTextSelectionHandle::skipTransitions() { if (opacityAnimation.state() == QAbstractAnimation::Running) { opacityAnimation.stop(); if (opacityAnimation.direction() == QAbstractAnimation::Forward) { setOpacity(opacityAnimation.endValue().toReal()); } else { setOpacity(opacityAnimation.startValue().toReal()); } onShowHideAnimationFinished(); } } void MTextSelectionHandle::disable() { if (disabled) { return; } disabled = true; if (!isVisible() || isHideInProgress()) { return; } if (hiddenTemporarily || !positionIsVisible) { return; } opacityAnimation.setDirection(QAbstractAnimation::Backward); opacityAnimation.setStartValue(style()->disableOpacity()); if (opacityAnimation.state() != QAbstractAnimation::Running) { opacityAnimation.setEndValue(opacity()); opacityAnimation.start(); } } void MTextSelectionHandle::enable() { if (!disabled) { return; } disabled = false; if (!isVisible() || isHideInProgress()) { return; } if (hiddenTemporarily || !positionIsVisible) { return; } opacityAnimation.setDirection(QAbstractAnimation::Forward); opacityAnimation.setEndValue(NormalOpacity); if (opacityAnimation.state() != QAbstractAnimation::Running) { opacityAnimation.setStartValue(opacity()); opacityAnimation.start(); } } QRectF MTextSelectionHandle::region() const { return geometry().adjusted(0, 0, 0, -style()->regionPadding()); } bool MTextSelectionHandle::isReady() const { return isVisible() && !disabled && !isHideInProgress() && !m_pressed; } bool MTextSelectionHandle::isHideInProgress() const { return (qFuzzyIsNull(opacityAnimation.startValue().toReal()) && opacityAnimation.state() == QAbstractAnimation::Running && opacityAnimation.direction() == QAbstractAnimation::Backward); } <|endoftext|>
<commit_before>/* * Copyright (c) 2008-2018, Hazelcast, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // // Created by sancar koyunlu on 26/02/14. // /** * This has to be the first include, so that Python.h is the first include. Otherwise, compilation warning such as * "_POSIX_C_SOURCE" redefined occurs. */ #include "HazelcastServer.h" #include <gtest/gtest.h> #include "ClientTestSupportBase.h" #include "HazelcastServerFactory.h" #include "hazelcast/util/CountDownLatch.h" #include "hazelcast/client/MembershipListener.h" #include "hazelcast/client/InitialMembershipEvent.h" #include "hazelcast/client/InitialMembershipListener.h" #include "hazelcast/client/MemberAttributeEvent.h" #include "hazelcast/client/EntryAdapter.h" #include "hazelcast/client/HazelcastClient.h" #include "hazelcast/client/LifecycleListener.h" namespace hazelcast { namespace client { namespace test { class ClusterTest : public ClientTestSupportBase, public ::testing::TestWithParam<ClientConfig *> { public: ClusterTest() : sslFactory(getSslFilePath()) {} protected: class ClientAllStatesListener : public LifecycleListener { public: ClientAllStatesListener(util::CountDownLatch *startingLatch, util::CountDownLatch *startedLatch = NULL, util::CountDownLatch *connectedLatch = NULL, util::CountDownLatch *disconnectedLatch = NULL, util::CountDownLatch *shuttingDownLatch = NULL, util::CountDownLatch *shutdownLatch = NULL) : startingLatch(startingLatch), startedLatch(startedLatch), connectedLatch(connectedLatch), disconnectedLatch(disconnectedLatch), shuttingDownLatch(shuttingDownLatch), shutdownLatch(shutdownLatch) {} virtual void stateChanged(const LifecycleEvent &lifecycleEvent) { switch (lifecycleEvent.getState()) { case LifecycleEvent::STARTING: if (startingLatch) { startingLatch->countDown(); } break; case LifecycleEvent::STARTED: if (startedLatch) { startedLatch->countDown(); } break; case LifecycleEvent::CLIENT_CONNECTED: if (connectedLatch) { connectedLatch->countDown(); } break; case LifecycleEvent::CLIENT_DISCONNECTED: if (disconnectedLatch) { disconnectedLatch->countDown(); } break; case LifecycleEvent::SHUTTING_DOWN: if (shuttingDownLatch) { shuttingDownLatch->countDown(); } break; case LifecycleEvent::SHUTDOWN: if (shutdownLatch) { shutdownLatch->countDown(); } break; default: FAIL() << "No such state expected:" << lifecycleEvent.getState(); } } private: util::CountDownLatch *startingLatch; util::CountDownLatch *startedLatch; util::CountDownLatch *connectedLatch; util::CountDownLatch *disconnectedLatch; util::CountDownLatch *shuttingDownLatch; util::CountDownLatch *shutdownLatch; }; private: HazelcastServerFactory sslFactory; }; class SmartTcpClientConfig : public ClientConfig { }; class SmartSSLClientConfig : public ClientConfig { public: SmartSSLClientConfig() { this->getNetworkConfig().getSSLConfig().setEnabled(true).addVerifyFile( ClientTestSupportBase::getCAFilePath()); } }; TEST_P(ClusterTest, testBehaviourWhenClusterNotFound) { ClientConfig &clientConfig = *const_cast<ParamType &>(GetParam()); ASSERT_THROW(HazelcastClient client(clientConfig), exception::IllegalStateException); } TEST_P(ClusterTest, testDummyClientBehaviourWhenClusterNotFound) { ClientConfig &clientConfig = *const_cast<ParamType &>(GetParam()); clientConfig.setSmart(false); ASSERT_THROW(HazelcastClient client(clientConfig), exception::IllegalStateException); } TEST_P(ClusterTest, testAllClientStates) { HazelcastServer instance(*g_srvFactory); ClientConfig clientConfig; clientConfig.setAttemptPeriod(1000); clientConfig.setConnectionAttemptLimit(1); util::CountDownLatch startingLatch(1); util::CountDownLatch startedLatch(1); util::CountDownLatch connectedLatch(1); util::CountDownLatch disconnectedLatch(1); util::CountDownLatch shuttingDownLatch(1); util::CountDownLatch shutdownLatch(1); ClientAllStatesListener listener(&startingLatch, &startedLatch, &connectedLatch, &disconnectedLatch, &shuttingDownLatch, &shutdownLatch); clientConfig.addListener(&listener); HazelcastClient client(clientConfig); ASSERT_TRUE(startingLatch.await(0)); ASSERT_TRUE(startedLatch.await(0)); ASSERT_TRUE(connectedLatch.await(0)); instance.shutdown(); ASSERT_OPEN_EVENTUALLY(disconnectedLatch); ASSERT_OPEN_EVENTUALLY(shuttingDownLatch); ASSERT_OPEN_EVENTUALLY(shutdownLatch); } TEST_P(ClusterTest, testConnectionAttemptPeriod) { ClientConfig &clientConfig = *const_cast<ParamType &>(GetParam()); clientConfig.getNetworkConfig().setConnectionAttemptPeriod(900). setConnectionTimeout(2000).setConnectionAttemptLimit(2); clientConfig.getNetworkConfig().addAddress(Address("8.8.8.8", 8000)); int64_t startTimeMillis = util::currentTimeMillis(); try { HazelcastClient client(clientConfig); } catch (exception::IllegalStateException &) { // this is expected } ASSERT_GE(util::currentTimeMillis() - startTimeMillis, 2 * 900); } TEST_P(ClusterTest, testAllClientStatesWhenUserShutdown) { HazelcastServer instance(*g_srvFactory); ClientConfig clientConfig; util::CountDownLatch startingLatch(1); util::CountDownLatch startedLatch(1); util::CountDownLatch connectedLatch(1); util::CountDownLatch disconnectedLatch(1); util::CountDownLatch shuttingDownLatch(1); util::CountDownLatch shutdownLatch(1); ClientAllStatesListener listener(&startingLatch, &startedLatch, &connectedLatch, &disconnectedLatch, &shuttingDownLatch, &shutdownLatch); clientConfig.addListener(&listener); HazelcastClient client(clientConfig); ASSERT_TRUE(startingLatch.await(0)); ASSERT_TRUE(startedLatch.await(0)); ASSERT_TRUE(connectedLatch.await(0)); client.shutdown(); ASSERT_OPEN_EVENTUALLY(shuttingDownLatch); ASSERT_OPEN_EVENTUALLY(shutdownLatch); } #ifdef HZ_BUILD_WITH_SSL INSTANTIATE_TEST_CASE_P(All, ClusterTest, ::testing::Values(new SmartTcpClientConfig(), new SmartSSLClientConfig())); #else INSTANTIATE_TEST_CASE_P(All, ClusterTest, ::testing::Values(new SmartTcpClientConfig(), new NonSmartTcpClientConfig())); #endif } } } <commit_msg>Fix for ClusterTest to compile correctly when SSL is disabled. (#400)<commit_after>/* * Copyright (c) 2008-2018, Hazelcast, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // // Created by sancar koyunlu on 26/02/14. // /** * This has to be the first include, so that Python.h is the first include. Otherwise, compilation warning such as * "_POSIX_C_SOURCE" redefined occurs. */ #include "HazelcastServer.h" #include <gtest/gtest.h> #include "ClientTestSupportBase.h" #include "HazelcastServerFactory.h" #include "hazelcast/util/CountDownLatch.h" #include "hazelcast/client/MembershipListener.h" #include "hazelcast/client/InitialMembershipEvent.h" #include "hazelcast/client/InitialMembershipListener.h" #include "hazelcast/client/MemberAttributeEvent.h" #include "hazelcast/client/EntryAdapter.h" #include "hazelcast/client/HazelcastClient.h" #include "hazelcast/client/LifecycleListener.h" namespace hazelcast { namespace client { namespace test { class ClusterTest : public ClientTestSupportBase, public ::testing::TestWithParam<ClientConfig *> { public: ClusterTest() : sslFactory(getSslFilePath()) {} protected: class ClientAllStatesListener : public LifecycleListener { public: ClientAllStatesListener(util::CountDownLatch *startingLatch, util::CountDownLatch *startedLatch = NULL, util::CountDownLatch *connectedLatch = NULL, util::CountDownLatch *disconnectedLatch = NULL, util::CountDownLatch *shuttingDownLatch = NULL, util::CountDownLatch *shutdownLatch = NULL) : startingLatch(startingLatch), startedLatch(startedLatch), connectedLatch(connectedLatch), disconnectedLatch(disconnectedLatch), shuttingDownLatch(shuttingDownLatch), shutdownLatch(shutdownLatch) {} virtual void stateChanged(const LifecycleEvent &lifecycleEvent) { switch (lifecycleEvent.getState()) { case LifecycleEvent::STARTING: if (startingLatch) { startingLatch->countDown(); } break; case LifecycleEvent::STARTED: if (startedLatch) { startedLatch->countDown(); } break; case LifecycleEvent::CLIENT_CONNECTED: if (connectedLatch) { connectedLatch->countDown(); } break; case LifecycleEvent::CLIENT_DISCONNECTED: if (disconnectedLatch) { disconnectedLatch->countDown(); } break; case LifecycleEvent::SHUTTING_DOWN: if (shuttingDownLatch) { shuttingDownLatch->countDown(); } break; case LifecycleEvent::SHUTDOWN: if (shutdownLatch) { shutdownLatch->countDown(); } break; default: FAIL() << "No such state expected:" << lifecycleEvent.getState(); } } private: util::CountDownLatch *startingLatch; util::CountDownLatch *startedLatch; util::CountDownLatch *connectedLatch; util::CountDownLatch *disconnectedLatch; util::CountDownLatch *shuttingDownLatch; util::CountDownLatch *shutdownLatch; }; private: HazelcastServerFactory sslFactory; }; class SmartTcpClientConfig : public ClientConfig { }; class SmartSSLClientConfig : public ClientConfig { public: SmartSSLClientConfig() { this->getNetworkConfig().getSSLConfig().setEnabled(true).addVerifyFile( ClientTestSupportBase::getCAFilePath()); } }; TEST_P(ClusterTest, testBehaviourWhenClusterNotFound) { ClientConfig &clientConfig = *const_cast<ParamType &>(GetParam()); ASSERT_THROW(HazelcastClient client(clientConfig), exception::IllegalStateException); } TEST_P(ClusterTest, testDummyClientBehaviourWhenClusterNotFound) { ClientConfig &clientConfig = *const_cast<ParamType &>(GetParam()); clientConfig.setSmart(false); ASSERT_THROW(HazelcastClient client(clientConfig), exception::IllegalStateException); } TEST_P(ClusterTest, testAllClientStates) { HazelcastServer instance(*g_srvFactory); ClientConfig clientConfig; clientConfig.setAttemptPeriod(1000); clientConfig.setConnectionAttemptLimit(1); util::CountDownLatch startingLatch(1); util::CountDownLatch startedLatch(1); util::CountDownLatch connectedLatch(1); util::CountDownLatch disconnectedLatch(1); util::CountDownLatch shuttingDownLatch(1); util::CountDownLatch shutdownLatch(1); ClientAllStatesListener listener(&startingLatch, &startedLatch, &connectedLatch, &disconnectedLatch, &shuttingDownLatch, &shutdownLatch); clientConfig.addListener(&listener); HazelcastClient client(clientConfig); ASSERT_TRUE(startingLatch.await(0)); ASSERT_TRUE(startedLatch.await(0)); ASSERT_TRUE(connectedLatch.await(0)); instance.shutdown(); ASSERT_OPEN_EVENTUALLY(disconnectedLatch); ASSERT_OPEN_EVENTUALLY(shuttingDownLatch); ASSERT_OPEN_EVENTUALLY(shutdownLatch); } TEST_P(ClusterTest, testConnectionAttemptPeriod) { ClientConfig &clientConfig = *const_cast<ParamType &>(GetParam()); clientConfig.getNetworkConfig().setConnectionAttemptPeriod(900). setConnectionTimeout(2000).setConnectionAttemptLimit(2); clientConfig.getNetworkConfig().addAddress(Address("8.8.8.8", 8000)); int64_t startTimeMillis = util::currentTimeMillis(); try { HazelcastClient client(clientConfig); } catch (exception::IllegalStateException &) { // this is expected } ASSERT_GE(util::currentTimeMillis() - startTimeMillis, 2 * 900); } TEST_P(ClusterTest, testAllClientStatesWhenUserShutdown) { HazelcastServer instance(*g_srvFactory); ClientConfig clientConfig; util::CountDownLatch startingLatch(1); util::CountDownLatch startedLatch(1); util::CountDownLatch connectedLatch(1); util::CountDownLatch disconnectedLatch(1); util::CountDownLatch shuttingDownLatch(1); util::CountDownLatch shutdownLatch(1); ClientAllStatesListener listener(&startingLatch, &startedLatch, &connectedLatch, &disconnectedLatch, &shuttingDownLatch, &shutdownLatch); clientConfig.addListener(&listener); HazelcastClient client(clientConfig); ASSERT_TRUE(startingLatch.await(0)); ASSERT_TRUE(startedLatch.await(0)); ASSERT_TRUE(connectedLatch.await(0)); client.shutdown(); ASSERT_OPEN_EVENTUALLY(shuttingDownLatch); ASSERT_OPEN_EVENTUALLY(shutdownLatch); } #ifdef HZ_BUILD_WITH_SSL INSTANTIATE_TEST_CASE_P(All, ClusterTest, ::testing::Values(new SmartTcpClientConfig(), new SmartSSLClientConfig())); #else INSTANTIATE_TEST_CASE_P(All, ClusterTest, ::testing::Values(new SmartTcpClientConfig())); #endif } } } <|endoftext|>
<commit_before>/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2012, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of Willow Garage 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. *********************************************************************/ /* Author: Ioan Sucan */ #include <moveit/rviz_plugin_render_tools/robot_state_visualization.h> #include <moveit/rviz_plugin_render_tools/planning_link_updater.h> #include <moveit/rviz_plugin_render_tools/render_shapes.h> namespace moveit_rviz_plugin { RobotStateVisualization::RobotStateVisualization(Ogre::SceneNode* root_node, rviz::DisplayContext* context, const std::string& name, rviz::Property* parent_property) : robot_(root_node, context, name, parent_property), octree_voxel_render_mode_(OCTOMAP_OCCUPIED_VOXELS), octree_voxel_color_mode_(OCTOMAP_Z_AXIS_COLOR), visible_(true), visual_visible_(true), collision_visible_(false) { default_attached_object_color_.r = 0.0f; default_attached_object_color_.g = 0.7f; default_attached_object_color_.b = 0.0f; default_attached_object_color_.a = 1.0f; render_shapes_.reset(new RenderShapes(context)); } void RobotStateVisualization::load(const urdf::ModelInterface &descr, bool visual, bool collision) { robot_.load(descr, visual, collision); robot_.setVisualVisible(visual_visible_); robot_.setCollisionVisible(collision_visible_); robot_.setVisible(visible_); } void RobotStateVisualization::clear() { robot_.clear(); render_shapes_->clear(); } void RobotStateVisualization::setDefaultAttachedObjectColor(const std_msgs::ColorRGBA &default_attached_object_color) { default_attached_object_color_ = default_attached_object_color; } void RobotStateVisualization::update(const robot_state::RobotStateConstPtr &kinematic_state) { updateHelper(kinematic_state, default_attached_object_color_, NULL); } void RobotStateVisualization::update(const robot_state::RobotStateConstPtr &kinematic_state, const std_msgs::ColorRGBA &default_attached_object_color) { updateHelper(kinematic_state, default_attached_object_color, NULL); } void RobotStateVisualization::update(const robot_state::RobotStateConstPtr &kinematic_state, const std_msgs::ColorRGBA &default_attached_object_color, const std::map<std::string, std_msgs::ColorRGBA> &color_map) { updateHelper(kinematic_state, default_attached_object_color, &color_map); } void RobotStateVisualization::updateHelper(const robot_state::RobotStateConstPtr &kinematic_state, const std_msgs::ColorRGBA &default_attached_object_color, const std::map<std::string, std_msgs::ColorRGBA> *color_map) { robot_.update(PlanningLinkUpdater(kinematic_state)); render_shapes_->clear(); std::vector<const robot_state::AttachedBody*> attached_bodies; kinematic_state->getAttachedBodies(attached_bodies); for (std::size_t i = 0 ; i < attached_bodies.size() ; ++i) { std_msgs::ColorRGBA color = default_attached_object_color; float alpha = robot_.getAlpha(); if (color_map) { std::map<std::string, std_msgs::ColorRGBA>::const_iterator it = color_map->find(attached_bodies[i]->getName()); if (it != color_map->end()) { // render attached bodies with a color that is a bit different color.r = std::max(1.0f, it->second.r * 1.05f); color.g = std::max(1.0f, it->second.g * 1.05f); color.b = std::max(1.0f, it->second.b * 1.05f); alpha = color.a = it->second.a; } } rviz::Color rcolor(color.r, color.g, color.b); const EigenSTL::vector_Affine3d &ab_t = attached_bodies[i]->getGlobalCollisionBodyTransforms(); const std::vector<shapes::ShapeConstPtr> &ab_shapes = attached_bodies[i]->getShapes(); for (std::size_t j = 0 ; j < ab_shapes.size() ; ++j) { render_shapes_->renderShape(robot_.getVisualNode(), ab_shapes[j].get(), ab_t[j], octree_voxel_render_mode_, octree_voxel_color_mode_, rcolor, alpha); render_shapes_->renderShape(robot_.getCollisionNode(), ab_shapes[j].get(), ab_t[j], octree_voxel_render_mode_, octree_voxel_color_mode_, rcolor, alpha); } } robot_.setVisualVisible(visual_visible_); robot_.setCollisionVisible(collision_visible_); robot_.setVisible(visible_); } void RobotStateVisualization::setVisible(bool visible) { visible_ = visible; robot_.setVisible(visible); } void RobotStateVisualization::setVisualVisible(bool visible) { visual_visible_ = visible; robot_.setVisualVisible(visible); } void RobotStateVisualization::setCollisionVisible(bool visible) { collision_visible_ = visible; robot_.setCollisionVisible(visible); } void RobotStateVisualization::setAlpha(float alpha) { robot_.setAlpha(alpha); } } <commit_msg>processEvents() queued by rviz when creating robot links<commit_after>/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2012, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of Willow Garage 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. *********************************************************************/ /* Author: Ioan Sucan */ #include <moveit/rviz_plugin_render_tools/robot_state_visualization.h> #include <moveit/rviz_plugin_render_tools/planning_link_updater.h> #include <moveit/rviz_plugin_render_tools/render_shapes.h> #include <QApplication> namespace moveit_rviz_plugin { RobotStateVisualization::RobotStateVisualization(Ogre::SceneNode* root_node, rviz::DisplayContext* context, const std::string& name, rviz::Property* parent_property) : robot_(root_node, context, name, parent_property), octree_voxel_render_mode_(OCTOMAP_OCCUPIED_VOXELS), octree_voxel_color_mode_(OCTOMAP_Z_AXIS_COLOR), visible_(true), visual_visible_(true), collision_visible_(false) { default_attached_object_color_.r = 0.0f; default_attached_object_color_.g = 0.7f; default_attached_object_color_.b = 0.0f; default_attached_object_color_.a = 1.0f; render_shapes_.reset(new RenderShapes(context)); } void RobotStateVisualization::load(const urdf::ModelInterface &descr, bool visual, bool collision) { robot_.load(descr, visual, collision); robot_.setVisualVisible(visual_visible_); robot_.setCollisionVisible(collision_visible_); robot_.setVisible(visible_); QApplication::processEvents(); } void RobotStateVisualization::clear() { robot_.clear(); render_shapes_->clear(); } void RobotStateVisualization::setDefaultAttachedObjectColor(const std_msgs::ColorRGBA &default_attached_object_color) { default_attached_object_color_ = default_attached_object_color; } void RobotStateVisualization::update(const robot_state::RobotStateConstPtr &kinematic_state) { updateHelper(kinematic_state, default_attached_object_color_, NULL); } void RobotStateVisualization::update(const robot_state::RobotStateConstPtr &kinematic_state, const std_msgs::ColorRGBA &default_attached_object_color) { updateHelper(kinematic_state, default_attached_object_color, NULL); } void RobotStateVisualization::update(const robot_state::RobotStateConstPtr &kinematic_state, const std_msgs::ColorRGBA &default_attached_object_color, const std::map<std::string, std_msgs::ColorRGBA> &color_map) { updateHelper(kinematic_state, default_attached_object_color, &color_map); } void RobotStateVisualization::updateHelper(const robot_state::RobotStateConstPtr &kinematic_state, const std_msgs::ColorRGBA &default_attached_object_color, const std::map<std::string, std_msgs::ColorRGBA> *color_map) { robot_.update(PlanningLinkUpdater(kinematic_state)); render_shapes_->clear(); std::vector<const robot_state::AttachedBody*> attached_bodies; kinematic_state->getAttachedBodies(attached_bodies); for (std::size_t i = 0 ; i < attached_bodies.size() ; ++i) { std_msgs::ColorRGBA color = default_attached_object_color; float alpha = robot_.getAlpha(); if (color_map) { std::map<std::string, std_msgs::ColorRGBA>::const_iterator it = color_map->find(attached_bodies[i]->getName()); if (it != color_map->end()) { // render attached bodies with a color that is a bit different color.r = std::max(1.0f, it->second.r * 1.05f); color.g = std::max(1.0f, it->second.g * 1.05f); color.b = std::max(1.0f, it->second.b * 1.05f); alpha = color.a = it->second.a; } } rviz::Color rcolor(color.r, color.g, color.b); const EigenSTL::vector_Affine3d &ab_t = attached_bodies[i]->getGlobalCollisionBodyTransforms(); const std::vector<shapes::ShapeConstPtr> &ab_shapes = attached_bodies[i]->getShapes(); for (std::size_t j = 0 ; j < ab_shapes.size() ; ++j) { render_shapes_->renderShape(robot_.getVisualNode(), ab_shapes[j].get(), ab_t[j], octree_voxel_render_mode_, octree_voxel_color_mode_, rcolor, alpha); render_shapes_->renderShape(robot_.getCollisionNode(), ab_shapes[j].get(), ab_t[j], octree_voxel_render_mode_, octree_voxel_color_mode_, rcolor, alpha); } } robot_.setVisualVisible(visual_visible_); robot_.setCollisionVisible(collision_visible_); robot_.setVisible(visible_); } void RobotStateVisualization::setVisible(bool visible) { visible_ = visible; robot_.setVisible(visible); } void RobotStateVisualization::setVisualVisible(bool visible) { visual_visible_ = visible; robot_.setVisualVisible(visible); } void RobotStateVisualization::setCollisionVisible(bool visible) { collision_visible_ = visible; robot_.setCollisionVisible(visible); } void RobotStateVisualization::setAlpha(float alpha) { robot_.setAlpha(alpha); } } <|endoftext|>
<commit_before>/* * Copyright (C) 2011 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 "space_test.h" #include "large_object_space.h" namespace art { namespace gc { namespace space { class LargeObjectSpaceTest : public SpaceTest { public: void LargeObjectTest(); }; void LargeObjectSpaceTest::LargeObjectTest() { size_t rand_seed = 0; for (size_t i = 0; i < 2; ++i) { LargeObjectSpace* los = nullptr; if (i == 0) { los = space::LargeObjectMapSpace::Create("large object space"); } else { los = space::FreeListSpace::Create("large object space", nullptr, 128 * MB); } static const size_t num_allocations = 64; static const size_t max_allocation_size = 0x100000; std::vector<std::pair<mirror::Object*, size_t>> requests; for (size_t phase = 0; phase < 2; ++phase) { while (requests.size() < num_allocations) { size_t request_size = test_rand(&rand_seed) % max_allocation_size; size_t allocation_size = 0; mirror::Object* obj = los->Alloc(Thread::Current(), request_size, &allocation_size, nullptr); ASSERT_TRUE(obj != nullptr); ASSERT_EQ(allocation_size, los->AllocationSize(obj, nullptr)); ASSERT_GE(allocation_size, request_size); // Fill in our magic value. byte magic = (request_size & 0xFF) | 1; memset(obj, magic, request_size); requests.push_back(std::make_pair(obj, request_size)); } // "Randomly" shuffle the requests. for (size_t k = 0; k < 10; ++k) { for (size_t j = 0; j < requests.size(); ++j) { std::swap(requests[j], requests[test_rand(&rand_seed) % requests.size()]); } } // Free 1 / 2 the allocations the first phase, and all the second phase. size_t limit = !phase ? requests.size() / 2 : 0; while (requests.size() > limit) { mirror::Object* obj = requests.back().first; size_t request_size = requests.back().second; requests.pop_back(); byte magic = (request_size & 0xFF) | 1; for (size_t k = 0; k < request_size; ++k) { ASSERT_EQ(reinterpret_cast<const byte*>(obj)[k], magic); } ASSERT_GE(los->Free(Thread::Current(), obj), request_size); } } size_t bytes_allocated = 0; // Checks that the coalescing works. mirror::Object* obj = los->Alloc(Thread::Current(), 100 * MB, &bytes_allocated, nullptr); EXPECT_TRUE(obj != nullptr); los->Free(Thread::Current(), obj); EXPECT_EQ(0U, los->GetBytesAllocated()); EXPECT_EQ(0U, los->GetObjectsAllocated()); delete los; } } TEST_F(LargeObjectSpaceTest, LargeObjectTest) { LargeObjectTest(); } } // namespace space } // namespace gc } // namespace art <commit_msg>am 5e036d82: am fbc3e0ba: Merge "ART: Add thread safety test for LargeObjectSpace"<commit_after>/* * Copyright (C) 2011 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 "space_test.h" #include "large_object_space.h" namespace art { namespace gc { namespace space { class LargeObjectSpaceTest : public SpaceTest { public: void LargeObjectTest(); static constexpr size_t kNumThreads = 10; static constexpr size_t kNumIterations = 1000; void RaceTest(); }; void LargeObjectSpaceTest::LargeObjectTest() { size_t rand_seed = 0; for (size_t i = 0; i < 2; ++i) { LargeObjectSpace* los = nullptr; if (i == 0) { los = space::LargeObjectMapSpace::Create("large object space"); } else { los = space::FreeListSpace::Create("large object space", nullptr, 128 * MB); } static const size_t num_allocations = 64; static const size_t max_allocation_size = 0x100000; std::vector<std::pair<mirror::Object*, size_t>> requests; for (size_t phase = 0; phase < 2; ++phase) { while (requests.size() < num_allocations) { size_t request_size = test_rand(&rand_seed) % max_allocation_size; size_t allocation_size = 0; mirror::Object* obj = los->Alloc(Thread::Current(), request_size, &allocation_size, nullptr); ASSERT_TRUE(obj != nullptr); ASSERT_EQ(allocation_size, los->AllocationSize(obj, nullptr)); ASSERT_GE(allocation_size, request_size); // Fill in our magic value. byte magic = (request_size & 0xFF) | 1; memset(obj, magic, request_size); requests.push_back(std::make_pair(obj, request_size)); } // "Randomly" shuffle the requests. for (size_t k = 0; k < 10; ++k) { for (size_t j = 0; j < requests.size(); ++j) { std::swap(requests[j], requests[test_rand(&rand_seed) % requests.size()]); } } // Free 1 / 2 the allocations the first phase, and all the second phase. size_t limit = !phase ? requests.size() / 2 : 0; while (requests.size() > limit) { mirror::Object* obj = requests.back().first; size_t request_size = requests.back().second; requests.pop_back(); byte magic = (request_size & 0xFF) | 1; for (size_t k = 0; k < request_size; ++k) { ASSERT_EQ(reinterpret_cast<const byte*>(obj)[k], magic); } ASSERT_GE(los->Free(Thread::Current(), obj), request_size); } } size_t bytes_allocated = 0; // Checks that the coalescing works. mirror::Object* obj = los->Alloc(Thread::Current(), 100 * MB, &bytes_allocated, nullptr); EXPECT_TRUE(obj != nullptr); los->Free(Thread::Current(), obj); EXPECT_EQ(0U, los->GetBytesAllocated()); EXPECT_EQ(0U, los->GetObjectsAllocated()); delete los; } } class AllocRaceTask : public Task { public: AllocRaceTask(size_t id, size_t iterations, size_t size, LargeObjectSpace* los) : id_(id), iterations_(iterations), size_(size), los_(los) {} void Run(Thread* self) { for (size_t i = 0; i < iterations_ ; ++i) { size_t alloc_size; mirror::Object* ptr = los_->Alloc(self, size_, &alloc_size, nullptr); NanoSleep((id_ + 3) * 1000); // (3+id) mu s los_->Free(self, ptr); } } virtual void Finalize() { delete this; } private: size_t id_; size_t iterations_; size_t size_; LargeObjectSpace* los_; }; void LargeObjectSpaceTest::RaceTest() { for (size_t los_type = 0; los_type < 2; ++los_type) { LargeObjectSpace* los = nullptr; if (los_type == 0) { los = space::LargeObjectMapSpace::Create("large object space"); } else { los = space::FreeListSpace::Create("large object space", nullptr, 128 * MB); } Thread* self = Thread::Current(); ThreadPool thread_pool("Large object space test thread pool", kNumThreads); for (size_t i = 0; i < kNumThreads; ++i) { thread_pool.AddTask(self, new AllocRaceTask(i, kNumIterations, 16 * KB, los)); } thread_pool.StartWorkers(self); thread_pool.Wait(self, true, false); delete los; } } TEST_F(LargeObjectSpaceTest, LargeObjectTest) { LargeObjectTest(); } TEST_F(LargeObjectSpaceTest, RaceTest) { RaceTest(); } } // namespace space } // namespace gc } // namespace art <|endoftext|>
<commit_before>#include <Player.h> #include <Globals.h> using namespace uth; Player::Player() : GameObject("Player") { AddChild(m_base = new GameObject()); m_base->AddTags({ "Player", "Base" }); m_base->AddComponent(new Sprite("PlayerBase.png")); AddChild(m_tip = new GameObject()); m_tip->AddTags({ "Player", "Tip" }); m_tip->AddComponent(new Sprite("PlayerTip.png")); Globals::SCORE = 0; } void Player::update(float dt) { pmath::Vec2 tipPos = m_tip->transform.GetPosition(); m_tip->transform.Move((tipPos + uth::Randomizer::InsideCircle((1 + tipPos.length())/10)) * dt); transform.Move(pmath::Mat2::createRotation(90) * tipPos * dt); } <commit_msg>added player movement<commit_after>#include <Player.h> #include <Globals.h> using namespace uth; pmath::Vec2 control() { pmath::Vec2 retVal; if (uthInput.Keyboard.IsKeyDown(Keyboard::Numpad1)) { retVal.x -= 1; retVal.y += 1; } if (uthInput.Keyboard.IsKeyDown(Keyboard::Numpad2) || uthInput.Keyboard.IsKeyDown(Keyboard::Down)) { retVal.y += 1; } if (uthInput.Keyboard.IsKeyDown(Keyboard::Numpad3)) { retVal.x += 1; retVal.y += 1; } if (uthInput.Keyboard.IsKeyDown(Keyboard::Numpad4) || uthInput.Keyboard.IsKeyDown(Keyboard::Left)) { retVal.x -= 1; } if (uthInput.Keyboard.IsKeyDown(Keyboard::Numpad6) || uthInput.Keyboard.IsKeyDown(Keyboard::Right)) { retVal.x += 1; } if (uthInput.Keyboard.IsKeyDown(Keyboard::Numpad7)) { retVal.x -= 1; retVal.y -= 1; } if (uthInput.Keyboard.IsKeyDown(Keyboard::Numpad8) || uthInput.Keyboard.IsKeyDown(Keyboard::Up)) { retVal.y -= 1; } if (uthInput.Keyboard.IsKeyDown(Keyboard::Numpad9)) { retVal.y -= 1; retVal.x += 1; } if (retVal != pmath::Vec2()) return retVal.normalize(); return retVal; } Player::Player() : GameObject("Player") { AddChild(m_base = new GameObject()); m_base->AddTags({ "Player", "Base" }); m_base->AddComponent(new Sprite("PlayerBase.png")); AddChild(m_tip = new GameObject()); m_tip->AddTags({ "Player", "Tip" }); m_tip->AddComponent(new Sprite("PlayerTip.png")); Globals::SCORE = 0; } void Player::update(float dt) { const pmath::Vec2 tipPos = m_tip->transform.GetPosition(); m_tip->transform.Move((/*tipPos +*/ uth::Randomizer::InsideCircle((5 + pow(tipPos.length(),0.1))/10)) * dt); m_tip->transform.Move(control() * dt * 80); pmath::Vec2 movement = pmath::Mat2::createRotation(90) * m_tip->transform.GetPosition() * sqrt(m_tip->transform.GetPosition().length()) * dt * 0.8f; m_tip->transform.Move(movement); transform.Move(-movement * 0.2); } <|endoftext|>
<commit_before>#include <SDL2/SDL.h> #ifdef main #undef main #endif #include "cudaray.h" #include <vector> #ifdef HAVE_OPENMP #include <omp.h> #endif static float rnd() { static long a = 3; a = (((a * 214013L + 2531011L) >> 16) & 32767); return (((a % 65556) + 1)) / 65556.0f; } struct t_light_aux { float r; float xangle; float yangle; float speed; }; double time_get() { uint64_t time = SDL_GetPerformanceCounter(); uint64_t frequency = SDL_GetPerformanceFrequency(); return ((double)time) / ((double)frequency); } int main( int argc, char * argv[] ) { int width = 800; int height = 800; int sphere_columns = 4; int sphere_rows = 4; int block_width = 32; int block_height = 32; bool cpu_mode = false; bool benchmark_mode = false; for( int i = 1; i < argc; ++i ) { char * arg = argv[i]; if( !strcmp( arg, "--cpu" ) ) cpu_mode = true; else if( !strcmp( arg, "--width" ) ) { i++; width = atoi( argv[i] ); } else if( !strcmp( arg, "--height" ) ) { i++; height = atoi( argv[i] ); } else if( !strcmp( arg, "--rows" ) ) { i++; sphere_rows = atoi( argv[i] ); } else if( !strcmp( arg, "--columns" ) ) { i++; sphere_columns = atoi( argv[i] ); } else if( !strcmp( arg, "--benchmark" ) ) { benchmark_mode = true; printf( "benchmark mode\n" ); } else if( !strcmp( arg, "--block-width" ) ) { i++; block_width = atoi( argv[i] ); } else if( !strcmp( arg, "--block-height" ) ) { i++; block_height = atoi( argv[i] ); } } if( cpu_mode ) { #ifdef HAVE_OPENMP omp_set_dynamic(0); printf( "running with OpenMP (use OMP_NUM_THREADS to change number of threads)\n" ); #else printf( "running on the CPU\n" ); #endif } else printf( "running on the GPU\n" ); SDL_Init( SDL_INIT_VIDEO ); SDL_Window * window; SDL_Renderer * renderer; SDL_CreateWindowAndRenderer( width, height, SDL_WINDOW_SHOWN, &window, &renderer ); SDL_Texture * texture = SDL_CreateTexture( renderer, SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_STREAMING, width, height ); SDL_RenderSetLogicalSize( renderer, width, height ); std :: vector< t_sphere > spheres; const int sphere_vertical_stride = height / sphere_rows; const int sphere_horizontal_stride = width / sphere_columns; const int n_spheres = sphere_rows * sphere_columns; for( int i = 0; i < n_spheres; ++i ) { t_sphere sphere; int y = i / sphere_columns; int x = i - y * sphere_columns; vec3_set( sphere.position, sphere_horizontal_stride * (x + 0.5), sphere_vertical_stride * (y + 0.5), 0.0f ); vec3_set( sphere.color, 0.50 + rnd() * 0.50, 0.50 + rnd() * 0.50, 0.50 + rnd() * 0.50 ); sphere.radius = sphere_horizontal_stride / 3.0f + (rnd() - 0.5f) * 2.0f * sphere_horizontal_stride / 8.0f; spheres.push_back( sphere ); } const size_t n_lights = 1; t_light * lights = (t_light *)calloc( n_lights, sizeof( t_light ) ); t_light_aux * lights_aux = ( t_light_aux * )calloc( n_lights, sizeof( t_light_aux ) ); for( int i = 1; i < n_lights; ++i ) { t_light * light = lights + i; t_light_aux * aux = lights_aux + i; light->intensity = 0.25f + rnd(); if( light->intensity > 1.0f ) light->intensity = 1.0f; vec3_set( light->color, rnd() + 0.25f, rnd() + 0.25f, rnd() + 0.25f ); vec3_clamp( light->color, 0.0f, 1.0f ); aux->r = 50.0f + rnd() * 200.0f; aux->xangle = rnd() * 3.14; aux->yangle = rnd() * 3.14; aux->speed = rnd() * 4.0f; } lights[0].intensity = 1.0f; vec3_set( lights[0].color, 1.0f, 1.0f, 1.0f ); vec3_set( lights[0].position, width / 2.0f, height / 2.0f, 500.0f ); uint32_t * img = (uint32_t *)malloc( width * height * sizeof( uint32_t ) ); memset( &img, 0, sizeof( img ) ); float t = 0.0f; float speed = 0.3f; int acceleration = 0;; double timestamp = time_get(); int frame_counter = 0; double average = 0.0f; bool running = true; uint32_t average_count = 0; while( running ) { SDL_Event event; while( SDL_PollEvent( &event ) ) { switch( event.type ) { case SDL_KEYUP: switch( event.key.keysym.sym ) { case SDLK_ESCAPE: running = false; break; case SDLK_RIGHT: if( !event.key.repeat ) acceleration -= 1; break; case SDLK_LEFT: if( !event.key.repeat ) acceleration += 1; break; } break; case SDL_KEYDOWN: switch( event.key.keysym.sym ) { case SDLK_RIGHT: if( !event.key.repeat ) acceleration += 1; break; case SDLK_LEFT: if( !event.key.repeat ) acceleration -= 1; break; } break; } if( !running ) break; } if( !running ) break; vec3_set( lights[0].position, width / 2.0f, height / 2.0f, 300.0f ); t_vec3 shift; vec3_set( shift, (150.0f) * cosf(t), 0.0f, (150.0f) * sinf(t) ); vec3_add( lights[0].position, shift ); for( int i = 1; i < n_lights; ++i ) { t_light * light = lights + i; t_light_aux * aux = lights_aux + i; t_vec3 shift; vec3_set( shift, aux->r * cosf( aux->xangle ) * sin( aux->yangle ), aux->r * sin( aux->xangle ) * cos( aux->yangle ), aux->r * sinf( aux->yangle ) ); vec3_set( light->position, width / 2.0f, height / 2.0f, 0.0f ); vec3_add( light->position, shift ); aux->xangle += speed * aux->speed; aux->yangle += speed * aux->speed; } if( cpu_mode ) cuda_main_cpu( width, height, (uint32_t *)img, &spheres.front(), spheres.size(), lights, n_lights, 0, 0 ); else cuda_main( width, height, (uint32_t *)img, &spheres.front(), spheres.size(), lights, n_lights, block_width, block_height ); SDL_UpdateTexture( texture, NULL, img, width * sizeof( uint32_t ) ); SDL_RenderClear( renderer ); SDL_RenderCopy( renderer, texture, NULL, NULL ); SDL_RenderPresent( renderer ); SDL_Delay( 2 ); t += speed; speed += acceleration * 0.01f; frame_counter++; if( frame_counter == 10 ) { frame_counter = 0; double now = time_get(); double time_per_frame = (now - timestamp) / 10.0; timestamp = now; printf( "time per frame: %fms\n", time_per_frame * 1000.0 ); if( average_count == 1 ) average = time_per_frame; else if( average_count > 1 ) average = (average + time_per_frame) / 2.0; if( average_count == 5 && benchmark_mode ) break; average_count++; } } printf( "average time per frame: %fms\n", average * 1000.0 ); SDL_DestroyWindow( window ); SDL_Quit(); return 0; } <commit_msg>Fix crash introduced in the previous commit.<commit_after>#include <SDL2/SDL.h> #ifdef main #undef main #endif #include "cudaray.h" #include <vector> #ifdef HAVE_OPENMP #include <omp.h> #endif static float rnd() { static long a = 3; a = (((a * 214013L + 2531011L) >> 16) & 32767); return (((a % 65556) + 1)) / 65556.0f; } struct t_light_aux { float r; float xangle; float yangle; float speed; }; double time_get() { uint64_t time = SDL_GetPerformanceCounter(); uint64_t frequency = SDL_GetPerformanceFrequency(); return ((double)time) / ((double)frequency); } int main( int argc, char * argv[] ) { int width = 800; int height = 800; int sphere_columns = 4; int sphere_rows = 4; int block_width = 32; int block_height = 32; bool cpu_mode = false; bool benchmark_mode = false; for( int i = 1; i < argc; ++i ) { char * arg = argv[i]; if( !strcmp( arg, "--cpu" ) ) cpu_mode = true; else if( !strcmp( arg, "--width" ) ) { i++; width = atoi( argv[i] ); } else if( !strcmp( arg, "--height" ) ) { i++; height = atoi( argv[i] ); } else if( !strcmp( arg, "--rows" ) ) { i++; sphere_rows = atoi( argv[i] ); } else if( !strcmp( arg, "--columns" ) ) { i++; sphere_columns = atoi( argv[i] ); } else if( !strcmp( arg, "--benchmark" ) ) { benchmark_mode = true; printf( "benchmark mode\n" ); } else if( !strcmp( arg, "--block-width" ) ) { i++; block_width = atoi( argv[i] ); } else if( !strcmp( arg, "--block-height" ) ) { i++; block_height = atoi( argv[i] ); } } if( cpu_mode ) { #ifdef HAVE_OPENMP omp_set_dynamic(0); printf( "running with OpenMP (use OMP_NUM_THREADS to change number of threads)\n" ); #else printf( "running on the CPU\n" ); #endif } else printf( "running on the GPU\n" ); SDL_Init( SDL_INIT_VIDEO ); SDL_Window * window; SDL_Renderer * renderer; SDL_CreateWindowAndRenderer( width, height, SDL_WINDOW_SHOWN, &window, &renderer ); SDL_Texture * texture = SDL_CreateTexture( renderer, SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_STREAMING, width, height ); SDL_RenderSetLogicalSize( renderer, width, height ); std :: vector< t_sphere > spheres; const int sphere_vertical_stride = height / sphere_rows; const int sphere_horizontal_stride = width / sphere_columns; const int n_spheres = sphere_rows * sphere_columns; for( int i = 0; i < n_spheres; ++i ) { t_sphere sphere; int y = i / sphere_columns; int x = i - y * sphere_columns; vec3_set( sphere.position, sphere_horizontal_stride * (x + 0.5), sphere_vertical_stride * (y + 0.5), 0.0f ); vec3_set( sphere.color, 0.50 + rnd() * 0.50, 0.50 + rnd() * 0.50, 0.50 + rnd() * 0.50 ); sphere.radius = sphere_horizontal_stride / 3.0f + (rnd() - 0.5f) * 2.0f * sphere_horizontal_stride / 8.0f; spheres.push_back( sphere ); } const size_t n_lights = 1; t_light * lights = (t_light *)calloc( n_lights, sizeof( t_light ) ); t_light_aux * lights_aux = ( t_light_aux * )calloc( n_lights, sizeof( t_light_aux ) ); for( int i = 1; i < n_lights; ++i ) { t_light * light = lights + i; t_light_aux * aux = lights_aux + i; light->intensity = 0.25f + rnd(); if( light->intensity > 1.0f ) light->intensity = 1.0f; vec3_set( light->color, rnd() + 0.25f, rnd() + 0.25f, rnd() + 0.25f ); vec3_clamp( light->color, 0.0f, 1.0f ); aux->r = 50.0f + rnd() * 200.0f; aux->xangle = rnd() * 3.14; aux->yangle = rnd() * 3.14; aux->speed = rnd() * 4.0f; } lights[0].intensity = 1.0f; vec3_set( lights[0].color, 1.0f, 1.0f, 1.0f ); vec3_set( lights[0].position, width / 2.0f, height / 2.0f, 500.0f ); uint32_t * img = (uint32_t *)malloc( width * height * sizeof( uint32_t ) ); memset( img, 0, sizeof( img ) ); float t = 0.0f; float speed = 0.3f; int acceleration = 0;; double timestamp = time_get(); int frame_counter = 0; double average = 0.0f; bool running = true; uint32_t average_count = 0; while( running ) { SDL_Event event; while( SDL_PollEvent( &event ) ) { switch( event.type ) { case SDL_KEYUP: switch( event.key.keysym.sym ) { case SDLK_ESCAPE: running = false; break; case SDLK_RIGHT: if( !event.key.repeat ) acceleration -= 1; break; case SDLK_LEFT: if( !event.key.repeat ) acceleration += 1; break; } break; case SDL_KEYDOWN: switch( event.key.keysym.sym ) { case SDLK_RIGHT: if( !event.key.repeat ) acceleration += 1; break; case SDLK_LEFT: if( !event.key.repeat ) acceleration -= 1; break; } break; } if( !running ) break; } if( !running ) break; vec3_set( lights[0].position, width / 2.0f, height / 2.0f, 300.0f ); t_vec3 shift; vec3_set( shift, (150.0f) * cosf(t), 0.0f, (150.0f) * sinf(t) ); vec3_add( lights[0].position, shift ); for( int i = 1; i < n_lights; ++i ) { t_light * light = lights + i; t_light_aux * aux = lights_aux + i; t_vec3 shift; vec3_set( shift, aux->r * cosf( aux->xangle ) * sin( aux->yangle ), aux->r * sin( aux->xangle ) * cos( aux->yangle ), aux->r * sinf( aux->yangle ) ); vec3_set( light->position, width / 2.0f, height / 2.0f, 0.0f ); vec3_add( light->position, shift ); aux->xangle += speed * aux->speed; aux->yangle += speed * aux->speed; } if( cpu_mode ) cuda_main_cpu( width, height, (uint32_t *)img, &spheres.front(), spheres.size(), lights, n_lights, 0, 0 ); else cuda_main( width, height, (uint32_t *)img, &spheres.front(), spheres.size(), lights, n_lights, block_width, block_height ); SDL_UpdateTexture( texture, NULL, img, width * sizeof( uint32_t ) ); SDL_RenderClear( renderer ); SDL_RenderCopy( renderer, texture, NULL, NULL ); SDL_RenderPresent( renderer ); SDL_Delay( 2 ); t += speed; speed += acceleration * 0.01f; frame_counter++; if( frame_counter == 10 ) { frame_counter = 0; double now = time_get(); double time_per_frame = (now - timestamp) / 10.0; timestamp = now; printf( "time per frame: %fms\n", time_per_frame * 1000.0 ); if( average_count == 1 ) average = time_per_frame; else if( average_count > 1 ) average = (average + time_per_frame) / 2.0; if( average_count == 5 && benchmark_mode ) break; average_count++; } } printf( "average time per frame: %fms\n", average * 1000.0 ); SDL_DestroyWindow( window ); SDL_Quit(); return 0; } <|endoftext|>
<commit_before>#ifndef _arena_hpp_INCLUDED #define _arena_hpp_INCLUDED #include <cassert> #include <cstdlib> #include <cstring> namespace CaDiCaL { // This memory allocation arena provides fixed size pre-allocated memory for // the moving garbage collector 'copy_non_garbage_clauses' in 'reduce.cpp' // to hold clauses which should survive garbage collection. The advantage // of using a pre-allocated arena is that the allocation order of the // clauses can be adapted in such a way that clauses watched by the same // literal are allocated consecutively. This improves locality and thus is // more cache friendly. A similar technique is implemented in MiniSAT and // Glucose and gives substantial speed-up in propagations per second even // though it might even almost double peek memory usage. Note that in // MiniSAT this arena is also required for MiniSAT to use 32 bit clauses // references instead of 64 bit pointers. This would restrict the maximum // number of clauses and thus is a restriction we do not want to use // anymore. New learned clauses are allocated in CaDiCaL outside of this // arena and moved to the arena during garbage collection. The additional // 'to' space required for such a moving garbage collector is only allocated // for those clauses surviving garbage collection, which usually needs much // less memory than all clauses. The net effect is that in this // implementation the moving garbage collector using this arena only needs // roughly 50% more memory than allocating the clauses directly. Both // implementations can be compared by varying the 'arena' option (which also // controls the allocation order of clauses during moving them). // The standard sequence of using the arena is as follows: // // Arena arena; // ... // arena.prepare (bytes); // q1 = arena.copy (p1, bytes1); // ... // qn = arena.copy (pn, bytesn); // assert (bytes1 + ... + bytesn <= bytes); // arena.swap (); // ... // if (!arena.contains (q)) delete q; // ... // arena.prepare (bytes); // q1 = arena.copy (p1, bytes1); // ... // qn = arena.copy (pn, bytesn); // assert (bytes1 + ... + bytesn <= bytes); // arena.swap (); // ... // // One has to be really careful with 'qi' references to arena memory. class Internal; class Arena { Internal * internal; struct { char * start, * top, * end; } from, to; public: Arena (Internal *); ~Arena (); // Prepare 'to' space to hold that amount of memory. Precondition is that // the 'to' space is empty. The following sequence of 'copy' operations // can use as much memory in sum as pre-allocated here. // void prepare (size_t bytes); // Does the memory pointed to by 'p' belong to this arena? More precisely // to the 'from' space, since that is the only one remaining after 'swap'. // bool contains (void * p) const { char * c = (char *) p; return from.start <= c && c < from.top; } // Allocate that amount of memory in 'to' space. This assumes the 'to' // space has been prepared to hold enough memory with 'prepare'. Then // copy the memory pointed to by 'p' of size 'bytes'. Note that it does // not matter whether 'p' is in 'from' or allocated outside of the arena. // char * copy (const char * p, size_t bytes) { char * res = to.top; to.top += bytes; assert (to.top <= to.end); memcpy (res, p, bytes); return res; } // Completely delete 'from' space and then replace 'from' by 'to' (by // pointer swapping). Everything previously allocated (in 'from') and not // explicitly copied to 'to' with 'copy' becomes invalid. // void swap (); }; }; #endif <commit_msg>went over arean<commit_after>#ifndef _arena_hpp_INCLUDED #define _arena_hpp_INCLUDED #include <cassert> #include <cstdlib> #include <cstring> namespace CaDiCaL { // This memory allocation arena provides fixed size pre-allocated memory for // the moving garbage collector 'copy_non_garbage_clauses' in 'reduce.cpp' // to hold clauses which should survive garbage collection. // The advantage of using a pre-allocated arena is that the allocation order // of the clauses can be adapted in such a way that clauses watched by the // same literal are allocated consecutively. This improves locality and // thus is more cache friendly. A similar technique is implemented in // MiniSAT and Glucose and gives substantial speed-up in propagations per // second even though it might even almost double peek memory usage. Note // that in MiniSAT this arena is also required for MiniSAT to use 32 bit // clauses references instead of 64 bit pointers. This would restrict the // maximum number of clauses and thus is a restriction we do not want to use // anymore. // New learned clauses are allocated in CaDiCaL outside of this arena and // moved to the arena during garbage collection. The additional 'to' space // required for such a moving garbage collector is only allocated for those // clauses surviving garbage collection, which usually needs much less // memory than all clauses. The net effect is that in our implementation // the moving garbage collector using this arena only needs roughly 50% more // memory than allocating the clauses directly. Both implementations can be // compared by varying the 'arena' option (which also controls the // allocation order of clauses during moving them). // The standard sequence of using the arena is as follows: // // Arena arena; // ... // arena.prepare (bytes); // q1 = arena.copy (p1, bytes1); // ... // qn = arena.copy (pn, bytesn); // assert (bytes1 + ... + bytesn <= bytes); // arena.swap (); // ... // if (!arena.contains (q)) delete q; // ... // arena.prepare (bytes); // q1 = arena.copy (p1, bytes1); // ... // qn = arena.copy (pn, bytesn); // assert (bytes1 + ... + bytesn <= bytes); // arena.swap (); // ... // // One has to be really careful with 'qi' references to arena memory. class Internal; class Arena { Internal * internal; struct { char * start, * top, * end; } from, to; public: Arena (Internal *); ~Arena (); // Prepare 'to' space to hold that amount of memory. Precondition is that // the 'to' space is empty. The following sequence of 'copy' operations // can use as much memory in sum as pre-allocated here. // void prepare (size_t bytes); // Does the memory pointed to by 'p' belong to this arena? More precisely // to the 'from' space, since that is the only one remaining after 'swap'. // bool contains (void * p) const { char * c = (char *) p; return from.start <= c && c < from.top; } // Allocate that amount of memory in 'to' space. This assumes the 'to' // space has been prepared to hold enough memory with 'prepare'. Then // copy the memory pointed to by 'p' of size 'bytes'. Note that it does // not matter whether 'p' is in 'from' or allocated outside of the arena. // char * copy (const char * p, size_t bytes) { char * res = to.top; to.top += bytes; assert (to.top <= to.end); memcpy (res, p, bytes); return res; } // Completely delete 'from' space and then replace 'from' by 'to' (by // pointer swapping). Everything previously allocated (in 'from') and not // explicitly copied to 'to' with 'copy' becomes invalid. // void swap (); }; }; #endif <|endoftext|>
<commit_before>// Copyright 2013 The Flutter 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 "flutter/shell/platform/android/android_surface_gl.h" #include <GLES/gl.h> #include <utility> #include "flutter/fml/logging.h" #include "flutter/fml/memory/ref_ptr.h" #include "flutter/shell/platform/android/android_shell_holder.h" namespace flutter { namespace { // GL renderer string prefix used by the Android emulator GLES implementation. constexpr char kEmulatorRendererPrefix[] = "Android Emulator OpenGL ES Translator"; } // anonymous namespace AndroidSurfaceGL::AndroidSurfaceGL( const std::shared_ptr<AndroidContext>& android_context, std::shared_ptr<PlatformViewAndroidJNI> jni_facade) : AndroidSurface(android_context), native_window_(nullptr), onscreen_surface_(nullptr), offscreen_surface_(nullptr) { // Acquire the offscreen surface. offscreen_surface_ = GLContextPtr()->CreateOffscreenSurface(); if (!offscreen_surface_->IsValid()) { offscreen_surface_ = nullptr; } } AndroidSurfaceGL::~AndroidSurfaceGL() = default; void AndroidSurfaceGL::TeardownOnScreenContext() { // When the onscreen surface is destroyed, the context and the surface // instance should be deleted. Issue: // https://github.com/flutter/flutter/issues/64414 GLContextPtr()->ClearCurrent(); onscreen_surface_ = nullptr; } bool AndroidSurfaceGL::IsValid() const { return offscreen_surface_ && GLContextPtr()->IsValid(); } std::unique_ptr<Surface> AndroidSurfaceGL::CreateGPUSurface( GrDirectContext* gr_context) { if (gr_context) { return std::make_unique<GPUSurfaceGL>(sk_ref_sp(gr_context), this, true); } else { sk_sp<GrDirectContext> main_skia_context = GLContextPtr()->GetMainSkiaContext(); if (!main_skia_context) { main_skia_context = GPUSurfaceGL::MakeGLContext(this); GLContextPtr()->SetMainSkiaContext(main_skia_context); } return std::make_unique<GPUSurfaceGL>(main_skia_context, this, true); } } bool AndroidSurfaceGL::OnScreenSurfaceResize(const SkISize& size) { FML_DCHECK(IsValid()); FML_DCHECK(onscreen_surface_); FML_DCHECK(native_window_); if (size == onscreen_surface_->GetSize()) { return true; } GLContextPtr()->ClearCurrent(); // Ensure the destructor is called since it destroys the `EGLSurface` before // creating a new onscreen surface. onscreen_surface_ = nullptr; onscreen_surface_ = GLContextPtr()->CreateOnscreenSurface(native_window_); if (!onscreen_surface_->IsValid()) { FML_LOG(ERROR) << "Unable to create EGL window surface on resize."; return false; } onscreen_surface_->MakeCurrent(); return true; } bool AndroidSurfaceGL::ResourceContextMakeCurrent() { FML_DCHECK(IsValid()); return offscreen_surface_->MakeCurrent(); } bool AndroidSurfaceGL::ResourceContextClearCurrent() { FML_DCHECK(IsValid()); return GLContextPtr()->ClearCurrent(); } bool AndroidSurfaceGL::SetNativeWindow( fml::RefPtr<AndroidNativeWindow> window) { FML_DCHECK(IsValid()); FML_DCHECK(window); native_window_ = window; // Ensure the destructor is called since it destroys the `EGLSurface` before // creating a new onscreen surface. onscreen_surface_ = nullptr; // Create the onscreen surface. onscreen_surface_ = GLContextPtr()->CreateOnscreenSurface(window); if (!onscreen_surface_->IsValid()) { return false; } return true; } std::unique_ptr<GLContextResult> AndroidSurfaceGL::GLContextMakeCurrent() { FML_DCHECK(IsValid()); FML_DCHECK(onscreen_surface_); auto default_context_result = std::make_unique<GLContextDefaultResult>( onscreen_surface_->MakeCurrent()); return std::move(default_context_result); } bool AndroidSurfaceGL::GLContextClearCurrent() { FML_DCHECK(IsValid()); return GLContextPtr()->ClearCurrent(); } bool AndroidSurfaceGL::GLContextPresent(uint32_t fbo_id) { FML_DCHECK(IsValid()); FML_DCHECK(onscreen_surface_); return onscreen_surface_->SwapBuffers(); } intptr_t AndroidSurfaceGL::GLContextFBO(GLFrameInfo frame_info) const { FML_DCHECK(IsValid()); // The default window bound framebuffer on Android. return 0; } // |GPUSurfaceGLDelegate| sk_sp<const GrGLInterface> AndroidSurfaceGL::GetGLInterface() const { // This is a workaround for a bug in the Android emulator EGL/GLES // implementation. Some versions of the emulator will not update the // GL version string when the process switches to a new EGL context // unless the EGL context is being made current for the first time. // The inaccurate version string will be rejected by Skia when it // tries to build the GrGLInterface. Flutter can work around this // by creating a new context, making it current to force an update // of the version, and then reverting to the previous context. const char* gl_renderer = reinterpret_cast<const char*>(glGetString(GL_RENDERER)); if (gl_renderer && strncmp(gl_renderer, kEmulatorRendererPrefix, strlen(kEmulatorRendererPrefix)) == 0) { EGLContext new_context = GLContextPtr()->CreateNewContext(); if (new_context != EGL_NO_CONTEXT) { EGLContext old_context = eglGetCurrentContext(); EGLDisplay display = eglGetCurrentDisplay(); EGLSurface draw_surface = eglGetCurrentSurface(EGL_DRAW); EGLSurface read_surface = eglGetCurrentSurface(EGL_READ); EGLBoolean result = eglMakeCurrent(display, draw_surface, read_surface, new_context); FML_DCHECK(result == EGL_TRUE); result = eglMakeCurrent(display, draw_surface, read_surface, old_context); FML_DCHECK(result == EGL_TRUE); result = eglDestroyContext(display, new_context); FML_DCHECK(result == EGL_TRUE); } } return GPUSurfaceGLDelegate::GetGLInterface(); } AndroidContextGL* AndroidSurfaceGL::GLContextPtr() const { return reinterpret_cast<AndroidContextGL*>(android_context_.get()); } } // namespace flutter <commit_msg>Fix a leak of the resource EGL context on Android (#26789)<commit_after>// Copyright 2013 The Flutter 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 "flutter/shell/platform/android/android_surface_gl.h" #include <GLES/gl.h> #include <utility> #include "flutter/fml/logging.h" #include "flutter/fml/memory/ref_ptr.h" #include "flutter/shell/platform/android/android_shell_holder.h" namespace flutter { namespace { // GL renderer string prefix used by the Android emulator GLES implementation. constexpr char kEmulatorRendererPrefix[] = "Android Emulator OpenGL ES Translator"; } // anonymous namespace AndroidSurfaceGL::AndroidSurfaceGL( const std::shared_ptr<AndroidContext>& android_context, std::shared_ptr<PlatformViewAndroidJNI> jni_facade) : AndroidSurface(android_context), native_window_(nullptr), onscreen_surface_(nullptr), offscreen_surface_(nullptr) { // Acquire the offscreen surface. offscreen_surface_ = GLContextPtr()->CreateOffscreenSurface(); if (!offscreen_surface_->IsValid()) { offscreen_surface_ = nullptr; } } AndroidSurfaceGL::~AndroidSurfaceGL() = default; void AndroidSurfaceGL::TeardownOnScreenContext() { // When the onscreen surface is destroyed, the context and the surface // instance should be deleted. Issue: // https://github.com/flutter/flutter/issues/64414 GLContextPtr()->ClearCurrent(); onscreen_surface_ = nullptr; } bool AndroidSurfaceGL::IsValid() const { return offscreen_surface_ && GLContextPtr()->IsValid(); } std::unique_ptr<Surface> AndroidSurfaceGL::CreateGPUSurface( GrDirectContext* gr_context) { if (gr_context) { return std::make_unique<GPUSurfaceGL>(sk_ref_sp(gr_context), this, true); } else { sk_sp<GrDirectContext> main_skia_context = GLContextPtr()->GetMainSkiaContext(); if (!main_skia_context) { main_skia_context = GPUSurfaceGL::MakeGLContext(this); GLContextPtr()->SetMainSkiaContext(main_skia_context); } return std::make_unique<GPUSurfaceGL>(main_skia_context, this, true); } } bool AndroidSurfaceGL::OnScreenSurfaceResize(const SkISize& size) { FML_DCHECK(IsValid()); FML_DCHECK(onscreen_surface_); FML_DCHECK(native_window_); if (size == onscreen_surface_->GetSize()) { return true; } GLContextPtr()->ClearCurrent(); // Ensure the destructor is called since it destroys the `EGLSurface` before // creating a new onscreen surface. onscreen_surface_ = nullptr; onscreen_surface_ = GLContextPtr()->CreateOnscreenSurface(native_window_); if (!onscreen_surface_->IsValid()) { FML_LOG(ERROR) << "Unable to create EGL window surface on resize."; return false; } onscreen_surface_->MakeCurrent(); return true; } bool AndroidSurfaceGL::ResourceContextMakeCurrent() { FML_DCHECK(IsValid()); return offscreen_surface_->MakeCurrent(); } bool AndroidSurfaceGL::ResourceContextClearCurrent() { FML_DCHECK(IsValid()); EGLBoolean result = eglMakeCurrent(eglGetCurrentDisplay(), EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); return result == EGL_TRUE; } bool AndroidSurfaceGL::SetNativeWindow( fml::RefPtr<AndroidNativeWindow> window) { FML_DCHECK(IsValid()); FML_DCHECK(window); native_window_ = window; // Ensure the destructor is called since it destroys the `EGLSurface` before // creating a new onscreen surface. onscreen_surface_ = nullptr; // Create the onscreen surface. onscreen_surface_ = GLContextPtr()->CreateOnscreenSurface(window); if (!onscreen_surface_->IsValid()) { return false; } return true; } std::unique_ptr<GLContextResult> AndroidSurfaceGL::GLContextMakeCurrent() { FML_DCHECK(IsValid()); FML_DCHECK(onscreen_surface_); auto default_context_result = std::make_unique<GLContextDefaultResult>( onscreen_surface_->MakeCurrent()); return std::move(default_context_result); } bool AndroidSurfaceGL::GLContextClearCurrent() { FML_DCHECK(IsValid()); return GLContextPtr()->ClearCurrent(); } bool AndroidSurfaceGL::GLContextPresent(uint32_t fbo_id) { FML_DCHECK(IsValid()); FML_DCHECK(onscreen_surface_); return onscreen_surface_->SwapBuffers(); } intptr_t AndroidSurfaceGL::GLContextFBO(GLFrameInfo frame_info) const { FML_DCHECK(IsValid()); // The default window bound framebuffer on Android. return 0; } // |GPUSurfaceGLDelegate| sk_sp<const GrGLInterface> AndroidSurfaceGL::GetGLInterface() const { // This is a workaround for a bug in the Android emulator EGL/GLES // implementation. Some versions of the emulator will not update the // GL version string when the process switches to a new EGL context // unless the EGL context is being made current for the first time. // The inaccurate version string will be rejected by Skia when it // tries to build the GrGLInterface. Flutter can work around this // by creating a new context, making it current to force an update // of the version, and then reverting to the previous context. const char* gl_renderer = reinterpret_cast<const char*>(glGetString(GL_RENDERER)); if (gl_renderer && strncmp(gl_renderer, kEmulatorRendererPrefix, strlen(kEmulatorRendererPrefix)) == 0) { EGLContext new_context = GLContextPtr()->CreateNewContext(); if (new_context != EGL_NO_CONTEXT) { EGLContext old_context = eglGetCurrentContext(); EGLDisplay display = eglGetCurrentDisplay(); EGLSurface draw_surface = eglGetCurrentSurface(EGL_DRAW); EGLSurface read_surface = eglGetCurrentSurface(EGL_READ); EGLBoolean result = eglMakeCurrent(display, draw_surface, read_surface, new_context); FML_DCHECK(result == EGL_TRUE); result = eglMakeCurrent(display, draw_surface, read_surface, old_context); FML_DCHECK(result == EGL_TRUE); result = eglDestroyContext(display, new_context); FML_DCHECK(result == EGL_TRUE); } } return GPUSurfaceGLDelegate::GetGLInterface(); } AndroidContextGL* AndroidSurfaceGL::GLContextPtr() const { return reinterpret_cast<AndroidContextGL*>(android_context_.get()); } } // namespace flutter <|endoftext|>
<commit_before>/* * Copyright (C) 2013 midnightBITS * * 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. */ #ifdef _WIN32 #include <sdkddkver.h> #endif #include <http/http.hpp> #include <http/server.hpp> #include <ssdp.hpp> #include <media_server.hpp> #include <boost/filesystem.hpp> #include <log.hpp> #include <config.hpp> #include <threads.hpp> namespace fs = boost::filesystem; namespace av = net::ssdp::import::av; namespace lan { extern Log::Module APP; struct log : public Log::basic_log<log> { static const Log::Module& module() { return APP; } }; namespace item { av::items::media_item_ptr from_path(av::MediaServer* device, const fs::path& path); } struct radio { radio(const net::ssdp::device_ptr& device, const net::config::config_ptr& config) : m_service() , m_signals(m_service) , m_upnp(m_service, device, config) { m_signals.add(SIGINT); m_signals.add(SIGTERM); #if defined(SIGQUIT) m_signals.add(SIGQUIT); #endif // defined(SIGQUIT) m_signals.async_wait([&](boost::system::error_code, int) { m_upnp.stop(); }); m_upnp.start(); } void run() { m_service.run(); } private: boost::asio::io_service m_service; boost::asio::signal_set m_signals; net::ssdp::server m_upnp; }; } #ifdef _WIN32 # define HAS_TERMINAL_API void set_terminal_title(const std::string& title) { SetConsoleTitleA(title.c_str()); } #endif void set_terminal_title(const net::config::config_ptr& config) { #ifdef HAS_TERMINAL_API std::ostringstream title; title << "LAN Radio [" << boost::asio::ip::host_name() << ", " << config->iface << ":" << config->port << "]"; set_terminal_title(title.str()); #endif } int main(int argc, char* argv []) { try { threads::set_name("main"); lan::log::info() << "\nStarting...\n"; net::ssdp::device_info info = { { "lanRadio", 0, 1 }, { "lanRadio", "LAN Radio [" + boost::asio::ip::host_name() + "]", "01", "http://www.midnightbits.org/lanRadio" }, { "midnightBITS", "http://www.midnightbits.com" } }; auto config = net::config::config::from_file("lanradio.conf"); set_terminal_title(config); auto server = std::make_shared<av::MediaServer>(info, config); for (int arg = 1; arg < argc; ++arg) { auto path = fs::absolute(argv[arg]); if (!fs::exists(path)) continue; if (fs::is_directory(path) && path.filename() == ".") path = path.parent_path(); auto item = lan::item::from_path(server.get(), path); if (item) { lan::log::info() << "Adding " << path; server->add_root_element(item); } } lan::radio lanRadio(server, config); lanRadio.run(); } catch (std::exception& e) { std::cerr << "Exception: " << e.what() << "\n"; } return 0; } <commit_msg>Memory checking<commit_after>/* * Copyright (C) 2013 midnightBITS * * 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. */ #ifdef _WIN32 #include <sdkddkver.h> #endif #include <http/http.hpp> #include <http/server.hpp> #include <ssdp.hpp> #include <media_server.hpp> #include <boost/filesystem.hpp> #include <log.hpp> #include <config.hpp> #include <threads.hpp> #include <boost/date_time/posix_time/posix_time.hpp> namespace fs = boost::filesystem; namespace av = net::ssdp::import::av; #if defined(DBG_ALLOCS) static size_t all_allocs = 0; void* operator new (size_t size) { void *out = ::malloc(size + sizeof(size_t)); if (!out) throw new std::bad_alloc(); size_t* p = (size_t*) out; *p = size; all_allocs += size; return p + 1; } void operator delete (void* ptr) { if (!ptr) return; size_t* p = (size_t*) ptr; --p; all_allocs -= *p; ::free(p); } void* operator new[] (size_t size) { void *out = ::malloc(size + sizeof(size_t)); if (!out) throw new std::bad_alloc(); size_t* p = (size_t*) out; *p = size; all_allocs += size; return p + 1; } void operator delete[] (void* ptr) { if (!ptr) return; size_t* p = (size_t*) ptr; --p; all_allocs -= *p; ::free(p); } #endif // defined(DBG_ALLOCS) namespace lan { extern Log::Module APP; #if defined(DBG_ALLOCS) extern Log::Module Memory{ "Memory" }; #endif struct log : public Log::basic_log<log> { static const Log::Module& module() { return APP; } }; #if defined(DBG_ALLOCS) struct memlog : public Log::basic_log<memlog> { static const Log::Module& module() { return Memory; } }; #endif namespace item { av::items::media_item_ptr from_path(av::MediaServer* device, const fs::path& path); } struct radio { radio(const net::ssdp::device_ptr& device, const net::config::config_ptr& config) : m_service() , m_signals(m_service) #if defined(DBG_ALLOCS) , m_timer(m_service, boost::posix_time::seconds(1)) #endif , m_upnp(m_service, device, config) { m_signals.add(SIGINT); m_signals.add(SIGTERM); #if defined(SIGQUIT) m_signals.add(SIGQUIT); #endif // defined(SIGQUIT) m_signals.async_wait([&](boost::system::error_code, int) { m_upnp.stop(); #if defined(DBG_ALLOCS) m_timer.cancel(); #endif }); #if defined(DBG_ALLOCS) m_timer.async_wait([this](const boost::system::error_code & /*e*/){ memlog::info() << all_allocs; m_timer.expires_at(m_timer.expires_at() + boost::posix_time::seconds(30)); }); #endif m_upnp.start(); } void run() { m_service.run(); } private: boost::asio::io_service m_service; boost::asio::signal_set m_signals; #if defined(DBG_ALLOCS) boost::asio::deadline_timer m_timer; #endif net::ssdp::server m_upnp; }; } #ifdef _WIN32 # define HAS_TERMINAL_API void set_terminal_title(const std::string& title) { SetConsoleTitleA(title.c_str()); } #endif void set_terminal_title(const net::config::config_ptr& config) { #ifdef HAS_TERMINAL_API std::ostringstream title; title << "LAN Radio [" << boost::asio::ip::host_name() << ", " << config->iface << ":" << config->port << "]"; set_terminal_title(title.str()); #endif } int main(int argc, char* argv []) { try { threads::set_name("main"); lan::log::info() << "\nStarting...\n"; net::ssdp::device_info info = { { "lanRadio", 0, 1 }, { "lanRadio", "LAN Radio [" + boost::asio::ip::host_name() + "]", "01", "http://www.midnightbits.org/lanRadio" }, { "midnightBITS", "http://www.midnightbits.com" } }; auto config = net::config::config::from_file("lanradio.conf"); set_terminal_title(config); auto server = std::make_shared<av::MediaServer>(info, config); for (int arg = 1; arg < argc; ++arg) { auto path = fs::absolute(argv[arg]); if (!fs::exists(path)) continue; if (fs::is_directory(path) && path.filename() == ".") path = path.parent_path(); auto item = lan::item::from_path(server.get(), path); if (item) { lan::log::info() << "Adding " << path; server->add_root_element(item); } } lan::radio lanRadio(server, config); lanRadio.run(); #if defined(DBG_ALLOCS) lan::memlog::info() << all_allocs; #endif } catch (std::exception& e) { std::cerr << "Exception: " << e.what() << "\n"; } return 0; } <|endoftext|>
<commit_before>// Copyright (c) 2018 PaddlePaddle 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 "paddle/fluid/framework/details/fetch_op_handle.h" #include <string> #include <vector> #include "paddle/fluid/platform/profiler.h" namespace paddle { namespace framework { namespace details { FetchOpHandle::FetchOpHandle(ir::Node *node, FeedFetchList *data, size_t offset, std::vector<Scope *> *local_scopes) : OpHandleBase(node), data_(data), offset_(offset), local_scopes_(local_scopes) {} FetchOpHandle::~FetchOpHandle() {} void FetchOpHandle::RecordWaitEventOnCtx(platform::DeviceContext *waited_ctx) { PADDLE_THROW("Nobody should wait FetchOp. Unexpceted Error"); } void FetchOpHandle::WaitAndMergeCPUTensors() const { std::vector<const LoDTensor *> tensors_ptr; tensors_ptr.reserve(tensors_.size()); for (auto &t : tensors_) { tensors_ptr.emplace_back(&t); } data_->at(offset_).MergeLoDTensor(tensors_ptr, platform::CPUPlace()); } void FetchOpHandle::RunImpl() { platform::RecordEvent record_event(Name()); WaitInputVarGenerated(platform::CPUPlace()); tensors_.resize(inputs_.size()); platform::CPUPlace cpu; auto &scopes = *local_scopes_; for (size_t i = 0; i < inputs_.size(); ++i) { auto *var_handle = static_cast<VarHandle *>(inputs_[i]); auto &scope = scopes.at(var_handle->scope_idx()); auto *var = scope->FindVar(kLocalExecScopeName) ->Get<Scope *>() ->FindVar(var_handle->name()); PADDLE_ENFORCE_NOT_NULL(var, "Cannot find variable %s in execution scope", var_handle->name()); auto &t = var->Get<framework::LoDTensor>(); if (platform::is_gpu_place(t.place())) { #ifdef PADDLE_WITH_CUDA TensorCopy(t, cpu, *dev_ctxes_.at(t.place()), &tensors_[i]); dev_ctxes_.at(t.place())->Wait(); #endif } else { tensors_[i].ShareDataWith(t); } tensors_[i].set_lod(t.lod()); } this->WaitAndMergeCPUTensors(); } void FetchOpHandle::WaitInputVarGenerated(const platform::Place &place) { auto cpu_ctx = platform::DeviceContextPool::Instance().Get(place); for (auto *input : inputs_) { if (input->GeneratedOp()) { input->GeneratedOp()->RecordWaitEventOnCtx(cpu_ctx); } } } bool FetchOpHandle::IsMultiDeviceTransfer() { return true; } std::string FetchOpHandle::Name() const { return "Fetch"; } } // namespace details } // namespace framework } // namespace paddle <commit_msg>use sync copy (#17291)<commit_after>// Copyright (c) 2018 PaddlePaddle 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 "paddle/fluid/framework/details/fetch_op_handle.h" #include <string> #include <vector> #include "paddle/fluid/platform/profiler.h" namespace paddle { namespace framework { namespace details { FetchOpHandle::FetchOpHandle(ir::Node *node, FeedFetchList *data, size_t offset, std::vector<Scope *> *local_scopes) : OpHandleBase(node), data_(data), offset_(offset), local_scopes_(local_scopes) {} FetchOpHandle::~FetchOpHandle() {} void FetchOpHandle::RecordWaitEventOnCtx(platform::DeviceContext *waited_ctx) { PADDLE_THROW("Nobody should wait FetchOp. Unexpceted Error"); } void FetchOpHandle::WaitAndMergeCPUTensors() const { std::vector<const LoDTensor *> tensors_ptr; tensors_ptr.reserve(tensors_.size()); for (auto &t : tensors_) { tensors_ptr.emplace_back(&t); } data_->at(offset_).MergeLoDTensor(tensors_ptr, platform::CPUPlace()); } void FetchOpHandle::RunImpl() { platform::RecordEvent record_event(Name()); WaitInputVarGenerated(platform::CPUPlace()); tensors_.resize(inputs_.size()); platform::CPUPlace cpu; auto &scopes = *local_scopes_; for (size_t i = 0; i < inputs_.size(); ++i) { auto *var_handle = static_cast<VarHandle *>(inputs_[i]); auto &scope = scopes.at(var_handle->scope_idx()); auto *var = scope->FindVar(kLocalExecScopeName) ->Get<Scope *>() ->FindVar(var_handle->name()); PADDLE_ENFORCE_NOT_NULL(var, "Cannot find variable %s in execution scope", var_handle->name()); auto &t = var->Get<framework::LoDTensor>(); if (platform::is_gpu_place(t.place())) { #ifdef PADDLE_WITH_CUDA TensorCopy(t, cpu, &tensors_[i]); #endif } else { tensors_[i].ShareDataWith(t); } tensors_[i].set_lod(t.lod()); } this->WaitAndMergeCPUTensors(); } void FetchOpHandle::WaitInputVarGenerated(const platform::Place &place) { auto cpu_ctx = platform::DeviceContextPool::Instance().Get(place); for (auto *input : inputs_) { if (input->GeneratedOp()) { input->GeneratedOp()->RecordWaitEventOnCtx(cpu_ctx); } } } bool FetchOpHandle::IsMultiDeviceTransfer() { return true; } std::string FetchOpHandle::Name() const { return "Fetch"; } } // namespace details } // namespace framework } // namespace paddle <|endoftext|>
<commit_before>/** * Copyright (c) 2013-2014 Tomas Dzetkulic * Copyright (c) 2013-2014 Pavol Rusnak * * 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. */ // Source: // https://github.com/trezor/trezor-crypto #include "bip39.h" #include "bip39_english.h" #include "crypto/sha256.h" #include "random.h" #include <openssl/evp.h> SecureString mnemonic_generate(int strength) { if (strength % 32 || strength < 128 || strength > 256) { return SecureString(); } uint8_t data[32]; // random_buffer(data, 32); GetRandBytes(data, 32); SecureString mnemonic = mnemonic_from_data(data, strength / 8); memory_cleanse(data, sizeof(data)); return mnemonic; } SecureString mnemonic_from_data(const uint8_t *data, int len) { if (len % 4 || len < 16 || len > 32) { return 0; return SecureString(); uint8_t bits[32 + 1]; CSHA256().Write(data, len).Finalize(bits); // checksum bits[len] = bits[0]; // data memcpy(bits, data, len); int mlen = len * 3 / 4; SecureString mnemonic; int i, j, idx; for (i = 0; i < mlen; i++) { idx = 0; for (j = 0; j < 11; j++) { idx <<= 1; idx += (bits[(i * 11 + j) / 8] & (1 << (7 - ((i * 11 + j) % 8)))) > 0; } mnemonic.append(wordlist[idx]); if (i < mlen - 1) { mnemonic += ' '; } } memory_cleanse(bits, sizeof(bits)); return mnemonic; } int mnemonic_check(SecureString mnemonic) { if (mnemonic.empty()) { return 0; } uint32_t i{}, n{}; while (mnemonic[i]) { if (mnemonic[i] == ' ') { n++; } i++; } n++; // check number of words if (n != 12 && n != 18 && n != 24) { return 0; } char current_word[10]; uint32_t j, k, ki, bi; uint8_t bits[32 + 1]{}; i = 0; bi = 0; while (mnemonic[i]) { j = 0; while (mnemonic[i] != ' ' && mnemonic[i] != 0) { if (j >= sizeof(current_word) - 1) { return 0; } current_word[j] = mnemonic[i]; i++; j++; } current_word[j] = 0; if (mnemonic[i] != 0) i++; k = 0; for (;;) { if (!wordlist[k]) { // word not found return 0; } if (strcmp(current_word, wordlist[k]) == 0) { // word found on index k for (ki = 0; ki < 11; ki++) { if (k & (1 << (10 - ki))) { bits[bi / 8] |= 1 << (7 - (bi % 8)); } bi++; } break; } k++; } } if (bi != n * 11) { return 0; } bits[32] = bits[n * 4 / 3]; CSHA256().Write(bits, n * 4 / 3).Finalize(bits); int result = 0; if (n == 12) { result = (bits[0] & 0xF0) == (bits[32] & 0xF0); // compare first 4 bits } else if (n == 18) { result = (bits[0] & 0xFC) == (bits[32] & 0xFC); // compare first 6 bits } else if (n == 24) { result = bits[0] == bits[32]; // compare 8 bits } memory_cleanse(bits, sizeof(bits)); return result; } // passphrase must be at most 256 characters or code may crash void mnemonic_to_seed(SecureString mnemonic, SecureString passphrase, SecureVector& seedRet) { SecureString ssSalt = SecureString("mnemonic") + passphrase; SecureVector vchSalt(ssSalt.begin(), ssSalt.end()); // int PKCS5_PBKDF2_HMAC(const char *pass, int passlen, // const unsigned char *salt, int saltlen, int iter, // const EVP_MD *digest, // int keylen, unsigned char *out); uint8_t seed[64]; PKCS5_PBKDF2_HMAC(mnemonic.c_str(), mnemonic.size(), &vchSalt[0], vchSalt.size(), 2048, EVP_sha512(), 64, seed); seedRet = SecureVector(seed, seed + 64); memory_cleanse(seed, sizeof(seed)); }<commit_msg>Whoops<commit_after>/** * Copyright (c) 2013-2014 Tomas Dzetkulic * Copyright (c) 2013-2014 Pavol Rusnak * * 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. */ // Source: // https://github.com/trezor/trezor-crypto #include "bip39.h" #include "bip39_english.h" #include "crypto/sha256.h" #include "random.h" #include <openssl/evp.h> SecureString mnemonic_generate(int strength) { if (strength % 32 || strength < 128 || strength > 256) { return SecureString(); } uint8_t data[32]; // random_buffer(data, 32); GetRandBytes(data, 32); SecureString mnemonic = mnemonic_from_data(data, strength / 8); memory_cleanse(data, sizeof(data)); return mnemonic; } SecureString mnemonic_from_data(const uint8_t *data, int len) { if (len % 4 || len < 16 || len > 32) { return SecureString(); } uint8_t bits[32 + 1]; CSHA256().Write(data, len).Finalize(bits); // checksum bits[len] = bits[0]; // data memcpy(bits, data, len); int mlen = len * 3 / 4; SecureString mnemonic; int i, j, idx; for (i = 0; i < mlen; i++) { idx = 0; for (j = 0; j < 11; j++) { idx <<= 1; idx += (bits[(i * 11 + j) / 8] & (1 << (7 - ((i * 11 + j) % 8)))) > 0; } mnemonic.append(wordlist[idx]); if (i < mlen - 1) { mnemonic += ' '; } } memory_cleanse(bits, sizeof(bits)); return mnemonic; } int mnemonic_check(SecureString mnemonic) { if (mnemonic.empty()) { return 0; } uint32_t i{}, n{}; while (mnemonic[i]) { if (mnemonic[i] == ' ') { n++; } i++; } n++; // check number of words if (n != 12 && n != 18 && n != 24) { return 0; } char current_word[10]; uint32_t j, k, ki, bi; uint8_t bits[32 + 1]{}; i = 0; bi = 0; while (mnemonic[i]) { j = 0; while (mnemonic[i] != ' ' && mnemonic[i] != 0) { if (j >= sizeof(current_word) - 1) { return 0; } current_word[j] = mnemonic[i]; i++; j++; } current_word[j] = 0; if (mnemonic[i] != 0) i++; k = 0; for (;;) { if (!wordlist[k]) { // word not found return 0; } if (strcmp(current_word, wordlist[k]) == 0) { // word found on index k for (ki = 0; ki < 11; ki++) { if (k & (1 << (10 - ki))) { bits[bi / 8] |= 1 << (7 - (bi % 8)); } bi++; } break; } k++; } } if (bi != n * 11) { return 0; } bits[32] = bits[n * 4 / 3]; CSHA256().Write(bits, n * 4 / 3).Finalize(bits); int result = 0; if (n == 12) { result = (bits[0] & 0xF0) == (bits[32] & 0xF0); // compare first 4 bits } else if (n == 18) { result = (bits[0] & 0xFC) == (bits[32] & 0xFC); // compare first 6 bits } else if (n == 24) { result = bits[0] == bits[32]; // compare 8 bits } memory_cleanse(bits, sizeof(bits)); return result; } // passphrase must be at most 256 characters or code may crash void mnemonic_to_seed(SecureString mnemonic, SecureString passphrase, SecureVector& seedRet) { SecureString ssSalt = SecureString("mnemonic") + passphrase; SecureVector vchSalt(ssSalt.begin(), ssSalt.end()); // int PKCS5_PBKDF2_HMAC(const char *pass, int passlen, // const unsigned char *salt, int saltlen, int iter, // const EVP_MD *digest, // int keylen, unsigned char *out); uint8_t seed[64]; PKCS5_PBKDF2_HMAC(mnemonic.c_str(), mnemonic.size(), &vchSalt[0], vchSalt.size(), 2048, EVP_sha512(), 64, seed); seedRet = SecureVector(seed, seed + 64); memory_cleanse(seed, sizeof(seed)); } <|endoftext|>
<commit_before>#include <cctype> #include <fstream> #include <stdio.h> #include "utils/logoutput.h" #include "settings.h" #define TRIM_STRING(s) do { while(((s).length() > 0) && isspace((s)[0])) { (s).erase(0, 1); } while(((s).length() > 0) && isspace((s)[(s).length() - 1])) { (s).erase((s).length() - 1); } } while(0) #define STRINGIFY(_s) #_s #define SETTING(name, default) do { _index.push_back(_ConfigSettingIndex(STRINGIFY(name), &name)); name = (default); } while(0) #define SETTING2(name, altname, default) do { _index.push_back(_ConfigSettingIndex(STRINGIFY(name), &name)); _index.push_back(_ConfigSettingIndex(STRINGIFY(altname), &name)); name = (default); } while(0) ConfigSettings::ConfigSettings() { SETTING(layerThickness, 100); SETTING(initialLayerThickness, 300); SETTING(filamentDiameter, 2890); SETTING(filamentFlow, 100); SETTING(extrusionWidth, 400); SETTING(insetCount, 2); SETTING(downSkinCount, 6); SETTING(upSkinCount, 6); SETTING(sparseInfillLineDistance, 100 * extrusionWidth / 20); SETTING(infillOverlap, 15); SETTING(skirtDistance, 6000); SETTING(skirtLineCount, 1); SETTING(skirtMinLength, 0); SETTING(initialSpeedupLayers, 4); SETTING(initialLayerSpeed, 20); SETTING(printSpeed, 50); SETTING(infillSpeed, 50); SETTING(inset0Speed, 50); SETTING(insetXSpeed, 50); SETTING(moveSpeed, 150); SETTING(fanFullOnLayerNr, 2); SETTING(supportAngle, -1); SETTING(supportEverywhere, 0); SETTING(supportLineDistance, sparseInfillLineDistance); SETTING(supportXYDistance, 700); SETTING(supportZDistance, 150); SETTING(supportExtruder, -1); SETTING(retractionAmount, 4500); SETTING(retractionSpeed, 45); SETTING(retractionAmountExtruderSwitch, 14500); SETTING(retractionMinimalDistance, 1500); SETTING(minimalExtrusionBeforeRetraction, 100); SETTING(retractionZHop, 0); SETTING(enableCombing, 1); SETTING(enableOozeShield, 0); SETTING(wipeTowerSize, 0); SETTING(multiVolumeOverlap, 0); SETTING2(objectPosition.X, posx, 102500); SETTING2(objectPosition.Y, posy, 102500); SETTING(objectSink, 0); SETTING(raftMargin, 5000); SETTING(raftLineSpacing, 1000); SETTING(raftBaseThickness, 0); SETTING(raftBaseLinewidth, 0); SETTING(raftInterfaceThickness, 0); SETTING(raftInterfaceLinewidth, 0); SETTING(minimalLayerTime, 5); SETTING(minimalFeedrate, 10); SETTING(coolHeadLift, 0); SETTING(fanSpeedMin, 100); SETTING(fanSpeedMax, 100); SETTING(fixHorrible, 0); SETTING(spiralizeMode, 0); SETTING(gcodeFlavor, GCODE_FLAVOR_REPRAP); SETTING(extruderOffset[1].X, 0); SETTING(extruderOffset[1].Y, 0); SETTING(extruderOffset[2].X, 0); SETTING(extruderOffset[2].Y, 0); SETTING(extruderOffset[3].X, 0); SETTING(extruderOffset[3].Y, 0); startCode = "M109 S210 ;Heatup to 210C\n" "G21 ;metric values\n" "G90 ;absolute positioning\n" "G28 ;Home\n" "G1 Z15.0 F300 ;move the platform down 15mm\n" "G92 E0 ;zero the extruded length\n" "G1 F200 E5 ;extrude 5mm of feed stock\n" "G92 E0 ;zero the extruded length again\n"; endCode = "M104 S0 ;extruder heater off\n" "M140 S0 ;heated bed heater off (if you have it)\n" "G91 ;relative positioning\n" "G1 E-1 F300 ;retract the filament a bit before lifting the nozzle, to release some of the pressure\n" "G1 Z+0.5 E-5 X-20 Y-20 F9000 ;move Z up a bit and retract filament even more\n" "G28 X0 Y0 ;move X/Y to min endstops, so the head is out of the way\n" "M84 ;steppers off\n" "G90 ;absolute positioning\n"; } #undef STRINGIFY #undef SETTING bool ConfigSettings::setSetting(const char* key, const char* value) { for(unsigned int n=0; n < _index.size(); n++) { if (strcasecmp(key, _index[n].key) == 0) { *_index[n].ptr = atoi(value); return true; } } if (strcasecmp(key, "startCode") == 0) { this->startCode = value; return true; } if (strcasecmp(key, "endCode") == 0) { this->endCode = value; return true; } return false; } bool ConfigSettings::readSettings(void) { return readSettings(DEFAULT_CONFIG_PATH); } bool ConfigSettings::readSettings(const char* path) { std::ifstream config(path); std::string line; size_t line_number = 0; if(!config.good()) return false; while(config.good()) { size_t pos = std::string::npos; std::getline(config, line); line_number += 1; // De-comment and trim, skipping anything that shows up empty pos = line.find_first_of('#'); if(pos != std::string::npos) line.erase(pos); TRIM_STRING(line); if(line.length() == 0) continue; // Split into key = val std::string key(""), val(""); pos = line.find_first_of('='); if(pos != std::string::npos && line.length() > (pos + 1)) { key = line.substr(0, pos); val = line.substr(pos + 1); TRIM_STRING(key); TRIM_STRING(val); } // Fail if we don't get a key and val if(key.length() == 0 || val.length() == 0) { logError("Config(%s): Line %zd: No key value pair found\n", path, line_number); return false; } // Set a config setting for the current K=V if(!setSetting(key.c_str(), val.c_str())) { logError("Config(%s):L%zd: Failed to set '%s' to '%s'\n", path, line_number, key.c_str(), val.c_str()); } } return true; } <commit_msg>Actually fail the read if a key is unknown<commit_after>#include <cctype> #include <fstream> #include <stdio.h> #include "utils/logoutput.h" #include "settings.h" #define TRIM_STRING(s) do { while(((s).length() > 0) && isspace((s)[0])) { (s).erase(0, 1); } while(((s).length() > 0) && isspace((s)[(s).length() - 1])) { (s).erase((s).length() - 1); } } while(0) #define STRINGIFY(_s) #_s #define SETTING(name, default) do { _index.push_back(_ConfigSettingIndex(STRINGIFY(name), &name)); name = (default); } while(0) #define SETTING2(name, altname, default) do { _index.push_back(_ConfigSettingIndex(STRINGIFY(name), &name)); _index.push_back(_ConfigSettingIndex(STRINGIFY(altname), &name)); name = (default); } while(0) ConfigSettings::ConfigSettings() { SETTING(layerThickness, 100); SETTING(initialLayerThickness, 300); SETTING(filamentDiameter, 2890); SETTING(filamentFlow, 100); SETTING(extrusionWidth, 400); SETTING(insetCount, 2); SETTING(downSkinCount, 6); SETTING(upSkinCount, 6); SETTING(sparseInfillLineDistance, 100 * extrusionWidth / 20); SETTING(infillOverlap, 15); SETTING(skirtDistance, 6000); SETTING(skirtLineCount, 1); SETTING(skirtMinLength, 0); SETTING(initialSpeedupLayers, 4); SETTING(initialLayerSpeed, 20); SETTING(printSpeed, 50); SETTING(infillSpeed, 50); SETTING(inset0Speed, 50); SETTING(insetXSpeed, 50); SETTING(moveSpeed, 150); SETTING(fanFullOnLayerNr, 2); SETTING(supportAngle, -1); SETTING(supportEverywhere, 0); SETTING(supportLineDistance, sparseInfillLineDistance); SETTING(supportXYDistance, 700); SETTING(supportZDistance, 150); SETTING(supportExtruder, -1); SETTING(retractionAmount, 4500); SETTING(retractionSpeed, 45); SETTING(retractionAmountExtruderSwitch, 14500); SETTING(retractionMinimalDistance, 1500); SETTING(minimalExtrusionBeforeRetraction, 100); SETTING(retractionZHop, 0); SETTING(enableCombing, 1); SETTING(enableOozeShield, 0); SETTING(wipeTowerSize, 0); SETTING(multiVolumeOverlap, 0); SETTING2(objectPosition.X, posx, 102500); SETTING2(objectPosition.Y, posy, 102500); SETTING(objectSink, 0); SETTING(raftMargin, 5000); SETTING(raftLineSpacing, 1000); SETTING(raftBaseThickness, 0); SETTING(raftBaseLinewidth, 0); SETTING(raftInterfaceThickness, 0); SETTING(raftInterfaceLinewidth, 0); SETTING(minimalLayerTime, 5); SETTING(minimalFeedrate, 10); SETTING(coolHeadLift, 0); SETTING(fanSpeedMin, 100); SETTING(fanSpeedMax, 100); SETTING(fixHorrible, 0); SETTING(spiralizeMode, 0); SETTING(gcodeFlavor, GCODE_FLAVOR_REPRAP); SETTING(extruderOffset[1].X, 0); SETTING(extruderOffset[1].Y, 0); SETTING(extruderOffset[2].X, 0); SETTING(extruderOffset[2].Y, 0); SETTING(extruderOffset[3].X, 0); SETTING(extruderOffset[3].Y, 0); startCode = "M109 S210 ;Heatup to 210C\n" "G21 ;metric values\n" "G90 ;absolute positioning\n" "G28 ;Home\n" "G1 Z15.0 F300 ;move the platform down 15mm\n" "G92 E0 ;zero the extruded length\n" "G1 F200 E5 ;extrude 5mm of feed stock\n" "G92 E0 ;zero the extruded length again\n"; endCode = "M104 S0 ;extruder heater off\n" "M140 S0 ;heated bed heater off (if you have it)\n" "G91 ;relative positioning\n" "G1 E-1 F300 ;retract the filament a bit before lifting the nozzle, to release some of the pressure\n" "G1 Z+0.5 E-5 X-20 Y-20 F9000 ;move Z up a bit and retract filament even more\n" "G28 X0 Y0 ;move X/Y to min endstops, so the head is out of the way\n" "M84 ;steppers off\n" "G90 ;absolute positioning\n"; } #undef STRINGIFY #undef SETTING bool ConfigSettings::setSetting(const char* key, const char* value) { for(unsigned int n=0; n < _index.size(); n++) { if (strcasecmp(key, _index[n].key) == 0) { *_index[n].ptr = atoi(value); return true; } } if (strcasecmp(key, "startCode") == 0) { this->startCode = value; return true; } if (strcasecmp(key, "endCode") == 0) { this->endCode = value; return true; } return false; } bool ConfigSettings::readSettings(void) { return readSettings(DEFAULT_CONFIG_PATH); } bool ConfigSettings::readSettings(const char* path) { std::ifstream config(path); std::string line; size_t line_number = 0; if(!config.good()) return false; while(config.good()) { size_t pos = std::string::npos; std::getline(config, line); line_number += 1; // De-comment and trim, skipping anything that shows up empty pos = line.find_first_of('#'); if(pos != std::string::npos) line.erase(pos); TRIM_STRING(line); if(line.length() == 0) continue; // Split into key = val std::string key(""), val(""); pos = line.find_first_of('='); if(pos != std::string::npos && line.length() > (pos + 1)) { key = line.substr(0, pos); val = line.substr(pos + 1); TRIM_STRING(key); TRIM_STRING(val); } // Fail if we don't get a key and val if(key.length() == 0 || val.length() == 0) { logError("Config(%s): Line %zd: No key value pair found\n", path, line_number); return false; } // Set a config setting for the current K=V if(!setSetting(key.c_str(), val.c_str())) { logError("Config(%s):L%zd: Failed to set '%s' to '%s'\n", path, line_number, key.c_str(), val.c_str()); return false; } } return true; } <|endoftext|>
<commit_before>/************************************************************************* * * * I|*j^3Cl|a "+!*% qt Nd gW * * l]{y+l?MM* !#Wla\NNP NW MM I| * * PW ?E| tWg Wg sC! AW ~@v~ * * NC ?M! yN| WW MK MW@K1Y%M@ RM #Q QP@tim * * CM| |WQCljAE| MD Mg RN cM~ NM WQ MQ * * #M aQ? MW M3 Mg Q( HQ YR IM| * * Dq {Ql MH iMX Mg MM QP QM Eg * * !EWNaPRag2$ +M" $WNaHaN% MQE$%EXW QQ CM %M%a$D * * * * Website: https://github.com/zpublic/zpublic * * * ************************************************************************/ /** * @file * @brief Ϣ */ #pragma once #include "win_utils_header.h" namespace zl { namespace WinUtils { namespace ZLMessage { inline UINT RegisterMessage(LPCTSTR lpMsgName) { return ::RegisterWindowMessage(lpMsgName); } typedef BOOL (__stdcall *ChangeWindowMessageFilterType)(UINT, DWORD); #define MSGFLT_ADD 1 // ChangeWindowMessageFilter ĵڶϢ #define MSGFLT_REMOVE 2 // ChangeWindowMessageFilter ĵڶƳϢ static BOOL ChangeMessageFilter(UINT uMsg, DWORD dwOper = MSGFLT_ADD) { BOOL bRet = FALSE; static HMODULE hModule = NULL; static ChangeWindowMessageFilterType pChangeWindowMessageFilterType = NULL; if (pChangeWindowMessageFilterType == NULL) { hModule = ::LoadLibrary(TEXT("user32.dll")); if (hModule == NULL) goto Exit0; pChangeWindowMessageFilterType = (ChangeWindowMessageFilterType)::GetProcAddress(hModule, "ChangeWindowMessageFilter"); if (pChangeWindowMessageFilterType == NULL) goto Exit0; } bRet = pChangeWindowMessageFilterType(uMsg, dwOper); Exit0: return bRet; } } } } <commit_msg>*message文件注释<commit_after>/************************************************************************* * * * I|*j^3Cl|a "+!*% qt Nd gW * * l]{y+l?MM* !#Wla\NNP NW MM I| * * PW ?E| tWg Wg sC! AW ~@v~ * * NC ?M! yN| WW MK MW@K1Y%M@ RM #Q QP@tim * * CM| |WQCljAE| MD Mg RN cM~ NM WQ MQ * * #M aQ? MW M3 Mg Q( HQ YR IM| * * Dq {Ql MH iMX Mg MM QP QM Eg * * !EWNaPRag2$ +M" $WNaHaN% MQE$%EXW QQ CM %M%a$D * * * * Website: https://github.com/zpublic/zpublic * * * ************************************************************************/ /** * @file * @brief Ϣ */ #pragma once #include "win_utils_header.h" namespace zl { namespace WinUtils { /** * @brief UIPIϢ */ namespace ZLMessage { inline UINT RegisterMessage(LPCTSTR lpMsgName) { return ::RegisterWindowMessage(lpMsgName); } typedef BOOL (__stdcall *ChangeWindowMessageFilterType)(UINT, DWORD); #define MSGFLT_ADD 1 // ChangeWindowMessageFilter ĵڶϢ #define MSGFLT_REMOVE 2 // ChangeWindowMessageFilter ĵڶƳϢ /** * @brief UIPIϢӻɾһϢ * @param[in] uMsg ָӻӹɾָϢ * @param[in] dwOper ָ * @return ɹTRUEʧܷFALSE * @see ChangeWindowMessageFilter */ static BOOL ChangeMessageFilter(UINT uMsg, DWORD dwOper = MSGFLT_ADD) { BOOL bRet = FALSE; static HMODULE hModule = NULL; static ChangeWindowMessageFilterType pChangeWindowMessageFilterType = NULL; if (pChangeWindowMessageFilterType == NULL) { hModule = ::LoadLibrary(TEXT("user32.dll")); if (hModule == NULL) goto Exit0; pChangeWindowMessageFilterType = (ChangeWindowMessageFilterType)::GetProcAddress(hModule, "ChangeWindowMessageFilter"); if (pChangeWindowMessageFilterType == NULL) goto Exit0; } bRet = pChangeWindowMessageFilterType(uMsg, dwOper); Exit0: return bRet; } } } } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: stdctrl.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: rt $ $Date: 2007-04-26 10:31:43 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_svtools.hxx" #include <stdctrl.hxx> // ======================================================================= FixedInfo::FixedInfo( Window* pParent, WinBits nWinStyle ) : FixedText( pParent, nWinStyle | WB_INFO ) { } // ----------------------------------------------------------------------- FixedInfo::FixedInfo( Window* pParent, const ResId& rResId ) : FixedText( pParent, rResId ) { SetStyle( GetStyle() | WB_INFO ); } namespace svt { // class svt::SelectableFixedText ---------------------------------------- SelectableFixedText::SelectableFixedText( Window* pParent, WinBits nWinStyle ) : Edit( pParent, nWinStyle ) { Init(); } // ----------------------------------------------------------------------- SelectableFixedText::SelectableFixedText( Window* pParent, const ResId& rResId ) : Edit( pParent, rResId ) { Init(); } // ----------------------------------------------------------------------- SelectableFixedText::~SelectableFixedText() { } // ----------------------------------------------------------------------- void SelectableFixedText::Init() { // no tabstop SetStyle( ( GetStyle() & ~WB_TABSTOP ) | WB_NOTABSTOP ); // no border SetBorderStyle( WINDOW_BORDER_NOBORDER ); // read-only SetReadOnly(); // make it transparent SetControlBackground(); SetBackground(); SetPaintTransparent( TRUE ); } // ----------------------------------------------------------------------- void SelectableFixedText::LoseFocus() { Edit::LoseFocus(); // clear cursor Invalidate(); } } // namespace svt <commit_msg>INTEGRATION: CWS vgbugs07 (1.4.36); FILE MERGED 2007/06/04 13:31:29 vg 1.4.36.1: #i76605# Remove -I .../inc/module hack introduced by hedaburemove01<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: stdctrl.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: hr $ $Date: 2007-06-27 21:25:46 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_svtools.hxx" #include <svtools/stdctrl.hxx> // ======================================================================= FixedInfo::FixedInfo( Window* pParent, WinBits nWinStyle ) : FixedText( pParent, nWinStyle | WB_INFO ) { } // ----------------------------------------------------------------------- FixedInfo::FixedInfo( Window* pParent, const ResId& rResId ) : FixedText( pParent, rResId ) { SetStyle( GetStyle() | WB_INFO ); } namespace svt { // class svt::SelectableFixedText ---------------------------------------- SelectableFixedText::SelectableFixedText( Window* pParent, WinBits nWinStyle ) : Edit( pParent, nWinStyle ) { Init(); } // ----------------------------------------------------------------------- SelectableFixedText::SelectableFixedText( Window* pParent, const ResId& rResId ) : Edit( pParent, rResId ) { Init(); } // ----------------------------------------------------------------------- SelectableFixedText::~SelectableFixedText() { } // ----------------------------------------------------------------------- void SelectableFixedText::Init() { // no tabstop SetStyle( ( GetStyle() & ~WB_TABSTOP ) | WB_NOTABSTOP ); // no border SetBorderStyle( WINDOW_BORDER_NOBORDER ); // read-only SetReadOnly(); // make it transparent SetControlBackground(); SetBackground(); SetPaintTransparent( TRUE ); } // ----------------------------------------------------------------------- void SelectableFixedText::LoseFocus() { Edit::LoseFocus(); // clear cursor Invalidate(); } } // namespace svt <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you under the Apache * License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.apache.org/licenses/LICENSE-2.0 . */ #include <unocrsr.hxx> #include <doc.hxx> #include <IDocumentLayoutAccess.hxx> #include <swtable.hxx> #include <docary.hxx> #include <rootfrm.hxx> #include <calbck.hxx> IMPL_FIXEDMEMPOOL_NEWDEL( SwUnoCrsr ) SwUnoCrsr::SwUnoCrsr( const SwPosition &rPos, SwPaM* pRing ) : SwCursor( rPos, pRing, false ) , SwModify(nullptr) , m_bRemainInSection(true) , m_bSkipOverHiddenSections(false) , m_bSkipOverProtectSections(false) {} SwUnoCrsr::~SwUnoCrsr() { SwDoc* pDoc = GetDoc(); if( !pDoc->IsInDtor() ) { #ifdef DBG_UTIL SwIterator<SwClient, SwUnoCrsr> pClient(*this); assert(!pClient.First()); #endif // remove the weak_ptr the document keeps to notify about document death pDoc->mvUnoCrsrTbl.remove_if( [this](const std::weak_ptr<SwUnoCrsr>& pWeakPtr) -> bool { return pWeakPtr.lock().get() == this; }); } // delete the whole ring while( GetNext() != this ) { Ring* pNxt = GetNext(); pNxt->MoveTo(nullptr); // remove from chain delete pNxt; // and delete } } std::shared_ptr<SwUnoCrsr> SwUnoTableCrsr::Clone() const { auto pNewCrsr(GetDoc()->CreateUnoCrsr(*GetPoint(), true)); if(HasMark()) { pNewCrsr->SetMark(); *pNewCrsr->GetMark() = *GetMark(); } return pNewCrsr; } bool SwUnoCrsr::IsReadOnlyAvailable() const { return true; } const SwContentFrm* SwUnoCrsr::DoSetBidiLevelLeftRight( bool &, bool, bool ) { return 0; // not for uno cursor } void SwUnoCrsr::DoSetBidiLevelUpDown() { return; // not for uno cursor } bool SwUnoCrsr::IsSelOvr( int eFlags ) { if (m_bRemainInSection) { SwDoc* pDoc = GetDoc(); SwNodeIndex aOldIdx( *pDoc->GetNodes()[ GetSavePos()->nNode ] ); SwNodeIndex& rPtIdx = GetPoint()->nNode; SwStartNode *pOldSttNd = aOldIdx.GetNode().StartOfSectionNode(), *pNewSttNd = rPtIdx.GetNode().StartOfSectionNode(); if( pOldSttNd != pNewSttNd ) { bool bMoveDown = GetSavePos()->nNode < rPtIdx.GetIndex(); bool bValidPos = false; // search the correct surrounded start node - which the index // can't leave. while( pOldSttNd->IsSectionNode() ) pOldSttNd = pOldSttNd->StartOfSectionNode(); // is the new index inside this surrounded section? if( rPtIdx > *pOldSttNd && rPtIdx < pOldSttNd->EndOfSectionIndex() ) { // check if it a valid move inside this section // (only over SwSection's !) const SwStartNode* pInvalidNode; do { pInvalidNode = 0; pNewSttNd = rPtIdx.GetNode().StartOfSectionNode(); const SwStartNode *pSttNd = pNewSttNd, *pEndNd = pOldSttNd; if( pSttNd->EndOfSectionIndex() > pEndNd->EndOfSectionIndex() ) { pEndNd = pNewSttNd; pSttNd = pOldSttNd; } while( pSttNd->GetIndex() > pEndNd->GetIndex() ) { if( !pSttNd->IsSectionNode() ) pInvalidNode = pSttNd; pSttNd = pSttNd->StartOfSectionNode(); } if( pInvalidNode ) { if( bMoveDown ) { rPtIdx.Assign( *pInvalidNode->EndOfSectionNode(), 1 ); if( !rPtIdx.GetNode().IsContentNode() && ( !pDoc->GetNodes().GoNextSection( &rPtIdx ) || rPtIdx > pOldSttNd->EndOfSectionIndex() ) ) break; } else { rPtIdx.Assign( *pInvalidNode, -1 ); if( !rPtIdx.GetNode().IsContentNode() && ( !SwNodes::GoPrevSection( &rPtIdx ) || rPtIdx < *pOldSttNd ) ) break; } } else bValidPos = true; } while ( pInvalidNode ); } if( bValidPos ) { SwContentNode* pCNd = GetContentNode(); GetPoint()->nContent.Assign( pCNd, (pCNd && !bMoveDown) ? pCNd->Len() : 0); } else { rPtIdx = GetSavePos()->nNode; GetPoint()->nContent.Assign( GetContentNode(), GetSavePos()->nContent ); return true; } } } return SwCursor::IsSelOvr( eFlags ); } SwUnoTableCrsr::SwUnoTableCrsr(const SwPosition& rPos) : SwCursor(rPos, 0, false) , SwUnoCrsr(rPos) , SwTableCursor(rPos) , m_aTableSel(rPos, 0, false) { SetRemainInSection(false); } SwUnoTableCrsr::~SwUnoTableCrsr() { while (m_aTableSel.GetNext() != &m_aTableSel) delete m_aTableSel.GetNext(); } bool SwUnoTableCrsr::IsSelOvr( int eFlags ) { bool bRet = SwUnoCrsr::IsSelOvr( eFlags ); if( !bRet ) { const SwTableNode* pTNd = GetPoint()->nNode.GetNode().FindTableNode(); bRet = !(pTNd == GetDoc()->GetNodes()[ GetSavePos()->nNode ]-> FindTableNode() && (!HasMark() || pTNd == GetMark()->nNode.GetNode().FindTableNode() )); } return bRet; } void SwUnoTableCrsr::MakeBoxSels() { const SwContentNode* pCNd; bool bMakeTableCrsrs = true; if( GetPoint()->nNode.GetIndex() && GetMark()->nNode.GetIndex() && 0 != ( pCNd = GetContentNode() ) && pCNd->getLayoutFrm( pCNd->GetDoc()->getIDocumentLayoutAccess().GetCurrentLayout() ) && 0 != ( pCNd = GetContentNode(false) ) && pCNd->getLayoutFrm( pCNd->GetDoc()->getIDocumentLayoutAccess().GetCurrentLayout() ) ) bMakeTableCrsrs = GetDoc()->getIDocumentLayoutAccess().GetCurrentLayout()->MakeTableCrsrs( *this ); if ( !bMakeTableCrsrs ) { SwSelBoxes const& rTmpBoxes = GetSelectedBoxes(); while (!rTmpBoxes.empty()) { DeleteBox(0); } } if( IsChgd() ) { SwTableCursor::MakeBoxSels( &m_aTableSel ); if (!GetSelectedBoxesCount()) { const SwTableBox* pBox; const SwNode* pBoxNd = GetPoint()->nNode.GetNode().FindTableBoxStartNode(); const SwTableNode* pTableNd = pBoxNd ? pBoxNd->FindTableNode() : 0; if( pTableNd && 0 != ( pBox = pTableNd->GetTable().GetTableBox( pBoxNd->GetIndex() )) ) InsertBox( *pBox ); } } } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>Silence failing assert for now<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you under the Apache * License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.apache.org/licenses/LICENSE-2.0 . */ #include <unocrsr.hxx> #include <doc.hxx> #include <IDocumentLayoutAccess.hxx> #include <swtable.hxx> #include <docary.hxx> #include <rootfrm.hxx> #include <calbck.hxx> IMPL_FIXEDMEMPOOL_NEWDEL( SwUnoCrsr ) SwUnoCrsr::SwUnoCrsr( const SwPosition &rPos, SwPaM* pRing ) : SwCursor( rPos, pRing, false ) , SwModify(nullptr) , m_bRemainInSection(true) , m_bSkipOverHiddenSections(false) , m_bSkipOverProtectSections(false) {} SwUnoCrsr::~SwUnoCrsr() { SwDoc* pDoc = GetDoc(); if( !pDoc->IsInDtor() ) { #ifdef DBG_UTIL_TODO SwIterator<SwClient, SwUnoCrsr> pClient(*this); assert(!pClient.First()); #endif // remove the weak_ptr the document keeps to notify about document death pDoc->mvUnoCrsrTbl.remove_if( [this](const std::weak_ptr<SwUnoCrsr>& pWeakPtr) -> bool { return pWeakPtr.lock().get() == this; }); } // delete the whole ring while( GetNext() != this ) { Ring* pNxt = GetNext(); pNxt->MoveTo(nullptr); // remove from chain delete pNxt; // and delete } } std::shared_ptr<SwUnoCrsr> SwUnoTableCrsr::Clone() const { auto pNewCrsr(GetDoc()->CreateUnoCrsr(*GetPoint(), true)); if(HasMark()) { pNewCrsr->SetMark(); *pNewCrsr->GetMark() = *GetMark(); } return pNewCrsr; } bool SwUnoCrsr::IsReadOnlyAvailable() const { return true; } const SwContentFrm* SwUnoCrsr::DoSetBidiLevelLeftRight( bool &, bool, bool ) { return 0; // not for uno cursor } void SwUnoCrsr::DoSetBidiLevelUpDown() { return; // not for uno cursor } bool SwUnoCrsr::IsSelOvr( int eFlags ) { if (m_bRemainInSection) { SwDoc* pDoc = GetDoc(); SwNodeIndex aOldIdx( *pDoc->GetNodes()[ GetSavePos()->nNode ] ); SwNodeIndex& rPtIdx = GetPoint()->nNode; SwStartNode *pOldSttNd = aOldIdx.GetNode().StartOfSectionNode(), *pNewSttNd = rPtIdx.GetNode().StartOfSectionNode(); if( pOldSttNd != pNewSttNd ) { bool bMoveDown = GetSavePos()->nNode < rPtIdx.GetIndex(); bool bValidPos = false; // search the correct surrounded start node - which the index // can't leave. while( pOldSttNd->IsSectionNode() ) pOldSttNd = pOldSttNd->StartOfSectionNode(); // is the new index inside this surrounded section? if( rPtIdx > *pOldSttNd && rPtIdx < pOldSttNd->EndOfSectionIndex() ) { // check if it a valid move inside this section // (only over SwSection's !) const SwStartNode* pInvalidNode; do { pInvalidNode = 0; pNewSttNd = rPtIdx.GetNode().StartOfSectionNode(); const SwStartNode *pSttNd = pNewSttNd, *pEndNd = pOldSttNd; if( pSttNd->EndOfSectionIndex() > pEndNd->EndOfSectionIndex() ) { pEndNd = pNewSttNd; pSttNd = pOldSttNd; } while( pSttNd->GetIndex() > pEndNd->GetIndex() ) { if( !pSttNd->IsSectionNode() ) pInvalidNode = pSttNd; pSttNd = pSttNd->StartOfSectionNode(); } if( pInvalidNode ) { if( bMoveDown ) { rPtIdx.Assign( *pInvalidNode->EndOfSectionNode(), 1 ); if( !rPtIdx.GetNode().IsContentNode() && ( !pDoc->GetNodes().GoNextSection( &rPtIdx ) || rPtIdx > pOldSttNd->EndOfSectionIndex() ) ) break; } else { rPtIdx.Assign( *pInvalidNode, -1 ); if( !rPtIdx.GetNode().IsContentNode() && ( !SwNodes::GoPrevSection( &rPtIdx ) || rPtIdx < *pOldSttNd ) ) break; } } else bValidPos = true; } while ( pInvalidNode ); } if( bValidPos ) { SwContentNode* pCNd = GetContentNode(); GetPoint()->nContent.Assign( pCNd, (pCNd && !bMoveDown) ? pCNd->Len() : 0); } else { rPtIdx = GetSavePos()->nNode; GetPoint()->nContent.Assign( GetContentNode(), GetSavePos()->nContent ); return true; } } } return SwCursor::IsSelOvr( eFlags ); } SwUnoTableCrsr::SwUnoTableCrsr(const SwPosition& rPos) : SwCursor(rPos, 0, false) , SwUnoCrsr(rPos) , SwTableCursor(rPos) , m_aTableSel(rPos, 0, false) { SetRemainInSection(false); } SwUnoTableCrsr::~SwUnoTableCrsr() { while (m_aTableSel.GetNext() != &m_aTableSel) delete m_aTableSel.GetNext(); } bool SwUnoTableCrsr::IsSelOvr( int eFlags ) { bool bRet = SwUnoCrsr::IsSelOvr( eFlags ); if( !bRet ) { const SwTableNode* pTNd = GetPoint()->nNode.GetNode().FindTableNode(); bRet = !(pTNd == GetDoc()->GetNodes()[ GetSavePos()->nNode ]-> FindTableNode() && (!HasMark() || pTNd == GetMark()->nNode.GetNode().FindTableNode() )); } return bRet; } void SwUnoTableCrsr::MakeBoxSels() { const SwContentNode* pCNd; bool bMakeTableCrsrs = true; if( GetPoint()->nNode.GetIndex() && GetMark()->nNode.GetIndex() && 0 != ( pCNd = GetContentNode() ) && pCNd->getLayoutFrm( pCNd->GetDoc()->getIDocumentLayoutAccess().GetCurrentLayout() ) && 0 != ( pCNd = GetContentNode(false) ) && pCNd->getLayoutFrm( pCNd->GetDoc()->getIDocumentLayoutAccess().GetCurrentLayout() ) ) bMakeTableCrsrs = GetDoc()->getIDocumentLayoutAccess().GetCurrentLayout()->MakeTableCrsrs( *this ); if ( !bMakeTableCrsrs ) { SwSelBoxes const& rTmpBoxes = GetSelectedBoxes(); while (!rTmpBoxes.empty()) { DeleteBox(0); } } if( IsChgd() ) { SwTableCursor::MakeBoxSels( &m_aTableSel ); if (!GetSelectedBoxesCount()) { const SwTableBox* pBox; const SwNode* pBoxNd = GetPoint()->nNode.GetNode().FindTableBoxStartNode(); const SwTableNode* pTableNd = pBoxNd ? pBoxNd->FindTableNode() : 0; if( pTableNd && 0 != ( pBox = pTableNd->GetTable().GetTableBox( pBoxNd->GetIndex() )) ) InsertBox( *pBox ); } } } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>/* * Copyright 2013, Tim Branyen @tbranyen <tim@tabdeveloper.com> * @author Michael Robinson @codeofinterest <mike@pagesofinterest.net> * * Dual licensed under the MIT and GPL licenses. */ #include <string.h> #include <v8.h> #include <node.h> #include "../vendor/libgit2/include/git2.h" #include "cvv8/v8-convert.hpp" #include "../include/reference.h" #include "../include/sig.h" #include "../include/repo.h" #include "../include/oid.h" #include "../include/tree.h" #include "../include/commit.h" #include "../include/error.h" #include "../include/functions/utilities.h" using namespace v8; using namespace cvv8; using namespace node; void GitCommit::Initialize(Handle<Object> target) { HandleScope scope; Local<FunctionTemplate> tpl = FunctionTemplate::New(New); tpl->InstanceTemplate()->SetInternalFieldCount(1); tpl->SetClassName(String::NewSymbol("Commit")); NODE_SET_PROTOTYPE_METHOD(tpl, "lookup", Lookup); NODE_SET_PROTOTYPE_METHOD(tpl, "close", Close); NODE_SET_PROTOTYPE_METHOD(tpl, "tree", Tree); NODE_SET_PROTOTYPE_METHOD(tpl, "parent", Parent); constructor_template = Persistent<Function>::New(tpl->GetFunction()); target->Set(String::NewSymbol("Commit"), constructor_template); } git_commit* GitCommit::GetValue() { return this->commit; } void GitCommit::SetValue(git_commit* commit) { this->commit = commit; } void GitCommit::Close() { git_commit_free(this->commit); this->commit = NULL; } Handle<Value> GitCommit::New(const Arguments& args) { HandleScope scope; GitCommit *commit = new GitCommit(); commit->Wrap(args.This()); return scope.Close(args.This()); } // Handle<Value> GitCommit::FetchDetailsSync(const Arguments& args) { // HandleScope scope; // GitCommit *commit = ObjectWrap::Unwrap<GitCommit>(args.This()); // git_commit* rawCommit = commit->GetValue(); // GitCommitDetails* details = new GitCommitDetails; // details->oid = git_commit_id(rawCommit); // details->sha[GIT_OID_HEXSZ] = '\0'; // git_oid_fmt(details->sha, details->oid); // details->message = git_commit_message(rawCommit); // details->time = git_commit_time(rawCommit); // details->timeOffset = git_commit_time_offset(rawCommit); // details->committer = git_commit_committer(rawCommit); // details->author = git_commit_author(rawCommit); // details->parentCount = git_commit_parentcount(rawCommit); // int parentCount = details->parentCount; // while (parentCount > 0) { // int parentIndex = parentCount -1; // char sha[GIT_OID_HEXSZ + 1]; // sha[GIT_OID_HEXSZ] = '\0'; // const git_oid *parentOid = git_commit_parent_id(rawCommit, parentIndex); // git_oid_fmt(sha, parentOid); // details->parentShas.push_back(sha); // parentCount--; // } // return scope.Close(createCommitDetailsObject(details)); // } // Handle<Value> GitCommit::FetchDetails(const Arguments& args) { // HandleScope scope; // if(args.Length() == 0 || !args[0]->IsFunction()) { // return ThrowException(Exception::Error(String::New("Callback is required and must be a Function."))); // } // FetchDetailsBaton* baton = new FetchDetailsBaton; // baton->request.data = baton; // baton->error = NULL; // baton->details = new GitCommitDetails; // baton->rawCommit = ObjectWrap::Unwrap<GitCommit>(args.This())->commit; // baton->callback = Persistent<Function>::New(Local<Function>::Cast(args[0])); // uv_queue_work(uv_default_loop(), &baton->request, FetchDetailsWork, (uv_after_work_cb)FetchDetailsAfterWork); // return Undefined(); // } // void GitCommit::FetchDetailsWork(uv_work_t *req) { // FetchDetailsBaton* baton = static_cast<FetchDetailsBaton*>(req->data); // GitCommitDetails* details = baton->details; // details->oid = git_commit_id(baton->rawCommit); // details->sha[GIT_OID_HEXSZ] = '\0'; // git_oid_fmt(details->sha, details->oid); // details->message = git_commit_message(baton->rawCommit); // details->time = git_commit_time(baton->rawCommit); // details->timeOffset = git_commit_time_offset(baton->rawCommit); // details->committer = git_commit_committer(baton->rawCommit); // details->author = git_commit_author(baton->rawCommit); // details->parentCount = git_commit_parentcount(baton->rawCommit); // int parentCount = details->parentCount; // while (parentCount > 0) { // int parentIndex = parentCount -1; // char sha[GIT_OID_HEXSZ + 1]; // sha[GIT_OID_HEXSZ] = '\0'; // const git_oid *parentOid = git_commit_parent_id(baton->rawCommit, parentIndex); // git_oid_fmt(sha, parentOid); // details->parentShas.push_back(sha); // parentCount--; // } // } // void GitCommit::FetchDetailsAfterWork(uv_work_t *req) { // HandleScope scope; // FetchDetailsBaton* baton = static_cast<FetchDetailsBaton* >(req->data); // if (baton->error) { // Local<Value> argv[1] = { // GitError::WrapError(baton->error) // }; // TryCatch try_catch; // baton->callback->Call(Context::GetCurrent()->Global(), 1, argv); // if (try_catch.HasCaught()) { // node::FatalException(try_catch); // } // } else { // Handle<Value> argv[2] = { // Local<Value>::New(Null()), // createCommitDetailsObject(baton->details) // }; // TryCatch try_catch; // baton->callback->Call(Context::GetCurrent()->Global(), 2, argv); // if (try_catch.HasCaught()) { // node::FatalException(try_catch); // } // } // delete req; // } Handle<Value> GitCommit::Lookup(const Arguments& args) { HandleScope scope; if(args.Length() == 0 || !args[0]->IsObject()) { return ThrowException(Exception::Error(String::New("Repo is required and must be an Object."))); } if(args.Length() == 1 || !(args[1]->IsObject() || args[1]->IsString())) { return ThrowException(Exception::Error(String::New("Oid is required and must be an Object or String"))); } if(args.Length() == 2 || !args[2]->IsFunction()) { return ThrowException(Exception::Error(String::New("Callback is required and must be a Function."))); } LookupBaton *baton = new LookupBaton; baton->request.data = baton; baton->error = NULL; baton->repo = ObjectWrap::Unwrap<GitRepo>(args[0]->ToObject())->GetValue(); if (args[1]->IsObject()) { baton->rawOid = ObjectWrap::Unwrap<GitOid>(args[1]->ToObject())->GetValue(); } else { baton->sha = stringArgToString(args[1]->ToString()); } baton->callback = Persistent<Function>::New(Local<Function>::Cast(args[2])); uv_queue_work(uv_default_loop(), &baton->request, LookupWork, (uv_after_work_cb)LookupAfterWork); return Undefined(); } void GitCommit::LookupWork(uv_work_t *req) { LookupBaton *baton = static_cast<LookupBaton *>(req->data); git_oid rawOid = baton->rawOid; if (!baton->sha.empty()) { int returnCode = git_oid_fromstr(&rawOid, baton->sha.c_str()); if (returnCode != GIT_OK) { baton->error = giterr_last(); return; } } baton->rawCommit = NULL; int returnCode = git_commit_lookup(&baton->rawCommit, baton->repo, &rawOid); if (returnCode != GIT_OK) { baton->error = giterr_last(); } } void GitCommit::LookupAfterWork(uv_work_t *req) { HandleScope scope; LookupBaton *baton = static_cast<LookupBaton *>(req->data); if (baton->error) { Local<Value> argv[1] = { GitError::WrapError(baton->error) }; TryCatch try_catch; baton->callback->Call(Context::GetCurrent()->Global(), 1, argv); if (try_catch.HasCaught()) { node::FatalException(try_catch); } } else { Local<Object> commit = GitCommit::constructor_template->NewInstance(); GitCommit *commitInstance = ObjectWrap::Unwrap<GitCommit>(commit); commitInstance->SetValue(baton->rawCommit); Handle<Value> argv[2] = { Local<Value>::New(Null()), commit }; TryCatch try_catch; baton->callback->Call(Context::GetCurrent()->Global(), 2, argv); if (try_catch.HasCaught()) { node::FatalException(try_catch); } } delete req; } Handle<Value> GitCommit::Close(const Arguments& args) { HandleScope scope; GitCommit *commit = ObjectWrap::Unwrap<GitCommit>(args.This()); commit->Close(); return scope.Close(Undefined()); } Handle<Value> GitCommit::Tree(const Arguments& args) { HandleScope scope; if(args.Length() == 0 || !args[0]->IsFunction()) { return ThrowException(Exception::Error(String::New("Callback is required and must be a Function."))); } TreeBaton* baton = new TreeBaton; baton->request.data = baton; baton->error = NULL; baton->rawTree = NULL; baton->rawCommit = ObjectWrap::Unwrap<GitCommit>(args.This())->GetValue(); baton->callback = Persistent<Function>::New(Local<Function>::Cast(args[0])); uv_queue_work(uv_default_loop(), &baton->request, TreeWork, (uv_after_work_cb)TreeAfterWork); return Undefined(); } void GitCommit::TreeWork(uv_work_t* req) { TreeBaton* baton = static_cast<TreeBaton*>(req->data); int returnCode = git_commit_tree(&baton->rawTree, baton->rawCommit); if (returnCode != GIT_OK) { baton->error = giterr_last(); } } void GitCommit::TreeAfterWork(uv_work_t* req) { HandleScope scope; TreeBaton* baton = static_cast<TreeBaton* >(req->data); if (success(baton->error, baton->callback)) { Local<Object> tree = GitTree::constructor_template->NewInstance(); GitTree *treeInstance = ObjectWrap::Unwrap<GitTree>(tree); treeInstance->SetValue(baton->rawTree); Handle<Value> argv[2] = { Local<Value>::New(Null()), tree }; TryCatch try_catch; baton->callback->Call(Context::GetCurrent()->Global(), 2, argv); if (try_catch.HasCaught()) { node::FatalException(try_catch); } } delete req; } Handle<Value> GitCommit::Parent(const Arguments& args) { HandleScope scope; if(args.Length() != 2) { return ThrowException(Exception::Error(String::New("Position and callback are required"))); } if(!args[0]->IsNumber()) { return ThrowException(Exception::Error(String::New("Position is required and must be a Number."))); } if(!args[1]->IsFunction()) { return ThrowException(Exception::Error(String::New("Callback is required and must be a Function."))); } ParentBaton* baton = new ParentBaton(); baton->request.data = baton; baton->rawCommit = ObjectWrap::Unwrap<GitCommit>(args.This())->GetValue(); baton->error = NULL; baton->rawParentCommit = NULL; baton->index = args[0]->ToInteger()->Value(); baton->callback = Persistent<Function>::New(Local<Function>::Cast(args[1])); uv_queue_work(uv_default_loop(), &baton->request, ParentWork, (uv_after_work_cb)ParentAfterWork); return Undefined(); } void GitCommit::ParentWork(uv_work_t* req) { ParentBaton* baton = static_cast<ParentBaton*>(req->data); int returnCode = git_commit_parent(&baton->rawParentCommit, baton->rawCommit, baton->index); if (returnCode != GIT_OK) { baton->error = giterr_last(); } } void GitCommit::ParentAfterWork(uv_work_t* req) { HandleScope scope; ParentBaton* baton = static_cast<ParentBaton* >(req->data); if (success(baton->error, baton->callback)) { Local<Object> parent = GitCommit::constructor_template->NewInstance(); GitCommit *parentInstance = ObjectWrap::Unwrap<GitCommit>(parent); parentInstance->SetValue(baton->rawParentCommit); Handle<Value> argv[2] = { Local<Value>::New(Null()), parent }; TryCatch try_catch; baton->callback->Call(Context::GetCurrent()->Global(), 2, argv); if (try_catch.HasCaught()) { node::FatalException(try_catch); } } delete req; } Persistent<Function> GitCommit::constructor_template; <commit_msg>Moved close to match position in header<commit_after>/* * Copyright 2013, Tim Branyen @tbranyen <tim@tabdeveloper.com> * @author Michael Robinson @codeofinterest <mike@pagesofinterest.net> * * Dual licensed under the MIT and GPL licenses. */ #include <string.h> #include <v8.h> #include <node.h> #include "../vendor/libgit2/include/git2.h" #include "cvv8/v8-convert.hpp" #include "../include/reference.h" #include "../include/sig.h" #include "../include/repo.h" #include "../include/oid.h" #include "../include/tree.h" #include "../include/commit.h" #include "../include/error.h" #include "../include/functions/utilities.h" using namespace v8; using namespace cvv8; using namespace node; void GitCommit::Initialize(Handle<Object> target) { HandleScope scope; Local<FunctionTemplate> tpl = FunctionTemplate::New(New); tpl->InstanceTemplate()->SetInternalFieldCount(1); tpl->SetClassName(String::NewSymbol("Commit")); NODE_SET_PROTOTYPE_METHOD(tpl, "lookup", Lookup); NODE_SET_PROTOTYPE_METHOD(tpl, "close", Close); NODE_SET_PROTOTYPE_METHOD(tpl, "tree", Tree); NODE_SET_PROTOTYPE_METHOD(tpl, "parent", Parent); constructor_template = Persistent<Function>::New(tpl->GetFunction()); target->Set(String::NewSymbol("Commit"), constructor_template); } git_commit* GitCommit::GetValue() { return this->commit; } void GitCommit::SetValue(git_commit* commit) { this->commit = commit; } Handle<Value> GitCommit::New(const Arguments& args) { HandleScope scope; GitCommit *commit = new GitCommit(); commit->Wrap(args.This()); return scope.Close(args.This()); } void GitCommit::Close() { git_commit_free(this->commit); this->commit = NULL; } // Handle<Value> GitCommit::FetchDetailsSync(const Arguments& args) { // HandleScope scope; // GitCommit *commit = ObjectWrap::Unwrap<GitCommit>(args.This()); // git_commit* rawCommit = commit->GetValue(); // GitCommitDetails* details = new GitCommitDetails; // details->oid = git_commit_id(rawCommit); // details->sha[GIT_OID_HEXSZ] = '\0'; // git_oid_fmt(details->sha, details->oid); // details->message = git_commit_message(rawCommit); // details->time = git_commit_time(rawCommit); // details->timeOffset = git_commit_time_offset(rawCommit); // details->committer = git_commit_committer(rawCommit); // details->author = git_commit_author(rawCommit); // details->parentCount = git_commit_parentcount(rawCommit); // int parentCount = details->parentCount; // while (parentCount > 0) { // int parentIndex = parentCount -1; // char sha[GIT_OID_HEXSZ + 1]; // sha[GIT_OID_HEXSZ] = '\0'; // const git_oid *parentOid = git_commit_parent_id(rawCommit, parentIndex); // git_oid_fmt(sha, parentOid); // details->parentShas.push_back(sha); // parentCount--; // } // return scope.Close(createCommitDetailsObject(details)); // } // Handle<Value> GitCommit::FetchDetails(const Arguments& args) { // HandleScope scope; // if(args.Length() == 0 || !args[0]->IsFunction()) { // return ThrowException(Exception::Error(String::New("Callback is required and must be a Function."))); // } // FetchDetailsBaton* baton = new FetchDetailsBaton; // baton->request.data = baton; // baton->error = NULL; // baton->details = new GitCommitDetails; // baton->rawCommit = ObjectWrap::Unwrap<GitCommit>(args.This())->commit; // baton->callback = Persistent<Function>::New(Local<Function>::Cast(args[0])); // uv_queue_work(uv_default_loop(), &baton->request, FetchDetailsWork, (uv_after_work_cb)FetchDetailsAfterWork); // return Undefined(); // } // void GitCommit::FetchDetailsWork(uv_work_t *req) { // FetchDetailsBaton* baton = static_cast<FetchDetailsBaton*>(req->data); // GitCommitDetails* details = baton->details; // details->oid = git_commit_id(baton->rawCommit); // details->sha[GIT_OID_HEXSZ] = '\0'; // git_oid_fmt(details->sha, details->oid); // details->message = git_commit_message(baton->rawCommit); // details->time = git_commit_time(baton->rawCommit); // details->timeOffset = git_commit_time_offset(baton->rawCommit); // details->committer = git_commit_committer(baton->rawCommit); // details->author = git_commit_author(baton->rawCommit); // details->parentCount = git_commit_parentcount(baton->rawCommit); // int parentCount = details->parentCount; // while (parentCount > 0) { // int parentIndex = parentCount -1; // char sha[GIT_OID_HEXSZ + 1]; // sha[GIT_OID_HEXSZ] = '\0'; // const git_oid *parentOid = git_commit_parent_id(baton->rawCommit, parentIndex); // git_oid_fmt(sha, parentOid); // details->parentShas.push_back(sha); // parentCount--; // } // } // void GitCommit::FetchDetailsAfterWork(uv_work_t *req) { // HandleScope scope; // FetchDetailsBaton* baton = static_cast<FetchDetailsBaton* >(req->data); // if (baton->error) { // Local<Value> argv[1] = { // GitError::WrapError(baton->error) // }; // TryCatch try_catch; // baton->callback->Call(Context::GetCurrent()->Global(), 1, argv); // if (try_catch.HasCaught()) { // node::FatalException(try_catch); // } // } else { // Handle<Value> argv[2] = { // Local<Value>::New(Null()), // createCommitDetailsObject(baton->details) // }; // TryCatch try_catch; // baton->callback->Call(Context::GetCurrent()->Global(), 2, argv); // if (try_catch.HasCaught()) { // node::FatalException(try_catch); // } // } // delete req; // } Handle<Value> GitCommit::Lookup(const Arguments& args) { HandleScope scope; if(args.Length() == 0 || !args[0]->IsObject()) { return ThrowException(Exception::Error(String::New("Repo is required and must be an Object."))); } if(args.Length() == 1 || !(args[1]->IsObject() || args[1]->IsString())) { return ThrowException(Exception::Error(String::New("Oid is required and must be an Object or String"))); } if(args.Length() == 2 || !args[2]->IsFunction()) { return ThrowException(Exception::Error(String::New("Callback is required and must be a Function."))); } LookupBaton *baton = new LookupBaton; baton->request.data = baton; baton->error = NULL; baton->repo = ObjectWrap::Unwrap<GitRepo>(args[0]->ToObject())->GetValue(); if (args[1]->IsObject()) { baton->rawOid = ObjectWrap::Unwrap<GitOid>(args[1]->ToObject())->GetValue(); } else { baton->sha = stringArgToString(args[1]->ToString()); } baton->callback = Persistent<Function>::New(Local<Function>::Cast(args[2])); uv_queue_work(uv_default_loop(), &baton->request, LookupWork, (uv_after_work_cb)LookupAfterWork); return Undefined(); } void GitCommit::LookupWork(uv_work_t *req) { LookupBaton *baton = static_cast<LookupBaton *>(req->data); git_oid rawOid = baton->rawOid; if (!baton->sha.empty()) { int returnCode = git_oid_fromstr(&rawOid, baton->sha.c_str()); if (returnCode != GIT_OK) { baton->error = giterr_last(); return; } } baton->rawCommit = NULL; int returnCode = git_commit_lookup(&baton->rawCommit, baton->repo, &rawOid); if (returnCode != GIT_OK) { baton->error = giterr_last(); } } void GitCommit::LookupAfterWork(uv_work_t *req) { HandleScope scope; LookupBaton *baton = static_cast<LookupBaton *>(req->data); if (baton->error) { Local<Value> argv[1] = { GitError::WrapError(baton->error) }; TryCatch try_catch; baton->callback->Call(Context::GetCurrent()->Global(), 1, argv); if (try_catch.HasCaught()) { node::FatalException(try_catch); } } else { Local<Object> commit = GitCommit::constructor_template->NewInstance(); GitCommit *commitInstance = ObjectWrap::Unwrap<GitCommit>(commit); commitInstance->SetValue(baton->rawCommit); Handle<Value> argv[2] = { Local<Value>::New(Null()), commit }; TryCatch try_catch; baton->callback->Call(Context::GetCurrent()->Global(), 2, argv); if (try_catch.HasCaught()) { node::FatalException(try_catch); } } delete req; } Handle<Value> GitCommit::Close(const Arguments& args) { HandleScope scope; GitCommit *commit = ObjectWrap::Unwrap<GitCommit>(args.This()); commit->Close(); return scope.Close(Undefined()); } Handle<Value> GitCommit::Tree(const Arguments& args) { HandleScope scope; if(args.Length() == 0 || !args[0]->IsFunction()) { return ThrowException(Exception::Error(String::New("Callback is required and must be a Function."))); } TreeBaton* baton = new TreeBaton; baton->request.data = baton; baton->error = NULL; baton->rawTree = NULL; baton->rawCommit = ObjectWrap::Unwrap<GitCommit>(args.This())->GetValue(); baton->callback = Persistent<Function>::New(Local<Function>::Cast(args[0])); uv_queue_work(uv_default_loop(), &baton->request, TreeWork, (uv_after_work_cb)TreeAfterWork); return Undefined(); } void GitCommit::TreeWork(uv_work_t* req) { TreeBaton* baton = static_cast<TreeBaton*>(req->data); int returnCode = git_commit_tree(&baton->rawTree, baton->rawCommit); if (returnCode != GIT_OK) { baton->error = giterr_last(); } } void GitCommit::TreeAfterWork(uv_work_t* req) { HandleScope scope; TreeBaton* baton = static_cast<TreeBaton* >(req->data); if (success(baton->error, baton->callback)) { Local<Object> tree = GitTree::constructor_template->NewInstance(); GitTree *treeInstance = ObjectWrap::Unwrap<GitTree>(tree); treeInstance->SetValue(baton->rawTree); Handle<Value> argv[2] = { Local<Value>::New(Null()), tree }; TryCatch try_catch; baton->callback->Call(Context::GetCurrent()->Global(), 2, argv); if (try_catch.HasCaught()) { node::FatalException(try_catch); } } delete req; } Handle<Value> GitCommit::Parent(const Arguments& args) { HandleScope scope; if(args.Length() != 2) { return ThrowException(Exception::Error(String::New("Position and callback are required"))); } if(!args[0]->IsNumber()) { return ThrowException(Exception::Error(String::New("Position is required and must be a Number."))); } if(!args[1]->IsFunction()) { return ThrowException(Exception::Error(String::New("Callback is required and must be a Function."))); } ParentBaton* baton = new ParentBaton(); baton->request.data = baton; baton->rawCommit = ObjectWrap::Unwrap<GitCommit>(args.This())->GetValue(); baton->error = NULL; baton->rawParentCommit = NULL; baton->index = args[0]->ToInteger()->Value(); baton->callback = Persistent<Function>::New(Local<Function>::Cast(args[1])); uv_queue_work(uv_default_loop(), &baton->request, ParentWork, (uv_after_work_cb)ParentAfterWork); return Undefined(); } void GitCommit::ParentWork(uv_work_t* req) { ParentBaton* baton = static_cast<ParentBaton*>(req->data); int returnCode = git_commit_parent(&baton->rawParentCommit, baton->rawCommit, baton->index); if (returnCode != GIT_OK) { baton->error = giterr_last(); } } void GitCommit::ParentAfterWork(uv_work_t* req) { HandleScope scope; ParentBaton* baton = static_cast<ParentBaton* >(req->data); if (success(baton->error, baton->callback)) { Local<Object> parent = GitCommit::constructor_template->NewInstance(); GitCommit *parentInstance = ObjectWrap::Unwrap<GitCommit>(parent); parentInstance->SetValue(baton->rawParentCommit); Handle<Value> argv[2] = { Local<Value>::New(Null()), parent }; TryCatch try_catch; baton->callback->Call(Context::GetCurrent()->Global(), 2, argv); if (try_catch.HasCaught()) { node::FatalException(try_catch); } } delete req; } Persistent<Function> GitCommit::constructor_template; <|endoftext|>
<commit_before>#include "Point.hpp" Point::Point(int px, int py) : x(px), y(py){ if(abs(px + py) > 4 || abs(px) > 4 || abs(py) > 4){ throw BoardBoundsException(px,py); } } bool Point::operator < (const Point& pToCompare) const{ return (this->x < pToCompare.x) || ((this->x == pToCompare.x) && (this->y < pToCompare.y)); } /* bool Point::operator < (const Point& pToCompare) const{ if(this->x < pToCompare.x){ return true; } else if(this->x == pToCompare.x){ return this->y > pToCompare.y; } else{ return false; } }*/ bool Point::operator== (const Point& pToCompare) const{ return x == pToCompare.x && y == pToCompare.y; } bool Point::operator!= (const Point& pToCompare) const{ return x != pToCompare.x || y != pToCompare.y; } std::ostream& operator<< (std::ostream& pStream, const Point& pPoint){ return (pStream << "(" << pPoint.x << "," << pPoint.y << ")"); } <commit_msg>Added Release macro.<commit_after>#include "Point.hpp" Point::Point(int px, int py) : x(px), y(py){ #ifndef RELEASE if(abs(px + py) > 4 || abs(px) > 4 || abs(py) > 4){ throw BoardBoundsException(px,py); } #endif } bool Point::operator < (const Point& pToCompare) const{ return (this->x < pToCompare.x) || ((this->x == pToCompare.x) && (this->y < pToCompare.y)); } bool Point::operator== (const Point& pToCompare) const{ return x == pToCompare.x && y == pToCompare.y; } bool Point::operator!= (const Point& pToCompare) const{ return x != pToCompare.x || y != pToCompare.y; } std::ostream& operator<< (std::ostream& pStream, const Point& pPoint){ return (pStream << "(" << pPoint.x << "," << pPoint.y << ")"); } <|endoftext|>
<commit_before>/// @brief provides stuff for std::tan in case of fixed-point numbers namespace std { template<typename T, size_t n, size_t f, class op, class up> typename core::fixed_point<T, n, f, op, up>::tan_type tan(core::fixed_point<T, n, f, op, up> const& val) { typedef core::fixed_point<T, n, f, op, up> fp; fp::sin_type const sin = std::sin(val); fp::cos_type const cos = std::cos(val); if (cos == fp::cos_type(0)) { throw std::exception("tan: cos is zero"); } return fp::tan_type(sin / cos); } } <commit_msg>tan.inl: class tan_of<commit_after>/// @brief provides stuff for std::tan in case of fixed-point numbers #include <boost/type_traits/is_floating_point.hpp> #include <boost/integer.hpp> namespace core { template<typename T> class tan_of { BOOST_STATIC_ASSERT(boost::is_floating_point<T>::value); public: typedef T type; }; template<typename T, size_t n, size_t f, class op, class up> class tan_of<fixed_point<T, n, f, op, up> > { typedef fixed_point<T, n, f, op, up> fp_type; public: typedef typename quotient< typename sin_of<fp_type>::type, typename cos_of<fp_type>::type >::type type; }; } namespace std { template<typename T, size_t n, size_t f, class op, class up> typename core::tan_of<core::fixed_point<T, n, f, op, up> >::type tan(core::fixed_point<T, n, f, op, up> val) { typedef core::fixed_point<T, n, f, op, up> fp; fp::sin_type const sin = std::sin(val); fp::cos_type const cos = std::cos(val); if (cos == fp::cos_type(0)) { throw std::exception("tan: cos is zero"); } return fp::tan_type(sin / cos); } } <|endoftext|>
<commit_before>#include "cinder/app/App.h" #include "cinder/Capture.h" #include "cinder/Utilities.h" #include "cinder/ImageIo.h" #include "cinder/app/RendererGl.h" #include "cinder/gl/Texture.h" #include "cinder/gl/Fbo.h" #include "cinder/gl/shader.h" #include "cinder/gl/draw.h" #include "cinder/gl/scoped.h" #include "cinder/params/Params.h" #include "cinder/qtime/QuickTimeGl.h" #include "TextureHelper.h" #include "CaptureHelper.h" #include "CinderOpenCV.h" #include "ciFaceTracker/ciFacetracker.h" #include "MiniConfig.h" #include "Clone.h" using namespace ci; using namespace app; using namespace std; #if defined( CINDER_GL_ES ) namespace cinder { namespace gl { void enableWireframe() {} void disableWireframe() {} } } #endif class FaceOff : public App { public: static void prepareSettings(Settings *settings) { readConfig(); settings->setWindowSize(APP_W, APP_H); settings->setFrameRate(60.0f); settings->setFullScreen(false); settings->setTitle("face-switcher"); } void keyUp(KeyEvent event) { switch (event.getChar()) { case 'f': { setFullScreen(!isFullScreen()); APP_W = getWindowBounds().getWidth(); APP_H = getWindowBounds().getHeight(); } break; case KeyEvent::KEY_ESCAPE: quit(); break; } } void fileDrop_DISABLED(FileDropEvent event) { if (event.getNumFiles() > 0) { console() << event.getFile(0); try { ImageSourceRef img = loadImage(event.getFile(0)); gl::Texture2dRef newTex; if (img) newTex = gl::Texture::create(img); shared_ptr<ciFaceTracker> newTracker = std::make_shared<ciFaceTracker>(); newTracker->setup(); newTracker->update(toOcv(img)); if (newTracker->getFound()) { mOfflineTracker = newTracker; mPhotoTex = newTex; } } catch (...) { } } } void setup(); void update(); void draw(); void shutdown() { } private: TriMesh mFaceMesh; ciFaceTracker mOnlineTracker; shared_ptr<ciFaceTracker> mOfflineTracker; gl::TextureRef mPhotoTex; qtime::MovieSurfaceRef mMovie; // vector<Capture::DeviceRef> mDevices; vector<string> mDeviceNames; CaptureHelper mCapture; vector<string> mPeopleNames; params::InterfaceGlRef mParam; gl::TextureRef mRefTex; gl::TextureRef mRenderedRefTex; gl::FboRef mSrcFbo, mMaskFbo; Clone mClone; // param int mDeviceId; int mPeopleId; bool mDoesCaptureNeedsInit; }; void FaceOff::setup() { APP_W = getWindowWidth(); APP_H = getWindowHeight(); // list out the devices vector<Capture::DeviceRef> devices(Capture::getDevices()); if (devices.empty()) { console() << "No camera device connected." << endl; quit(); return; } for (auto device : devices) { console() << "Found Device " << device->getName() << " ID: " << device->getUniqueId() << endl; if (device->checkAvailable()) { mDevices.push_back(device); mDeviceNames.push_back(device->getName()); } } mOnlineTracker.setup(); mOnlineTracker.setRescale(0.5f); // TODO: assert fs::directory_iterator kEnd; fs::path peopleFolder = getAssetPath("people"); for (fs::directory_iterator it(peopleFolder); it != kEnd; ++it) { mPeopleNames.push_back(it->path().filename().string()); } #if !defined( CINDER_GL_ES ) mParam = params::InterfaceGl::create("param", ivec2(300, getConfigUIHeight())); setupConfigUI(mParam.get()); // TODO: assert if (DEVICE_ID > mDeviceNames.size() - 1) { DEVICE_ID = 0; } ADD_ENUM_TO_INT(mParam, DEVICE_ID, mDeviceNames); mDeviceId = -1; if (PEOPLE_ID > mPeopleNames.size() - 1) { PEOPLE_ID = 0; } ADD_ENUM_TO_INT(mParam, PEOPLE_ID, mPeopleNames); #else DEVICE_ID = 1; // pick front camera for mobile devices #endif mPeopleId = -1; gl::disableDepthRead(); gl::disableDepthWrite(); } void FaceOff::update() { if (MOVIE_MODE) { if (!mMovie) { fs::path moviePath = getAssetPath(MOVIE_PATH); try { // load up the movie, set it to loop, and begin playing mMovie = qtime::MovieSurface::create(moviePath); mMovie->setLoop(); mMovie->play(); mRefTex.reset(); mRenderedRefTex.reset(); } catch (ci::Exception &exc) { console() << "Exception caught trying to load the movie from path: " << moviePath << ", what: " << exc.what() << std::endl; mMovie.reset(); } } else { if (mMovie->checkNewFrame()) { auto surface = mMovie->getSurface(); if (!mRefTex) { mRefTex = gl::Texture2d::create(*surface, gl::Texture::Format().loadTopDown()); } else { mRefTex->update(*surface); } } } } else { if (mMovie) { mMovie.reset(); } mRefTex = mPhotoTex; } if (mDeviceId != DEVICE_ID) { mDeviceId = DEVICE_ID; mDoesCaptureNeedsInit = true; mCapture.setup(CAM_W, CAM_H, mDevices[DEVICE_ID]); } if (mPeopleId != PEOPLE_ID) { mPeopleId = PEOPLE_ID; mOfflineTracker = std::make_shared<ciFaceTracker>(); mOfflineTracker->setup(); //mOfflineTracker->setRescale(0.5f); ImageSourceRef img = loadImage(loadAsset("people/" + mPeopleNames[PEOPLE_ID])); if (img) { mRefTex = mPhotoTex = gl::Texture::create(img, gl::Texture::Format().loadTopDown()); } mOfflineTracker->update(toOcv(img)); mFaceMesh.getBufferTexCoords0().clear(); } // TODO: more robust // use signal? if (mCapture.isDirty()) { if (mDoesCaptureNeedsInit) { mDoesCaptureNeedsInit = false; // TODO: more robust // use signal? CAM_W = mCapture.size.x; CAM_H = mCapture.size.y; gl::Fbo::Format fboFormat; //fboFormat.setColorTextureFormat(texFormat); fboFormat.enableDepthBuffer(false); mSrcFbo = gl::Fbo::create(CAM_W, CAM_H, fboFormat); mMaskFbo = gl::Fbo::create(CAM_W, CAM_H, fboFormat); mClone.setup(CAM_W, CAM_H); mClone.setStrength(16); } Surface8u surface = mCapture.surface; mOnlineTracker.update(toOcv(surface)); if (!mOnlineTracker.getFound()) return; int nPoints = mOnlineTracker.size(); if (mFaceMesh.getBufferTexCoords0().empty()) { for (int i = 0; i < nPoints; i++) { mFaceMesh.appendTexCoord(mOfflineTracker->getUVPoint(i)); } mOnlineTracker.addTriangleIndices(mFaceMesh); } mFaceMesh.getBufferPositions().clear(); for (int i = 0; i < nPoints; i++) { mFaceMesh.appendPosition(vec3(mOnlineTracker.getImagePoint(i), 0)); } if (FACE_SUB_VISIBLE && mRefTex) { //gl::setMatricesWindow(getWindowSize(), false); // TODO: merge these two passes w/ MRTs { gl::ScopedFramebuffer fbo(mSrcFbo); gl::ScopedGlslProg glsl(gl::getStockShader(gl::ShaderDef().texture())); gl::ScopedTextureBind t0(mRefTex, 0); gl::clear(ColorA::black(), false); gl::draw(mFaceMesh); mRenderedRefTex = mSrcFbo->getColorTexture(); } if (!MOVIE_MODE) { { gl::ScopedFramebuffer fbo(mMaskFbo); gl::clear(ColorA::black(), false); mRefTex->unbind(); gl::draw(mFaceMesh); } mClone.update(mRenderedRefTex, mCapture.texture, mMaskFbo->getColorTexture()); } } } } void FaceOff::draw() { gl::clear(ColorA::black(), false); if (!mCapture.isReady()) return; gl::setMatricesWindow(getWindowSize()); gl::enableAlphaBlending(); float camAspect = CAM_W / (float)CAM_H; float winAspect = getWindowAspectRatio(); float adaptiveCamW = 0; float adaptiveCamH = 0; if (camAspect > winAspect) { adaptiveCamW = APP_W; adaptiveCamH = APP_W / camAspect; } else { adaptiveCamH = APP_H; adaptiveCamW = APP_H * camAspect; } Area srcArea = {0, 0, CAM_W, CAM_H}; Rectf dstRect = { APP_W * 0.5f - adaptiveCamW * 0.5f, APP_H * 0.5f - adaptiveCamH * 0.5f, APP_W * 0.5f + adaptiveCamW * 0.5f, APP_H * 0.5f + adaptiveCamH * 0.5f }; if (FACE_SUB_VISIBLE && mOnlineTracker.getFound()) { // gl::ScopedModelMatrix modelMatrix; // gl::scale(APP_W / (float)CAM_W, APP_H / (float)CAM_H); if (MOVIE_MODE) { if (mRenderedRefTex) gl::draw(mRenderedRefTex, srcArea, dstRect); } else { gl::draw(mClone.getResultTexture(), srcArea, dstRect); } } else { gl::draw(mCapture.texture, srcArea, dstRect); } if (REF_VISIBLE) { gl::draw(mRefTex); } FPS = getAverageFps(); gl::disableAlphaBlending(); if (WIREFRAME_MODE && mOnlineTracker.getFound()) { gl::enableWireframe(); gl::ScopedModelMatrix modelMatrix; gl::ScopedColor color(ColorA(0, 1.0f, 0, 1.0f)); gl::translate(APP_W * 0.5f - adaptiveCamW * 0.5f, APP_H * 0.5f - adaptiveCamH * 0.5f); gl::draw(mOnlineTracker.getImageMesh()); if (REF_VISIBLE) { gl::draw(mOfflineTracker->getImageMesh()); } gl::disableWireframe(); } } CINDER_APP(FaceOff, RendererGl, &FaceOff::prepareSettings)<commit_msg>Nevers renders raw texture in MOVIE_MODE.<commit_after>#include "cinder/app/App.h" #include "cinder/Capture.h" #include "cinder/Utilities.h" #include "cinder/ImageIo.h" #include "cinder/app/RendererGl.h" #include "cinder/gl/Texture.h" #include "cinder/gl/Fbo.h" #include "cinder/gl/shader.h" #include "cinder/gl/draw.h" #include "cinder/gl/scoped.h" #include "cinder/params/Params.h" #include "cinder/qtime/QuickTimeGl.h" #include "TextureHelper.h" #include "CaptureHelper.h" #include "CinderOpenCV.h" #include "ciFaceTracker/ciFacetracker.h" #include "MiniConfig.h" #include "Clone.h" using namespace ci; using namespace app; using namespace std; #if defined( CINDER_GL_ES ) namespace cinder { namespace gl { void enableWireframe() {} void disableWireframe() {} } } #endif class FaceOff : public App { public: static void prepareSettings(Settings *settings) { readConfig(); settings->setWindowSize(APP_W, APP_H); settings->setFrameRate(60.0f); settings->setFullScreen(false); settings->setTitle("face-switcher"); } void keyUp(KeyEvent event) { switch (event.getChar()) { case 'f': { setFullScreen(!isFullScreen()); APP_W = getWindowBounds().getWidth(); APP_H = getWindowBounds().getHeight(); } break; case KeyEvent::KEY_ESCAPE: quit(); break; } } void fileDrop_DISABLED(FileDropEvent event) { if (event.getNumFiles() > 0) { console() << event.getFile(0); try { ImageSourceRef img = loadImage(event.getFile(0)); gl::Texture2dRef newTex; if (img) newTex = gl::Texture::create(img); shared_ptr<ciFaceTracker> newTracker = std::make_shared<ciFaceTracker>(); newTracker->setup(); newTracker->update(toOcv(img)); if (newTracker->getFound()) { mOfflineTracker = newTracker; mPhotoTex = newTex; } } catch (...) { } } } void setup(); void update(); void draw(); void shutdown() { } private: TriMesh mFaceMesh; ciFaceTracker mOnlineTracker; shared_ptr<ciFaceTracker> mOfflineTracker; gl::TextureRef mPhotoTex; qtime::MovieSurfaceRef mMovie; // vector<Capture::DeviceRef> mDevices; vector<string> mDeviceNames; CaptureHelper mCapture; vector<string> mPeopleNames; params::InterfaceGlRef mParam; gl::TextureRef mRefTex; gl::TextureRef mRenderedRefTex; gl::FboRef mSrcFbo, mMaskFbo; Clone mClone; // param int mDeviceId; int mPeopleId; bool mDoesCaptureNeedsInit; }; void FaceOff::setup() { APP_W = getWindowWidth(); APP_H = getWindowHeight(); // list out the devices vector<Capture::DeviceRef> devices(Capture::getDevices()); if (devices.empty()) { console() << "No camera device connected." << endl; quit(); return; } for (auto device : devices) { console() << "Found Device " << device->getName() << " ID: " << device->getUniqueId() << endl; if (device->checkAvailable()) { mDevices.push_back(device); mDeviceNames.push_back(device->getName()); } } mOnlineTracker.setup(); mOnlineTracker.setRescale(0.5f); // TODO: assert fs::directory_iterator kEnd; fs::path peopleFolder = getAssetPath("people"); for (fs::directory_iterator it(peopleFolder); it != kEnd; ++it) { mPeopleNames.push_back(it->path().filename().string()); } #if !defined( CINDER_GL_ES ) mParam = params::InterfaceGl::create("param", ivec2(300, getConfigUIHeight())); setupConfigUI(mParam.get()); // TODO: assert if (DEVICE_ID > mDeviceNames.size() - 1) { DEVICE_ID = 0; } ADD_ENUM_TO_INT(mParam, DEVICE_ID, mDeviceNames); mDeviceId = -1; if (PEOPLE_ID > mPeopleNames.size() - 1) { PEOPLE_ID = 0; } ADD_ENUM_TO_INT(mParam, PEOPLE_ID, mPeopleNames); #else DEVICE_ID = 1; // pick front camera for mobile devices #endif mPeopleId = -1; gl::disableDepthRead(); gl::disableDepthWrite(); } void FaceOff::update() { if (MOVIE_MODE) { if (!mMovie) { fs::path moviePath = getAssetPath(MOVIE_PATH); try { // load up the movie, set it to loop, and begin playing mMovie = qtime::MovieSurface::create(moviePath); mMovie->setLoop(); mMovie->play(); mRefTex.reset(); mRenderedRefTex.reset(); } catch (ci::Exception &exc) { console() << "Exception caught trying to load the movie from path: " << MOVIE_PATH << ", what: " << exc.what() << std::endl; mMovie.reset(); } } else { if (mMovie->checkNewFrame()) { auto surface = mMovie->getSurface(); if (!mRefTex) { mRefTex = gl::Texture2d::create(*surface, gl::Texture::Format().loadTopDown()); } else { mRefTex->update(*surface); } } } } else { if (mMovie) { mMovie.reset(); } mRefTex = mPhotoTex; } if (mDeviceId != DEVICE_ID) { mDeviceId = DEVICE_ID; mDoesCaptureNeedsInit = true; mCapture.setup(CAM_W, CAM_H, mDevices[DEVICE_ID]); } if (mPeopleId != PEOPLE_ID) { mPeopleId = PEOPLE_ID; mOfflineTracker = std::make_shared<ciFaceTracker>(); mOfflineTracker->setup(); //mOfflineTracker->setRescale(0.5f); ImageSourceRef img = loadImage(loadAsset("people/" + mPeopleNames[PEOPLE_ID])); if (img) { mRefTex = mPhotoTex = gl::Texture::create(img, gl::Texture::Format().loadTopDown()); } mOfflineTracker->update(toOcv(img)); mFaceMesh.getBufferTexCoords0().clear(); } // TODO: more robust // use signal? if (mCapture.isDirty()) { if (mDoesCaptureNeedsInit) { mDoesCaptureNeedsInit = false; // TODO: more robust // use signal? CAM_W = mCapture.size.x; CAM_H = mCapture.size.y; gl::Fbo::Format fboFormat; //fboFormat.setColorTextureFormat(texFormat); fboFormat.enableDepthBuffer(false); mSrcFbo = gl::Fbo::create(CAM_W, CAM_H, fboFormat); mMaskFbo = gl::Fbo::create(CAM_W, CAM_H, fboFormat); mClone.setup(CAM_W, CAM_H); mClone.setStrength(16); } Surface8u surface = mCapture.surface; mOnlineTracker.update(toOcv(surface)); if (!mOnlineTracker.getFound()) return; int nPoints = mOnlineTracker.size(); if (mFaceMesh.getBufferTexCoords0().empty()) { for (int i = 0; i < nPoints; i++) { mFaceMesh.appendTexCoord(mOfflineTracker->getUVPoint(i)); } mOnlineTracker.addTriangleIndices(mFaceMesh); } mFaceMesh.getBufferPositions().clear(); for (int i = 0; i < nPoints; i++) { mFaceMesh.appendPosition(vec3(mOnlineTracker.getImagePoint(i), 0)); } if (FACE_SUB_VISIBLE && mRefTex) { //gl::setMatricesWindow(getWindowSize(), false); // TODO: merge these two passes w/ MRTs { gl::ScopedFramebuffer fbo(mSrcFbo); gl::ScopedGlslProg glsl(gl::getStockShader(gl::ShaderDef().texture())); gl::ScopedTextureBind t0(mRefTex, 0); gl::clear(ColorA::black(), false); gl::draw(mFaceMesh); mRenderedRefTex = mSrcFbo->getColorTexture(); } if (!MOVIE_MODE) { { gl::ScopedFramebuffer fbo(mMaskFbo); gl::clear(ColorA::black(), false); mRefTex->unbind(); gl::draw(mFaceMesh); } mClone.update(mRenderedRefTex, mCapture.texture, mMaskFbo->getColorTexture()); } } } } void FaceOff::draw() { gl::clear(ColorA::black(), false); if (!mCapture.isReady()) return; gl::setMatricesWindow(getWindowSize()); gl::enableAlphaBlending(); float camAspect = CAM_W / (float)CAM_H; float winAspect = getWindowAspectRatio(); float adaptiveCamW = 0; float adaptiveCamH = 0; if (camAspect > winAspect) { adaptiveCamW = APP_W; adaptiveCamH = APP_W / camAspect; } else { adaptiveCamH = APP_H; adaptiveCamW = APP_H * camAspect; } Area srcArea = {0, 0, CAM_W, CAM_H}; Rectf dstRect = { APP_W * 0.5f - adaptiveCamW * 0.5f, APP_H * 0.5f - adaptiveCamH * 0.5f, APP_W * 0.5f + adaptiveCamW * 0.5f, APP_H * 0.5f + adaptiveCamH * 0.5f }; if (FACE_SUB_VISIBLE) { // gl::ScopedModelMatrix modelMatrix; // gl::scale(APP_W / (float)CAM_W, APP_H / (float)CAM_H); if (MOVIE_MODE) { gl::draw(mRenderedRefTex, srcArea, dstRect); } else if (mOnlineTracker.getFound()) { gl::draw(mClone.getResultTexture(), srcArea, dstRect); } } else { gl::draw(mCapture.texture, srcArea, dstRect); } if (REF_VISIBLE) { gl::draw(mRefTex); } FPS = getAverageFps(); gl::disableAlphaBlending(); if (WIREFRAME_MODE && (MOVIE_MODE || mOnlineTracker.getFound())) { gl::enableWireframe(); gl::ScopedModelMatrix modelMatrix; gl::ScopedColor color(ColorA(0, 1.0f, 0, 1.0f)); gl::translate(APP_W * 0.5f - adaptiveCamW * 0.5f, APP_H * 0.5f - adaptiveCamH * 0.5f); gl::draw(mOnlineTracker.getImageMesh()); if (REF_VISIBLE) { gl::draw(mOfflineTracker->getImageMesh()); } gl::disableWireframe(); } } CINDER_APP(FaceOff, RendererGl, &FaceOff::prepareSettings)<|endoftext|>
<commit_before>/* * G28Handler.cpp * * Created on: 15 maj 2014 * Author: MattLech */ #include "G28Handler.h" static G28Handler *instance; G28Handler *G28Handler::getInstance() { if (!instance) { instance = new G28Handler(); }; return instance; }; G28Handler::G28Handler() { } int G28Handler::execute(Command *command) { //Serial.print("home\r\n"); long sourcePoint[2] = {0, 0}; sourcePoint[0] = CurrentState::getInstance()->getX(); sourcePoint[1] = CurrentState::getInstance()->getY(); StepperControl::getInstance()->moveToCoords(sourcePoint[0], sourcePoint[1], 0, 0, 0, 0, false, false, false); StepperControl::getInstance()->moveToCoords(sourcePoint[0], 0, 0, 0, 0, 0, false, false, false); StepperControl::getInstance()->moveToCoords(0, 0, 0, 0, 0, 0, false, false, false); if (LOGGING) { CurrentState::getInstance()->print(); } return 0; } <commit_msg>G28 units fix<commit_after>/* * G28Handler.cpp * * Created on: 15 maj 2014 * Author: MattLech */ #include "G28Handler.h" static G28Handler *instance; G28Handler *G28Handler::getInstance() { if (!instance) { instance = new G28Handler(); }; return instance; }; G28Handler::G28Handler() { } int G28Handler::execute(Command *command) { //Serial.print("home\r\n"); long stepsPerMm[2] = {0, 0}; stepsPerMm[0] = ParameterList::getInstance()->getValue(MOVEMENT_STEP_PER_MM_X); stepsPerMm[1] = ParameterList::getInstance()->getValue(MOVEMENT_STEP_PER_MM_Y); long sourcePoint[2] = {0.0, 0.0}; sourcePoint[0] = CurrentState::getInstance()->getX(); sourcePoint[1] = CurrentState::getInstance()->getY(); double currentPoint[2] = {0.0, 0.0}; currentPoint[0] = sourcePoint[0] / (float)stepsPerMm[0]; currentPoint[1] = sourcePoint[1] / (float)stepsPerMm[1]; StepperControl::getInstance()->moveToCoords(currentPoint[0], currentPoint[1], 0, 0, 0, 0, false, false, false); StepperControl::getInstance()->moveToCoords(currentPoint[0], 0, 0, 0, 0, 0, false, false, false); StepperControl::getInstance()->moveToCoords(0, 0, 0, 0, 0, 0, false, false, false); if (LOGGING) { CurrentState::getInstance()->print(); } return 0; } <|endoftext|>
<commit_before>#include "Genes/Gene.h" #include <cmath> #include <iostream> #include <algorithm> #include <utility> #include <map> #include <fstream> #include <numeric> #include <iterator> #include "Game/Board.h" #include "Game/Color.h" #include "Utility/Random.h" #include "Utility/String.h" #include "Utility/Exceptions.h" std::map<std::string, double> Gene::list_properties() const noexcept { auto properties = std::map<std::string, double>{{"Priority", scoring_priority}, {"Active", double(active)}}; adjust_properties(properties); return properties; } void Gene::adjust_properties(std::map<std::string, double>&) const noexcept { } void Gene::load_properties(const std::map<std::string, double>& properties) { if(properties.count("Priority") > 0) { scoring_priority = properties.at("Priority"); } if(properties.count("Active") > 0) { active = properties.at("Active") > 0.0; } load_gene_properties(properties); } void Gene::load_gene_properties(const std::map<std::string, double>&) { } size_t Gene::mutatable_components() const noexcept { return list_properties().size(); } void Gene::read_from(std::istream& is) { auto properties = list_properties(); std::map<std::string, bool> property_found; std::transform(properties.begin(), properties.end(), std::inserter(property_found, property_found.begin()), [](const auto& key_value) { return std::make_pair(key_value.first, false); }); std::string line; while(std::getline(is, line)) { if(String::trim_outer_whitespace(line).empty()) { break; } line = String::strip_comments(line, "#"); if(line.empty()) { continue; } auto split_line = String::split(line, ":"); if(split_line.size() != 2) { throw_on_invalid_line(line, "There should be exactly one colon per gene property line."); } auto property_name = String::remove_extra_whitespace(split_line[0]); auto property_data = String::remove_extra_whitespace(split_line[1]); if(property_name == "Name") { if(String::remove_extra_whitespace(property_data) == name()) { continue; } else { throw_on_invalid_line(line, "Reading data for wrong gene. Gene is " + name() + ", data is for " + property_data + "."); } } try { properties.at(property_name) = std::stod(property_data); property_found.at(property_name) = true; } catch(const std::out_of_range&) { throw_on_invalid_line(line, "Unrecognized parameter name."); } catch(const std::invalid_argument&) { throw_on_invalid_line(line, "Bad parameter value."); } } auto missing_data = std::accumulate(property_found.begin(), property_found.end(), std::string{}, [](const auto& so_far, const auto& name_found) { return so_far + ( ! name_found.second ? "\n" + name_found.first : ""); }); if( ! missing_data.empty()) { throw Genetic_AI_Creation_Error("Missing gene data for " + name() + ":" + missing_data); } load_properties(properties); } void Gene::read_from(const std::string& file_name) { auto ifs = std::ifstream(file_name); if( ! ifs) { throw Genetic_AI_Creation_Error("Could not open " + file_name + " to read."); } std::string line; while(std::getline(ifs, line)) { if(String::starts_with(line, "Name: ")) { auto gene_name = String::remove_extra_whitespace(String::split(line, ":", 1)[1]); if(gene_name == name()) { try { read_from(ifs); return; } catch(const std::exception& e) { throw Genetic_AI_Creation_Error("Error in reading data for " + name() + " from " + file_name + "\n" + e.what()); } } } } throw Genetic_AI_Creation_Error(name() + " not found in " + file_name); } void Gene::throw_on_invalid_line(const std::string& line, const std::string& reason) const { throw Genetic_AI_Creation_Error("Invalid line in while reading for " + name() + ": " + line + "\n" + reason); } void Gene::mutate() noexcept { if(is_active()) { if(Random::success_probability(1, 1000)) { active = false; } } else { if(Random::success_probability(1, 100)) { active = true; } } if( ! is_active()) { return; } auto properties = list_properties(); if(Random::success_probability(properties.count("Priority"), properties.size())) { scoring_priority += Random::random_laplace(0.005); } else { gene_specific_mutation(); } } void Gene::gene_specific_mutation() noexcept { } double Gene::evaluate(const Board& board, Piece_Color perspective, size_t depth) const noexcept { if(is_active()) { return scoring_priority*score_board(board, perspective, depth); } else { return 0.0; } } void Gene::print(std::ostream& os) const noexcept { auto properties = list_properties(); os << "Name: " << name() << "\n"; for(const auto& [name, value] : properties) { os << name << ": " << value << "\n"; } os << "\n"; } void Gene::reset_piece_strength_gene(const Piece_Strength_Gene*) noexcept { } double Gene::priority() const noexcept { return scoring_priority; } void Gene::scale_priority(double k) noexcept { scoring_priority *= k; } void Gene::zero_out_priority() noexcept { scoring_priority = 0.0; } bool Gene::is_active() const noexcept { return active; } void Gene::test(bool& test_variable, const Board& board, Piece_Color perspective, double expected_score) const noexcept { auto result = score_board(board, perspective, board.game_length() == 0 ? 0 : 1); if(std::abs(result - expected_score) > 1e-6) { std::cerr << "Error in " << name() << ": Expected " << expected_score << ", Got: " << result << '\n'; test_variable = false; } } <commit_msg>Delete extra space<commit_after>#include "Genes/Gene.h" #include <cmath> #include <iostream> #include <algorithm> #include <utility> #include <map> #include <fstream> #include <numeric> #include <iterator> #include "Game/Board.h" #include "Game/Color.h" #include "Utility/Random.h" #include "Utility/String.h" #include "Utility/Exceptions.h" std::map<std::string, double> Gene::list_properties() const noexcept { auto properties = std::map<std::string, double>{{"Priority", scoring_priority}, {"Active", double(active)}}; adjust_properties(properties); return properties; } void Gene::adjust_properties(std::map<std::string, double>&) const noexcept { } void Gene::load_properties(const std::map<std::string, double>& properties) { if(properties.count("Priority") > 0) { scoring_priority = properties.at("Priority"); } if(properties.count("Active") > 0) { active = properties.at("Active") > 0.0; } load_gene_properties(properties); } void Gene::load_gene_properties(const std::map<std::string, double>&) { } size_t Gene::mutatable_components() const noexcept { return list_properties().size(); } void Gene::read_from(std::istream& is) { auto properties = list_properties(); std::map<std::string, bool> property_found; std::transform(properties.begin(), properties.end(), std::inserter(property_found, property_found.begin()), [](const auto& key_value) { return std::make_pair(key_value.first, false); }); std::string line; while(std::getline(is, line)) { if(String::trim_outer_whitespace(line).empty()) { break; } line = String::strip_comments(line, "#"); if(line.empty()) { continue; } auto split_line = String::split(line, ":"); if(split_line.size() != 2) { throw_on_invalid_line(line, "There should be exactly one colon per gene property line."); } auto property_name = String::remove_extra_whitespace(split_line[0]); auto property_data = String::remove_extra_whitespace(split_line[1]); if(property_name == "Name") { if(String::remove_extra_whitespace(property_data) == name()) { continue; } else { throw_on_invalid_line(line, "Reading data for wrong gene. Gene is " + name() + ", data is for " + property_data + "."); } } try { properties.at(property_name) = std::stod(property_data); property_found.at(property_name) = true; } catch(const std::out_of_range&) { throw_on_invalid_line(line, "Unrecognized parameter name."); } catch(const std::invalid_argument&) { throw_on_invalid_line(line, "Bad parameter value."); } } auto missing_data = std::accumulate(property_found.begin(), property_found.end(), std::string{}, [](const auto& so_far, const auto& name_found) { return so_far + ( ! name_found.second ? "\n" + name_found.first : ""); }); if( ! missing_data.empty()) { throw Genetic_AI_Creation_Error("Missing gene data for " + name() + ":" + missing_data); } load_properties(properties); } void Gene::read_from(const std::string& file_name) { auto ifs = std::ifstream(file_name); if( ! ifs) { throw Genetic_AI_Creation_Error("Could not open " + file_name + " to read."); } std::string line; while(std::getline(ifs, line)) { if(String::starts_with(line, "Name: ")) { auto gene_name = String::remove_extra_whitespace(String::split(line, ":", 1)[1]); if(gene_name == name()) { try { read_from(ifs); return; } catch(const std::exception& e) { throw Genetic_AI_Creation_Error("Error in reading data for " + name() + " from " + file_name + "\n" + e.what()); } } } } throw Genetic_AI_Creation_Error(name() + " not found in " + file_name); } void Gene::throw_on_invalid_line(const std::string& line, const std::string& reason) const { throw Genetic_AI_Creation_Error("Invalid line in while reading for " + name() + ": " + line + "\n" + reason); } void Gene::mutate() noexcept { if(is_active()) { if(Random::success_probability(1, 1000)) { active = false; } } else { if(Random::success_probability(1, 100)) { active = true; } } if( ! is_active()) { return; } auto properties = list_properties(); if(Random::success_probability(properties.count("Priority"), properties.size())) { scoring_priority += Random::random_laplace(0.005); } else { gene_specific_mutation(); } } void Gene::gene_specific_mutation() noexcept { } double Gene::evaluate(const Board& board, Piece_Color perspective, size_t depth) const noexcept { if(is_active()) { return scoring_priority*score_board(board, perspective, depth); } else { return 0.0; } } void Gene::print(std::ostream& os) const noexcept { auto properties = list_properties(); os << "Name: " << name() << "\n"; for(const auto& [name, value] : properties) { os << name << ": " << value << "\n"; } os << "\n"; } void Gene::reset_piece_strength_gene(const Piece_Strength_Gene*) noexcept { } double Gene::priority() const noexcept { return scoring_priority; } void Gene::scale_priority(double k) noexcept { scoring_priority *= k; } void Gene::zero_out_priority() noexcept { scoring_priority = 0.0; } bool Gene::is_active() const noexcept { return active; } void Gene::test(bool& test_variable, const Board& board, Piece_Color perspective, double expected_score) const noexcept { auto result = score_board(board, perspective, board.game_length() == 0 ? 0 : 1); if(std::abs(result - expected_score) > 1e-6) { std::cerr << "Error in " << name() << ": Expected " << expected_score << ", Got: " << result << '\n'; test_variable = false; } } <|endoftext|>
<commit_before>/// Copyright (C) 2013 Kojack /// /// 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. /// Modified 05 Auggust 2013 by Ybalrid #include "OgreOculus.h" #include <OVR.h> #include <OgreSceneManager.h> #include <OgreRenderWindow.h> #include <OgreCompositorManager.h> #include <OgreCompositorInstance.h> #include <OgreCompositionTargetPass.h> #include <OgreCompositionPass.h> using namespace OVR; namespace { const float g_defaultNearClip = 0.01f; const float g_defaultFarClip = 10000.0f; const float g_defaultIPD = 0.064f; const Ogre::ColourValue g_defaultViewportColour(97/255.0f, 97/255.0f, 200/255.0f); const float g_defaultProjectionCentreOffset = 0.14529906f; const float g_defaultDistortion[4] = {1.0f, 0.22f, 0.24f, 0}; } Oculus::Oculus(void):m_sensorFusion(0), m_stereoConfig(0), m_hmd(0), m_deviceManager(0), m_oculusReady(false), m_ogreReady(false), m_driftCorrection(false), m_sensor(0), m_centreOffset(g_defaultProjectionCentreOffset), m_window(0), m_sceneManager(0), m_cameraNode(0) { for(int i=0;i<2;++i) { m_cameras[i] = 0; m_viewports[i] = 0; m_compositors[i] = 0; } } Oculus::~Oculus(void) { shutDownOgre(); shutDownOculus(); } void Oculus::shutDownOculus() { m_oculusReady = false; delete m_stereoConfig; m_stereoConfig = 0; delete m_sensorFusion; m_sensorFusion = 0; if(m_sensor) { m_sensor->Release(); } if(m_hmd) { m_hmd->Release(); m_hmd = 0; } if(m_deviceManager) { m_deviceManager->Release(); m_deviceManager = 0; } System::Destroy(); } void Oculus::shutDownOgre() { m_ogreReady = false; for(int i=0;i<2;++i) { if(m_compositors[i]) { Ogre::CompositorManager::getSingleton().removeCompositor(m_viewports[i], "Oculus"); m_compositors[i] = 0; } if(m_viewports[i]) { m_window->removeViewport(i); m_viewports[i] = 0; } if(m_cameras[i]) { m_cameras[i]->getParentSceneNode()->detachObject(m_cameras[i]); m_sceneManager->destroyCamera(m_cameras[i]); m_cameras[i] = 0; } } if(m_cameraNode) { m_cameraNode->getParentSceneNode()->removeChild(m_cameraNode); m_sceneManager->destroySceneNode(m_cameraNode); m_cameraNode = 0; } m_window = 0; m_sceneManager = 0; } bool Oculus::isOculusReady() const { return m_oculusReady; } bool Oculus::isOgreReady() const { return m_ogreReady; } bool Oculus::setupOculus() { if(m_oculusReady) { Ogre::LogManager::getSingleton().logMessage("Oculus: Already Initialised"); return true; } Ogre::LogManager::getSingleton().logMessage("Oculus: Initialising system"); System::Init(Log::ConfigureDefaultLog(LogMask_All)); m_deviceManager = DeviceManager::Create(); if(!m_deviceManager) { Ogre::LogManager::getSingleton().logMessage("Oculus: Failed to create Device Manager"); return false; } Ogre::LogManager::getSingleton().logMessage("Oculus: Created Device Manager"); m_stereoConfig = new Util::Render::StereoConfig(); if(!m_stereoConfig) { Ogre::LogManager::getSingleton().logMessage("Oculus: Failed to create StereoConfig"); return false; } m_centreOffset = m_stereoConfig->GetProjectionCenterOffset(); Ogre::LogManager::getSingleton().logMessage("Oculus: Created StereoConfig"); m_hmd = m_deviceManager->EnumerateDevices<HMDDevice>().CreateDevice(); if(!m_hmd) { Ogre::LogManager::getSingleton().logMessage("Oculus: Failed to create HMD"); return false; } Ogre::LogManager::getSingleton().logMessage("Oculus: Created HMD"); HMDInfo devinfo; m_hmd->GetDeviceInfo(&devinfo); m_stereoConfig->SetHMDInfo(devinfo); m_sensor = m_hmd->GetSensor(); if(!m_sensor) { Ogre::LogManager::getSingleton().logMessage("Oculus: Failed to create sensor"); return false; } Ogre::LogManager::getSingleton().logMessage("Oculus: Created sensor"); m_sensorFusion = new SensorFusion(); if(!m_sensorFusion) { Ogre::LogManager::getSingleton().logMessage("Oculus: Failed to create SensorFusion"); return false; } Ogre::LogManager::getSingleton().logMessage("Oculus: Created SensorFusion"); m_sensorFusion->AttachToSensor(m_sensor); m_oculusReady = true; Ogre::LogManager::getSingleton().logMessage("Oculus: Oculus setup completed successfully"); setReferencePoint(); //for drift correction return true; } bool Oculus::setupOgre(Ogre::SceneManager *sm, Ogre::RenderWindow *win, Ogre::SceneNode *parent) { m_window = win; m_sceneManager = sm; Ogre::LogManager::getSingleton().logMessage("Oculus: Setting up Ogre"); if(parent) m_cameraNode = parent->createChildSceneNode("StereoCameraNode"); else m_cameraNode = sm->getRootSceneNode()->createChildSceneNode("StereoCameraNode"); m_cameras[0] = sm->createCamera("CameraLeft"); m_cameras[1] = sm->createCamera("CameraRight"); Ogre::MaterialPtr matLeft = Ogre::MaterialManager::getSingleton().getByName("Ogre/Compositor/Oculus"); Ogre::MaterialPtr matRight = matLeft->clone("Ogre/Compositor/Oculus/Right"); Ogre::GpuProgramParametersSharedPtr pParamsLeft = matLeft->getTechnique(0)->getPass(0)->getFragmentProgramParameters(); Ogre::GpuProgramParametersSharedPtr pParamsRight = matRight->getTechnique(0)->getPass(0)->getFragmentProgramParameters(); Ogre::Vector4 hmdwarp; if(m_stereoConfig) { hmdwarp = Ogre::Vector4(m_stereoConfig->GetDistortionK(0), m_stereoConfig->GetDistortionK(1), m_stereoConfig->GetDistortionK(2), m_stereoConfig->GetDistortionK(3)); } else { hmdwarp = Ogre::Vector4(g_defaultDistortion[0], g_defaultDistortion[1], g_defaultDistortion[2], g_defaultDistortion[3]); } pParamsLeft->setNamedConstant("HmdWarpParam", hmdwarp); pParamsRight->setNamedConstant("HmdWarpParam", hmdwarp); pParamsLeft->setNamedConstant("LensCentre", 0.5f+(m_stereoConfig->GetProjectionCenterOffset()/2.0f)); pParamsRight->setNamedConstant("LensCentre", 0.5f-(m_stereoConfig->GetProjectionCenterOffset()/2.0f)); Ogre::CompositorPtr comp = Ogre::CompositorManager::getSingleton().getByName("OculusRight"); comp->getTechnique(0)->getOutputTargetPass()->getPass(0)->setMaterialName("Ogre/Compositor/Oculus/Right"); for(int i=0;i<2;++i) { m_cameraNode->attachObject(m_cameras[i]); if(m_stereoConfig) { // Setup cameras. m_cameras[i]->setNearClipDistance(m_stereoConfig->GetEyeToScreenDistance()); m_cameras[i]->setFarClipDistance(g_defaultFarClip); m_cameras[i]->setPosition((i * 2 - 1) * m_stereoConfig->GetIPD() * 0.5f, 0, 0); m_cameras[i]->setAspectRatio(m_stereoConfig->GetAspect()); m_cameras[i]->setFOVy(Ogre::Radian(m_stereoConfig->GetYFOVRadians())); // Oculus requires offset projection, create a custom projection matrix Ogre::Matrix4 proj = Ogre::Matrix4::IDENTITY; float temp = m_stereoConfig->GetProjectionCenterOffset(); proj.setTrans(Ogre::Vector3(-m_stereoConfig->GetProjectionCenterOffset() * (2 * i - 1), 0, 0)); m_cameras[i]->setCustomProjectionMatrix(true, proj * m_cameras[i]->getProjectionMatrix()); } else { m_cameras[i]->setNearClipDistance(g_defaultNearClip); m_cameras[i]->setFarClipDistance(g_defaultFarClip); m_cameras[i]->setPosition((i*2-1) * g_defaultIPD * 0.5f, 0, 0); } m_viewports[i] = win->addViewport(m_cameras[i], i, 0.5f*i, 0, 0.5f, 1.0f); m_viewports[i]->setBackgroundColour(g_defaultViewportColour); m_compositors[i] = Ogre::CompositorManager::getSingleton().addCompositor(m_viewports[i],i==0?"OculusLeft":"OculusRight"); m_compositors[i]->setEnabled(true); } m_ogreReady = true; Ogre::LogManager::getSingleton().logMessage("Oculus: Oculus setup completed successfully"); return true; } void Oculus::update() { if(m_ogreReady) { m_cameraNode->setOrientation(getOrientation()); } } Ogre::SceneNode *Oculus::getCameraNode() { return m_cameraNode; } Ogre::Quaternion Oculus::getOrientation() //const <- I have to call tryCalibration each frame { if(m_oculusReady) { this->tryCalibration(); Quatf q = m_sensorFusion->GetOrientation(); return Ogre::Quaternion(q.w,q.x,q.y,q.z); } else { return Ogre::Quaternion::IDENTITY; } } Ogre::CompositorInstance *Oculus::getCompositor(unsigned int i) { return m_compositors[i]; } float Oculus::getCentreOffset() const { return m_centreOffset; } void Oculus::resetOrientation() { if(m_sensorFusion) m_sensorFusion->Reset(); } void Oculus::setupDriftCorrection(float minMagDist, float minQuatDist) { if(!m_oculusReady) return; //don't do anything if the oculus is not ready. Will cause the program to stuck here m_MagCal.SetMinMagDistance(minMagDist); m_MagCal.SetMinQuatDistance(minQuatDist); m_MagCal.BeginAutoCalibration(*m_sensorFusion); m_driftCorrection = true; } void Oculus::setReferencePoint() { //new oculus SDK dont need that // m_sensorFusion->SetMagReference(); } void Oculus::tryCalibration() { if(!m_driftCorrection) return; //from SDK documentation if (m_MagCal.IsAutoCalibrating()) { m_MagCal.UpdateAutoCalibration(*m_sensorFusion); if (m_MagCal.IsCalibrated()) { Vector3f mc = m_MagCal.GetMagCenter(); printf("Magnetometer Calibration Complete\nCenter: %f %f %f\n",mc.x,mc.y,mc.z); printf("Mag has been successfully calibrated"); } } if(!m_sensorFusion->IsYawCorrectionEnabled()) // if (m_sensorFusion->IsMagReady()) // don't exist anymore m_sensorFusion->SetYawCorrectionEnabled(true); } <commit_msg>Make headtracking works even if HMD not detected<commit_after>/// Copyright (C) 2013 Kojack /// /// 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. /// Modified 05 Auggust 2013 by Ybalrid #include "OgreOculus.h" #include <OVR.h> #include <OgreSceneManager.h> #include <OgreRenderWindow.h> #include <OgreCompositorManager.h> #include <OgreCompositorInstance.h> #include <OgreCompositionTargetPass.h> #include <OgreCompositionPass.h> using namespace OVR; namespace { const float g_defaultNearClip = 0.01f; const float g_defaultFarClip = 10000.0f; const float g_defaultIPD = 0.064f; const Ogre::ColourValue g_defaultViewportColour(97/255.0f, 97/255.0f, 200/255.0f); const float g_defaultProjectionCentreOffset = 0.14529906f; const float g_defaultDistortion[4] = {1.0f, 0.22f, 0.24f, 0}; } Oculus::Oculus(void):m_sensorFusion(0), m_stereoConfig(0), m_hmd(0), m_deviceManager(0), m_oculusReady(false), m_ogreReady(false), m_driftCorrection(false), m_sensor(0), m_centreOffset(g_defaultProjectionCentreOffset), m_window(0), m_sceneManager(0), m_cameraNode(0) { for(int i=0;i<2;++i) { m_cameras[i] = 0; m_viewports[i] = 0; m_compositors[i] = 0; } } Oculus::~Oculus(void) { shutDownOgre(); shutDownOculus(); } void Oculus::shutDownOculus() { m_oculusReady = false; delete m_stereoConfig; m_stereoConfig = 0; delete m_sensorFusion; m_sensorFusion = 0; if(m_sensor) { m_sensor->Release(); } if(m_hmd) { m_hmd->Release(); m_hmd = 0; } if(m_deviceManager) { m_deviceManager->Release(); m_deviceManager = 0; } System::Destroy(); } void Oculus::shutDownOgre() { m_ogreReady = false; for(int i=0;i<2;++i) { if(m_compositors[i]) { Ogre::CompositorManager::getSingleton().removeCompositor(m_viewports[i], "Oculus"); m_compositors[i] = 0; } if(m_viewports[i]) { m_window->removeViewport(i); m_viewports[i] = 0; } if(m_cameras[i]) { m_cameras[i]->getParentSceneNode()->detachObject(m_cameras[i]); m_sceneManager->destroyCamera(m_cameras[i]); m_cameras[i] = 0; } } if(m_cameraNode) { m_cameraNode->getParentSceneNode()->removeChild(m_cameraNode); m_sceneManager->destroySceneNode(m_cameraNode); m_cameraNode = 0; } m_window = 0; m_sceneManager = 0; } bool Oculus::isOculusReady() const { return m_oculusReady; } bool Oculus::isOgreReady() const { return m_ogreReady; } bool Oculus::setupOculus() { if(m_oculusReady) { Ogre::LogManager::getSingleton().logMessage("Oculus: Already Initialised"); return true; } Ogre::LogManager::getSingleton().logMessage("Oculus: Initialising system"); System::Init(Log::ConfigureDefaultLog(LogMask_All)); m_deviceManager = DeviceManager::Create(); if(!m_deviceManager) { Ogre::LogManager::getSingleton().logMessage("Oculus: Failed to create Device Manager"); return false; } Ogre::LogManager::getSingleton().logMessage("Oculus: Created Device Manager"); m_stereoConfig = new Util::Render::StereoConfig(); if(!m_stereoConfig) { Ogre::LogManager::getSingleton().logMessage("Oculus: Failed to create StereoConfig"); return false; } m_centreOffset = m_stereoConfig->GetProjectionCenterOffset(); Ogre::LogManager::getSingleton().logMessage("Oculus: Created StereoConfig"); m_hmd = m_deviceManager->EnumerateDevices<HMDDevice>().CreateDevice(); /*if(!m_hmd) { Ogre::LogManager::getSingleton().logMessage("Oculus: Failed to create HMD"); return false; }*/ Ogre::LogManager::getSingleton().logMessage("Oculus: Created HMD"); HMDInfo devinfo; m_hmd->GetDeviceInfo(&devinfo); m_stereoConfig->SetHMDInfo(devinfo); m_sensor = m_hmd->GetSensor(); if(!m_sensor) { Ogre::LogManager::getSingleton().logMessage("Oculus: Failed to create sensor"); return false; } Ogre::LogManager::getSingleton().logMessage("Oculus: Created sensor"); m_sensorFusion = new SensorFusion(); if(!m_sensorFusion) { Ogre::LogManager::getSingleton().logMessage("Oculus: Failed to create SensorFusion"); return false; } Ogre::LogManager::getSingleton().logMessage("Oculus: Created SensorFusion"); m_sensorFusion->AttachToSensor(m_sensor); m_oculusReady = true; Ogre::LogManager::getSingleton().logMessage("Oculus: Oculus setup completed successfully"); setReferencePoint(); //for drift correction return true; } bool Oculus::setupOgre(Ogre::SceneManager *sm, Ogre::RenderWindow *win, Ogre::SceneNode *parent) { m_window = win; m_sceneManager = sm; Ogre::LogManager::getSingleton().logMessage("Oculus: Setting up Ogre"); if(parent) m_cameraNode = parent->createChildSceneNode("StereoCameraNode"); else m_cameraNode = sm->getRootSceneNode()->createChildSceneNode("StereoCameraNode"); m_cameras[0] = sm->createCamera("CameraLeft"); m_cameras[1] = sm->createCamera("CameraRight"); Ogre::MaterialPtr matLeft = Ogre::MaterialManager::getSingleton().getByName("Ogre/Compositor/Oculus"); Ogre::MaterialPtr matRight = matLeft->clone("Ogre/Compositor/Oculus/Right"); Ogre::GpuProgramParametersSharedPtr pParamsLeft = matLeft->getTechnique(0)->getPass(0)->getFragmentProgramParameters(); Ogre::GpuProgramParametersSharedPtr pParamsRight = matRight->getTechnique(0)->getPass(0)->getFragmentProgramParameters(); Ogre::Vector4 hmdwarp; if(m_stereoConfig) { hmdwarp = Ogre::Vector4(m_stereoConfig->GetDistortionK(0), m_stereoConfig->GetDistortionK(1), m_stereoConfig->GetDistortionK(2), m_stereoConfig->GetDistortionK(3)); } else { hmdwarp = Ogre::Vector4(g_defaultDistortion[0], g_defaultDistortion[1], g_defaultDistortion[2], g_defaultDistortion[3]); } pParamsLeft->setNamedConstant("HmdWarpParam", hmdwarp); pParamsRight->setNamedConstant("HmdWarpParam", hmdwarp); pParamsLeft->setNamedConstant("LensCentre", 0.5f+(m_stereoConfig->GetProjectionCenterOffset()/2.0f)); pParamsRight->setNamedConstant("LensCentre", 0.5f-(m_stereoConfig->GetProjectionCenterOffset()/2.0f)); Ogre::CompositorPtr comp = Ogre::CompositorManager::getSingleton().getByName("OculusRight"); comp->getTechnique(0)->getOutputTargetPass()->getPass(0)->setMaterialName("Ogre/Compositor/Oculus/Right"); for(int i=0;i<2;++i) { m_cameraNode->attachObject(m_cameras[i]); if(m_stereoConfig) { // Setup cameras. m_cameras[i]->setNearClipDistance(m_stereoConfig->GetEyeToScreenDistance()); m_cameras[i]->setFarClipDistance(g_defaultFarClip); m_cameras[i]->setPosition((i * 2 - 1) * m_stereoConfig->GetIPD() * 0.5f, 0, 0); m_cameras[i]->setAspectRatio(m_stereoConfig->GetAspect()); m_cameras[i]->setFOVy(Ogre::Radian(m_stereoConfig->GetYFOVRadians())); // Oculus requires offset projection, create a custom projection matrix Ogre::Matrix4 proj = Ogre::Matrix4::IDENTITY; float temp = m_stereoConfig->GetProjectionCenterOffset(); proj.setTrans(Ogre::Vector3(-m_stereoConfig->GetProjectionCenterOffset() * (2 * i - 1), 0, 0)); m_cameras[i]->setCustomProjectionMatrix(true, proj * m_cameras[i]->getProjectionMatrix()); } else { m_cameras[i]->setNearClipDistance(g_defaultNearClip); m_cameras[i]->setFarClipDistance(g_defaultFarClip); m_cameras[i]->setPosition((i*2-1) * g_defaultIPD * 0.5f, 0, 0); } m_viewports[i] = win->addViewport(m_cameras[i], i, 0.5f*i, 0, 0.5f, 1.0f); m_viewports[i]->setBackgroundColour(g_defaultViewportColour); m_compositors[i] = Ogre::CompositorManager::getSingleton().addCompositor(m_viewports[i],i==0?"OculusLeft":"OculusRight"); m_compositors[i]->setEnabled(true); } m_ogreReady = true; Ogre::LogManager::getSingleton().logMessage("Oculus: Oculus setup completed successfully"); return true; } void Oculus::update() { if(m_ogreReady) { m_cameraNode->setOrientation(getOrientation()); } } Ogre::SceneNode *Oculus::getCameraNode() { return m_cameraNode; } Ogre::Quaternion Oculus::getOrientation() //const <- I have to call tryCalibration each frame { if(m_oculusReady) { this->tryCalibration(); Quatf q = m_sensorFusion->GetOrientation(); return Ogre::Quaternion(q.w,q.x,q.y,q.z); } else { return Ogre::Quaternion::IDENTITY; } } Ogre::CompositorInstance *Oculus::getCompositor(unsigned int i) { return m_compositors[i]; } float Oculus::getCentreOffset() const { return m_centreOffset; } void Oculus::resetOrientation() { if(m_sensorFusion) m_sensorFusion->Reset(); } void Oculus::setupDriftCorrection(float minMagDist, float minQuatDist) { if(!m_oculusReady) return; //don't do anything if the oculus is not ready. Will cause the program to stuck here m_MagCal.SetMinMagDistance(minMagDist); m_MagCal.SetMinQuatDistance(minQuatDist); m_MagCal.BeginAutoCalibration(*m_sensorFusion); m_driftCorrection = true; } void Oculus::setReferencePoint() { //new oculus SDK dont need that // m_sensorFusion->SetMagReference(); } void Oculus::tryCalibration() { if(!m_driftCorrection) return; //from SDK documentation if (m_MagCal.IsAutoCalibrating()) { m_MagCal.UpdateAutoCalibration(*m_sensorFusion); if (m_MagCal.IsCalibrated()) { Vector3f mc = m_MagCal.GetMagCenter(); printf("Magnetometer Calibration Complete\nCenter: %f %f %f\n",mc.x,mc.y,mc.z); printf("Mag has been successfully calibrated"); } } if(!m_sensorFusion->IsYawCorrectionEnabled()) // if (m_sensorFusion->IsMagReady()) // don't exist anymore m_sensorFusion->SetYawCorrectionEnabled(true); } <|endoftext|>
<commit_before>#include "NewsItemWidget.h" #include <QVBoxLayout> #include <QDesktopServices> #include <QUrl> /** * NewsItemWidget constructor * \param p The color palette for the UI * \param URL The URL to the RSS article * \param source The RSS feed the headline came from * \param title The headline to be displayed * \param parent The parent QWidget */ NewsItemWidget::NewsItemWidget(QSettings* p, QString URL, QString source, QString title, QString descriptionString, QWidget* parent) : QWidget(parent) { this->setStyleSheet( "QLabel {" "color: " + p->value("Primary/LightText").toString() + ";" "font-family: SourceSansPro;" "font-size: 16px;" "}"); QVBoxLayout* layout = new QVBoxLayout(this); imageLabel = new QLabel (""); //TODO: Change this to default image layout->addWidget(imageLabel); titleLabel = new QLabel (title); titleLabel->setWordWrap(true); layout->addWidget(titleLabel); descriptionLabel = new QLabel(descriptionString); descriptionLabel->setWordWrap(true); descriptionLabel->setStyleSheet("font-size: 12px"); layout->addWidget(descriptionLabel); sourceLabel = new QLabel (source); sourceLabel->setWordWrap(true); sourceLabel->setStyleSheet("font-size: 10px;"); layout->addWidget(sourceLabel); this->urlString = URL; this->descriptionString = descriptionString; //Load thumbnail manager = new QNetworkAccessManager(this); const QUrl url(this->urlString); QNetworkRequest* req = new QNetworkRequest(url); req->setRawHeader("User-Agent", "Horizon Launcher"); QNetworkReply* reply = manager->get(*req); connect (reply, &QNetworkReply::finished, [=] { if(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt() == 301) { QString newUrl = reply->attribute(QNetworkRequest::RedirectionTargetAttribute).toString(); QNetworkRequest* req = new QNetworkRequest(newUrl); req->setRawHeader("User-Agent", "Horizon Launcher"); QNetworkReply* newReply = manager->get(*req); connect(newReply, &QNetworkReply::finished, [=] { sourceCodeFetchComplete(newReply); }); } else { sourceCodeFetchComplete(reply); } }); } void NewsItemWidget::mousePressEvent(QMouseEvent *) { QDesktopServices::openUrl(QUrl(this->urlString)); } /** * Called when the source HTML is fetched for a webpage. * Retrieves the thumbnail for the page using the OpenGraph image property, if * defined in the source * @param reply The network reply containing the HTML source */ void NewsItemWidget::sourceCodeFetchComplete(QNetworkReply* reply) { QString htmlSource = reply->readAll(); //TODO: Get rid of magic numbers here LEARN REGEX int startIndex = htmlSource.indexOf("og:image") + 19; int endIndex = htmlSource.indexOf("jpg", startIndex); QString imgUrl = htmlSource.mid(startIndex, endIndex - startIndex + 3); const QUrl url(imgUrl); QNetworkRequest* req = new QNetworkRequest(url); req->setRawHeader("User-Agent", "Horizon Launcher"); QNetworkReply* imageReply = manager->get(*req); connect (imageReply, &QNetworkReply::finished, [=] { QByteArray jpegData = imageReply->readAll(); QPixmap pixmap; pixmap.loadFromData(jpegData); imageLabel->setPixmap(pixmap.scaledToWidth(imageLabel->width())); }); } <commit_msg>Get rid of `QPixmap::scaleWidth: Pixmap is a null pixmap` errors<commit_after>#include "NewsItemWidget.h" #include <QVBoxLayout> #include <QDesktopServices> #include <QUrl> /** * NewsItemWidget constructor * \param p The color palette for the UI * \param URL The URL to the RSS article * \param source The RSS feed the headline came from * \param title The headline to be displayed * \param parent The parent QWidget */ NewsItemWidget::NewsItemWidget(QSettings* p, QString URL, QString source, QString title, QString descriptionString, QWidget* parent) : QWidget(parent) { this->setStyleSheet( "QLabel {" "color: " + p->value("Primary/LightText").toString() + ";" "font-family: SourceSansPro;" "font-size: 16px;" "}" ""); QVBoxLayout* layout = new QVBoxLayout(this); imageLabel = new QLabel (""); //TODO: Change this to default image layout->addWidget(imageLabel); titleLabel = new QLabel (title); titleLabel->setWordWrap(true); layout->addWidget(titleLabel); descriptionLabel = new QLabel(descriptionString); descriptionLabel->setWordWrap(true); descriptionLabel->setStyleSheet("font-size: 12px"); layout->addWidget(descriptionLabel); sourceLabel = new QLabel (source); sourceLabel->setWordWrap(true); sourceLabel->setStyleSheet("font-size: 10px;"); layout->addWidget(sourceLabel); this->urlString = URL; this->descriptionString = descriptionString; //Load thumbnail manager = new QNetworkAccessManager(this); const QUrl url(this->urlString); QNetworkRequest* req = new QNetworkRequest(url); req->setRawHeader("User-Agent", "Horizon Launcher"); QNetworkReply* reply = manager->get(*req); connect (reply, &QNetworkReply::finished, [=] { if(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt() == 301) { QString newUrl = reply->attribute(QNetworkRequest::RedirectionTargetAttribute).toString(); QNetworkRequest* req = new QNetworkRequest(newUrl); req->setRawHeader("User-Agent", "Horizon Launcher"); QNetworkReply* newReply = manager->get(*req); connect(newReply, &QNetworkReply::finished, [=] { sourceCodeFetchComplete(newReply); }); } else { sourceCodeFetchComplete(reply); } }); } void NewsItemWidget::mousePressEvent(QMouseEvent *) { QDesktopServices::openUrl(QUrl(this->urlString)); } /** * Called when the source HTML is fetched for a webpage. * Retrieves the thumbnail for the page using the OpenGraph image property, if * defined in the source * @param reply The network reply containing the HTML source */ void NewsItemWidget::sourceCodeFetchComplete(QNetworkReply* reply) { QString htmlSource = reply->readAll(); //TODO: Get rid of magic numbers here LEARN REGEX int startIndex = htmlSource.indexOf("og:image") + 19; int endIndex = htmlSource.indexOf("jpg", startIndex); QString imgUrl = htmlSource.mid(startIndex, endIndex - startIndex + 3); const QUrl url(imgUrl); QNetworkRequest* req = new QNetworkRequest(url); req->setRawHeader("User-Agent", "Horizon Launcher"); QNetworkReply* imageReply = manager->get(*req); connect (imageReply, &QNetworkReply::finished, [=] { QByteArray jpegData = imageReply->readAll(); QPixmap pixmap; pixmap.loadFromData(jpegData); if (!pixmap) { return; } imageLabel->setPixmap(pixmap.scaledToWidth(imageLabel->width())); }); } <|endoftext|>
<commit_before>#include <Python.h> #include "numpy/arrayobject.h" #include "types.h" #include "index_table.h" #include <vector> /*Wraps the flux_extractor into a python module called spectra_priv. Don't call this directly, call the python wrapper.*/ /*Helper function to copy los data into the form expected by the work functions*/ void setup_los_data(los* los_table, PyArrayObject *cofm, PyArrayObject *axis, const int NumLos) { //Initialise los_table from input for(int i=0; i< NumLos; i++){ los_table[i].axis = *(npy_int32 *) PyArray_GETPTR1(axis,i); los_table[i].xx = *(double *) PyArray_GETPTR2(cofm,i,0); los_table[i].yy = *(double *) PyArray_GETPTR2(cofm,i,1); los_table[i].zz = *(double *) PyArray_GETPTR2(cofm,i,2); } } /*Check whether the passed array has type typename. Returns 1 if it doesn't, 0 if it does.*/ int check_type(PyArrayObject * arr, int npy_typename) { return !PyArray_EquivTypes(PyArray_DESCR(arr), PyArray_DescrFromType(npy_typename)); } int check_float(PyArrayObject * arr) { return check_type(arr, NPY_FLOAT); } /*****************************************************************************/ /*Interface for SPH interpolation*/ extern "C" PyObject * Py_SPH_Interpolation(PyObject *self, PyObject *args) { //Things which should be from input int nbins, NumLos, rho_H; long long Npart; double box100; double * rho_H_data=NULL; npy_intp size[2]; //Input variables in np format PyArrayObject *pos, *vel, *mass, *u, *ne, *h, *fractions; PyArrayObject *cofm, *axis; PyArrayObject *rho_H_out=NULL, *rho_out, *temp_out, *vel_out; //For storing output interp species; //Temp variables los *los_table=NULL; struct particle_data P; //Get our input if(!PyArg_ParseTuple(args, "iidO!O!O!O!O!O!O!O!O!",&rho_H, &nbins, &box100, &PyArray_Type, &pos, &PyArray_Type, &vel, &PyArray_Type, &mass, &PyArray_Type, &u, &PyArray_Type, &ne, &PyArray_Type, &fractions, &PyArray_Type, &h, &PyArray_Type, &axis, &PyArray_Type, &cofm) ) { PyErr_SetString(PyExc_AttributeError, "Incorrect arguments: use nbins, box100, pos, vel, mass, u, ne, fractions, h, axis, cofm\n"); return NULL; } //Check that our input has the right types if(check_float(pos) || check_float(vel) || check_float(mass) || check_float(u) || check_float(ne) || check_float(h) || check_float(fractions)){ PyErr_SetString(PyExc_TypeError, "One of the data arrays does not have 32-bit float type\n"); return NULL; } if(check_type(cofm,NPY_DOUBLE)){ PyErr_SetString(PyExc_TypeError, "Sightline positions must have 64-bit float type\n"); return NULL; } if(check_type(axis, NPY_INT32)){ PyErr_SetString(PyExc_TypeError, "Axis must be a 32-bit integer\n"); return NULL; } NumLos = PyArray_DIM(cofm,0); Npart = PyArray_DIM(pos,0); //NOTE if nspecies == 1, fractions must have shape [N,1], rather than [N] /* nspecies = PyArray_DIM(fractions, 1); */ //Malloc stuff los_table=(los *)malloc(NumLos*sizeof(los)); size[0] = NumLos; size[1] = nbins; //Number of metal species /* size[2] = nspecies; */ if(NumLos != PyArray_DIM(axis,0) || 3 != PyArray_DIM(cofm,1)) { PyErr_SetString(PyExc_ValueError, "cofm must have dimensions (np.size(axis),3) \n"); return NULL; } /* Allocate array space. This is (I hope) contiguous. * Note: for an array of shape (a,b), element (i,j) can be accessed as * [i*b+j] */ rho_out = (PyArrayObject *) PyArray_SimpleNew(2, size, NPY_DOUBLE); vel_out = (PyArrayObject *) PyArray_SimpleNew(2, size, NPY_DOUBLE); temp_out = (PyArrayObject *) PyArray_SimpleNew(2, size, NPY_DOUBLE); if ( !rho_out || !vel_out || !temp_out){ PyErr_SetString(PyExc_MemoryError, "Could not allocate memory for output arrays\n"); return NULL; } //Initialise output arrays to 0. PyArray_FILLWBYTE(rho_out, 0); PyArray_FILLWBYTE(vel_out, 0); PyArray_FILLWBYTE(temp_out, 0); if(rho_H){ rho_H_out = (PyArrayObject *) PyArray_SimpleNew(2, size, NPY_DOUBLE); PyArray_FILLWBYTE(rho_H_out, 0); rho_H_data = (double *) PyArray_DATA(rho_H_out); } //Here comes the cheat species.rho = (double *) PyArray_DATA(rho_out); species.temp = (double *) PyArray_DATA(temp_out); species.veloc = (double *) PyArray_DATA(vel_out); //Initialise P from the data in the input numpy arrays. //Note: better be sure they are float32 in the calling function. P.Pos =(float *) PyArray_DATA(PyArray_GETCONTIGUOUS(pos)); P.Vel =(float *) PyArray_DATA(PyArray_GETCONTIGUOUS(vel)); P.Mass =(float *) PyArray_DATA(PyArray_GETCONTIGUOUS(mass)); P.U =(float *) PyArray_DATA(PyArray_GETCONTIGUOUS(u)); P.Ne =(float *) PyArray_DATA(PyArray_GETCONTIGUOUS(ne)); P.h =(float *) PyArray_DATA(PyArray_GETCONTIGUOUS(h)); P.fraction =(float *) PyArray_DATA(PyArray_GETCONTIGUOUS(fractions)); setup_los_data(los_table, cofm, axis, NumLos); //Do the work IndexTable sort_los_table(los_table, NumLos, box100); SPH_Interpolation(rho_H_data,&species, 1, nbins, Npart, NumLos, box100, los_table,sort_los_table, &P); //Build a tuple from the interp struct PyObject * for_return; if(rho_H){ for_return = Py_BuildValue("OOOO",rho_H_out, rho_out, vel_out, temp_out); Py_DECREF(rho_H_out); } else for_return = Py_BuildValue("OOO", rho_out, vel_out, temp_out); //Free free(los_table); //Decrement the refcount Py_DECREF(rho_out); Py_DECREF(vel_out); Py_DECREF(temp_out); return for_return; } /* When handed a list of particles, * return a list of bools with True for those nearby to a sightline*/ extern "C" PyObject * Py_near_lines(PyObject *self, PyObject *args) { int NumLos; long long Npart; double box100; PyArrayObject *cofm, *axis, *pos, *hh, *is_a_line; PyObject *out; los *los_table=NULL; //Vector to store a list of particles near the lines std::vector<int> near_lines; if(!PyArg_ParseTuple(args, "dO!O!O!O!",&box100, &PyArray_Type, &pos, &PyArray_Type, &hh, &PyArray_Type, &axis, &PyArray_Type, &cofm) ) return NULL; NumLos = PyArray_DIM(cofm,0); Npart = PyArray_DIM(pos,0); los_table=(los *)malloc(NumLos*sizeof(los)); if(NumLos != PyArray_DIM(axis,0) || 3 != PyArray_DIM(cofm,1)) { PyErr_SetString(PyExc_ValueError, "cofm must have dimensions (np.size(axis),3) \n"); return NULL; } //Setup los_tables setup_los_data(los_table, cofm, axis, NumLos); IndexTable sort_los_table(los_table, NumLos, box100); //find lists // #pragma omp parallel for for(long long i=0; i < Npart; i++){ float ppos[3]; ppos[0] = *(float *) PyArray_GETPTR2(pos,i,0); ppos[1] = *(float *) PyArray_GETPTR2(pos,i,1); ppos[2] = *(float *) PyArray_GETPTR2(pos,i,2); double h = *(float *) PyArray_GETPTR1(hh,i)*0.5; std::map<int, double> nearby=sort_los_table.get_near_lines(ppos,h); if(nearby.size()>0) near_lines.push_back(i); } free(los_table); //Copy data into python npy_intp size = near_lines.size(); is_a_line = (PyArrayObject *) PyArray_SimpleNew(1, &size, NPY_INT); int i=0; for (std::vector<int>::iterator it = near_lines.begin(); it != near_lines.end() && i < size; ++it, ++i){ *(npy_int *)PyArray_GETPTR1(is_a_line,i) = (*it); } out = Py_BuildValue("O", is_a_line); Py_DECREF(is_a_line); return out; } extern "C" PyObject * Py_Compute_Absorption(PyObject *self, PyObject *args) { PyArrayObject * tau, *rho, *veloc, *temp; int nbins; npy_intp nbins_npy; double *tau_C, *rho_C, *veloc_C, *temp_C; double Hz, h100, box100, atime, lambda_lya, gamma_lya, fosc_lya, mass; if(!PyArg_ParseTuple(args, "O!O!O!idddddddd",&PyArray_Type, &rho, &PyArray_Type, &veloc, &PyArray_Type, &temp,&nbins, &Hz, &h100, &box100, &atime, &lambda_lya, &gamma_lya,&fosc_lya,&mass) ) return NULL; nbins_npy = nbins; tau = (PyArrayObject *) PyArray_SimpleNew(1, &nbins_npy, NPY_DOUBLE); PyArray_FILLWBYTE(tau, 0); tau_C = (double *) PyArray_DATA(tau); rho_C =(double *) PyArray_DATA(PyArray_GETCONTIGUOUS(rho)); veloc_C =(double *) PyArray_DATA(PyArray_GETCONTIGUOUS(veloc)); temp_C =(double *) PyArray_DATA(PyArray_GETCONTIGUOUS(temp)); Compute_Absorption(tau_C, rho_C, veloc_C, temp_C, nbins, Hz, h100, box100, atime, lambda_lya, gamma_lya, fosc_lya, mass); return Py_BuildValue("O",tau); } static PyMethodDef spectrae[] = { {"_SPH_Interpolate", Py_SPH_Interpolation, METH_VARARGS, "Find LOS density by SPH interpolation: " " Arguments: nbins, box100, pos, vel, mass, u, ne, fractions, h, axis, cofm" " "}, {"_near_lines", Py_near_lines,METH_VARARGS, "Give a list of particles and sightlines, " "return a list of booleans for those particles near " "a sightline." " Arguments: box, pos, h, axis, cofm"}, {"_Compute_Absorption", Py_Compute_Absorption, METH_VARARGS, "Compute tau along a sightline. " " Arguments: rho, veloc, temp, nbins, Hz, h100, box100, atime, lambda, gamma, fosc, mass" " "}, {NULL, NULL, 0, NULL}, }; PyMODINIT_FUNC init_spectra_priv(void) { Py_InitModule("_spectra_priv", spectrae); import_array(); } <commit_msg>Re-enable parallel line searching<commit_after>#include <Python.h> #include "numpy/arrayobject.h" #include "types.h" #include "index_table.h" #include <vector> /*Wraps the flux_extractor into a python module called spectra_priv. Don't call this directly, call the python wrapper.*/ /*Helper function to copy los data into the form expected by the work functions*/ void setup_los_data(los* los_table, PyArrayObject *cofm, PyArrayObject *axis, const int NumLos) { //Initialise los_table from input for(int i=0; i< NumLos; i++){ los_table[i].axis = *(npy_int32 *) PyArray_GETPTR1(axis,i); los_table[i].xx = *(double *) PyArray_GETPTR2(cofm,i,0); los_table[i].yy = *(double *) PyArray_GETPTR2(cofm,i,1); los_table[i].zz = *(double *) PyArray_GETPTR2(cofm,i,2); } } /*Check whether the passed array has type typename. Returns 1 if it doesn't, 0 if it does.*/ int check_type(PyArrayObject * arr, int npy_typename) { return !PyArray_EquivTypes(PyArray_DESCR(arr), PyArray_DescrFromType(npy_typename)); } int check_float(PyArrayObject * arr) { return check_type(arr, NPY_FLOAT); } /*****************************************************************************/ /*Interface for SPH interpolation*/ extern "C" PyObject * Py_SPH_Interpolation(PyObject *self, PyObject *args) { //Things which should be from input int nbins, NumLos, rho_H; long long Npart; double box100; double * rho_H_data=NULL; npy_intp size[2]; //Input variables in np format PyArrayObject *pos, *vel, *mass, *u, *ne, *h, *fractions; PyArrayObject *cofm, *axis; PyArrayObject *rho_H_out=NULL, *rho_out, *temp_out, *vel_out; //For storing output interp species; //Temp variables los *los_table=NULL; struct particle_data P; //Get our input if(!PyArg_ParseTuple(args, "iidO!O!O!O!O!O!O!O!O!",&rho_H, &nbins, &box100, &PyArray_Type, &pos, &PyArray_Type, &vel, &PyArray_Type, &mass, &PyArray_Type, &u, &PyArray_Type, &ne, &PyArray_Type, &fractions, &PyArray_Type, &h, &PyArray_Type, &axis, &PyArray_Type, &cofm) ) { PyErr_SetString(PyExc_AttributeError, "Incorrect arguments: use nbins, box100, pos, vel, mass, u, ne, fractions, h, axis, cofm\n"); return NULL; } //Check that our input has the right types if(check_float(pos) || check_float(vel) || check_float(mass) || check_float(u) || check_float(ne) || check_float(h) || check_float(fractions)){ PyErr_SetString(PyExc_TypeError, "One of the data arrays does not have 32-bit float type\n"); return NULL; } if(check_type(cofm,NPY_DOUBLE)){ PyErr_SetString(PyExc_TypeError, "Sightline positions must have 64-bit float type\n"); return NULL; } if(check_type(axis, NPY_INT32)){ PyErr_SetString(PyExc_TypeError, "Axis must be a 32-bit integer\n"); return NULL; } NumLos = PyArray_DIM(cofm,0); Npart = PyArray_DIM(pos,0); //NOTE if nspecies == 1, fractions must have shape [N,1], rather than [N] /* nspecies = PyArray_DIM(fractions, 1); */ //Malloc stuff los_table=(los *)malloc(NumLos*sizeof(los)); size[0] = NumLos; size[1] = nbins; //Number of metal species /* size[2] = nspecies; */ if(NumLos != PyArray_DIM(axis,0) || 3 != PyArray_DIM(cofm,1)) { PyErr_SetString(PyExc_ValueError, "cofm must have dimensions (np.size(axis),3) \n"); return NULL; } /* Allocate array space. This is (I hope) contiguous. * Note: for an array of shape (a,b), element (i,j) can be accessed as * [i*b+j] */ rho_out = (PyArrayObject *) PyArray_SimpleNew(2, size, NPY_DOUBLE); vel_out = (PyArrayObject *) PyArray_SimpleNew(2, size, NPY_DOUBLE); temp_out = (PyArrayObject *) PyArray_SimpleNew(2, size, NPY_DOUBLE); if ( !rho_out || !vel_out || !temp_out){ PyErr_SetString(PyExc_MemoryError, "Could not allocate memory for output arrays\n"); return NULL; } //Initialise output arrays to 0. PyArray_FILLWBYTE(rho_out, 0); PyArray_FILLWBYTE(vel_out, 0); PyArray_FILLWBYTE(temp_out, 0); if(rho_H){ rho_H_out = (PyArrayObject *) PyArray_SimpleNew(2, size, NPY_DOUBLE); PyArray_FILLWBYTE(rho_H_out, 0); rho_H_data = (double *) PyArray_DATA(rho_H_out); } //Here comes the cheat species.rho = (double *) PyArray_DATA(rho_out); species.temp = (double *) PyArray_DATA(temp_out); species.veloc = (double *) PyArray_DATA(vel_out); //Initialise P from the data in the input numpy arrays. //Note: better be sure they are float32 in the calling function. P.Pos =(float *) PyArray_DATA(PyArray_GETCONTIGUOUS(pos)); P.Vel =(float *) PyArray_DATA(PyArray_GETCONTIGUOUS(vel)); P.Mass =(float *) PyArray_DATA(PyArray_GETCONTIGUOUS(mass)); P.U =(float *) PyArray_DATA(PyArray_GETCONTIGUOUS(u)); P.Ne =(float *) PyArray_DATA(PyArray_GETCONTIGUOUS(ne)); P.h =(float *) PyArray_DATA(PyArray_GETCONTIGUOUS(h)); P.fraction =(float *) PyArray_DATA(PyArray_GETCONTIGUOUS(fractions)); setup_los_data(los_table, cofm, axis, NumLos); //Do the work IndexTable sort_los_table(los_table, NumLos, box100); SPH_Interpolation(rho_H_data,&species, 1, nbins, Npart, NumLos, box100, los_table,sort_los_table, &P); //Build a tuple from the interp struct PyObject * for_return; if(rho_H){ for_return = Py_BuildValue("OOOO",rho_H_out, rho_out, vel_out, temp_out); Py_DECREF(rho_H_out); } else for_return = Py_BuildValue("OOO", rho_out, vel_out, temp_out); //Free free(los_table); //Decrement the refcount Py_DECREF(rho_out); Py_DECREF(vel_out); Py_DECREF(temp_out); return for_return; } /* When handed a list of particles, * return a list of bools with True for those nearby to a sightline*/ extern "C" PyObject * Py_near_lines(PyObject *self, PyObject *args) { int NumLos; long long Npart; double box100; PyArrayObject *cofm, *axis, *pos, *hh, *is_a_line; PyObject *out; los *los_table=NULL; //Vector to store a list of particles near the lines std::vector<int> near_lines; if(!PyArg_ParseTuple(args, "dO!O!O!O!",&box100, &PyArray_Type, &pos, &PyArray_Type, &hh, &PyArray_Type, &axis, &PyArray_Type, &cofm) ) return NULL; NumLos = PyArray_DIM(cofm,0); Npart = PyArray_DIM(pos,0); los_table=(los *)malloc(NumLos*sizeof(los)); if(NumLos != PyArray_DIM(axis,0) || 3 != PyArray_DIM(cofm,1)) { PyErr_SetString(PyExc_ValueError, "cofm must have dimensions (np.size(axis),3) \n"); return NULL; } //Setup los_tables setup_los_data(los_table, cofm, axis, NumLos); IndexTable sort_los_table(los_table, NumLos, box100); //find lists #pragma omp parallel for for(long long i=0; i < Npart; i++){ float ppos[3]; ppos[0] = *(float *) PyArray_GETPTR2(pos,i,0); ppos[1] = *(float *) PyArray_GETPTR2(pos,i,1); ppos[2] = *(float *) PyArray_GETPTR2(pos,i,2); double h = *(float *) PyArray_GETPTR1(hh,i)*0.5; std::map<int, double> nearby=sort_los_table.get_near_lines(ppos,h); if(nearby.size()>0){ #pragma omp critical { near_lines.push_back(i); } } } free(los_table); //Copy data into python npy_intp size = near_lines.size(); is_a_line = (PyArrayObject *) PyArray_SimpleNew(1, &size, NPY_INT); int i=0; for (std::vector<int>::iterator it = near_lines.begin(); it != near_lines.end() && i < size; ++it, ++i){ *(npy_int *)PyArray_GETPTR1(is_a_line,i) = (*it); } out = Py_BuildValue("O", is_a_line); Py_DECREF(is_a_line); return out; } extern "C" PyObject * Py_Compute_Absorption(PyObject *self, PyObject *args) { PyArrayObject * tau, *rho, *veloc, *temp; int nbins; npy_intp nbins_npy; double *tau_C, *rho_C, *veloc_C, *temp_C; double Hz, h100, box100, atime, lambda_lya, gamma_lya, fosc_lya, mass; if(!PyArg_ParseTuple(args, "O!O!O!idddddddd",&PyArray_Type, &rho, &PyArray_Type, &veloc, &PyArray_Type, &temp,&nbins, &Hz, &h100, &box100, &atime, &lambda_lya, &gamma_lya,&fosc_lya,&mass) ) return NULL; nbins_npy = nbins; tau = (PyArrayObject *) PyArray_SimpleNew(1, &nbins_npy, NPY_DOUBLE); PyArray_FILLWBYTE(tau, 0); tau_C = (double *) PyArray_DATA(tau); rho_C =(double *) PyArray_DATA(PyArray_GETCONTIGUOUS(rho)); veloc_C =(double *) PyArray_DATA(PyArray_GETCONTIGUOUS(veloc)); temp_C =(double *) PyArray_DATA(PyArray_GETCONTIGUOUS(temp)); Compute_Absorption(tau_C, rho_C, veloc_C, temp_C, nbins, Hz, h100, box100, atime, lambda_lya, gamma_lya, fosc_lya, mass); return Py_BuildValue("O",tau); } static PyMethodDef spectrae[] = { {"_SPH_Interpolate", Py_SPH_Interpolation, METH_VARARGS, "Find LOS density by SPH interpolation: " " Arguments: nbins, box100, pos, vel, mass, u, ne, fractions, h, axis, cofm" " "}, {"_near_lines", Py_near_lines,METH_VARARGS, "Give a list of particles and sightlines, " "return a list of booleans for those particles near " "a sightline." " Arguments: box, pos, h, axis, cofm"}, {"_Compute_Absorption", Py_Compute_Absorption, METH_VARARGS, "Compute tau along a sightline. " " Arguments: rho, veloc, temp, nbins, Hz, h100, box100, atime, lambda, gamma, fosc, mass" " "}, {NULL, NULL, 0, NULL}, }; PyMODINIT_FUNC init_spectra_priv(void) { Py_InitModule("_spectra_priv", spectrae); import_array(); } <|endoftext|>
<commit_before>#include "GameEntity.h" GameEntity::GameEntity() { position = VecF3(0.0f, 0.0f, 0.0f); rotation = VecF3(0.0f, 0.0f, 0.0f); scale = VecF3(1.0f, 1.0f, 1.0f); graphicsContainer = NULL; initMatrices(); } GameEntity::GameEntity( VecF3 position, VecF3 rotation, VecF3 scale, vector<Component*> components, GraphicsContainer* graphicsContainer) { this->position = position; this->rotation = rotation; this->scale = scale; this->components = components; this->graphicsContainer = graphicsContainer; initMatrices(); } GameEntity::~GameEntity() { for(unsigned int i=0; i<components.size(); i++) delete components[i]; delete graphicsContainer; } void GameEntity::rebuildTranslationMatrix() { translationMatrix.translation(position.x, position.y, position.z); } void GameEntity::rebuildRotationMatrix() { rotationMatrix.rotation(rotation.x, rotation.y, rotation.z); } void GameEntity::rebuildScalingMatrix() { scalingMatrix.scaling(scale.x, scale.y, scale.z); } void GameEntity::rebuildWorldMatrix() { worldMatrix = scalingMatrix * rotationMatrix * translationMatrix; } void GameEntity::initMatrices() { rebuildTranslationMatrix(); rebuildRotationMatrix(); rebuildScalingMatrix(); rebuildWorldMatrix(); } void GameEntity::setPosition(VecF3 position) { this->position = position; rebuildTranslationMatrix(); rebuildWorldMatrix(); } void GameEntity::setRotation(VecF3 rotation) { this->rotation = rotation; rebuildRotationMatrix(); rebuildWorldMatrix(); } void GameEntity::setScale(VecF3 scale) { this->scale = scale; rebuildScalingMatrix(); rebuildWorldMatrix(); } VecF3 GameEntity::getPosition() { return position; } VecF3 GameEntity::getRotation() { return rotation; } VecF3 GameEntity::getScale() { return scale; } void GameEntity::setTranslationMatrix(MatF4 translationMatrix) { this->translationMatrix = translationMatrix; rebuildWorldMatrix(); } void GameEntity::setRotationMatrix(MatF4 rotationMatrix) { this->rotationMatrix = rotationMatrix; rebuildWorldMatrix(); } void GameEntity::setScalingMatrix(MatF4 scalingMatrix) { this->scalingMatrix = scalingMatrix; rebuildWorldMatrix(); } MatF4 GameEntity::getTranslationMatrix() { return translationMatrix; } MatF4 GameEntity::getRotationMatrix() { return rotationMatrix; } MatF4 GameEntity::getScalingMatrix() { return scalingMatrix; } void GameEntity::update(double delta) { for(unsigned int i=0; i<components.size(); i++) components[i]->update(delta); }<commit_msg>GameEntity has a setGraphicsContainer method and can send Render messages<commit_after>#include "GameEntity.h" GameEntity::GameEntity() { position = VecF3(0.0f, 0.0f, 0.0f); rotation = VecF3(0.0f, 0.0f, 0.0f); scale = VecF3(1.0f, 1.0f, 1.0f); graphicsContainer = NULL; initMatrices(); } GameEntity::GameEntity( VecF3 position, VecF3 rotation, VecF3 scale) { this->position = position; this->rotation = rotation; this->scale = scale; this->components = components; this->graphicsContainer = graphicsContainer; initMatrices(); } GameEntity::~GameEntity() { for(unsigned int i=0; i<components.size(); i++) delete components[i]; delete graphicsContainer; } void GameEntity::rebuildTranslationMatrix() { translationMatrix.translation(position.x, position.y, position.z); } void GameEntity::rebuildRotationMatrix() { rotationMatrix.rotation(rotation.x, rotation.y, rotation.z); } void GameEntity::rebuildScalingMatrix() { scalingMatrix.scaling(scale.x, scale.y, scale.z); } void GameEntity::rebuildWorldMatrix() { worldMatrix = scalingMatrix * rotationMatrix * translationMatrix; } void GameEntity::initMatrices() { rebuildTranslationMatrix(); rebuildRotationMatrix(); rebuildScalingMatrix(); rebuildWorldMatrix(); } void GameEntity::setPosition(VecF3 position) { this->position = position; rebuildTranslationMatrix(); rebuildWorldMatrix(); } void GameEntity::setRotation(VecF3 rotation) { this->rotation = rotation; rebuildRotationMatrix(); rebuildWorldMatrix(); } void GameEntity::setScale(VecF3 scale) { this->scale = scale; rebuildScalingMatrix(); rebuildWorldMatrix(); } VecF3 GameEntity::getPosition() { return position; } VecF3 GameEntity::getRotation() { return rotation; } VecF3 GameEntity::getScale() { return scale; } void GameEntity::setTranslationMatrix(MatF4 translationMatrix) { this->translationMatrix = translationMatrix; rebuildWorldMatrix(); } void GameEntity::setRotationMatrix(MatF4 rotationMatrix) { this->rotationMatrix = rotationMatrix; rebuildWorldMatrix(); } void GameEntity::setScalingMatrix(MatF4 scalingMatrix) { this->scalingMatrix = scalingMatrix; rebuildWorldMatrix(); } MatF4 GameEntity::getTranslationMatrix() { return translationMatrix; } MatF4 GameEntity::getRotationMatrix() { return rotationMatrix; } MatF4 GameEntity::getScalingMatrix() { return scalingMatrix; } void GameEntity::setGraphicsContainer(GraphicsContainer* graphicsContainer) { this->graphicsContainer = graphicsContainer; } void GameEntity::update(double delta) { for(unsigned int i=0; i<components.size(); i++) components[i]->update(delta); }<|endoftext|>
<commit_before>/* This file is part of cpp-ethereum. cpp-ethereum is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. cpp-ethereum 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 cpp-ethereum. If not, see <http://www.gnu.org/licenses/>. */ /** @file main.cpp * @author Gav Wood <i@gavwood.com> * @date 2014 * RLP tool. */ #include <fstream> #include <iostream> #include <boost/algorithm/string.hpp> #include <libdevcore/CommonIO.h> #include <libdevcore/RLP.h> #include <libdevcrypto/SHA3.h> using namespace std; using namespace dev; void help() { cout << "Usage rlp [OPTIONS] [ <file> | -- ]" << endl << "Options:" << endl << " -r,--render Render the given RLP. Options:" << endl << " --indent <string> Use string as the level indentation (default ' ')." << endl << " --hex-ints Render integers in hex." << endl << " --force-string Force all data to be rendered as C-style strings." << endl << " --force-escape When rendering as C-style strings, force all characters to be escaped." << endl << " --force-hex Force all data to be rendered as raw hex." << endl << " -l,--list-archive List the items in the RLP list by hash and size." << endl << " -e,--extract-archive Extract all items in the RLP list, named by hash." << endl << "General options:" << endl << " -L,--lenience Try not to bomb out early if possible." << endl << " -x,--hex,--base-16 Treat input RLP as hex encoded data." << endl << " --64,--base-64 Treat input RLP as base-64 encoded data." << endl << " -b,--bin,--base-256 Treat input RLP as raw binary data." << endl << " -h,--help Print this help message and exit." << endl << " -V,--version Show the version and exit." << endl ; exit(0); } void version() { cout << "rlp version " << dev::Version << endl; exit(0); } enum class Mode { ListArchive, ExtractArchive, Render, }; enum class Encoding { Auto, Hex, Base64, Binary, }; bool isAscii(string const& _s) { for (char c: _s) if (c < 32) return false; return true; } class RLPStreamer { public: struct Prefs { string indent = " "; bool hexInts = false; bool forceString = false; bool escapeAll = false; bool forceHex = false; }; RLPStreamer(ostream& _out, Prefs _p): m_out(_out), m_prefs(_p) {} void output(RLP const& _d, unsigned _level = 0) { if (_d.isNull()) m_out << "null"; else if (_d.isInt()) if (m_prefs.hexInts) m_out << toHex(toCompactBigEndian(_d.toInt<bigint>(RLP::LaisezFaire), 1), 1); else m_out << _d.toInt<bigint>(RLP::LaisezFaire); else if (_d.isData()) if (m_prefs.forceString || (!m_prefs.forceHex && isAscii(_d.toString()))) m_out << escaped(_d.toString(), m_prefs.escapeAll); else m_out << toHex(_d.data()); else if (_d.isList()) { m_out << "["; string newline = "\n"; for (unsigned i = 0; i < _level + 1; ++i) newline += m_prefs.indent; int j = 0; for (auto i: _d) { m_out << (j++ ? (m_prefs.indent.empty() ? ", " : ("," + newline)) : (m_prefs.indent.empty() ? " " : newline)); output(i, _level + 1); } newline = newline.substr(0, newline.size() - m_prefs.indent.size()); m_out << (m_prefs.indent.empty() ? (j ? " ]" : "]") : (j ? newline + "]" : "]")); } } private: std::ostream& m_out; Prefs m_prefs; }; int main(int argc, char** argv) { Encoding encoding = Encoding::Auto; Mode mode = Mode::Render; string inputFile = "--"; bool lenience = false; RLPStreamer::Prefs prefs; for (int i = 1; i < argc; ++i) { string arg = argv[i]; if (arg == "-h" || arg == "--help") help(); else if (arg == "-r" || arg == "--render") mode = Mode::Render; else if ((arg == "-i" || arg == "--indent") && argc > i) prefs.indent = argv[++i]; else if (arg == "--hex-ints") prefs.hexInts = true; else if (arg == "--force-string") prefs.forceString = true; else if (arg == "--force-hex") prefs.forceHex = true; else if (arg == "--force-escape") prefs.escapeAll = true; else if (arg == "-l" || arg == "--list-archive") mode = Mode::ListArchive; else if (arg == "-e" || arg == "--extract-archive") mode = Mode::ExtractArchive; else if (arg == "-L" || arg == "--lenience") lenience = true; else if (arg == "-V" || arg == "--version") version(); else if (arg == "-x" || arg == "--hex" || arg == "--base-16") encoding = Encoding::Hex; else if (arg == "--64" || arg == "--base-64") encoding = Encoding::Base64; else if (arg == "-b" || arg == "--bin" || arg == "--base-256") encoding = Encoding::Binary; else inputFile = arg; } bytes in; if (inputFile == "--") for (int i = cin.get(); i != -1; i = cin.get()) in.push_back((byte)i); else in = contents(inputFile); if (encoding == Encoding::Auto) { encoding = Encoding::Hex; for (char b: in) if (b != '\n' && b != ' ' && b != '\t') { if (encoding == Encoding::Hex && (b < '0' || b > '9' ) && (b < 'a' || b > 'f' ) && (b < 'A' || b > 'F' )) { cerr << "'" << b << "':" << (int)b << endl; encoding = Encoding::Base64; } if (encoding == Encoding::Base64 && (b < '0' || b > '9' ) && (b < 'a' || b > 'z' ) && (b < 'A' || b > 'Z' ) && b != '+' && b != '/') { encoding = Encoding::Binary; break; } } } bytes b; switch (encoding) { case Encoding::Hex: { string s = asString(in); boost::algorithm::replace_all(s, " ", ""); boost::algorithm::replace_all(s, "\n", ""); boost::algorithm::replace_all(s, "\t", ""); b = fromHex(s); break; } case Encoding::Base64: { string s = asString(in); boost::algorithm::replace_all(s, " ", ""); boost::algorithm::replace_all(s, "\n", ""); boost::algorithm::replace_all(s, "\t", ""); b = fromBase64(s); break; } default: swap(b, in); break; } try { RLP rlp(b); switch (mode) { case Mode::ListArchive: { if (!rlp.isList()) { cout << "Error: Invalid format; RLP data is not a list." << endl; exit(1); } cout << rlp.itemCount() << " items:" << endl; for (auto i: rlp) { if (!i.isData()) { cout << "Error: Invalid format; RLP list item is not data." << endl; if (!lenience) exit(1); } cout << " " << i.size() << " bytes: " << sha3(i.data()) << endl; } break; } case Mode::ExtractArchive: { if (!rlp.isList()) { cout << "Error: Invalid format; RLP data is not a list." << endl; exit(1); } cout << rlp.itemCount() << " items:" << endl; for (auto i: rlp) { if (!i.isData()) { cout << "Error: Invalid format; RLP list item is not data." << endl; if (!lenience) exit(1); } ofstream fout; fout.open(toString(sha3(i.data()))); fout.write(reinterpret_cast<char const*>(i.data().data()), i.data().size()); } break; } case Mode::Render: { RLPStreamer s(cout, prefs); s.output(rlp); cout << endl; break; } default:; } } catch (...) { cerr << "Error: Invalid format; bad RLP." << endl; exit(1); } return 0; } <commit_msg>Make RLP JSON compatible by default.<commit_after>/* This file is part of cpp-ethereum. cpp-ethereum is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. cpp-ethereum 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 cpp-ethereum. If not, see <http://www.gnu.org/licenses/>. */ /** @file main.cpp * @author Gav Wood <i@gavwood.com> * @date 2014 * RLP tool. */ #include <fstream> #include <iostream> #include <boost/algorithm/string.hpp> #include <libdevcore/CommonIO.h> #include <libdevcore/RLP.h> #include <libdevcrypto/SHA3.h> using namespace std; using namespace dev; void help() { cout << "Usage rlp [OPTIONS] [ <file> | -- ]" << endl << "Options:" << endl << " -r,--render Render the given RLP. Options:" << endl << " --indent <string> Use string as the level indentation (default ' ')." << endl << " --hex-ints Render integers in hex." << endl << " --ascii-strings Render data as C-style strings or hex depending on content being ASCII." << endl << " --force-string Force all data to be rendered as C-style strings." << endl << " --force-escape When rendering as C-style strings, force all characters to be escaped." << endl << " --force-hex Force all data to be rendered as raw hex." << endl << " -l,--list-archive List the items in the RLP list by hash and size." << endl << " -e,--extract-archive Extract all items in the RLP list, named by hash." << endl << "General options:" << endl << " -L,--lenience Try not to bomb out early if possible." << endl << " -x,--hex,--base-16 Treat input RLP as hex encoded data." << endl << " --64,--base-64 Treat input RLP as base-64 encoded data." << endl << " -b,--bin,--base-256 Treat input RLP as raw binary data." << endl << " -h,--help Print this help message and exit." << endl << " -V,--version Show the version and exit." << endl ; exit(0); } void version() { cout << "rlp version " << dev::Version << endl; exit(0); } enum class Mode { ListArchive, ExtractArchive, Render, }; enum class Encoding { Auto, Hex, Base64, Binary, }; bool isAscii(string const& _s) { for (char c: _s) if (c < 32) return false; return true; } class RLPStreamer { public: struct Prefs { string indent = " "; bool hexInts = false; bool forceString = true; bool escapeAll = false; bool forceHex = false; }; RLPStreamer(ostream& _out, Prefs _p): m_out(_out), m_prefs(_p) {} void output(RLP const& _d, unsigned _level = 0) { if (_d.isNull()) m_out << "null"; else if (_d.isInt()) if (m_prefs.hexInts) m_out << toHex(toCompactBigEndian(_d.toInt<bigint>(RLP::LaisezFaire), 1), 1); else m_out << _d.toInt<bigint>(RLP::LaisezFaire); else if (_d.isData()) if (m_prefs.forceString || (!m_prefs.forceHex && isAscii(_d.toString()))) m_out << escaped(_d.toString(), m_prefs.escapeAll); else m_out << toHex(_d.data()); else if (_d.isList()) { m_out << "["; string newline = "\n"; for (unsigned i = 0; i < _level + 1; ++i) newline += m_prefs.indent; int j = 0; for (auto i: _d) { m_out << (j++ ? (m_prefs.indent.empty() ? ", " : ("," + newline)) : (m_prefs.indent.empty() ? " " : newline)); output(i, _level + 1); } newline = newline.substr(0, newline.size() - m_prefs.indent.size()); m_out << (m_prefs.indent.empty() ? (j ? " ]" : "]") : (j ? newline + "]" : "]")); } } private: std::ostream& m_out; Prefs m_prefs; }; int main(int argc, char** argv) { Encoding encoding = Encoding::Auto; Mode mode = Mode::Render; string inputFile = "--"; bool lenience = false; RLPStreamer::Prefs prefs; for (int i = 1; i < argc; ++i) { string arg = argv[i]; if (arg == "-h" || arg == "--help") help(); else if (arg == "-r" || arg == "--render") mode = Mode::Render; else if ((arg == "-i" || arg == "--indent") && argc > i) prefs.indent = argv[++i]; else if (arg == "--hex-ints") prefs.hexInts = true; else if (arg == "--ascii-strings") prefs.forceString = prefs.forceHex = false; else if (arg == "--force-string") prefs.forceString = true; else if (arg == "--force-hex") prefs.forceHex = true; else if (arg == "--force-escape") prefs.escapeAll = true; else if (arg == "-l" || arg == "--list-archive") mode = Mode::ListArchive; else if (arg == "-e" || arg == "--extract-archive") mode = Mode::ExtractArchive; else if (arg == "-L" || arg == "--lenience") lenience = true; else if (arg == "-V" || arg == "--version") version(); else if (arg == "-x" || arg == "--hex" || arg == "--base-16") encoding = Encoding::Hex; else if (arg == "--64" || arg == "--base-64") encoding = Encoding::Base64; else if (arg == "-b" || arg == "--bin" || arg == "--base-256") encoding = Encoding::Binary; else inputFile = arg; } bytes in; if (inputFile == "--") for (int i = cin.get(); i != -1; i = cin.get()) in.push_back((byte)i); else in = contents(inputFile); if (encoding == Encoding::Auto) { encoding = Encoding::Hex; for (char b: in) if (b != '\n' && b != ' ' && b != '\t') { if (encoding == Encoding::Hex && (b < '0' || b > '9' ) && (b < 'a' || b > 'f' ) && (b < 'A' || b > 'F' )) { cerr << "'" << b << "':" << (int)b << endl; encoding = Encoding::Base64; } if (encoding == Encoding::Base64 && (b < '0' || b > '9' ) && (b < 'a' || b > 'z' ) && (b < 'A' || b > 'Z' ) && b != '+' && b != '/') { encoding = Encoding::Binary; break; } } } bytes b; switch (encoding) { case Encoding::Hex: { string s = asString(in); boost::algorithm::replace_all(s, " ", ""); boost::algorithm::replace_all(s, "\n", ""); boost::algorithm::replace_all(s, "\t", ""); b = fromHex(s); break; } case Encoding::Base64: { string s = asString(in); boost::algorithm::replace_all(s, " ", ""); boost::algorithm::replace_all(s, "\n", ""); boost::algorithm::replace_all(s, "\t", ""); b = fromBase64(s); break; } default: swap(b, in); break; } try { RLP rlp(b); switch (mode) { case Mode::ListArchive: { if (!rlp.isList()) { cout << "Error: Invalid format; RLP data is not a list." << endl; exit(1); } cout << rlp.itemCount() << " items:" << endl; for (auto i: rlp) { if (!i.isData()) { cout << "Error: Invalid format; RLP list item is not data." << endl; if (!lenience) exit(1); } cout << " " << i.size() << " bytes: " << sha3(i.data()) << endl; } break; } case Mode::ExtractArchive: { if (!rlp.isList()) { cout << "Error: Invalid format; RLP data is not a list." << endl; exit(1); } cout << rlp.itemCount() << " items:" << endl; for (auto i: rlp) { if (!i.isData()) { cout << "Error: Invalid format; RLP list item is not data." << endl; if (!lenience) exit(1); } ofstream fout; fout.open(toString(sha3(i.data()))); fout.write(reinterpret_cast<char const*>(i.data().data()), i.data().size()); } break; } case Mode::Render: { RLPStreamer s(cout, prefs); s.output(rlp); cout << endl; break; } default:; } } catch (...) { cerr << "Error: Invalid format; bad RLP." << endl; exit(1); } return 0; } <|endoftext|>
<commit_before>// // AppDelegate.cpp // ee_x_test // // Created by Zinge on 5/17/17. // // #include "AppDelegate.hpp" #include "CrashlyticsAgent.hpp" #include "NotificationAgent.hpp" #include <cocos2d.h> #include <ee/Core.hpp> #include <ee/FacebookAds.hpp> #include <ee/Macro.hpp> namespace { const auto DesignResolution = cocos2d::Size(480, 320); } // namespace AppDelegate::AppDelegate() {} AppDelegate::~AppDelegate() {} void AppDelegate::initGLContextAttrs() { #if CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID GLContextAttrs glContextAttrs = {8, 8, 8, 8, 16, 8}; #else // CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID GLContextAttrs glContextAttrs = {8, 8, 8, 8, 24, 8}; #endif // CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID cocos2d::GLView::setGLContextAttrs(glContextAttrs); } bool AppDelegate::applicationDidFinishLaunching() { cocos2d::log(__PRETTY_FUNCTION__); auto director = cocos2d::Director::getInstance(); auto glView = director->getOpenGLView(); if (glView == nullptr) { #if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) || \ (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) || \ (CC_TARGET_PLATFORM == CC_PLATFORM_LINUX) glView = cocos2d::GLViewImpl::createWithRect( "HelloCpp", cocos2d::Rect(0, 0, DesignResolution.width, DesignResolution.height)); #else glView = cocos2d::GLViewImpl::create("HelloCpp"); #endif director->setOpenGLView(glView); } director->setDisplayStats(true); director->setAnimationInterval(1.0f / 60); auto resolutionPolicy = (DesignResolution.height > DesignResolution.width ? ResolutionPolicy::FIXED_WIDTH : ResolutionPolicy::FIXED_HEIGHT); glView->setDesignResolutionSize(DesignResolution.width, DesignResolution.height, resolutionPolicy); auto&& frameSize = glView->getFrameSize(); cocos2d::log("frameSize = %f %f", frameSize.width, frameSize.height); auto&& winSize = director->getWinSize(); cocos2d::log("winSize = %f %f", winSize.width, winSize.height); ee::Metrics::initialize(frameSize.height / winSize.height); constexpr float points = 200; auto metrics = ee::Metrics::fromPoint(points); auto dp = metrics.toDip(); auto pixels = metrics.toPixel(); cocos2d::log("%f pt = %f pixels = %f dp", points, pixels, dp); CrashlyticsAgent::getInstance()->initialize(); CrashlyticsAgent::getInstance()->logDebug("debug_message"); CrashlyticsAgent::getInstance()->logInfo("info_message"); CrashlyticsAgent::getInstance()->logError("error_message"); CrashlyticsAgent::getInstance()->trackLevelStart("level_test"); CrashlyticsAgent::getInstance()->trackLevelEnd("level_test", 100, true); CrashlyticsAgent::getInstance()->trackPurchase( 100.f, "USD", true, "Item Test", "Test Type", "TEST_ID"); CrashlyticsAgent::CustomAttributesType attrs; attrs["title"] = "Beautiful in white"; attrs["singer"] = "Westlife"; CrashlyticsAgent::getInstance()->trackCustomEvent("PlaySong", attrs); CrashlyticsAgent::getInstance()->trackInvite("Twitter"); cocos2d::log("Create FacebookAds plugin"); static auto plugin = ee::FacebookAds(); ee::runOnUiThread([] { cocos2d::log("Create Facebook native ad begin"); static auto native = plugin.createNativeAd( ee::FacebookNativeAdBuilder() .setAdId("869337403086643_1444948412192203") .setLayoutName("fb_native_spin")); // native->setVisible(true); // native->setPosition(400, 100); cocos2d::log("Create Facebook native ad end"); cocos2d::log("Native ad size: %d %d", native->getSize().first, native->getSize().second); cocos2d::log("Native ad position: %d %d", native->getPosition().first, native->getPosition().second); }); cocos2d::log("Create scene"); auto scene = cocos2d::Scene::create(); auto layer = cocos2d::LayerColor::create(cocos2d::Color4B(150, 150, 150, 150)); scene->addChild(layer); director->runWithScene(scene); return true; } void AppDelegate::applicationDidEnterBackground() { cocos2d::log(__PRETTY_FUNCTION__); cocos2d::Director::getInstance()->stopAnimation(); #ifndef EE_X_DESKTOP NotificationAgent::getInstance()->scheduleAll(); #endif // EE_X_DESKTOP } void AppDelegate::applicationWillEnterForeground() { cocos2d::log(__PRETTY_FUNCTION__); cocos2d::Director::getInstance()->startAnimation(); #ifndef EE_X_DESKTOP NotificationAgent::getInstance()->unscheduleAll(); #endif // EE_X_DESKTOP } <commit_msg>Update test.<commit_after>// // AppDelegate.cpp // ee_x_test // // Created by Zinge on 5/17/17. // // #include "AppDelegate.hpp" #include "CrashlyticsAgent.hpp" #include "NotificationAgent.hpp" #include <cocos2d.h> #include <ee/Core.hpp> #include <ee/FacebookAds.hpp> #include <ee/Macro.hpp> namespace { const auto DesignResolution = cocos2d::Size(480, 320); } // namespace namespace { ee::Logger& getLogger() { static ee::Logger logger("ee_x"); return logger; } void scheduleOnce(float delay, const std::function<void()>& f) { static int target; static int counter; auto scheduler = cocos2d::Director::getInstance()->getScheduler(); scheduler->schedule(std::bind(f), &target, 0, 0, delay, false, std::to_string(counter++)); } ee::FacebookAds* facebookAds_; std::shared_ptr<ee::FacebookNativeAd> facebookNativeAd_; } // namespace AppDelegate::AppDelegate() {} AppDelegate::~AppDelegate() {} void AppDelegate::initGLContextAttrs() { #if CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID GLContextAttrs glContextAttrs = {8, 8, 8, 8, 16, 8}; #else // CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID GLContextAttrs glContextAttrs = {8, 8, 8, 8, 24, 8}; #endif // CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID cocos2d::GLView::setGLContextAttrs(glContextAttrs); } bool AppDelegate::applicationDidFinishLaunching() { cocos2d::log(__PRETTY_FUNCTION__); auto director = cocos2d::Director::getInstance(); auto glView = director->getOpenGLView(); if (glView == nullptr) { #if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) || \ (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) || \ (CC_TARGET_PLATFORM == CC_PLATFORM_LINUX) glView = cocos2d::GLViewImpl::createWithRect( "HelloCpp", cocos2d::Rect(0, 0, DesignResolution.width, DesignResolution.height)); #else glView = cocos2d::GLViewImpl::create("HelloCpp"); #endif director->setOpenGLView(glView); } director->setDisplayStats(true); director->setAnimationInterval(1.0f / 60); auto resolutionPolicy = (DesignResolution.height > DesignResolution.width ? ResolutionPolicy::FIXED_WIDTH : ResolutionPolicy::FIXED_HEIGHT); glView->setDesignResolutionSize(DesignResolution.width, DesignResolution.height, resolutionPolicy); auto&& frameSize = glView->getFrameSize(); getLogger().info(cocos2d::StringUtils::format( "frameSize = %f %f", frameSize.width, frameSize.height)); auto&& winSize = director->getWinSize(); getLogger().info(cocos2d::StringUtils::format( "winSize = %f %f", winSize.width, winSize.height)); int screenWidth = static_cast<int>(frameSize.width); int screenHeight = static_cast<int>(frameSize.height); ee::Metrics::initialize(frameSize.height / winSize.height); constexpr float points = 1; auto metrics = ee::Metrics::fromPoint(points); auto dp = metrics.toDip(); auto pixels = metrics.toPixel(); getLogger().info(cocos2d::StringUtils::format("%f pt = %f pixels = %f dp", points, pixels, dp)); CrashlyticsAgent::getInstance()->initialize(); CrashlyticsAgent::getInstance()->logDebug("debug_message"); CrashlyticsAgent::getInstance()->logInfo("info_message"); CrashlyticsAgent::getInstance()->logError("error_message"); CrashlyticsAgent::getInstance()->trackLevelStart("level_test"); CrashlyticsAgent::getInstance()->trackLevelEnd("level_test", 100, true); CrashlyticsAgent::getInstance()->trackPurchase( 100.f, "USD", true, "Item Test", "Test Type", "TEST_ID"); CrashlyticsAgent::CustomAttributesType attrs; attrs["title"] = "Beautiful in white"; attrs["singer"] = "Westlife"; CrashlyticsAgent::getInstance()->trackCustomEvent("PlaySong", attrs); CrashlyticsAgent::getInstance()->trackInvite("Twitter"); float delay = 0.0f; scheduleOnce(delay += 1.0f, [] { getLogger().info("Create FacebookAds plugin"); static auto plugin = ee::FacebookAds(); facebookAds_ = &plugin; }); scheduleOnce(delay += 1.0f, [] { ee::runOnUiThread([] { getLogger().info("Create Facebook native ad"); facebookNativeAd_ = facebookAds_->createNativeAd( ee::FacebookNativeAdBuilder() .setAdId("869337403086643_1444948412192203") .setLayoutName("fb_native_spin") .setIcon("native_ad_icon") .setTitle("native_ad_title") .setMedia("native_ad_media") .setSocialContext("native_ad_social_context") .setAdChoices("ad_choices_container") .setBody("native_ad_body") .setAction("native_ad_call_to_action")); facebookNativeAd_->setVisible(true); }); }); scheduleOnce(delay += 1.0f, [screenWidth, screenHeight] { ee::runOnUiThread([screenWidth, screenHeight] { getLogger().info("Resize = screen size / 4"); facebookNativeAd_->setPosition(3 * screenWidth / 8, 3 * screenHeight / 8); facebookNativeAd_->setSize(screenWidth / 4, screenHeight / 4); }); }); scheduleOnce(delay += 1.0f, [] { ee::runOnUiThread([] { getLogger().info("Move to top-left"); facebookNativeAd_->setPosition(0, 0); }); }); scheduleOnce(delay += 1.0f, [screenWidth] { ee::runOnUiThread([screenWidth] { getLogger().info("Move to top-right"); int width, height; std::tie(width, height) = facebookNativeAd_->getSize(); facebookNativeAd_->setPosition(screenWidth - width, 0); }); }); scheduleOnce(delay += 1.0f, [screenWidth, screenHeight] { ee::runOnUiThread([screenWidth, screenHeight] { getLogger().info("Move to bottom-right"); int width, height; std::tie(width, height) = facebookNativeAd_->getSize(); facebookNativeAd_->setPosition(screenWidth - width, screenHeight - height); }); }); scheduleOnce(delay += 1.0f, [screenHeight] { ee::runOnUiThread([screenHeight] { getLogger().info("Move to bottom-left"); int width, height; std::tie(width, height) = facebookNativeAd_->getSize(); facebookNativeAd_->setPosition(0, screenHeight - height); }); }); scheduleOnce(delay += 1.0f, [screenWidth, screenHeight] { ee::runOnUiThread([screenWidth, screenHeight] { getLogger().info("Move to center"); int width, height; std::tie(width, height) = facebookNativeAd_->getSize(); facebookNativeAd_->setPosition((screenWidth - width) / 2, (screenHeight - height) / 2); }); }); scheduleOnce(delay += 1.0f, [screenWidth, screenHeight] { ee::runOnUiThread([screenWidth, screenHeight] { getLogger().info("Resize = screen size"); facebookNativeAd_->setPosition(0, 0); facebookNativeAd_->setSize(screenWidth, screenHeight); }); }); scheduleOnce(delay += 1.0f, [screenWidth, screenHeight] { ee::runOnUiThread([screenWidth, screenHeight] { getLogger().info("Resize = screen size / 2"); facebookNativeAd_->setPosition(screenWidth / 4, screenHeight / 4); facebookNativeAd_->setSize(screenWidth / 2, screenHeight / 2); }); }); cocos2d::log("Create scene"); auto scene = cocos2d::Scene::create(); auto layer = cocos2d::LayerColor::create(cocos2d::Color4B(150, 150, 150, 150)); scene->addChild(layer); director->runWithScene(scene); return true; } void AppDelegate::applicationDidEnterBackground() { cocos2d::log(__PRETTY_FUNCTION__); cocos2d::Director::getInstance()->stopAnimation(); #ifndef EE_X_DESKTOP NotificationAgent::getInstance()->scheduleAll(); #endif // EE_X_DESKTOP } void AppDelegate::applicationWillEnterForeground() { cocos2d::log(__PRETTY_FUNCTION__); cocos2d::Director::getInstance()->startAnimation(); #ifndef EE_X_DESKTOP NotificationAgent::getInstance()->unscheduleAll(); #endif // EE_X_DESKTOP } <|endoftext|>
<commit_before>#include <Interfaces/PacketSocket.h> #include "HealthEcho.h" #include <poll.h> #include <iostream> int main(int argc, char** argv) { int interface_index = 0; try { nshdev::PacketSocket interface(interface_index); HealthEcho echo; interface.SetConsumer(&echo); int fd = interface.GetWaitFD(); while(1) { struct pollfd fds; fds.fd = fd; fds.events = POLLIN; fds.revents = 0; int ready = poll(&fds, 1, /*timeout ms*/ 1000000 ); if(ready > 0) { interface.Run(); } } } catch(const std::exception& e) { std::cerr << "Caught exception (aborting)" << std::endl << e.what() << std::endl; } return 1; // can only get here by exception } <commit_msg>Comment in main.cpp<commit_after>//! This program uses a PacketSocket interface to answer OAM health checks. //! This example program uses the interfaces directly. //! You wouldn't normally do that after the Demux module is added... #include <Interfaces/PacketSocket.h> #include "HealthEcho.h" #include <poll.h> #include <iostream> int main(int argc, char** argv) { int interface_index = 0; try { nshdev::PacketSocket interface(interface_index); HealthEcho echo; interface.SetConsumer(&echo); int fd = interface.GetWaitFD(); while(1) { struct pollfd fds; fds.fd = fd; fds.events = POLLIN; fds.revents = 0; int ready = poll(&fds, 1, /*timeout ms*/ 1000000 ); if(ready > 0) { interface.Run(); } } } catch(const std::exception& e) { std::cerr << "Caught exception (aborting)" << std::endl << e.what() << std::endl; } return 1; // can only get here by exception } <|endoftext|>
<commit_before><commit_msg>templates dlg: close window and use _default target for template creation<commit_after><|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: prtsetup.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: pl $ $Date: 2001-12-06 17:19:58 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _PAD_PRTSETUP_HXX_ #define _PAD_PRTSETUP_HXX_ #ifndef _LINK_HXX #include <tools/link.hxx> #endif #ifndef _SV_TABDLG_HXX #include <vcl/tabdlg.hxx> #endif #ifndef _SV_TABPAGE_HXX #include <vcl/tabpage.hxx> #endif #ifndef _SV_TABCTRL_HXX #include <vcl/tabctrl.hxx> #endif #ifndef _SV_BUTTON_HXX #include <vcl/button.hxx> #endif #ifndef _SV_FIXED_HXX #include <vcl/fixed.hxx> #endif #ifndef _SV_LSTBOX_HXX #include <vcl/lstbox.hxx> #endif #ifndef _SV_FIELD_HXX #include <vcl/field.hxx> #endif #ifndef _SV_COMBOBOX_HXX #include <vcl/combobox.hxx> #endif #ifndef _PSPPRINT_PPDPARSER_HXX_ #include <psprint/ppdparser.hxx> #endif #ifndef _PSPRINT_PRINTERINFOMANAGER_HXX_ #include <psprint/printerinfomanager.hxx> #endif #ifndef _PAD_HELPER_HXX_ #include <helper.hxx> #endif namespace padmin { class RTSPaperPage; class RTSDevicePage; class RTSOtherPage; class RTSFontSubstPage; class RTSCommandPage; class RTSDialog : public TabDialog { friend class RTSPaperPage; friend class RTSDevicePage; friend class RTSOtherPage; friend class RTSFontSubstPage; friend class RTSCommandPage; ::psp::PrinterInfo m_aJobData; String m_aPrinter; // controls TabControl m_aTabControl; OKButton m_aOKButton; CancelButton m_aCancelButton; // pages RTSPaperPage* m_pPaperPage; RTSDevicePage* m_pDevicePage; RTSOtherPage* m_pOtherPage; RTSFontSubstPage* m_pFontSubstPage; RTSCommandPage* m_pCommandPage; // some resources String m_aInvalidString; String m_aFromDriverString; DECL_LINK( ActivatePage, TabControl* ); DECL_LINK( ClickButton, Button* ); // helper functions void insertAllPPDValues( ListBox&, const ::psp::PPDKey* ); String getPaperSize(); public: RTSDialog( const ::psp::PrinterInfo& rJobData, const String& rPrinter, bool bAllPages, Window* pParent = NULL ); ~RTSDialog(); const ::psp::PrinterInfo& getSetup() const { return m_aJobData; } }; class RTSPaperPage : public TabPage { RTSDialog* m_pParent; FixedText m_aPaperText; ListBox m_aPaperBox; FixedText m_aOrientText; ListBox m_aOrientBox; FixedText m_aDuplexText; ListBox m_aDuplexBox; FixedText m_aSlotText; ListBox m_aSlotBox; FixedText m_aScaleText; MetricField m_aScaleBox; DECL_LINK( SelectHdl, ListBox* ); public: RTSPaperPage( RTSDialog* ); ~RTSPaperPage(); void update(); ULONG getScale() { return m_aScaleBox.GetValue(); } String getOrientation() { return m_aOrientBox.GetSelectEntry(); } }; class RTSDevicePage : public TabPage { RTSDialog* m_pParent; String m_aSpaceColor; String m_aSpaceGray; FixedText m_aPPDKeyText; ListBox m_aPPDKeyBox; FixedText m_aPPDValueText; ListBox m_aPPDValueBox; FixedText m_aLevelText; ListBox m_aLevelBox; FixedText m_aSpaceText; ListBox m_aSpaceBox; FixedText m_aDepthText; ListBox m_aDepthBox; void FillValueBox( const ::psp::PPDKey* ); DECL_LINK( SelectHdl, ListBox* ); public: RTSDevicePage( RTSDialog* ); ~RTSDevicePage(); void update(); ULONG getLevel() { return m_aLevelBox.GetSelectEntry().ToInt32(); } ULONG getDepth() { return m_aDepthBox.GetSelectEntry().ToInt32(); } ULONG getColorDevice() { String aSpace( m_aSpaceBox.GetSelectEntry() ); return aSpace == m_aSpaceColor ? 1 : ( aSpace == m_aSpaceGray ? -1 : 0 ); } }; class RTSOtherPage : public TabPage { RTSDialog* m_pParent; FixedText m_aLeftTxt; MetricField m_aLeftLB; FixedText m_aTopTxt; MetricField m_aTopLB; FixedText m_aRightTxt; MetricField m_aRightLB; FixedText m_aBottomTxt; MetricField m_aBottomLB; FixedText m_aCommentTxt; Edit m_aCommentEdt; PushButton m_aDefaultBtn; void initValues(); DECL_LINK( ClickBtnHdl, Button *); public: RTSOtherPage( RTSDialog* ); ~RTSOtherPage(); void save(); }; class RTSFontSubstPage : public TabPage { RTSDialog* m_pParent; FixedText m_aSubstitutionsText; DelMultiListBox m_aSubstitutionsBox; FixedText m_aFromFontText; ComboBox m_aFromFontBox; FixedText m_aToFontText; ListBox m_aToFontBox; PushButton m_aAddButton; PushButton m_aRemoveButton; CheckBox m_aEnableBox; DECL_LINK( ClickBtnHdl, Button* ); DECL_LINK( SelectHdl, ListBox* ); DECL_LINK( DelPressedHdl, ListBox* ); void update(); public: RTSFontSubstPage( RTSDialog* ); ~RTSFontSubstPage(); }; } // namespace #endif // _PAD_PRTSETUP_HXX <commit_msg>INTEGRATION: CWS ooo19126 (1.2.244); FILE MERGED 2005/09/05 13:16:15 rt 1.2.244.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: prtsetup.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2005-09-08 16:29:00 $ * * 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 _PAD_PRTSETUP_HXX_ #define _PAD_PRTSETUP_HXX_ #ifndef _LINK_HXX #include <tools/link.hxx> #endif #ifndef _SV_TABDLG_HXX #include <vcl/tabdlg.hxx> #endif #ifndef _SV_TABPAGE_HXX #include <vcl/tabpage.hxx> #endif #ifndef _SV_TABCTRL_HXX #include <vcl/tabctrl.hxx> #endif #ifndef _SV_BUTTON_HXX #include <vcl/button.hxx> #endif #ifndef _SV_FIXED_HXX #include <vcl/fixed.hxx> #endif #ifndef _SV_LSTBOX_HXX #include <vcl/lstbox.hxx> #endif #ifndef _SV_FIELD_HXX #include <vcl/field.hxx> #endif #ifndef _SV_COMBOBOX_HXX #include <vcl/combobox.hxx> #endif #ifndef _PSPPRINT_PPDPARSER_HXX_ #include <psprint/ppdparser.hxx> #endif #ifndef _PSPRINT_PRINTERINFOMANAGER_HXX_ #include <psprint/printerinfomanager.hxx> #endif #ifndef _PAD_HELPER_HXX_ #include <helper.hxx> #endif namespace padmin { class RTSPaperPage; class RTSDevicePage; class RTSOtherPage; class RTSFontSubstPage; class RTSCommandPage; class RTSDialog : public TabDialog { friend class RTSPaperPage; friend class RTSDevicePage; friend class RTSOtherPage; friend class RTSFontSubstPage; friend class RTSCommandPage; ::psp::PrinterInfo m_aJobData; String m_aPrinter; // controls TabControl m_aTabControl; OKButton m_aOKButton; CancelButton m_aCancelButton; // pages RTSPaperPage* m_pPaperPage; RTSDevicePage* m_pDevicePage; RTSOtherPage* m_pOtherPage; RTSFontSubstPage* m_pFontSubstPage; RTSCommandPage* m_pCommandPage; // some resources String m_aInvalidString; String m_aFromDriverString; DECL_LINK( ActivatePage, TabControl* ); DECL_LINK( ClickButton, Button* ); // helper functions void insertAllPPDValues( ListBox&, const ::psp::PPDKey* ); String getPaperSize(); public: RTSDialog( const ::psp::PrinterInfo& rJobData, const String& rPrinter, bool bAllPages, Window* pParent = NULL ); ~RTSDialog(); const ::psp::PrinterInfo& getSetup() const { return m_aJobData; } }; class RTSPaperPage : public TabPage { RTSDialog* m_pParent; FixedText m_aPaperText; ListBox m_aPaperBox; FixedText m_aOrientText; ListBox m_aOrientBox; FixedText m_aDuplexText; ListBox m_aDuplexBox; FixedText m_aSlotText; ListBox m_aSlotBox; FixedText m_aScaleText; MetricField m_aScaleBox; DECL_LINK( SelectHdl, ListBox* ); public: RTSPaperPage( RTSDialog* ); ~RTSPaperPage(); void update(); ULONG getScale() { return m_aScaleBox.GetValue(); } String getOrientation() { return m_aOrientBox.GetSelectEntry(); } }; class RTSDevicePage : public TabPage { RTSDialog* m_pParent; String m_aSpaceColor; String m_aSpaceGray; FixedText m_aPPDKeyText; ListBox m_aPPDKeyBox; FixedText m_aPPDValueText; ListBox m_aPPDValueBox; FixedText m_aLevelText; ListBox m_aLevelBox; FixedText m_aSpaceText; ListBox m_aSpaceBox; FixedText m_aDepthText; ListBox m_aDepthBox; void FillValueBox( const ::psp::PPDKey* ); DECL_LINK( SelectHdl, ListBox* ); public: RTSDevicePage( RTSDialog* ); ~RTSDevicePage(); void update(); ULONG getLevel() { return m_aLevelBox.GetSelectEntry().ToInt32(); } ULONG getDepth() { return m_aDepthBox.GetSelectEntry().ToInt32(); } ULONG getColorDevice() { String aSpace( m_aSpaceBox.GetSelectEntry() ); return aSpace == m_aSpaceColor ? 1 : ( aSpace == m_aSpaceGray ? -1 : 0 ); } }; class RTSOtherPage : public TabPage { RTSDialog* m_pParent; FixedText m_aLeftTxt; MetricField m_aLeftLB; FixedText m_aTopTxt; MetricField m_aTopLB; FixedText m_aRightTxt; MetricField m_aRightLB; FixedText m_aBottomTxt; MetricField m_aBottomLB; FixedText m_aCommentTxt; Edit m_aCommentEdt; PushButton m_aDefaultBtn; void initValues(); DECL_LINK( ClickBtnHdl, Button *); public: RTSOtherPage( RTSDialog* ); ~RTSOtherPage(); void save(); }; class RTSFontSubstPage : public TabPage { RTSDialog* m_pParent; FixedText m_aSubstitutionsText; DelMultiListBox m_aSubstitutionsBox; FixedText m_aFromFontText; ComboBox m_aFromFontBox; FixedText m_aToFontText; ListBox m_aToFontBox; PushButton m_aAddButton; PushButton m_aRemoveButton; CheckBox m_aEnableBox; DECL_LINK( ClickBtnHdl, Button* ); DECL_LINK( SelectHdl, ListBox* ); DECL_LINK( DelPressedHdl, ListBox* ); void update(); public: RTSFontSubstPage( RTSDialog* ); ~RTSFontSubstPage(); }; } // namespace #endif // _PAD_PRTSETUP_HXX <|endoftext|>
<commit_before>// Copyright (c) 2008-2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/command_line.h" #include "googleurl/src/gurl.h" #include "media/filters/ffmpeg_audio_decoder.h" #include "media/filters/ffmpeg_demuxer.h" #include "media/filters/ffmpeg_video_decoder.h" #include "media/filters/null_audio_renderer.h" #include "webkit/api/public/WebRect.h" #include "webkit/api/public/WebSize.h" #include "webkit/api/public/WebURL.h" #include "webkit/glue/media/simple_data_source.h" #include "webkit/glue/media/video_renderer_impl.h" #include "webkit/glue/webmediaplayer_impl.h" using WebKit::WebCanvas; using WebKit::WebRect; using WebKit::WebSize; namespace webkit_glue { ///////////////////////////////////////////////////////////////////////////// // Task to be posted on main thread that fire WebMediaPlayer methods. class NotifyWebMediaPlayerTask : public CancelableTask { public: NotifyWebMediaPlayerTask(WebMediaPlayerImpl* media_player, WebMediaPlayerClientMethod method) : media_player_(media_player), method_(method) {} virtual void Run() { if (media_player_) { (media_player_->client()->*(method_))(); media_player_->DidTask(this); } } virtual void Cancel() { media_player_ = NULL; } private: WebMediaPlayerImpl* media_player_; WebMediaPlayerClientMethod method_; DISALLOW_COPY_AND_ASSIGN(NotifyWebMediaPlayerTask); }; ///////////////////////////////////////////////////////////////////////////// // WebMediaPlayerImpl implementation WebMediaPlayerImpl::WebMediaPlayerImpl(WebKit::WebMediaPlayerClient* client, media::FilterFactoryCollection* factory) : network_state_(WebKit::WebMediaPlayer::Empty), ready_state_(WebKit::WebMediaPlayer::HaveNothing), main_loop_(NULL), filter_factory_(factory), video_renderer_(NULL), client_(client), tasks_(kLastTaskIndex) { // Add in the default filter factories. filter_factory_->AddFactory(media::FFmpegDemuxer::CreateFilterFactory()); filter_factory_->AddFactory(media::FFmpegAudioDecoder::CreateFactory()); filter_factory_->AddFactory(media::FFmpegVideoDecoder::CreateFactory()); filter_factory_->AddFactory(media::NullAudioRenderer::CreateFilterFactory()); filter_factory_->AddFactory(VideoRendererImpl::CreateFactory(this)); // TODO(hclam): Provide a valid routing id to simple data source. filter_factory_->AddFactory( SimpleDataSource::CreateFactory(MessageLoop::current(), 0)); DCHECK(client_); // Saves the current message loop. DCHECK(!main_loop_); main_loop_ = MessageLoop::current(); // Also we want to be notified of |main_loop_| destruction. main_loop_->AddDestructionObserver(this); } WebMediaPlayerImpl::~WebMediaPlayerImpl() { pipeline_.Stop(); // Cancel all tasks posted on the |main_loop_|. CancelAllTasks(); // Finally tell the |main_loop_| we don't want to be notified of destruction // event. if (main_loop_) { main_loop_->RemoveDestructionObserver(this); } } void WebMediaPlayerImpl::load(const WebKit::WebURL& url) { DCHECK(main_loop_ && MessageLoop::current() == main_loop_); // Initialize the pipeline pipeline_.Start(filter_factory_.get(), url.spec(), NewCallback(this, &WebMediaPlayerImpl::OnPipelineInitialize)); } void WebMediaPlayerImpl::cancelLoad() { DCHECK(main_loop_ && MessageLoop::current() == main_loop_); // TODO(hclam): Calls to render_view_ to stop resource load } void WebMediaPlayerImpl::play() { DCHECK(main_loop_ && MessageLoop::current() == main_loop_); // TODO(hclam): We should restore the previous playback rate rather than // having it at 1.0. pipeline_.SetPlaybackRate(1.0f); } void WebMediaPlayerImpl::pause() { DCHECK(main_loop_ && MessageLoop::current() == main_loop_); pipeline_.SetPlaybackRate(0.0f); } void WebMediaPlayerImpl::stop() { DCHECK(main_loop_ && MessageLoop::current() == main_loop_); // We can fire Stop() multiple times. pipeline_.Stop(); } void WebMediaPlayerImpl::seek(float seconds) { DCHECK(main_loop_ && MessageLoop::current() == main_loop_); // Try to preserve as much accuracy as possible. float microseconds = seconds * base::Time::kMicrosecondsPerSecond; if (seconds != 0) pipeline_.Seek( base::TimeDelta::FromMicroseconds(static_cast<int64>(microseconds)), NewCallback(this, &WebMediaPlayerImpl::OnPipelineSeek)); } void WebMediaPlayerImpl::setEndTime(float seconds) { DCHECK(main_loop_ && MessageLoop::current() == main_loop_); // TODO(hclam): add method call when it has been implemented. return; } void WebMediaPlayerImpl::setRate(float rate) { DCHECK(main_loop_ && MessageLoop::current() == main_loop_); pipeline_.SetPlaybackRate(rate); } void WebMediaPlayerImpl::setVolume(float volume) { DCHECK(main_loop_ && MessageLoop::current() == main_loop_); pipeline_.SetVolume(volume); } void WebMediaPlayerImpl::setVisible(bool visible) { DCHECK(main_loop_ && MessageLoop::current() == main_loop_); // TODO(hclam): add appropriate method call when pipeline has it implemented. return; } bool WebMediaPlayerImpl::setAutoBuffer(bool autoBuffer) { DCHECK(main_loop_ && MessageLoop::current() == main_loop_); return false; } bool WebMediaPlayerImpl::totalBytesKnown() { DCHECK(main_loop_ && MessageLoop::current() == main_loop_); return pipeline_.GetTotalBytes() != 0; } bool WebMediaPlayerImpl::hasVideo() const { DCHECK(main_loop_ && MessageLoop::current() == main_loop_); size_t width, height; pipeline_.GetVideoSize(&width, &height); return width != 0 && height != 0; } WebKit::WebSize WebMediaPlayerImpl::naturalSize() const { DCHECK(main_loop_ && MessageLoop::current() == main_loop_); size_t width, height; pipeline_.GetVideoSize(&width, &height); return WebKit::WebSize(width, height); } bool WebMediaPlayerImpl::paused() const { DCHECK(main_loop_ && MessageLoop::current() == main_loop_); return pipeline_.GetPlaybackRate() == 0.0f; } bool WebMediaPlayerImpl::seeking() const { DCHECK(main_loop_ && MessageLoop::current() == main_loop_); return tasks_[kTimeChangedTaskIndex] != NULL; } float WebMediaPlayerImpl::duration() const { DCHECK(main_loop_ && MessageLoop::current() == main_loop_); return static_cast<float>(pipeline_.GetDuration().InSecondsF()); } float WebMediaPlayerImpl::currentTime() const { DCHECK(main_loop_ && MessageLoop::current() == main_loop_); return static_cast<float>(pipeline_.GetTime().InSecondsF()); } int WebMediaPlayerImpl::dataRate() const { DCHECK(main_loop_ && MessageLoop::current() == main_loop_); // TODO(hclam): Add this method call if pipeline has it in the interface. return 0; } float WebMediaPlayerImpl::maxTimeBuffered() const { DCHECK(main_loop_ && MessageLoop::current() == main_loop_); return static_cast<float>(pipeline_.GetBufferedTime().InSecondsF()); } float WebMediaPlayerImpl::maxTimeSeekable() const { DCHECK(main_loop_ && MessageLoop::current() == main_loop_); // TODO(scherkus): move this logic down into the pipeline. if (pipeline_.GetTotalBytes() == 0) { return 0.0f; } double total_bytes = static_cast<double>(pipeline_.GetTotalBytes()); double buffered_bytes = static_cast<double>(pipeline_.GetBufferedBytes()); double duration = static_cast<double>(pipeline_.GetDuration().InSecondsF()); return static_cast<float>(duration * (buffered_bytes / total_bytes)); } unsigned long long WebMediaPlayerImpl::bytesLoaded() const { DCHECK(main_loop_ && MessageLoop::current() == main_loop_); return pipeline_.GetBufferedBytes(); } unsigned long long WebMediaPlayerImpl::totalBytes() const { DCHECK(main_loop_ && MessageLoop::current() == main_loop_); return pipeline_.GetTotalBytes(); } void WebMediaPlayerImpl::setSize(const WebSize& size) { DCHECK(main_loop_ && MessageLoop::current() == main_loop_); if (video_renderer_) { // TODO(scherkus): Change API to use SetSize(). video_renderer_->SetRect(gfx::Rect(0, 0, size.width, size.height)); } } void WebMediaPlayerImpl::paint(WebCanvas* canvas, const WebRect& rect) { DCHECK(main_loop_ && MessageLoop::current() == main_loop_); if (video_renderer_) { video_renderer_->Paint(canvas, rect); } } void WebMediaPlayerImpl::WillDestroyCurrentMessageLoop() { pipeline_.Stop(); } void WebMediaPlayerImpl::OnPipelineInitialize(bool successful) { if (successful) { // Since we have initialized the pipeline, say we have everything. // TODO(hclam): change this to report the correct status. ready_state_ = WebKit::WebMediaPlayer::HaveEnoughData; network_state_ = WebKit::WebMediaPlayer::Loaded; } else { // TODO(hclam): should use pipeline_.GetError() to determine the state // properly and reports error using MediaError. ready_state_ = WebKit::WebMediaPlayer::HaveNothing; network_state_ = WebKit::WebMediaPlayer::NetworkError; } PostTask(kNetworkStateTaskIndex, &WebKit::WebMediaPlayerClient::networkStateChanged); PostTask(kReadyStateTaskIndex, &WebKit::WebMediaPlayerClient::readyStateChanged); } void WebMediaPlayerImpl::OnPipelineSeek(bool successful) { PostTask(kTimeChangedTaskIndex, &WebKit::WebMediaPlayerClient::timeChanged); } void WebMediaPlayerImpl::SetVideoRenderer(VideoRendererImpl* video_renderer) { video_renderer_ = video_renderer; } void WebMediaPlayerImpl::DidTask(CancelableTask* task) { AutoLock auto_lock(task_lock_); for (size_t i = 0; i < tasks_.size(); ++i) { if (tasks_[i] == task) { tasks_[i] = NULL; return; } } NOTREACHED(); } void WebMediaPlayerImpl::CancelAllTasks() { AutoLock auto_lock(task_lock_); // Loop through the list of tasks and cancel tasks that are still alive. for (size_t i = 0; i < tasks_.size(); ++i) { if (tasks_[i]) tasks_[i]->Cancel(); } } void WebMediaPlayerImpl::PostTask(int index, WebMediaPlayerClientMethod method) { DCHECK(main_loop_); AutoLock auto_lock(task_lock_); if (!tasks_[index]) { CancelableTask* task = new NotifyWebMediaPlayerTask(this, method); tasks_[index] = task; main_loop_->PostTask(FROM_HERE, task); } } void WebMediaPlayerImpl::PostRepaintTask() { PostTask(kRepaintTaskIndex, &WebKit::WebMediaPlayerClient::repaint); } } // namespace webkit_glue <commit_msg>Report load errors for <video> according to WebKit's <commit_after>// Copyright (c) 2008-2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/command_line.h" #include "googleurl/src/gurl.h" #include "media/filters/ffmpeg_audio_decoder.h" #include "media/filters/ffmpeg_demuxer.h" #include "media/filters/ffmpeg_video_decoder.h" #include "media/filters/null_audio_renderer.h" #include "webkit/api/public/WebRect.h" #include "webkit/api/public/WebSize.h" #include "webkit/api/public/WebURL.h" #include "webkit/glue/media/simple_data_source.h" #include "webkit/glue/media/video_renderer_impl.h" #include "webkit/glue/webmediaplayer_impl.h" using WebKit::WebCanvas; using WebKit::WebRect; using WebKit::WebSize; namespace webkit_glue { ///////////////////////////////////////////////////////////////////////////// // Task to be posted on main thread that fire WebMediaPlayer methods. class NotifyWebMediaPlayerTask : public CancelableTask { public: NotifyWebMediaPlayerTask(WebMediaPlayerImpl* media_player, WebMediaPlayerClientMethod method) : media_player_(media_player), method_(method) {} virtual void Run() { if (media_player_) { (media_player_->client()->*(method_))(); media_player_->DidTask(this); } } virtual void Cancel() { media_player_ = NULL; } private: WebMediaPlayerImpl* media_player_; WebMediaPlayerClientMethod method_; DISALLOW_COPY_AND_ASSIGN(NotifyWebMediaPlayerTask); }; ///////////////////////////////////////////////////////////////////////////// // WebMediaPlayerImpl implementation WebMediaPlayerImpl::WebMediaPlayerImpl(WebKit::WebMediaPlayerClient* client, media::FilterFactoryCollection* factory) : network_state_(WebKit::WebMediaPlayer::Empty), ready_state_(WebKit::WebMediaPlayer::HaveNothing), main_loop_(NULL), filter_factory_(factory), video_renderer_(NULL), client_(client), tasks_(kLastTaskIndex) { // Add in the default filter factories. filter_factory_->AddFactory(media::FFmpegDemuxer::CreateFilterFactory()); filter_factory_->AddFactory(media::FFmpegAudioDecoder::CreateFactory()); filter_factory_->AddFactory(media::FFmpegVideoDecoder::CreateFactory()); filter_factory_->AddFactory(media::NullAudioRenderer::CreateFilterFactory()); filter_factory_->AddFactory(VideoRendererImpl::CreateFactory(this)); // TODO(hclam): Provide a valid routing id to simple data source. filter_factory_->AddFactory( SimpleDataSource::CreateFactory(MessageLoop::current(), 0)); DCHECK(client_); // Saves the current message loop. DCHECK(!main_loop_); main_loop_ = MessageLoop::current(); // Also we want to be notified of |main_loop_| destruction. main_loop_->AddDestructionObserver(this); } WebMediaPlayerImpl::~WebMediaPlayerImpl() { pipeline_.Stop(); // Cancel all tasks posted on the |main_loop_|. CancelAllTasks(); // Finally tell the |main_loop_| we don't want to be notified of destruction // event. if (main_loop_) { main_loop_->RemoveDestructionObserver(this); } } void WebMediaPlayerImpl::load(const WebKit::WebURL& url) { DCHECK(main_loop_ && MessageLoop::current() == main_loop_); // Initialize the pipeline. if (network_state_ != WebKit::WebMediaPlayer::Loading) { network_state_ = WebKit::WebMediaPlayer::Loading; client_->networkStateChanged(); } if (ready_state_ != WebKit::WebMediaPlayer::HaveNothing) { ready_state_ = WebKit::WebMediaPlayer::HaveNothing; client_->readyStateChanged(); } pipeline_.Start(filter_factory_.get(), url.spec(), NewCallback(this, &WebMediaPlayerImpl::OnPipelineInitialize)); } void WebMediaPlayerImpl::cancelLoad() { DCHECK(main_loop_ && MessageLoop::current() == main_loop_); // TODO(hclam): Calls to render_view_ to stop resource load } void WebMediaPlayerImpl::play() { DCHECK(main_loop_ && MessageLoop::current() == main_loop_); // TODO(hclam): We should restore the previous playback rate rather than // having it at 1.0. pipeline_.SetPlaybackRate(1.0f); } void WebMediaPlayerImpl::pause() { DCHECK(main_loop_ && MessageLoop::current() == main_loop_); pipeline_.SetPlaybackRate(0.0f); } void WebMediaPlayerImpl::stop() { DCHECK(main_loop_ && MessageLoop::current() == main_loop_); // We can fire Stop() multiple times. pipeline_.Stop(); } void WebMediaPlayerImpl::seek(float seconds) { DCHECK(main_loop_ && MessageLoop::current() == main_loop_); // Try to preserve as much accuracy as possible. float microseconds = seconds * base::Time::kMicrosecondsPerSecond; if (seconds != 0) pipeline_.Seek( base::TimeDelta::FromMicroseconds(static_cast<int64>(microseconds)), NewCallback(this, &WebMediaPlayerImpl::OnPipelineSeek)); } void WebMediaPlayerImpl::setEndTime(float seconds) { DCHECK(main_loop_ && MessageLoop::current() == main_loop_); // TODO(hclam): add method call when it has been implemented. return; } void WebMediaPlayerImpl::setRate(float rate) { DCHECK(main_loop_ && MessageLoop::current() == main_loop_); pipeline_.SetPlaybackRate(rate); } void WebMediaPlayerImpl::setVolume(float volume) { DCHECK(main_loop_ && MessageLoop::current() == main_loop_); pipeline_.SetVolume(volume); } void WebMediaPlayerImpl::setVisible(bool visible) { DCHECK(main_loop_ && MessageLoop::current() == main_loop_); // TODO(hclam): add appropriate method call when pipeline has it implemented. return; } bool WebMediaPlayerImpl::setAutoBuffer(bool autoBuffer) { DCHECK(main_loop_ && MessageLoop::current() == main_loop_); return false; } bool WebMediaPlayerImpl::totalBytesKnown() { DCHECK(main_loop_ && MessageLoop::current() == main_loop_); return pipeline_.GetTotalBytes() != 0; } bool WebMediaPlayerImpl::hasVideo() const { DCHECK(main_loop_ && MessageLoop::current() == main_loop_); size_t width, height; pipeline_.GetVideoSize(&width, &height); return width != 0 && height != 0; } WebKit::WebSize WebMediaPlayerImpl::naturalSize() const { DCHECK(main_loop_ && MessageLoop::current() == main_loop_); size_t width, height; pipeline_.GetVideoSize(&width, &height); return WebKit::WebSize(width, height); } bool WebMediaPlayerImpl::paused() const { DCHECK(main_loop_ && MessageLoop::current() == main_loop_); return pipeline_.GetPlaybackRate() == 0.0f; } bool WebMediaPlayerImpl::seeking() const { DCHECK(main_loop_ && MessageLoop::current() == main_loop_); return tasks_[kTimeChangedTaskIndex] != NULL; } float WebMediaPlayerImpl::duration() const { DCHECK(main_loop_ && MessageLoop::current() == main_loop_); return static_cast<float>(pipeline_.GetDuration().InSecondsF()); } float WebMediaPlayerImpl::currentTime() const { DCHECK(main_loop_ && MessageLoop::current() == main_loop_); return static_cast<float>(pipeline_.GetTime().InSecondsF()); } int WebMediaPlayerImpl::dataRate() const { DCHECK(main_loop_ && MessageLoop::current() == main_loop_); // TODO(hclam): Add this method call if pipeline has it in the interface. return 0; } float WebMediaPlayerImpl::maxTimeBuffered() const { DCHECK(main_loop_ && MessageLoop::current() == main_loop_); return static_cast<float>(pipeline_.GetBufferedTime().InSecondsF()); } float WebMediaPlayerImpl::maxTimeSeekable() const { DCHECK(main_loop_ && MessageLoop::current() == main_loop_); // TODO(scherkus): move this logic down into the pipeline. if (pipeline_.GetTotalBytes() == 0) { return 0.0f; } double total_bytes = static_cast<double>(pipeline_.GetTotalBytes()); double buffered_bytes = static_cast<double>(pipeline_.GetBufferedBytes()); double duration = static_cast<double>(pipeline_.GetDuration().InSecondsF()); return static_cast<float>(duration * (buffered_bytes / total_bytes)); } unsigned long long WebMediaPlayerImpl::bytesLoaded() const { DCHECK(main_loop_ && MessageLoop::current() == main_loop_); return pipeline_.GetBufferedBytes(); } unsigned long long WebMediaPlayerImpl::totalBytes() const { DCHECK(main_loop_ && MessageLoop::current() == main_loop_); return pipeline_.GetTotalBytes(); } void WebMediaPlayerImpl::setSize(const WebSize& size) { DCHECK(main_loop_ && MessageLoop::current() == main_loop_); if (video_renderer_) { // TODO(scherkus): Change API to use SetSize(). video_renderer_->SetRect(gfx::Rect(0, 0, size.width, size.height)); } } void WebMediaPlayerImpl::paint(WebCanvas* canvas, const WebRect& rect) { DCHECK(main_loop_ && MessageLoop::current() == main_loop_); if (video_renderer_) { video_renderer_->Paint(canvas, rect); } } void WebMediaPlayerImpl::WillDestroyCurrentMessageLoop() { pipeline_.Stop(); } void WebMediaPlayerImpl::OnPipelineInitialize(bool successful) { WebKit::WebMediaPlayer::ReadyState old_ready_state = ready_state_; WebKit::WebMediaPlayer::NetworkState old_network_state = network_state_; if (successful) { // Since we have initialized the pipeline, say we have everything. // TODO(hclam): change this to report the correct status. ready_state_ = WebKit::WebMediaPlayer::HaveEnoughData; network_state_ = WebKit::WebMediaPlayer::Loaded; } else { // TODO(hclam): should use pipeline_.GetError() to determine the state // properly and reports error using MediaError. // WebKit uses FormatError to indicate an error for bogus URL or bad file. // Since we are at the initialization stage we can safely treat every error // as format error. network_state_ = WebKit::WebMediaPlayer::FormatError; } if (network_state_ != old_network_state) { PostTask(kNetworkStateTaskIndex, &WebKit::WebMediaPlayerClient::networkStateChanged); } if (ready_state_ != old_ready_state) { PostTask(kReadyStateTaskIndex, &WebKit::WebMediaPlayerClient::readyStateChanged); } } void WebMediaPlayerImpl::OnPipelineSeek(bool successful) { PostTask(kTimeChangedTaskIndex, &WebKit::WebMediaPlayerClient::timeChanged); } void WebMediaPlayerImpl::SetVideoRenderer(VideoRendererImpl* video_renderer) { video_renderer_ = video_renderer; } void WebMediaPlayerImpl::DidTask(CancelableTask* task) { AutoLock auto_lock(task_lock_); for (size_t i = 0; i < tasks_.size(); ++i) { if (tasks_[i] == task) { tasks_[i] = NULL; return; } } NOTREACHED(); } void WebMediaPlayerImpl::CancelAllTasks() { AutoLock auto_lock(task_lock_); // Loop through the list of tasks and cancel tasks that are still alive. for (size_t i = 0; i < tasks_.size(); ++i) { if (tasks_[i]) tasks_[i]->Cancel(); } } void WebMediaPlayerImpl::PostTask(int index, WebMediaPlayerClientMethod method) { DCHECK(main_loop_); AutoLock auto_lock(task_lock_); if (!tasks_[index]) { CancelableTask* task = new NotifyWebMediaPlayerTask(this, method); tasks_[index] = task; main_loop_->PostTask(FROM_HERE, task); } } void WebMediaPlayerImpl::PostRepaintTask() { PostTask(kRepaintTaskIndex, &WebKit::WebMediaPlayerClient::repaint); } } // namespace webkit_glue <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: dp_identifier.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: rt $ $Date: 2007-01-19 09:14:21 $ * * 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 2007 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 INCLUDED_DESKTOP_SOURCE_DEPLOYMENT_INC_DP_IDENTIFIER_HXX #define INCLUDED_DESKTOP_SOURCE_DEPLOYMENT_INC_DP_IDENTIFIER_HXX #include "sal/config.h" #include "boost/optional.hpp" #include "com/sun/star/uno/Reference.hxx" #include "dp_misc_api.hxx" namespace com { namespace sun { namespace star { namespace deployment { class XPackage; } } } } namespace rtl { class OUString; } namespace dp_misc { /** Generates an identifier from an optional identifier. @param optional an optional identifier @param fileName a file name @return the given optional identifier if present, otherwise a legacy identifier based on the given file name */ DESKTOP_DEPLOYMENTMISC_DLLPUBLIC ::rtl::OUString generateIdentifier( ::boost::optional< ::rtl::OUString > const & optional, ::rtl::OUString const & fileName); /** Gets the identifier of a package. @param package a non-null package @return the explicit identifier of the given package if present, otherwise the implicit legacy identifier of the given package @throws com::sun::star::uno::RuntimeException */ DESKTOP_DEPLOYMENTMISC_DLLPUBLIC ::rtl::OUString getIdentifier( ::com::sun::star::uno::Reference< ::com::sun::star::deployment::XPackage > const & package); /** Generates a legacy identifier based on a file name. @param fileName a file name @return a legacy identifier based on the given file name */ DESKTOP_DEPLOYMENTMISC_DLLPUBLIC ::rtl::OUString generateLegacyIdentifier( ::rtl::OUString const & fileName); } #endif <commit_msg>INTEGRATION: CWS changefileheader (1.2.296); FILE MERGED 2008/03/28 15:26:41 rt 1.2.296.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: dp_identifier.hxx,v $ * $Revision: 1.3 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef INCLUDED_DESKTOP_SOURCE_DEPLOYMENT_INC_DP_IDENTIFIER_HXX #define INCLUDED_DESKTOP_SOURCE_DEPLOYMENT_INC_DP_IDENTIFIER_HXX #include "sal/config.h" #include "boost/optional.hpp" #include "com/sun/star/uno/Reference.hxx" #include "dp_misc_api.hxx" namespace com { namespace sun { namespace star { namespace deployment { class XPackage; } } } } namespace rtl { class OUString; } namespace dp_misc { /** Generates an identifier from an optional identifier. @param optional an optional identifier @param fileName a file name @return the given optional identifier if present, otherwise a legacy identifier based on the given file name */ DESKTOP_DEPLOYMENTMISC_DLLPUBLIC ::rtl::OUString generateIdentifier( ::boost::optional< ::rtl::OUString > const & optional, ::rtl::OUString const & fileName); /** Gets the identifier of a package. @param package a non-null package @return the explicit identifier of the given package if present, otherwise the implicit legacy identifier of the given package @throws com::sun::star::uno::RuntimeException */ DESKTOP_DEPLOYMENTMISC_DLLPUBLIC ::rtl::OUString getIdentifier( ::com::sun::star::uno::Reference< ::com::sun::star::deployment::XPackage > const & package); /** Generates a legacy identifier based on a file name. @param fileName a file name @return a legacy identifier based on the given file name */ DESKTOP_DEPLOYMENTMISC_DLLPUBLIC ::rtl::OUString generateLegacyIdentifier( ::rtl::OUString const & fileName); } #endif <|endoftext|>
<commit_before>/* * Copyright 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 <memory> #include <vector> #include "webrtc/base/bind.h" #include "webrtc/base/event.h" #include "webrtc/base/gunit.h" #include "webrtc/base/task_queue.h" #include "webrtc/base/timeutils.h" namespace rtc { namespace { void CheckCurrent(const char* expected_queue, Event* signal, TaskQueue* queue) { EXPECT_TRUE(TaskQueue::IsCurrent(expected_queue)); EXPECT_TRUE(queue->IsCurrent()); if (signal) signal->Set(); } } // namespace TEST(TaskQueueTest, Construct) { static const char kQueueName[] = "Construct"; TaskQueue queue(kQueueName); EXPECT_FALSE(queue.IsCurrent()); } TEST(TaskQueueTest, PostAndCheckCurrent) { static const char kQueueName[] = "PostAndCheckCurrent"; TaskQueue queue(kQueueName); // We're not running a task, so there shouldn't be a current queue. EXPECT_FALSE(queue.IsCurrent()); EXPECT_FALSE(TaskQueue::Current()); Event event(false, false); queue.PostTask(Bind(&CheckCurrent, kQueueName, &event, &queue)); EXPECT_TRUE(event.Wait(1000)); } TEST(TaskQueueTest, PostCustomTask) { static const char kQueueName[] = "PostCustomImplementation"; TaskQueue queue(kQueueName); Event event(false, false); class CustomTask : public QueuedTask { public: explicit CustomTask(Event* event) : event_(event) {} private: bool Run() override { event_->Set(); return false; // Never allows the task to be deleted by the queue. } Event* const event_; } my_task(&event); // Please don't do this in production code! :) queue.PostTask(std::unique_ptr<QueuedTask>(&my_task)); EXPECT_TRUE(event.Wait(1000)); } TEST(TaskQueueTest, PostLambda) { static const char kQueueName[] = "PostLambda"; TaskQueue queue(kQueueName); Event event(false, false); queue.PostTask([&event]() { event.Set(); }); EXPECT_TRUE(event.Wait(1000)); } TEST(TaskQueueTest, PostFromQueue) { static const char kQueueName[] = "PostFromQueue"; TaskQueue queue(kQueueName); Event event(false, false); queue.PostTask( [&event, &queue]() { queue.PostTask([&event]() { event.Set(); }); }); EXPECT_TRUE(event.Wait(1000)); } TEST(TaskQueueTest, DISABLED_PostDelayed) { static const char kQueueName[] = "PostDelayed"; TaskQueue queue(kQueueName); Event event(false, false); uint32_t start = Time(); queue.PostDelayedTask(Bind(&CheckCurrent, kQueueName, &event, &queue), 100); EXPECT_TRUE(event.Wait(1000)); uint32_t end = Time(); EXPECT_GE(end - start, 100u); EXPECT_NEAR(end - start, 200u, 100u); // Accept 100-300. } TEST(TaskQueueTest, PostMultipleDelayed) { static const char kQueueName[] = "PostMultipleDelayed"; TaskQueue queue(kQueueName); std::vector<std::unique_ptr<Event>> events; for (int i = 0; i < 10; ++i) { events.push_back(std::unique_ptr<Event>(new Event(false, false))); queue.PostDelayedTask( Bind(&CheckCurrent, kQueueName, events.back().get(), &queue), 10); } for (const auto& e : events) EXPECT_TRUE(e->Wait(100)); } TEST(TaskQueueTest, PostDelayedAfterDestruct) { static const char kQueueName[] = "PostDelayedAfterDestruct"; Event event(false, false); { TaskQueue queue(kQueueName); queue.PostDelayedTask(Bind(&CheckCurrent, kQueueName, &event, &queue), 100); } EXPECT_FALSE(event.Wait(200)); // Task should not run. } TEST(TaskQueueTest, PostAndReply) { static const char kPostQueue[] = "PostQueue"; static const char kReplyQueue[] = "ReplyQueue"; TaskQueue post_queue(kPostQueue); TaskQueue reply_queue(kReplyQueue); Event event(false, false); post_queue.PostTaskAndReply( Bind(&CheckCurrent, kPostQueue, nullptr, &post_queue), Bind(&CheckCurrent, kReplyQueue, &event, &reply_queue), &reply_queue); EXPECT_TRUE(event.Wait(1000)); } TEST(TaskQueueTest, PostAndReuse) { static const char kPostQueue[] = "PostQueue"; static const char kReplyQueue[] = "ReplyQueue"; TaskQueue post_queue(kPostQueue); TaskQueue reply_queue(kReplyQueue); int call_count = 0; class ReusedTask : public QueuedTask { public: ReusedTask(int* counter, TaskQueue* reply_queue, Event* event) : counter_(counter), reply_queue_(reply_queue), event_(event) { EXPECT_EQ(0, *counter_); } private: bool Run() override { if (++(*counter_) == 1) { std::unique_ptr<QueuedTask> myself(this); reply_queue_->PostTask(std::move(myself)); // At this point, the object is owned by reply_queue_ and it's // theoratically possible that the object has been deleted (e.g. if // posting wasn't possible). So, don't touch any member variables here. // Indicate to the current queue that ownership has been transferred. return false; } else { EXPECT_EQ(2, *counter_); EXPECT_TRUE(reply_queue_->IsCurrent()); event_->Set(); return true; // Indicate that the object should be deleted. } } int* const counter_; TaskQueue* const reply_queue_; Event* const event_; }; Event event(false, false); std::unique_ptr<QueuedTask> task( new ReusedTask(&call_count, &reply_queue, &event)); post_queue.PostTask(std::move(task)); EXPECT_TRUE(event.Wait(1000)); } TEST(TaskQueueTest, PostAndReplyLambda) { static const char kPostQueue[] = "PostQueue"; static const char kReplyQueue[] = "ReplyQueue"; TaskQueue post_queue(kPostQueue); TaskQueue reply_queue(kReplyQueue); Event event(false, false); bool my_flag = false; post_queue.PostTaskAndReply([&my_flag]() { my_flag = true; }, [&event]() { event.Set(); }, &reply_queue); EXPECT_TRUE(event.Wait(1000)); EXPECT_TRUE(my_flag); } void TestPostTaskAndReply(TaskQueue* work_queue, const char* work_queue_name, Event* event) { ASSERT_FALSE(work_queue->IsCurrent()); work_queue->PostTaskAndReply( Bind(&CheckCurrent, work_queue_name, nullptr, work_queue), NewClosure([event]() { event->Set(); })); } // Does a PostTaskAndReply from within a task to post and reply to the current // queue. All in all there will be 3 tasks posted and run. TEST(TaskQueueTest, PostAndReply2) { static const char kQueueName[] = "PostAndReply2"; static const char kWorkQueueName[] = "PostAndReply2_Worker"; TaskQueue queue(kQueueName); TaskQueue work_queue(kWorkQueueName); Event event(false, false); queue.PostTask( Bind(&TestPostTaskAndReply, &work_queue, kWorkQueueName, &event)); EXPECT_TRUE(event.Wait(1000)); } // Tests posting more messages than a queue can queue up. // In situations like that, tasks will get dropped. TEST(TaskQueueTest, PostALot) { // To destruct the event after the queue has gone out of scope. Event event(false, false); int tasks_executed = 0; int tasks_cleaned_up = 0; static const int kTaskCount = 0xffff; { static const char kQueueName[] = "PostALot"; TaskQueue queue(kQueueName); // On linux, the limit of pending bytes in the pipe buffer is 0xffff. // So here we post a total of 0xffff+1 messages, which triggers a failure // case inside of the libevent queue implementation. queue.PostTask([&event]() { event.Wait(Event::kForever); }); for (int i = 0; i < kTaskCount; ++i) queue.PostTask(NewClosure([&tasks_executed]() { ++tasks_executed; }, [&tasks_cleaned_up]() { ++tasks_cleaned_up; })); event.Set(); // Unblock the first task. } EXPECT_GE(tasks_cleaned_up, tasks_executed); EXPECT_EQ(kTaskCount, tasks_cleaned_up); } } // namespace rtc <commit_msg>Re-enable the PostDelayed TaskQueue test on all platforms except Windows.<commit_after>/* * Copyright 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 <memory> #include <vector> #include "webrtc/base/bind.h" #include "webrtc/base/event.h" #include "webrtc/base/gunit.h" #include "webrtc/base/task_queue.h" #include "webrtc/base/timeutils.h" namespace rtc { namespace { void CheckCurrent(const char* expected_queue, Event* signal, TaskQueue* queue) { EXPECT_TRUE(TaskQueue::IsCurrent(expected_queue)); EXPECT_TRUE(queue->IsCurrent()); if (signal) signal->Set(); } } // namespace TEST(TaskQueueTest, Construct) { static const char kQueueName[] = "Construct"; TaskQueue queue(kQueueName); EXPECT_FALSE(queue.IsCurrent()); } TEST(TaskQueueTest, PostAndCheckCurrent) { static const char kQueueName[] = "PostAndCheckCurrent"; TaskQueue queue(kQueueName); // We're not running a task, so there shouldn't be a current queue. EXPECT_FALSE(queue.IsCurrent()); EXPECT_FALSE(TaskQueue::Current()); Event event(false, false); queue.PostTask(Bind(&CheckCurrent, kQueueName, &event, &queue)); EXPECT_TRUE(event.Wait(1000)); } TEST(TaskQueueTest, PostCustomTask) { static const char kQueueName[] = "PostCustomImplementation"; TaskQueue queue(kQueueName); Event event(false, false); class CustomTask : public QueuedTask { public: explicit CustomTask(Event* event) : event_(event) {} private: bool Run() override { event_->Set(); return false; // Never allows the task to be deleted by the queue. } Event* const event_; } my_task(&event); // Please don't do this in production code! :) queue.PostTask(std::unique_ptr<QueuedTask>(&my_task)); EXPECT_TRUE(event.Wait(1000)); } TEST(TaskQueueTest, PostLambda) { static const char kQueueName[] = "PostLambda"; TaskQueue queue(kQueueName); Event event(false, false); queue.PostTask([&event]() { event.Set(); }); EXPECT_TRUE(event.Wait(1000)); } TEST(TaskQueueTest, PostFromQueue) { static const char kQueueName[] = "PostFromQueue"; TaskQueue queue(kQueueName); Event event(false, false); queue.PostTask( [&event, &queue]() { queue.PostTask([&event]() { event.Set(); }); }); EXPECT_TRUE(event.Wait(1000)); } // Currently flaky on Windows. See issue 6610. #if defined(WEBRTC_WIN) #define MAYBE_PostDelayed DISABLED_PostDelayed #else #define MAYBE_PostDelayed PostDelayed #endif TEST(TaskQueueTest, MAYBE_PostDelayed) { static const char kQueueName[] = "PostDelayed"; TaskQueue queue(kQueueName); Event event(false, false); uint32_t start = Time(); queue.PostDelayedTask(Bind(&CheckCurrent, kQueueName, &event, &queue), 100); EXPECT_TRUE(event.Wait(1000)); uint32_t end = Time(); EXPECT_GE(end - start, 100u); EXPECT_NEAR(end - start, 200u, 100u); // Accept 100-300. } TEST(TaskQueueTest, PostMultipleDelayed) { static const char kQueueName[] = "PostMultipleDelayed"; TaskQueue queue(kQueueName); std::vector<std::unique_ptr<Event>> events; for (int i = 0; i < 10; ++i) { events.push_back(std::unique_ptr<Event>(new Event(false, false))); queue.PostDelayedTask( Bind(&CheckCurrent, kQueueName, events.back().get(), &queue), 10); } for (const auto& e : events) EXPECT_TRUE(e->Wait(100)); } TEST(TaskQueueTest, PostDelayedAfterDestruct) { static const char kQueueName[] = "PostDelayedAfterDestruct"; Event event(false, false); { TaskQueue queue(kQueueName); queue.PostDelayedTask(Bind(&CheckCurrent, kQueueName, &event, &queue), 100); } EXPECT_FALSE(event.Wait(200)); // Task should not run. } TEST(TaskQueueTest, PostAndReply) { static const char kPostQueue[] = "PostQueue"; static const char kReplyQueue[] = "ReplyQueue"; TaskQueue post_queue(kPostQueue); TaskQueue reply_queue(kReplyQueue); Event event(false, false); post_queue.PostTaskAndReply( Bind(&CheckCurrent, kPostQueue, nullptr, &post_queue), Bind(&CheckCurrent, kReplyQueue, &event, &reply_queue), &reply_queue); EXPECT_TRUE(event.Wait(1000)); } TEST(TaskQueueTest, PostAndReuse) { static const char kPostQueue[] = "PostQueue"; static const char kReplyQueue[] = "ReplyQueue"; TaskQueue post_queue(kPostQueue); TaskQueue reply_queue(kReplyQueue); int call_count = 0; class ReusedTask : public QueuedTask { public: ReusedTask(int* counter, TaskQueue* reply_queue, Event* event) : counter_(counter), reply_queue_(reply_queue), event_(event) { EXPECT_EQ(0, *counter_); } private: bool Run() override { if (++(*counter_) == 1) { std::unique_ptr<QueuedTask> myself(this); reply_queue_->PostTask(std::move(myself)); // At this point, the object is owned by reply_queue_ and it's // theoratically possible that the object has been deleted (e.g. if // posting wasn't possible). So, don't touch any member variables here. // Indicate to the current queue that ownership has been transferred. return false; } else { EXPECT_EQ(2, *counter_); EXPECT_TRUE(reply_queue_->IsCurrent()); event_->Set(); return true; // Indicate that the object should be deleted. } } int* const counter_; TaskQueue* const reply_queue_; Event* const event_; }; Event event(false, false); std::unique_ptr<QueuedTask> task( new ReusedTask(&call_count, &reply_queue, &event)); post_queue.PostTask(std::move(task)); EXPECT_TRUE(event.Wait(1000)); } TEST(TaskQueueTest, PostAndReplyLambda) { static const char kPostQueue[] = "PostQueue"; static const char kReplyQueue[] = "ReplyQueue"; TaskQueue post_queue(kPostQueue); TaskQueue reply_queue(kReplyQueue); Event event(false, false); bool my_flag = false; post_queue.PostTaskAndReply([&my_flag]() { my_flag = true; }, [&event]() { event.Set(); }, &reply_queue); EXPECT_TRUE(event.Wait(1000)); EXPECT_TRUE(my_flag); } void TestPostTaskAndReply(TaskQueue* work_queue, const char* work_queue_name, Event* event) { ASSERT_FALSE(work_queue->IsCurrent()); work_queue->PostTaskAndReply( Bind(&CheckCurrent, work_queue_name, nullptr, work_queue), NewClosure([event]() { event->Set(); })); } // Does a PostTaskAndReply from within a task to post and reply to the current // queue. All in all there will be 3 tasks posted and run. TEST(TaskQueueTest, PostAndReply2) { static const char kQueueName[] = "PostAndReply2"; static const char kWorkQueueName[] = "PostAndReply2_Worker"; TaskQueue queue(kQueueName); TaskQueue work_queue(kWorkQueueName); Event event(false, false); queue.PostTask( Bind(&TestPostTaskAndReply, &work_queue, kWorkQueueName, &event)); EXPECT_TRUE(event.Wait(1000)); } // Tests posting more messages than a queue can queue up. // In situations like that, tasks will get dropped. TEST(TaskQueueTest, PostALot) { // To destruct the event after the queue has gone out of scope. Event event(false, false); int tasks_executed = 0; int tasks_cleaned_up = 0; static const int kTaskCount = 0xffff; { static const char kQueueName[] = "PostALot"; TaskQueue queue(kQueueName); // On linux, the limit of pending bytes in the pipe buffer is 0xffff. // So here we post a total of 0xffff+1 messages, which triggers a failure // case inside of the libevent queue implementation. queue.PostTask([&event]() { event.Wait(Event::kForever); }); for (int i = 0; i < kTaskCount; ++i) queue.PostTask(NewClosure([&tasks_executed]() { ++tasks_executed; }, [&tasks_cleaned_up]() { ++tasks_cleaned_up; })); event.Set(); // Unblock the first task. } EXPECT_GE(tasks_cleaned_up, tasks_executed); EXPECT_EQ(kTaskCount, tasks_cleaned_up); } } // namespace rtc <|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 <algorithm> #include "libtorrent/entry.hpp" #include <boost/bind.hpp> #include <boost/next_prior.hpp> #if defined(_MSC_VER) namespace std { using ::isprint; } #define for if (false) {} else for #endif namespace { template <class T> void call_destructor(T* o) { assert(o); o->~T(); } struct compare_string { compare_string(char const* s): m_str(s) {} bool operator()( std::pair<std::string , libtorrent::entry> const& e) const { return e.first == m_str; } char const* m_str; }; } namespace libtorrent { namespace detail { char const* integer_to_str(char* buf, int size, entry::integer_type val) { int sign = 0; if (val < 0) { sign = 1; val = -val; } buf[--size] = '\0'; if (val == 0) buf[--size] = '0'; for (; size > sign && val != 0;) { buf[--size] = '0' + char(val % 10); val /= 10; } if (sign) buf[--size] = '-'; return buf + size; } } entry& entry::operator[](char const* key) { dictionary_type::iterator i = std::find_if( dict().begin() , dict().end() , compare_string(key)); if (i != dict().end()) return i->second; dictionary_type::iterator ret = dict().insert( dict().end() , std::make_pair(std::string(key), entry())); return ret->second; } entry& entry::operator[](std::string const& key) { return (*this)[key.c_str()]; } entry* entry::find_key(char const* key) { dictionary_type::iterator i = std::find_if( dict().begin() , dict().end() , compare_string(key)); if (i == dict().end()) return 0; return &i->second; } entry const* entry::find_key(char const* key) const { dictionary_type::const_iterator i = std::find_if( dict().begin() , dict().end() , compare_string(key)); if (i == dict().end()) return 0; return &i->second; } const entry& entry::operator[](char const* key) const { dictionary_type::const_iterator i = std::find_if( dict().begin() , dict().end() , compare_string(key)); if (i == dict().end()) throw type_error("key not found"); return i->second; } const entry& entry::operator[](std::string const& key) const { return (*this)[key.c_str()]; } entry::entry(const dictionary_type& v) { new(data) dictionary_type(v); m_type = dictionary_t; } entry::entry(const string_type& v) { new(data) string_type(v); m_type = string_t; } entry::entry(const list_type& v) { new(data) list_type(v); m_type = list_t; } entry::entry(const integer_type& v) { new(data) integer_type(v); m_type = int_t; } void entry::operator=(const dictionary_type& v) { destruct(); new(data) dictionary_type(v); m_type = dictionary_t; } void entry::operator=(const string_type& v) { destruct(); new(data) string_type(v); m_type = string_t; } void entry::operator=(const list_type& v) { destruct(); new(data) list_type(v); m_type = list_t; } void entry::operator=(const integer_type& v) { destruct(); new(data) integer_type(v); m_type = int_t; } bool entry::operator==(entry const& e) const { if (m_type != e.m_type) return false; switch(m_type) { case int_t: return integer() == e.integer(); case string_t: return string() == e.string(); case list_t: return list() == e.list(); case dictionary_t: return dict() == e.dict(); default: assert(m_type == undefined_t); return true; } } void entry::construct(data_type t) { m_type = t; switch(m_type) { case int_t: new(data) integer_type; break; case string_t: new(data) string_type; break; case list_t: new(data) list_type; break; case dictionary_t: new (data) dictionary_type; break; default: assert(m_type == undefined_t); m_type = undefined_t; } } void entry::copy(const entry& e) { m_type = e.m_type; switch(m_type) { case int_t: new(data) integer_type(e.integer()); break; case string_t: new(data) string_type(e.string()); break; case list_t: new(data) list_type(e.list()); break; case dictionary_t: new (data) dictionary_type(e.dict()); break; default: m_type = undefined_t; } } void entry::destruct() { switch(m_type) { case int_t: call_destructor(reinterpret_cast<integer_type*>(data)); break; case string_t: call_destructor(reinterpret_cast<string_type*>(data)); break; case list_t: call_destructor(reinterpret_cast<list_type*>(data)); break; case dictionary_t: call_destructor(reinterpret_cast<dictionary_type*>(data)); break; default: assert(m_type == undefined_t); break; } } void entry::print(std::ostream& os, int indent) const { assert(indent >= 0); for (int i = 0; i < indent; ++i) os << " "; switch (m_type) { case int_t: os << integer() << "\n"; break; case string_t: { bool binary_string = false; for (std::string::const_iterator i = string().begin(); i != string().end(); ++i) { if (!std::isprint(static_cast<unsigned char>(*i))) { binary_string = true; break; } } if (binary_string) { os.unsetf(std::ios_base::dec); os.setf(std::ios_base::hex); for (std::string::const_iterator i = string().begin(); i != string().end(); ++i) os << static_cast<unsigned int>((unsigned char)*i); os.unsetf(std::ios_base::hex); os.setf(std::ios_base::dec); os << "\n"; } else { os << string() << "\n"; } } break; case list_t: { os << "list\n"; for (list_type::const_iterator i = list().begin(); i != list().end(); ++i) { i->print(os, indent+1); } } break; case dictionary_t: { os << "dictionary\n"; for (dictionary_type::const_iterator i = dict().begin(); i != dict().end(); ++i) { for (int j = 0; j < indent+1; ++j) os << " "; os << "[" << i->first << "]"; if (i->second.type() != entry::string_t && i->second.type() != entry::int_t) os << "\n"; else os << " "; i->second.print(os, indent+2); } } break; default: os << "<uninitialized>\n"; } } } <commit_msg>optimizations to entry (using std::maps find instead of linear search)<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 <algorithm> #include "libtorrent/entry.hpp" #include <boost/bind.hpp> #include <boost/next_prior.hpp> #if defined(_MSC_VER) namespace std { using ::isprint; } #define for if (false) {} else for #endif namespace { template <class T> void call_destructor(T* o) { assert(o); o->~T(); } struct compare_string { compare_string(char const* s): m_str(s) {} bool operator()( std::pair<std::string , libtorrent::entry> const& e) const { return e.first == m_str; } char const* m_str; }; } namespace libtorrent { namespace detail { char const* integer_to_str(char* buf, int size, entry::integer_type val) { int sign = 0; if (val < 0) { sign = 1; val = -val; } buf[--size] = '\0'; if (val == 0) buf[--size] = '0'; for (; size > sign && val != 0;) { buf[--size] = '0' + char(val % 10); val /= 10; } if (sign) buf[--size] = '-'; return buf + size; } } entry& entry::operator[](char const* key) { dictionary_type::iterator i = dict().find(key); if (i != dict().end()) return i->second; dictionary_type::iterator ret = dict().insert( dict().begin() , std::make_pair(std::string(key), entry())); return ret->second; } entry& entry::operator[](std::string const& key) { return (*this)[key.c_str()]; } entry* entry::find_key(char const* key) { dictionary_type::iterator i = std::find_if( dict().begin() , dict().end() , compare_string(key)); if (i == dict().end()) return 0; return &i->second; } entry const* entry::find_key(char const* key) const { dictionary_type::const_iterator i = dict().find(key); if (i == dict().end()) return 0; return &i->second; } const entry& entry::operator[](char const* key) const { dictionary_type::const_iterator i = dict().find(key); if (i == dict().end()) throw type_error( (std::string("key not found: ") + key).c_str()); return i->second; } const entry& entry::operator[](std::string const& key) const { return (*this)[key.c_str()]; } entry::entry(const dictionary_type& v) { new(data) dictionary_type(v); m_type = dictionary_t; } entry::entry(const string_type& v) { new(data) string_type(v); m_type = string_t; } entry::entry(const list_type& v) { new(data) list_type(v); m_type = list_t; } entry::entry(const integer_type& v) { new(data) integer_type(v); m_type = int_t; } void entry::operator=(const dictionary_type& v) { destruct(); new(data) dictionary_type(v); m_type = dictionary_t; } void entry::operator=(const string_type& v) { destruct(); new(data) string_type(v); m_type = string_t; } void entry::operator=(const list_type& v) { destruct(); new(data) list_type(v); m_type = list_t; } void entry::operator=(const integer_type& v) { destruct(); new(data) integer_type(v); m_type = int_t; } bool entry::operator==(entry const& e) const { if (m_type != e.m_type) return false; switch(m_type) { case int_t: return integer() == e.integer(); case string_t: return string() == e.string(); case list_t: return list() == e.list(); case dictionary_t: return dict() == e.dict(); default: assert(m_type == undefined_t); return true; } } void entry::construct(data_type t) { m_type = t; switch(m_type) { case int_t: new(data) integer_type; break; case string_t: new(data) string_type; break; case list_t: new(data) list_type; break; case dictionary_t: new (data) dictionary_type; break; default: assert(m_type == undefined_t); m_type = undefined_t; } } void entry::copy(const entry& e) { m_type = e.m_type; switch(m_type) { case int_t: new(data) integer_type(e.integer()); break; case string_t: new(data) string_type(e.string()); break; case list_t: new(data) list_type(e.list()); break; case dictionary_t: new (data) dictionary_type(e.dict()); break; default: m_type = undefined_t; } } void entry::destruct() { switch(m_type) { case int_t: call_destructor(reinterpret_cast<integer_type*>(data)); break; case string_t: call_destructor(reinterpret_cast<string_type*>(data)); break; case list_t: call_destructor(reinterpret_cast<list_type*>(data)); break; case dictionary_t: call_destructor(reinterpret_cast<dictionary_type*>(data)); break; default: assert(m_type == undefined_t); break; } } void entry::print(std::ostream& os, int indent) const { assert(indent >= 0); for (int i = 0; i < indent; ++i) os << " "; switch (m_type) { case int_t: os << integer() << "\n"; break; case string_t: { bool binary_string = false; for (std::string::const_iterator i = string().begin(); i != string().end(); ++i) { if (!std::isprint(static_cast<unsigned char>(*i))) { binary_string = true; break; } } if (binary_string) { os.unsetf(std::ios_base::dec); os.setf(std::ios_base::hex); for (std::string::const_iterator i = string().begin(); i != string().end(); ++i) os << static_cast<unsigned int>((unsigned char)*i); os.unsetf(std::ios_base::hex); os.setf(std::ios_base::dec); os << "\n"; } else { os << string() << "\n"; } } break; case list_t: { os << "list\n"; for (list_type::const_iterator i = list().begin(); i != list().end(); ++i) { i->print(os, indent+1); } } break; case dictionary_t: { os << "dictionary\n"; for (dictionary_type::const_iterator i = dict().begin(); i != dict().end(); ++i) { for (int j = 0; j < indent+1; ++j) os << " "; os << "[" << i->first << "]"; if (i->second.type() != entry::string_t && i->second.type() != entry::int_t) os << "\n"; else os << " "; i->second.print(os, indent+2); } } break; default: os << "<uninitialized>\n"; } } } <|endoftext|>
<commit_before>/* * File: main.cpp * Author: Luca Bettinelli * * Created on July 18, 2017, 3:20 PM */ #include <stdlib.h> #include <core.hpp> #include <imgproc.hpp> #include <highgui.hpp> #include <iostream> #include <math.h> #include<string.h> #include<fstream> #include<dirent.h> #include "Filter.h" #include "Gradient.h" using namespace std; using namespace cv; /* * */ Mat toBN(Mat img); vector<string> listFile(const char* dirPath); bool has_suffix(const string& s, const string& suffix); vector<Mat> getGradient(Mat img); int main(int argc, char** argv) { vector<string> list = listFile("."); vector<Mat> stack; vector<Gradient> I; for(int i = 0; i < list.size(); i++) { Mat m = imread(list[i], CV_LOAD_IMAGE_COLOR); namedWindow(list[i], WINDOW_AUTOSIZE); Mat img = toBN(m); stack.push_back(img); I.push_back(Gradient(img)); imshow(list[i], img); waitKey(0); } for(int i = 0; i < I.size(); i++){ namedWindow("Ix", WINDOW_AUTOSIZE); namedWindow("Iy", WINDOW_AUTOSIZE); imshow("Ix", I[i].get_Ix()); imshow("Iy", I[i].get_Iy()); waitKey(0); } return 0; } Mat toBN(Mat img){ Mat res(img.rows, img.cols, CV_32FC1); for(int i = 0; i < img.rows; i++){ for(int j = 0; j < img.cols; j++){ float new_pixel = 0; Vec3b pixel = img.at<Vec3b>(i,j); for(int k = 0; k < 3; k++){ new_pixel += (int)pixel.val[k]; } new_pixel = (((double)1/3) * new_pixel)/255; res.at<float>(i,j) = (float) new_pixel; } } return res; } bool has_suffix(const string& s, const string& suffix) { return (s.size() >= suffix.size()) && equal(suffix.rbegin(), suffix.rend(), s.rbegin()); } vector<string> listFile(const char* dirPath){ DIR *pDIR; vector<string> list; struct dirent *entry; if( pDIR=opendir(dirPath) ){ while(entry = readdir(pDIR)){ if(has_suffix(entry->d_name, ".jpg")) { string s = entry->d_name; list.push_back(s); cout << entry->d_name << "\n"; } } closedir(pDIR); } return list; } <commit_msg>Delete function definition not needed<commit_after>/* * File: main.cpp * Author: Luca Bettinelli * * Created on July 18, 2017, 3:20 PM */ #include <stdlib.h> #include <core.hpp> #include <imgproc.hpp> #include <highgui.hpp> #include <iostream> #include <math.h> #include<string.h> #include<fstream> #include<dirent.h> #include "Filter.h" #include "Gradient.h" using namespace std; using namespace cv; /* * */ Mat toBN(Mat img); vector<string> listFile(const char* dirPath); bool has_suffix(const string& s, const string& suffix); int main(int argc, char** argv) { vector<string> list = listFile("."); vector<Mat> stack; vector<Gradient> I; for(int i = 0; i < list.size(); i++) { Mat m = imread(list[i], CV_LOAD_IMAGE_COLOR); namedWindow(list[i], WINDOW_AUTOSIZE); Mat img = toBN(m); stack.push_back(img); I.push_back(Gradient(img)); imshow(list[i], img); waitKey(0); } for(int i = 0; i < I.size(); i++){ namedWindow("Ix", WINDOW_AUTOSIZE); namedWindow("Iy", WINDOW_AUTOSIZE); imshow("Ix", I[i].get_Ix()); imshow("Iy", I[i].get_Iy()); waitKey(0); } return 0; } Mat toBN(Mat img){ Mat res(img.rows, img.cols, CV_32FC1); for(int i = 0; i < img.rows; i++){ for(int j = 0; j < img.cols; j++){ float new_pixel = 0; Vec3b pixel = img.at<Vec3b>(i,j); for(int k = 0; k < 3; k++){ new_pixel += (int)pixel.val[k]; } new_pixel = (((double)1/3) * new_pixel)/255; res.at<float>(i,j) = (float) new_pixel; } } return res; } bool has_suffix(const string& s, const string& suffix) { return (s.size() >= suffix.size()) && equal(suffix.rbegin(), suffix.rend(), s.rbegin()); } vector<string> listFile(const char* dirPath){ DIR *pDIR; vector<string> list; struct dirent *entry; if( pDIR=opendir(dirPath) ){ while(entry = readdir(pDIR)){ if(has_suffix(entry->d_name, ".jpg")) { string s = entry->d_name; list.push_back(s); cout << entry->d_name << "\n"; } } closedir(pDIR); } return list; } <|endoftext|>
<commit_before>/******************************************************************************* fsm11 - A C++11-compliant framework for finite state machines Copyright (c) 2015, Manuel Freiberger All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *******************************************************************************/ #include "error.hpp" using namespace FSM11STD; namespace fsm11 { class fsm11_category_impl : public error_category { public: virtual const char* name() const noexcept override { return "fsm11"; } virtual auto message(int err_val) const -> decltype(declval<error_category>().message(0)) override { switch (static_cast<FsmErrorCode>(err_val)) { case FsmErrorCode::InvalidStateRelationship: return "Invalid state relationship"; case FsmErrorCode::TransitionConflict: return "Transition conflict"; case FsmErrorCode::ThreadPoolUnderflow: return "Thread pool underflow"; default: return "Unkown error"; } } }; const error_category& fsm11_category() noexcept { static fsm11_category_impl categoryInstance; return categoryInstance; } } // namespace fsm11 <commit_msg>Added a missing header.<commit_after>/******************************************************************************* fsm11 - A C++11-compliant framework for finite state machines Copyright (c) 2015, Manuel Freiberger All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *******************************************************************************/ #include "error.hpp" #ifdef FSM11_USE_WEOS #include <weos/utility.hpp> #else #include <utility> #endif // FSM11_USE_WEOS using namespace FSM11STD; namespace fsm11 { class fsm11_category_impl : public error_category { public: virtual const char* name() const noexcept override { return "fsm11"; } virtual auto message(int err_val) const -> decltype(declval<error_category>().message(0)) override { switch (static_cast<FsmErrorCode>(err_val)) { case FsmErrorCode::InvalidStateRelationship: return "Invalid state relationship"; case FsmErrorCode::TransitionConflict: return "Transition conflict"; case FsmErrorCode::ThreadPoolUnderflow: return "Thread pool underflow"; default: return "Unkown error"; } } }; const error_category& fsm11_category() noexcept { static fsm11_category_impl categoryInstance; return categoryInstance; } } // namespace fsm11 <|endoftext|>
<commit_before>// // Reference : Chapter 6, "Introduction to Algorithms 3rd ed", aka CLRS. // #pragma once #include <vector> #include <functional> #include <stdexcept> #include <algorithm> using std::move; using std::find_if; using std::swap; namespace search { // // parent // O(1) // template<typename Iterator> auto inline parent(Iterator first, Iterator it) -> Iterator { return first + (it - first - 1) / 2; } // // left_child // O(1) // template<typename Iterator> auto inline left_child(Iterator first, Iterator last, Iterator it) -> Iterator { auto size = last - first; auto offset = 2 * (it - first) + 1; return offset > size ? last : first + offset; } // // right_child // O(1) // template<typename Iterator> auto inline right_child(Iterator first, Iterator last, Iterator it) -> Iterator { auto left = left_child(first, last, it); return left != last ? left + 1 : last; } // // heapify // O(lg n) // maintain heap's peroperties with a float down way // template<typename Iterator, typename CompareFunc> auto heapify(Iterator first, Iterator last, Iterator curr, CompareFunc && compare) -> void { while (true) { auto left = left_child(first, last, curr); auto right = right_child(first, last, curr); //! find max or min amoung curr, left and right children, depending on the CommpareFunc passed in. auto max_min = (left != last && compare(*left, *curr)) ? left : curr; if (right != last && compare(*right, *max_min)) max_min = right; if (curr == max_min) return; //! exchange. swap(*max_min, *curr); curr = max_min; } } // // build_heap // O(n) // template<typename Iterator, typename CompareFunc> auto inline build_heap(Iterator first, Iterator last, CompareFunc && compare) -> void { auto size = last - first; for (auto curr = first + size / 2 - 1; /* */; --curr) { heapify(first, last, curr, compare); if (curr == first) return; } } template<typename Iterator, typename CompareFunc> auto inline sift_up(Iterator first, Iterator curr, CompareFunc && compare) -> bool { auto c = curr; auto p = [&] { return parent(first, c); }; auto is_needed = [&] { return c != first && !compare(*p(), *c); }; if (!is_needed()) return false; for (; is_needed(); c = p()) std::swap(*p(), *c); return true; } // // PriorityQueue // template<typename Value, typename CompareFunc> class PriorityQueue { public: using Vector = std::vector < Value >; using SizeType = typename Vector::size_type; using Iterator = typename Vector::iterator; PriorityQueue() = default; PriorityQueue(CompareFunc c) : _seq{}, _compare{ c } { } PriorityQueue(std::initializer_list<Value>&& list, CompareFunc&& c) : _seq(std::move(list)), _compare{ std::move(c) } { if (!empty()) build_heap(_seq.begin(), _seq.end(), _compare); } template<typename Iterator> PriorityQueue(Iterator first, Iterator last, CompareFunc&& c) : _seq(first, last), _compare{ std::move(c) } { if (!empty()) build_heap(_seq.begin(), _seq.end(), _compare); } auto top() const -> Value const& { return _seq.front(); } auto size() const -> SizeType { return _seq.size(); } auto empty() const -> bool { return _seq.empty(); } auto contains(Value const& value) const -> bool { return _seq.cend() != std::find(_seq.cbegin(), _seq.cend(), value); } template<typename Predicate> auto any(Predicate predicate) const -> bool { return std::any_of(_seq.cbegin(), _seq.cend(), predicate); } auto push(Value const& new_val) -> void { // find the right place for new_val _seq.resize(size() + 1); auto curr = _seq.end() - 1; for (; curr > _seq.begin() && _compare(new_val, *parent(_seq.begin(), curr)); curr = parent(_seq.begin(), curr)) *curr = *parent(_seq.begin(), curr); // insert *curr = new_val; } auto pop() -> Value { if (empty()) throw std::underflow_error{ "underflow." }; auto popped = _seq.front(); _seq.front() = _seq.back(); _seq.resize(_seq.size() - 1); heapify(_seq.begin(), _seq.end(), _seq.begin(), _compare); return popped; } auto remove(Value const& item) -> void { auto it = std::find(_seq.begin(), _seq.end(), item); if (_seq.end() != it) remove(it); } // // O(lg n) // auto substitute(Value const& old_value, Value const& new_value) -> void { remove(old_value); push(new_value); } template<typename Predicate> auto update_with_if(Value const& new_value, Predicate predicate) -> void { auto iterator = find_if(_seq.begin(), _seq.end(), [&](Value const& value) { return predicate(value); }); if (iterator != _seq.end() && _compare(new_value, *iterator)) substitute(*iterator, new_value); } void reset() { _seq.clear(); } void reset(CompareFunc && c) { _compare = move(c); reset(); } private: Vector _seq; CompareFunc _compare; // // Make sure vector is not empty. // O(lg n) // template<typename Iterator> auto remove(Iterator at) -> void { std::swap(*at, *(_seq.end() - 1)); if (!sift_up(_seq.begin(), at, _compare)) heapify(_seq.begin(), _seq.end() - 1, at, _compare);//avoid involving the last item. _seq.resize(size() - 1); } }; }<commit_msg>polished modified: planning/lib/priority_queue.hpp<commit_after>// // Reference : Chapter 6, "Introduction to Algorithms 3rd ed", aka CLRS. // #pragma once #include <vector> #include <functional> #include <stdexcept> #include <algorithm> using std::move; using std::find_if; using std::swap; using std::find; using std::any_of; using std::underflow_error; using std::initializer_list; using std::vector; namespace search { // // parent // O(1) // template<typename Iterator> auto inline parent(Iterator first, Iterator it) -> Iterator { return first + (it - first - 1) / 2; } // // left_child // O(1) // template<typename Iterator> auto inline left_child(Iterator first, Iterator last, Iterator it) -> Iterator { auto size = last - first; auto offset = 2 * (it - first) + 1; return offset > size ? last : first + offset; } // // right_child // O(1) // template<typename Iterator> auto inline right_child(Iterator first, Iterator last, Iterator it) -> Iterator { auto left = left_child(first, last, it); return left != last ? left + 1 : last; } // // heapify // O(lg n) // maintain heap's peroperties with a float down way // template<typename Iterator, typename CompareFunc> auto heapify(Iterator first, Iterator last, Iterator curr, CompareFunc && compare) -> void { while (true) { auto left = left_child(first, last, curr); auto right = right_child(first, last, curr); // find max or min amoung curr, left and right children, depending on the CommpareFunc passed in. auto max_min = (left != last && compare(*left, *curr)) ? left : curr; if (right != last && compare(*right, *max_min)) max_min = right; // exchange when needed if (curr != max_min) swap(*max_min, *curr), curr = max_min; else return; } } // // build_heap // O(n) // template<typename Iterator, typename CompareFunc> auto inline build_heap(Iterator first, Iterator last, CompareFunc && compare) -> void { auto size = last - first; for (auto curr = first + size / 2 - 1; /* */; --curr) { heapify(first, last, curr, compare); if (curr == first) return; } } template<typename Iterator, typename CompareFunc> auto inline sift_up(Iterator first, Iterator curr, CompareFunc && compare) -> bool { auto c = curr; auto p = [&] { return parent(first, c); }; auto is_needed = [&] { return c != first && !compare(*p(), *c); }; if (!is_needed()) return false; for (; is_needed(); c = p()) swap(*p(), *c); return true; } // // PriorityQueue // template<typename Value, typename CompareFunc> class PriorityQueue { public: using Vector = vector < Value >; using SizeType = typename Vector::size_type; using Iterator = typename Vector::iterator; PriorityQueue() = default; PriorityQueue(CompareFunc c) : _seq{}, _compare{ c } { } PriorityQueue(initializer_list<Value>&& list, CompareFunc&& c) : _seq(move(list)), _compare{ move(c) } { if (!empty()) build_heap(_seq.begin(), _seq.end(), _compare); } template<typename Iterator> PriorityQueue(Iterator first, Iterator last, CompareFunc&& c) : _seq(first, last), _compare{ move(c) } { if (!empty()) build_heap(_seq.begin(), _seq.end(), _compare); } auto top() const -> Value const& { return _seq.front(); } auto size() const -> SizeType { return _seq.size(); } auto empty() const -> bool { return _seq.empty(); } auto contains(Value const& value) const -> bool { return _seq.cend() != find(_seq.cbegin(), _seq.cend(), value); } template<typename Predicate> auto any(Predicate predicate) const -> bool { return any_of(_seq.cbegin(), _seq.cend(), predicate); } auto push(Value const& new_val) -> void { // find the right place for new_val _seq.resize(size() + 1); auto curr = _seq.end() - 1; for (; curr > _seq.begin() && _compare(new_val, *parent(_seq.begin(), curr)); curr = parent(_seq.begin(), curr)) *curr = *parent(_seq.begin(), curr); // insert *curr = new_val; } auto pop() -> Value { if (empty()) throw underflow_error{ "underflow." }; auto popped = _seq.front(); _seq.front() = _seq.back(); _seq.resize(_seq.size() - 1); heapify(_seq.begin(), _seq.end(), _seq.begin(), _compare); return popped; } auto remove(Value const& item) -> void { auto it = find(_seq.begin(), _seq.end(), item); if (_seq.end() != it) remove(it); } // // O(lg n) // auto substitute(Value const& old_value, Value const& new_value) -> void { remove(old_value); push(new_value); } template<typename Predicate> auto update_with_if(Value const& new_value, Predicate predicate) -> void { auto iterator = find_if(_seq.begin(), _seq.end(), [&](Value const& v) { return predicate(v); }); if (iterator != _seq.end() && _compare(new_value, *iterator)) substitute(*iterator, new_value); } void reset() { _seq.clear(); } void reset(CompareFunc && c) { _compare = move(c); reset(); } private: Vector _seq; CompareFunc _compare; // // Make sure vector is not empty. // O(lg n) // template<typename Iterator> auto remove(Iterator at) -> void { swap(*at, *(_seq.end() - 1)); if (!sift_up(_seq.begin(), at, _compare)) heapify(_seq.begin(), _seq.end() - 1, at, _compare);//avoid involving the last item. _seq.resize(size() - 1); } }; }<|endoftext|>
<commit_before>/* This file is part of kdepim. Copyright (c) 2004 Cornelius Schumacher <schumacher@kde.org> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #include <interfaces/bodypartformatter.h> #include <interfaces/bodypart.h> #include <interfaces/bodyparturlhandler.h> #include <khtmlparthtmlwriter.h> #include <libkcal/calendarlocal.h> #include <libkcal/icalformat.h> #include <libkcal/attendee.h> #include <libkcal/incidence.h> #include <libkcal/incidenceformatter.h> #include <kpimprefs.h> // for the timezone #include <kmail/callback.h> #include <kmail/kmmessage.h> #include <kmail/kmcommands.h> #include <email.h> #include <kglobal.h> #include <klocale.h> #include <kstringhandler.h> #include <kglobalsettings.h> #include <kiconloader.h> #include <kdebug.h> #include <kmessagebox.h> #include <kstandarddirs.h> #include <kapplication.h> #include <ktempfile.h> #include <qurl.h> #include <qdir.h> #include <qtextstream.h> #include <kdepimmacros.h> using namespace KCal; namespace { class KMInvitationFormatterHelper : public KCal::InvitationFormatterHelper { public: KMInvitationFormatterHelper( KMail::Interface::BodyPart *bodyPart ) : mBodyPart( bodyPart ) {} virtual QString generateLinkURL( const QString &id ) { return mBodyPart->makeLink( id ); } private: KMail::Interface::BodyPart *mBodyPart; }; class Formatter : public KMail::Interface::BodyPartFormatter { public: Result format( KMail::Interface::BodyPart *bodyPart, KMail::HtmlWriter *writer ) const { if ( !writer ) // Guard against crashes in createReply() return Ok; CalendarLocal cl( KPimPrefs::timezone() ); KMInvitationFormatterHelper helper( bodyPart ); QString html = IncidenceFormatter::formatICalInvitation( bodyPart->asText(), &cl, &helper ); if ( html.isEmpty() ) return AsIcon; writer->queue( html ); return Ok; } }; class UrlHandler : public KMail::Interface::BodyPartURLHandler { public: UrlHandler() { kdDebug() << "UrlHandler() (iCalendar)" << endl; } Incidence* icalToString( const QString& iCal ) const { CalendarLocal calendar( KPimPrefs::timezone() ) ; ICalFormat format; ScheduleMessage *message = format.parseScheduleMessage( &calendar, iCal ); if ( !message ) //TODO: Error message? return 0; return dynamic_cast<Incidence*>( message->event() ); } Attendee *findMyself( Incidence* incidence, const QString& receiver ) const { Attendee::List attendees = incidence->attendees(); Attendee::List::ConstIterator it; Attendee* myself = 0; // Find myself. There will always be all attendees listed, even if // only I need to answer it. if ( attendees.count() == 1 ) // Only one attendee, that must be me myself = *attendees.begin(); else { for ( it = attendees.begin(); it != attendees.end(); ++it ) { // match only the email part, not the name if( KPIM::compareEmail( (*it)->email(), receiver, false ) ) { // We are the current one, and even the receiver, note // this and quit searching. myself = (*it); break; } } } return myself; } static bool heuristicalRSVP( Incidence *incidence ) { bool rsvp = true; // better send superfluously than not at all Attendee::List attendees = incidence->attendees(); Attendee::List::ConstIterator it; for ( it = attendees.begin(); it != attendees.end(); ++it ) { if ( it == attendees.begin() ) { rsvp = (*it)->RSVP(); // use what the first one has } else { if ( (*it)->RSVP() != rsvp ) { rsvp = true; // they differ, default break; } } } return rsvp; } static Attendee::Role heuristicalRole( Incidence *incidence ) { Attendee::Role role = Attendee::OptParticipant; Attendee::List attendees = incidence->attendees(); Attendee::List::ConstIterator it; for ( it = attendees.begin(); it != attendees.end(); ++it ) { if ( it == attendees.begin() ) { role = (*it)->role(); // use what the first one has } else { if ( (*it)->role() != role ) { role = Attendee::OptParticipant; // they differ, default break; } } } return role; } void setStatusOnMyself( Incidence* incidence, Attendee* myself, Attendee::PartStat status, const QString &receiver ) const { Attendee* newMyself = 0; QString name; QString email; KPIM::getNameAndMail( receiver, name, email ); if ( name.isEmpty() && myself ) name = myself->name(); if ( email.isEmpty()&& myself ) email = myself->email(); Q_ASSERT( !email.isEmpty() ); // delivery must be possible newMyself = new Attendee( name, email, true, // RSVP, otherwise we would not be here status, myself ? myself->role() : heuristicalRole( incidence ), myself ? myself->uid() : QString::null ); // Make sure only ourselves is in the event incidence->clearAttendees(); if( newMyself ) incidence->addAttendee( newMyself ); } bool mail( Incidence* incidence, KMail::Callback& callback ) const { ICalFormat format; format.setTimeZone( KPimPrefs::timezone(), false ); QString msg = format.createScheduleMessage( incidence, Scheduler::Reply ); QString subject; if ( !incidence->summary().isEmpty() ) subject = i18n( "Answer: %1" ).arg( incidence->summary() ); else subject = i18n( "Answer: Incidence with no summary" ); return callback.mailICal( incidence->organizer().fullName(), msg, subject ); } bool saveFile( const QString& receiver, const QString& iCal, const QString& type ) const { KTempFile file( locateLocal( "data", "korganizer/income." + type + '/', true ) ); QTextStream* ts = file.textStream(); if ( !ts ) { KMessageBox::error( 0, i18n("Could not save file to KOrganizer") ); return false; } ts->setEncoding( QTextStream::UnicodeUTF8 ); (*ts) << receiver << '\n' << iCal; return true; } bool handleInvitation( const QString& iCal, Attendee::PartStat status, KMail::Callback &callback ) const { bool ok = true; const QString receiver = callback.receiver(); if ( receiver.isEmpty() ) // Must be some error. Still return true though, since we did handle it return true; // First, save it for KOrganizer to handle QString dir; if ( status == Attendee::Accepted ) dir = "accepted"; else if ( status == Attendee::Tentative ) dir = "accepted"; else if ( status == Attendee::Declined ) dir = "tentative"; else return true; // unknown status saveFile( receiver, iCal, dir ); // Now produce the return message Incidence* incidence = icalToString( iCal ); if( !incidence ) return false; Attendee *myself = findMyself( incidence, receiver ); if ( ( myself && myself->RSVP() ) || heuristicalRSVP( incidence ) ) { setStatusOnMyself( incidence, myself, status, receiver ); ok = mail( incidence, callback ); } else { ( new KMDeleteMsgCommand( callback.getMsg()->getMsgSerNum() ) )->start(); } delete incidence; return ok; } bool handleIgnore( const QString&, KMail::Callback& c ) const { // simply move the message to trash ( new KMDeleteMsgCommand( c.getMsg()->getMsgSerNum() ) )->start(); return true; } bool handleClick( KMail::Interface::BodyPart *part, const QString &path, KMail::Callback& c ) const { QString iCal = part->asText(); if ( path == "accept" ) return handleInvitation( iCal, Attendee::Accepted, c ); if ( path == "accept_conditionally" ) return handleInvitation( iCal, Attendee::Tentative, c ); if ( path == "ignore" ) return handleIgnore( iCal, c ); if ( path == "decline" ) return handleInvitation( iCal, Attendee::Declined, c ); if ( path == "reply" || path == "cancel" ) // These should just be saved with their type as the dir if ( saveFile( "Receiver Not Searched", iCal, path ) ) ( new KMDeleteMsgCommand( c.getMsg()->getMsgSerNum() ) )->start(); return false; } bool handleContextMenuRequest( KMail::Interface::BodyPart *, const QString &, const QPoint & ) const { return false; } QString statusBarMessage( KMail::Interface::BodyPart *, const QString &path ) const { if ( !path.isEmpty() ) { if ( path == "accept" ) return i18n("Accept incidence"); if ( path == "accept_conditionally" ) return i18n( "Accept incidence conditionally" ); if ( path == "ignore" ) return i18n( "Throw mail away" ); if ( path == "decline" ) return i18n( "Decline incidence" ); if ( path == "check_calendar" ) return i18n("Check my calendar..." ); if ( path == "reply" ) return i18n( "Enter incidence into my calendar" ); if ( path == "cancel" ) return i18n( "Remove incidence from my calendar" ); } return QString::null; } }; class Plugin : public KMail::Interface::BodyPartFormatterPlugin { public: const KMail::Interface::BodyPartFormatter *bodyPartFormatter( int idx ) const { if ( idx == 0 ) return new Formatter(); else return 0; } const char *type( int idx ) const { if ( idx == 0 ) return "text"; else return 0; } const char *subtype( int idx ) const { if ( idx == 0 ) return "calendar"; else return 0; } const KMail::Interface::BodyPartURLHandler * urlHandler( int idx ) const { if ( idx == 0 ) return new UrlHandler(); else return 0; } }; } extern "C" KDE_EXPORT KMail::Interface::BodyPartFormatterPlugin * libkmail_bodypartformatter_text_calendar_create_bodypart_formatter_plugin() { KGlobal::locale()->insertCatalogue( "kmail_text_calendar_plugin" ); return new Plugin(); } <commit_msg>Backport: If a text/calendar part does not have an encoding set, fall back to utf8 as per iCalendar standard, instead of using the KMail fallback encoding.<commit_after>/* This file is part of kdepim. Copyright (c) 2004 Cornelius Schumacher <schumacher@kde.org> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #include <interfaces/bodypartformatter.h> #include <interfaces/bodypart.h> #include <interfaces/bodyparturlhandler.h> #include <khtmlparthtmlwriter.h> #include <libkcal/calendarlocal.h> #include <libkcal/icalformat.h> #include <libkcal/attendee.h> #include <libkcal/incidence.h> #include <libkcal/incidenceformatter.h> #include <kpimprefs.h> // for the timezone #include <kmail/callback.h> #include <kmail/kmmessage.h> #include <kmail/kmcommands.h> #include <email.h> #include <kglobal.h> #include <klocale.h> #include <kstringhandler.h> #include <kglobalsettings.h> #include <kiconloader.h> #include <kdebug.h> #include <kmessagebox.h> #include <kstandarddirs.h> #include <kapplication.h> #include <ktempfile.h> #include <qurl.h> #include <qdir.h> #include <qtextstream.h> #include <kdepimmacros.h> using namespace KCal; namespace { class KMInvitationFormatterHelper : public KCal::InvitationFormatterHelper { public: KMInvitationFormatterHelper( KMail::Interface::BodyPart *bodyPart ) : mBodyPart( bodyPart ) {} virtual QString generateLinkURL( const QString &id ) { return mBodyPart->makeLink( id ); } private: KMail::Interface::BodyPart *mBodyPart; }; class Formatter : public KMail::Interface::BodyPartFormatter { public: Result format( KMail::Interface::BodyPart *bodyPart, KMail::HtmlWriter *writer ) const { if ( !writer ) // Guard against crashes in createReply() return Ok; CalendarLocal cl( KPimPrefs::timezone() ); KMInvitationFormatterHelper helper( bodyPart ); QString source; /* If the bodypart does not have a charset specified, we need to fall back to utf8, not the KMail fallback encoding, so get the contents as binary and decode explicitely. */ if ( bodyPart->contentTypeParameter( "charset").isEmpty() ) { const QByteArray &ba = bodyPart->asBinary(); source = QString::fromUtf8(ba); } else { source = bodyPart->asText(); } QString html = IncidenceFormatter::formatICalInvitation( source, &cl, &helper ); if ( html.isEmpty() ) return AsIcon; writer->queue( html ); return Ok; } }; class UrlHandler : public KMail::Interface::BodyPartURLHandler { public: UrlHandler() { kdDebug() << "UrlHandler() (iCalendar)" << endl; } Incidence* icalToString( const QString& iCal ) const { CalendarLocal calendar( KPimPrefs::timezone() ) ; ICalFormat format; ScheduleMessage *message = format.parseScheduleMessage( &calendar, iCal ); if ( !message ) //TODO: Error message? return 0; return dynamic_cast<Incidence*>( message->event() ); } Attendee *findMyself( Incidence* incidence, const QString& receiver ) const { Attendee::List attendees = incidence->attendees(); Attendee::List::ConstIterator it; Attendee* myself = 0; // Find myself. There will always be all attendees listed, even if // only I need to answer it. if ( attendees.count() == 1 ) // Only one attendee, that must be me myself = *attendees.begin(); else { for ( it = attendees.begin(); it != attendees.end(); ++it ) { // match only the email part, not the name if( KPIM::compareEmail( (*it)->email(), receiver, false ) ) { // We are the current one, and even the receiver, note // this and quit searching. myself = (*it); break; } } } return myself; } static bool heuristicalRSVP( Incidence *incidence ) { bool rsvp = true; // better send superfluously than not at all Attendee::List attendees = incidence->attendees(); Attendee::List::ConstIterator it; for ( it = attendees.begin(); it != attendees.end(); ++it ) { if ( it == attendees.begin() ) { rsvp = (*it)->RSVP(); // use what the first one has } else { if ( (*it)->RSVP() != rsvp ) { rsvp = true; // they differ, default break; } } } return rsvp; } static Attendee::Role heuristicalRole( Incidence *incidence ) { Attendee::Role role = Attendee::OptParticipant; Attendee::List attendees = incidence->attendees(); Attendee::List::ConstIterator it; for ( it = attendees.begin(); it != attendees.end(); ++it ) { if ( it == attendees.begin() ) { role = (*it)->role(); // use what the first one has } else { if ( (*it)->role() != role ) { role = Attendee::OptParticipant; // they differ, default break; } } } return role; } void setStatusOnMyself( Incidence* incidence, Attendee* myself, Attendee::PartStat status, const QString &receiver ) const { Attendee* newMyself = 0; QString name; QString email; KPIM::getNameAndMail( receiver, name, email ); if ( name.isEmpty() && myself ) name = myself->name(); if ( email.isEmpty()&& myself ) email = myself->email(); Q_ASSERT( !email.isEmpty() ); // delivery must be possible newMyself = new Attendee( name, email, true, // RSVP, otherwise we would not be here status, myself ? myself->role() : heuristicalRole( incidence ), myself ? myself->uid() : QString::null ); // Make sure only ourselves is in the event incidence->clearAttendees(); if( newMyself ) incidence->addAttendee( newMyself ); } bool mail( Incidence* incidence, KMail::Callback& callback ) const { ICalFormat format; format.setTimeZone( KPimPrefs::timezone(), false ); QString msg = format.createScheduleMessage( incidence, Scheduler::Reply ); QString subject; if ( !incidence->summary().isEmpty() ) subject = i18n( "Answer: %1" ).arg( incidence->summary() ); else subject = i18n( "Answer: Incidence with no summary" ); return callback.mailICal( incidence->organizer().fullName(), msg, subject ); } bool saveFile( const QString& receiver, const QString& iCal, const QString& type ) const { KTempFile file( locateLocal( "data", "korganizer/income." + type + '/', true ) ); QTextStream* ts = file.textStream(); if ( !ts ) { KMessageBox::error( 0, i18n("Could not save file to KOrganizer") ); return false; } ts->setEncoding( QTextStream::UnicodeUTF8 ); (*ts) << receiver << '\n' << iCal; return true; } bool handleInvitation( const QString& iCal, Attendee::PartStat status, KMail::Callback &callback ) const { bool ok = true; const QString receiver = callback.receiver(); if ( receiver.isEmpty() ) // Must be some error. Still return true though, since we did handle it return true; // First, save it for KOrganizer to handle QString dir; if ( status == Attendee::Accepted ) dir = "accepted"; else if ( status == Attendee::Tentative ) dir = "accepted"; else if ( status == Attendee::Declined ) dir = "tentative"; else return true; // unknown status saveFile( receiver, iCal, dir ); // Now produce the return message Incidence* incidence = icalToString( iCal ); if( !incidence ) return false; Attendee *myself = findMyself( incidence, receiver ); if ( ( myself && myself->RSVP() ) || heuristicalRSVP( incidence ) ) { setStatusOnMyself( incidence, myself, status, receiver ); ok = mail( incidence, callback ); } else { ( new KMDeleteMsgCommand( callback.getMsg()->getMsgSerNum() ) )->start(); } delete incidence; return ok; } bool handleIgnore( const QString&, KMail::Callback& c ) const { // simply move the message to trash ( new KMDeleteMsgCommand( c.getMsg()->getMsgSerNum() ) )->start(); return true; } bool handleClick( KMail::Interface::BodyPart *part, const QString &path, KMail::Callback& c ) const { QString iCal = part->asText(); if ( path == "accept" ) return handleInvitation( iCal, Attendee::Accepted, c ); if ( path == "accept_conditionally" ) return handleInvitation( iCal, Attendee::Tentative, c ); if ( path == "ignore" ) return handleIgnore( iCal, c ); if ( path == "decline" ) return handleInvitation( iCal, Attendee::Declined, c ); if ( path == "reply" || path == "cancel" ) // These should just be saved with their type as the dir if ( saveFile( "Receiver Not Searched", iCal, path ) ) ( new KMDeleteMsgCommand( c.getMsg()->getMsgSerNum() ) )->start(); return false; } bool handleContextMenuRequest( KMail::Interface::BodyPart *, const QString &, const QPoint & ) const { return false; } QString statusBarMessage( KMail::Interface::BodyPart *, const QString &path ) const { if ( !path.isEmpty() ) { if ( path == "accept" ) return i18n("Accept incidence"); if ( path == "accept_conditionally" ) return i18n( "Accept incidence conditionally" ); if ( path == "ignore" ) return i18n( "Throw mail away" ); if ( path == "decline" ) return i18n( "Decline incidence" ); if ( path == "check_calendar" ) return i18n("Check my calendar..." ); if ( path == "reply" ) return i18n( "Enter incidence into my calendar" ); if ( path == "cancel" ) return i18n( "Remove incidence from my calendar" ); } return QString::null; } }; class Plugin : public KMail::Interface::BodyPartFormatterPlugin { public: const KMail::Interface::BodyPartFormatter *bodyPartFormatter( int idx ) const { if ( idx == 0 ) return new Formatter(); else return 0; } const char *type( int idx ) const { if ( idx == 0 ) return "text"; else return 0; } const char *subtype( int idx ) const { if ( idx == 0 ) return "calendar"; else return 0; } const KMail::Interface::BodyPartURLHandler * urlHandler( int idx ) const { if ( idx == 0 ) return new UrlHandler(); else return 0; } }; } extern "C" KDE_EXPORT KMail::Interface::BodyPartFormatterPlugin * libkmail_bodypartformatter_text_calendar_create_bodypart_formatter_plugin() { KGlobal::locale()->insertCatalogue( "kmail_text_calendar_plugin" ); return new Plugin(); } <|endoftext|>
<commit_before>#pragma once #include <stdint.h> #include "mrboom.h" #include "common.hpp" #ifndef DEBUG #define NDEBUG #endif #include "assert.h" #ifdef __cplusplus extern "C" { #endif #define DELTA_X 3 #define DELTA_Y 14 #define COUNTDOWN_DURATON 256 #define CELLPIXELSSIZE 16 #define grid_size_x_with_padding (32) #define grid_size_x (grid_size_x_with_padding - 13) #define grid_size_y (13) #define NUMBER_OF_CELLS (grid_size_x * grid_size_y) #define GETXPIXELSTOCENTEROFCELL(player) (-7 + ((m.donnee[player] + DELTA_X) % CELLPIXELSSIZE)) #define GETYPIXELSTOCENTEROFCELL(player) (-7 + ((m.donnee[nb_dyna + player] + DELTA_Y) % CELLPIXELSSIZE)) #define CELLINDEX(cellx, celly) (((celly) * grid_size_x) + (cellx)) #define CELLX(cell) (cell % grid_size_x) #define CELLY(cell) (cell / grid_size_x) #define CELLXWITHPADDING(cell) (cell % grid_size_x_with_padding) #define CELLYWITHPADDING(cell) (cell / grid_size_x_with_padding) #define TRAVELCOST_CANTGO 9999 #define FLAME_DURATION (16 * 5 + 6 * 4 * 2) #define MAX_PIXELS_PER_FRAME 8 enum Bonus { no_bonus, bonus_bomb, bonus_flame, bonus_skull, bonus_bulletproofjacket, bonus_heart, bonus_remote, bonus_push, bonus_roller, bonus_time, bonus_tribomb, bonus_banana, bonus_egg }; bool someHumanPlayersAlive(); bool someHumanPlayersNotDead(); bool isInTheApocalypse(); bool isAlive(int player); bool isAIActiveForPlayer(int player); void addOneAIPlayer(); void addXAIPlayers(int x); void pressStart(); void pressESC(); bool inline hasKangaroo(int player) { return(m.lapipipino[player] == 1); } bool hasRemote(int player); bool hasRollers(int player); bool hasPush(int player); bool hasTriBomb(int player); bool hasAnyDisease(int player); bool hasSlowDisease(int player); bool hasSpeedDisease(int player); bool hasInvertedDisease(int player); bool hasDiarrheaDisease(int player); bool hasSmallBombDisease(int player); bool hasConstipationDisease(int player); void setDisease(int player, int disease, int duration); int nbBombsLeft(int player); bool bonusPlayerWouldLike(int player, enum Bonus bonus); int numberOfPlayers(); bool inTheMenu(); bool isGameActive(); bool isAboutToWin(); bool isDrawGame(); bool won(); void activeCheatMode(); void activeApocalypse(); bool isApocalypseSoon(); bool playerGotDisease(); void setNoMonsterMode(bool on); int invincibility(int player); int framesToCrossACell(int player); int pixelsPerFrame(int player); int inline frameNumber() { return(m.changement); } void setFrameNumber(int frame); int flameSize(int player); void chooseLevel(int level); bool replay(); int level(); void setTeamMode(int teamMode); int teamMode(); void setAutofire(bool on); bool autofire(); void pauseGameButton(); bool isGamePaused(); bool isGameUnPaused(); int xPlayer(int player); int yPlayer(int player); int cellPlayer(int player); bool tracesDecisions(int player); bool isInMiddleOfCell(int player); int dangerousCellForMonster(int player); int victories(int player); int inline getAdderX(int player) { int sign = GETXPIXELSTOCENTEROFCELL(player) < 0 ? -1 : 1; return((abs(GETXPIXELSTOCENTEROFCELL(player) * framesToCrossACell(player)) / CELLPIXELSSIZE) * sign); } int inline getAdderY(int player) { int sign = GETYPIXELSTOCENTEROFCELL(player) < 0 ? -1 : 1; return((abs(GETYPIXELSTOCENTEROFCELL(player) * framesToCrossACell(player)) / CELLPIXELSSIZE) * sign); } bool isSuicideOK(int player); int nbLives(int player); enum playerKind { player_team1 = 1, player_team2 = 2, player_team3 = 4, player_team4 = 8, player_team5 = 16, player_team6 = 32, player_team7 = 64, player_team8 = 128, monster_team = 256 }; enum playerKind inline teamOfPlayer(int player) { if (player >= numberOfPlayers()) { return(monster_team); } else { return(static_cast <playerKind>(1 << m.team[player])); } } int getInputForPlayer(unsigned int player); int latestWinner(); bool sameTeamWin(int player); void addTeamWin(); #ifdef __cplusplus } #endif <commit_msg>Revert Helper: Workaround gcc 7.5.0 division bug (#79) (#80)<commit_after>#pragma once #include <stdint.h> #include "mrboom.h" #include "common.hpp" #ifndef DEBUG #define NDEBUG #endif #include "assert.h" #ifdef __cplusplus extern "C" { #endif #define DELTA_X 3 #define DELTA_Y 14 #define COUNTDOWN_DURATON 256 #define CELLPIXELSSIZE 16 #define grid_size_x_with_padding (32) #define grid_size_x (grid_size_x_with_padding - 13) #define grid_size_y (13) #define NUMBER_OF_CELLS (grid_size_x * grid_size_y) #define GETXPIXELSTOCENTEROFCELL(player) (-7 + ((m.donnee[player] + DELTA_X) % CELLPIXELSSIZE)) #define GETYPIXELSTOCENTEROFCELL(player) (-7 + ((m.donnee[nb_dyna + player] + DELTA_Y) % CELLPIXELSSIZE)) #define CELLINDEX(cellx, celly) (((celly) * grid_size_x) + (cellx)) #define CELLX(cell) (cell % grid_size_x) #define CELLY(cell) (cell / grid_size_x) #define CELLXWITHPADDING(cell) (cell % grid_size_x_with_padding) #define CELLYWITHPADDING(cell) (cell / grid_size_x_with_padding) #define TRAVELCOST_CANTGO 9999 #define FLAME_DURATION (16 * 5 + 6 * 4 * 2) #define MAX_PIXELS_PER_FRAME 8 enum Bonus { no_bonus, bonus_bomb, bonus_flame, bonus_skull, bonus_bulletproofjacket, bonus_heart, bonus_remote, bonus_push, bonus_roller, bonus_time, bonus_tribomb, bonus_banana, bonus_egg }; bool someHumanPlayersAlive(); bool someHumanPlayersNotDead(); bool isInTheApocalypse(); bool isAlive(int player); bool isAIActiveForPlayer(int player); void addOneAIPlayer(); void addXAIPlayers(int x); void pressStart(); void pressESC(); bool inline hasKangaroo(int player) { return(m.lapipipino[player] == 1); } bool hasRemote(int player); bool hasRollers(int player); bool hasPush(int player); bool hasTriBomb(int player); bool hasAnyDisease(int player); bool hasSlowDisease(int player); bool hasSpeedDisease(int player); bool hasInvertedDisease(int player); bool hasDiarrheaDisease(int player); bool hasSmallBombDisease(int player); bool hasConstipationDisease(int player); void setDisease(int player, int disease, int duration); int nbBombsLeft(int player); bool bonusPlayerWouldLike(int player, enum Bonus bonus); int numberOfPlayers(); bool inTheMenu(); bool isGameActive(); bool isAboutToWin(); bool isDrawGame(); bool won(); void activeCheatMode(); void activeApocalypse(); bool isApocalypseSoon(); bool playerGotDisease(); void setNoMonsterMode(bool on); int invincibility(int player); int framesToCrossACell(int player); int pixelsPerFrame(int player); int inline frameNumber() { return(m.changement); } void setFrameNumber(int frame); int flameSize(int player); void chooseLevel(int level); bool replay(); int level(); void setTeamMode(int teamMode); int teamMode(); void setAutofire(bool on); bool autofire(); void pauseGameButton(); bool isGamePaused(); bool isGameUnPaused(); int xPlayer(int player); int yPlayer(int player); int cellPlayer(int player); bool tracesDecisions(int player); bool isInMiddleOfCell(int player); int dangerousCellForMonster(int player); int victories(int player); int inline getAdderX(int player) { return(GETXPIXELSTOCENTEROFCELL(player) * framesToCrossACell(player) / CELLPIXELSSIZE); } int inline getAdderY(int player) { return(GETYPIXELSTOCENTEROFCELL(player) * framesToCrossACell(player) / CELLPIXELSSIZE); } bool isSuicideOK(int player); int nbLives(int player); enum playerKind { player_team1 = 1, player_team2 = 2, player_team3 = 4, player_team4 = 8, player_team5 = 16, player_team6 = 32, player_team7 = 64, player_team8 = 128, monster_team = 256 }; enum playerKind inline teamOfPlayer(int player) { if (player >= numberOfPlayers()) { return(monster_team); } else { return(static_cast <playerKind>(1 << m.team[player])); } } int getInputForPlayer(unsigned int player); int latestWinner(); bool sameTeamWin(int player); void addTeamWin(); #ifdef __cplusplus } #endif <|endoftext|>
<commit_before>/* * Copyright (c) 2008,2009, University of California, Los Angeles 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 NLnetLabs 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. */ // Modified: Jonathan Park (jpark@cs.ucla.edu) #include <bgpparser.h> #include "MRTCommonHeader.h" #include "MRTBgp4MPStateChange.h" #include "MRTBgp4MPStateChangeAS4.h" #include "MRTBgp4MPMessage.h" #include "MRTBgp4MPMessageAS4.h" #include "MRTBgp4MPEntry.h" #include "MRTBgp4MPSnapshot.h" #include "MRTTblDump.h" #include "MRTTblDumpV2PeerIndexTbl.h" #include "MRTTblDumpV2RibHeader.h" #include "MRTTblDumpV2RibIPv4Unicast.h" #include "MRTTblDumpV2RibIPv4Multicast.h" #include "MRTTblDumpV2RibIPv6Unicast.h" #include "MRTTblDumpV2RibIPv6Multicast.h" #include "MRTTblDumpV2RibGeneric.h" #include "BGPCommonHeader.h" #include <Exceptions.h> using namespace std; #include <boost/iostreams/read.hpp> #include <boost/iostreams/skip.hpp> #include <boost/iostreams/device/array.hpp> #include <boost/iostreams/stream.hpp> namespace io = boost::iostreams; log4cxx::LoggerPtr MRTCommonHeader::Logger = log4cxx::Logger::getLogger( "bgpparser.MRTCommonHeader" ); MRTCommonHeader::MRTCommonHeader(void) { /* nothing */ throw std::exception( ); } MRTCommonHeader::MRTCommonHeader( istream &input ) { int len=io::read( input, reinterpret_cast<char*>(&pkt), sizeof(MRTCommonHeaderPacket) ); if( len<0 ) throw EOFException( ); if( len!=sizeof(MRTCommonHeaderPacket) ) throw MRTException( "MRT format error" ); timestamp = ntohl(pkt.timestamp); type = ntohs(pkt.type); subtype = ntohs(pkt.subtype); length = ntohl(pkt.length); if( length==0 ) return; data=boost::shared_ptr<char>( new char[length] ); len=io::read( input, data.get(), length ); if( len!=length ) { LOG4CXX_ERROR(Logger, "MRT length field = " << (int)length << ", but could read only " << (int)len << " bytes" ); throw MRTException( "MRT read error" ); } } MRTCommonHeader::~MRTCommonHeader(void) { /* nothing */ } time_t MRTCommonHeader::getTimestamp(void) const { return timestamp; } uint16_t MRTCommonHeader::getType(void) const { return type; } uint16_t MRTCommonHeader::getSubType(void) const { return subtype; } uint32_t MRTCommonHeader::getLength(void) const { return length; } /* * Factory method for creating MRTMessages */ MRTMessagePtr MRTCommonHeader::newMessage( istream &input ) { LOG4CXX_TRACE( Logger, "==> MRTCommonHeader::newMessage( istream &input )" ); MRTMessagePtr msg; MRTMessagePtr header( new MRTCommonHeader(input) ); msg=header; LOG4CXX_DEBUG( Logger, "Type: " << (int)header->getType() ); LOG4CXX_DEBUG( Logger, "SubType: " << (int)header->getSubType() ); LOG4CXX_DEBUG( Logger, "Length: " << (int)header->getLength() ); io::stream<io::array_source> in( header->data.get(), header->length ); /* only accept BGP4MP message and TABLE_DUMP message types */ if ((header->getType() != BGP4MP) && /*(header.getType() != BGP4MP_ET) && */ (header->getType() != TABLE_DUMP) && (header->getType() != TABLE_DUMP_V2) ) { LOG4CXX_ERROR(Logger,"Nonsupported MRT type ["<<(int)header->getType()<<"]"); // return msg; } try { if( header->getType( ) == BGP4MP ) { switch( header->getSubType( ) ) { case BGP4MP_STATE_CHANGE: LOG4CXX_TRACE(Logger,"MRTBgp4MPStateChange"); msg = MRTMessagePtr( new MRTBgp4MPStateChange(*header, in) ); break; case BGP4MP_STATE_CHANGE_AS4: LOG4CXX_TRACE(Logger,"MRTBgp4MPStateChange"); msg = MRTMessagePtr( new MRTBgp4MPStateChangeAS4(*header, in) ); break; case BGP4MP_MESSAGE: LOG4CXX_TRACE(Logger,"MRTBgp4MPMessage"); msg = MRTMessagePtr( new MRTBgp4MPMessage(*header, in) ); break; case BGP4MP_MESSAGE_AS4: LOG4CXX_TRACE(Logger,"MRTBgp4MPMessage"); msg = MRTMessagePtr( new MRTBgp4MPMessageAS4(*header, in) ); break; case BGP4MP_ENTRY: //PRINT_DBG(" Case BGP4MP_ENTRY"); //msg = new MRTBgp4MPEntry(ptr); /* not supported yet */ //break; case BGP4MP_SNAPSHOT: //PRINT_DBG(" Case BGP4MP_SNAPSHOT"); //msg = new MRTBgp4MPSnapshot(ptr); /* not supported yet */ //break; default: LOG4CXX_ERROR( Logger, "unrecognized subtype ["<< (int)header->getSubType() <<"] for bgp4mp." ); break; } } else if( (header->getType( ) == TABLE_DUMP) || (header->getType( ) == TABLE_DUMP_V2) ) { switch( header->getType( ) ) { case TABLE_DUMP: msg = MRTMessagePtr( new MRTTblDump(*header,in) ); LOG4CXX_TRACE(Logger,"MRTTblDump"); break; case TABLE_DUMP_V2: switch( header->getSubType( ) ) { case PEER_INDEX_TABLE: { LOG4CXX_TRACE(Logger,"MRTTblDumpV2PeerIndexTbl"); MRTTblDumpV2PeerIndexTblPtr indexTbl( new MRTTblDumpV2PeerIndexTbl(*header, in) ); MRTTblDumpV2RibHeader::setPeerIndexTbl( indexTbl ); msg = MRTMessagePtr( indexTbl ); break; } case RIB_IPV4_UNICAST: { LOG4CXX_TRACE(Logger,"MRTTblDumpV2RibIPv4Unicast"); msg = MRTMessagePtr( new MRTTblDumpV2RibIPv4Unicast(*header, in) ); break; } case RIB_IPV4_MULTICAST: { LOG4CXX_TRACE(Logger,"MRTTblDumpV2RibIPv4Multicast"); msg = MRTMessagePtr( new MRTTblDumpV2RibIPv4Multicast(*header, in) ); break; } case RIB_IPV6_UNICAST: { LOG4CXX_TRACE(Logger,"MRTTblDumpV2RibIPv6Unicast"); msg = MRTMessagePtr( new MRTTblDumpV2RibIPv6Unicast(*header, in) ); break; } case RIB_IPV6_MULTICAST: { LOG4CXX_TRACE(Logger,"MRTTblDumpV2RibIPv6Multicast"); msg = MRTMessagePtr( new MRTTblDumpV2RibIPv6Multicast(*header, in) ); break; } case RIB_GENERIC: { LOG4CXX_TRACE(Logger,"MRTTblDumpV2RibGeneric"); msg = MRTMessagePtr( new MRTTblDumpV2RibGeneric(*header, in) ); break; } default: LOG4CXX_ERROR( Logger, "unrecognized subtype ["<< (int)header->getSubType() <<"] for table-dump-v2." ); break; } break; default: LOG4CXX_ERROR( Logger, "unrecognized type ["<< (int)header->getType() <<"] for table-dump-v2" ); break; } } } catch( BGPError &e ) { LOG4CXX_ERROR( Logger, "Error parsing MRT message. Setting type to MRT_INVALID" ); header->type=MRT_INVALID; msg=header; } LOG4CXX_TRACE( Logger, "<== MRTCommonHeader::newMessage( istream &input )" ); return msg; } <commit_msg>Handling stream errors happened during MRT processing in the same way as BGPError exception (return MRT_INVALID)<commit_after>/* * Copyright (c) 2008,2009, University of California, Los Angeles 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 NLnetLabs 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. */ // Modified: Jonathan Park (jpark@cs.ucla.edu) #include <bgpparser.h> #include "MRTCommonHeader.h" #include "MRTBgp4MPStateChange.h" #include "MRTBgp4MPStateChangeAS4.h" #include "MRTBgp4MPMessage.h" #include "MRTBgp4MPMessageAS4.h" #include "MRTBgp4MPEntry.h" #include "MRTBgp4MPSnapshot.h" #include "MRTTblDump.h" #include "MRTTblDumpV2PeerIndexTbl.h" #include "MRTTblDumpV2RibHeader.h" #include "MRTTblDumpV2RibIPv4Unicast.h" #include "MRTTblDumpV2RibIPv4Multicast.h" #include "MRTTblDumpV2RibIPv6Unicast.h" #include "MRTTblDumpV2RibIPv6Multicast.h" #include "MRTTblDumpV2RibGeneric.h" #include "BGPCommonHeader.h" #include <Exceptions.h> using namespace std; #include <boost/iostreams/read.hpp> #include <boost/iostreams/skip.hpp> #include <boost/iostreams/device/array.hpp> #include <boost/iostreams/stream.hpp> namespace io = boost::iostreams; log4cxx::LoggerPtr MRTCommonHeader::Logger = log4cxx::Logger::getLogger( "bgpparser.MRTCommonHeader" ); MRTCommonHeader::MRTCommonHeader(void) { /* nothing */ throw std::exception( ); } MRTCommonHeader::MRTCommonHeader( istream &input ) { int len=io::read( input, reinterpret_cast<char*>(&pkt), sizeof(MRTCommonHeaderPacket) ); if( len<0 ) throw EOFException( ); if( len!=sizeof(MRTCommonHeaderPacket) ) throw MRTException( "MRT format error" ); timestamp = ntohl(pkt.timestamp); type = ntohs(pkt.type); subtype = ntohs(pkt.subtype); length = ntohl(pkt.length); if( length==0 ) return; data=boost::shared_ptr<char>( new char[length] ); len=io::read( input, data.get(), length ); if( len!=length ) { LOG4CXX_ERROR(Logger, "MRT length field = " << (int)length << ", but could read only " << (int)len << " bytes" ); throw MRTException( "MRT read error" ); } } MRTCommonHeader::~MRTCommonHeader(void) { /* nothing */ } time_t MRTCommonHeader::getTimestamp(void) const { return timestamp; } uint16_t MRTCommonHeader::getType(void) const { return type; } uint16_t MRTCommonHeader::getSubType(void) const { return subtype; } uint32_t MRTCommonHeader::getLength(void) const { return length; } /* * Factory method for creating MRTMessages */ MRTMessagePtr MRTCommonHeader::newMessage( istream &input ) { LOG4CXX_TRACE( Logger, "==> MRTCommonHeader::newMessage( istream &input )" ); MRTMessagePtr msg; MRTMessagePtr header( new MRTCommonHeader(input) ); msg=header; LOG4CXX_DEBUG( Logger, "Type: " << (int)header->getType() ); LOG4CXX_DEBUG( Logger, "SubType: " << (int)header->getSubType() ); LOG4CXX_DEBUG( Logger, "Length: " << (int)header->getLength() ); io::stream<io::array_source> in( header->data.get(), header->length ); /* only accept BGP4MP message and TABLE_DUMP message types */ if ((header->getType() != BGP4MP) && /*(header.getType() != BGP4MP_ET) && */ (header->getType() != TABLE_DUMP) && (header->getType() != TABLE_DUMP_V2) ) { LOG4CXX_ERROR(Logger,"Nonsupported MRT type ["<<(int)header->getType()<<"]"); // return msg; } try { if( header->getType( ) == BGP4MP ) { switch( header->getSubType( ) ) { case BGP4MP_STATE_CHANGE: LOG4CXX_TRACE(Logger,"MRTBgp4MPStateChange"); msg = MRTMessagePtr( new MRTBgp4MPStateChange(*header, in) ); break; case BGP4MP_STATE_CHANGE_AS4: LOG4CXX_TRACE(Logger,"MRTBgp4MPStateChange"); msg = MRTMessagePtr( new MRTBgp4MPStateChangeAS4(*header, in) ); break; case BGP4MP_MESSAGE: LOG4CXX_TRACE(Logger,"MRTBgp4MPMessage"); msg = MRTMessagePtr( new MRTBgp4MPMessage(*header, in) ); break; case BGP4MP_MESSAGE_AS4: LOG4CXX_TRACE(Logger,"MRTBgp4MPMessage"); msg = MRTMessagePtr( new MRTBgp4MPMessageAS4(*header, in) ); break; case BGP4MP_ENTRY: //PRINT_DBG(" Case BGP4MP_ENTRY"); //msg = new MRTBgp4MPEntry(ptr); /* not supported yet */ //break; case BGP4MP_SNAPSHOT: //PRINT_DBG(" Case BGP4MP_SNAPSHOT"); //msg = new MRTBgp4MPSnapshot(ptr); /* not supported yet */ //break; default: LOG4CXX_ERROR( Logger, "unrecognized subtype ["<< (int)header->getSubType() <<"] for bgp4mp." ); break; } } else if( (header->getType( ) == TABLE_DUMP) || (header->getType( ) == TABLE_DUMP_V2) ) { switch( header->getType( ) ) { case TABLE_DUMP: msg = MRTMessagePtr( new MRTTblDump(*header,in) ); LOG4CXX_TRACE(Logger,"MRTTblDump"); break; case TABLE_DUMP_V2: switch( header->getSubType( ) ) { case PEER_INDEX_TABLE: { LOG4CXX_TRACE(Logger,"MRTTblDumpV2PeerIndexTbl"); MRTTblDumpV2PeerIndexTblPtr indexTbl( new MRTTblDumpV2PeerIndexTbl(*header, in) ); MRTTblDumpV2RibHeader::setPeerIndexTbl( indexTbl ); msg = MRTMessagePtr( indexTbl ); break; } case RIB_IPV4_UNICAST: { LOG4CXX_TRACE(Logger,"MRTTblDumpV2RibIPv4Unicast"); msg = MRTMessagePtr( new MRTTblDumpV2RibIPv4Unicast(*header, in) ); break; } case RIB_IPV4_MULTICAST: { LOG4CXX_TRACE(Logger,"MRTTblDumpV2RibIPv4Multicast"); msg = MRTMessagePtr( new MRTTblDumpV2RibIPv4Multicast(*header, in) ); break; } case RIB_IPV6_UNICAST: { LOG4CXX_TRACE(Logger,"MRTTblDumpV2RibIPv6Unicast"); msg = MRTMessagePtr( new MRTTblDumpV2RibIPv6Unicast(*header, in) ); break; } case RIB_IPV6_MULTICAST: { LOG4CXX_TRACE(Logger,"MRTTblDumpV2RibIPv6Multicast"); msg = MRTMessagePtr( new MRTTblDumpV2RibIPv6Multicast(*header, in) ); break; } case RIB_GENERIC: { LOG4CXX_TRACE(Logger,"MRTTblDumpV2RibGeneric"); msg = MRTMessagePtr( new MRTTblDumpV2RibGeneric(*header, in) ); break; } default: LOG4CXX_ERROR( Logger, "unrecognized subtype ["<< (int)header->getSubType() <<"] for table-dump-v2." ); break; } break; default: LOG4CXX_ERROR( Logger, "unrecognized type ["<< (int)header->getType() <<"] for table-dump-v2" ); break; } } } catch( std::istream::failure e ) { LOG4CXX_ERROR( Logger, "Error parsing MRT message (stream error). Setting type to MRT_INVALID" ); header->type=MRT_INVALID; msg=header; } catch( BGPError &e ) { LOG4CXX_ERROR( Logger, "Error parsing MRT message (format error). Setting type to MRT_INVALID" ); header->type=MRT_INVALID; msg=header; } LOG4CXX_TRACE( Logger, "<== MRTCommonHeader::newMessage( istream &input )" ); return msg; } <|endoftext|>
<commit_before>/* * yosys -- Yosys Open SYnthesis Suite * * Copyright (C) 2012 Clifford Wolf <clifford@clifford.at> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * */ #include "kernel/yosys.h" #include "kernel/sigtools.h" USING_YOSYS_NAMESPACE PRIVATE_NAMESPACE_BEGIN // for peepopt_pm bool did_something; #include "passes/pmgen/xilinx_srl_pm.h" #include "passes/pmgen/ice40_dsp_pm.h" #include "passes/pmgen/peepopt_pm.h" void run_fixed(xilinx_srl_pm &pm) { auto &st = pm.st_fixed; auto &ud = pm.ud_fixed; auto param_def = [&ud](Cell *cell, IdString param) { auto def = ud.default_params.at(std::make_pair(cell->type,param)); return cell->parameters.at(param, def); }; log("Found fixed chain of length %d (%s):\n", GetSize(ud.longest_chain), log_id(st.first->type)); auto last_cell = ud.longest_chain.back(); SigSpec initval; for (auto cell : ud.longest_chain) { log_debug(" %s\n", log_id(cell)); if (cell->type.in(ID($_DFF_N_), ID($_DFF_P_), ID($_DFFE_NN_), ID($_DFFE_NP_), ID($_DFFE_PN_), ID($_DFFE_PP_))) { SigBit Q = cell->getPort(ID(Q)); log_assert(Q.wire); auto it = Q.wire->attributes.find(ID(init)); if (it != Q.wire->attributes.end()) { initval.append(it->second[Q.offset]); } else initval.append(State::Sx); } else if (cell->type.in(ID(FDRE), ID(FDRE_1))) initval.append(param_def(cell, ID(INIT))); else log_abort(); if (cell != last_cell) pm.autoremove(cell); } Cell *c = last_cell; SigBit Q = st.first->getPort(ID(Q)); c->setPort(ID(Q), Q); if (c->type.in(ID($_DFF_N_), ID($_DFF_P_), ID($_DFFE_NN_), ID($_DFFE_NP_), ID($_DFFE_PN_), ID($_DFFE_PP_), ID(FDRE), ID(FDRE_1))) { c->parameters.clear(); c->setParam(ID(DEPTH), GetSize(ud.longest_chain)); c->setParam(ID(INIT), initval.as_const()); if (c->type.in(ID($_DFF_P_), ID($_DFFE_PN_), ID($_DFFE_PP_))) c->setParam(ID(CLKPOL), 1); else if (c->type.in(ID($_DFF_N_), ID($DFFE_NN_), ID($_DFFE_NP_), ID(FDRE_1))) c->setParam(ID(CLKPOL), 0); else if (c->type.in(ID(FDRE))) c->setParam(ID(CLKPOL), param_def(c, ID(IS_C_INVERTED)).as_bool() ? 0 : 1); else log_abort(); if (c->type.in(ID($_DFFE_NP_), ID($_DFFE_PP_))) c->setParam(ID(ENPOL), 1); else if (c->type.in(ID($_DFFE_NN_), ID($_DFFE_PN_))) c->setParam(ID(ENPOL), 0); else c->setParam(ID(ENPOL), 2); if (c->type.in(ID($_DFF_N_), ID($_DFF_P_))) c->setPort(ID(E), State::S1); c->setPort(ID(L), GetSize(ud.longest_chain)-1); c->type = ID($__XILINX_SHREG_); } else log_abort(); log(" -> %s (%s)\n", log_id(c), log_id(c->type)); } void run_variable(xilinx_srl_pm &pm) { auto &st = pm.st_variable; auto &ud = pm.ud_variable; log("Found variable chain of length %d (%s):\n", GetSize(ud.chain), log_id(st.first->type)); auto last_cell = ud.chain.back(); SigSpec initval; for (auto cell : ud.chain) { log_debug(" %s\n", log_id(cell)); if (cell->type.in(ID($_DFF_N_), ID($_DFF_P_), ID($_DFFE_NN_), ID($_DFFE_NP_), ID($_DFFE_PN_), ID($_DFFE_PP_))) { SigBit Q = cell->getPort(ID(Q)); log_assert(Q.wire); auto it = Q.wire->attributes.find(ID(init)); if (it != Q.wire->attributes.end()) { initval.append(it->second[Q.offset]); } else initval.append(State::Sx); } else log_abort(); if (cell != last_cell) pm.autoremove(cell); } pm.autoremove(st.shiftx); Cell *c = last_cell; SigBit Q = st.first->getPort(ID(Q)); c->setPort(ID(Q), Q); if (c->type.in(ID($_DFF_N_), ID($_DFF_P_), ID($_DFFE_NN_), ID($_DFFE_NP_), ID($_DFFE_PN_), ID($_DFFE_PP_))) { c->parameters.clear(); c->setParam(ID(DEPTH), GetSize(ud.chain)); c->setParam(ID(INIT), initval.as_const()); if (c->type.in(ID($_DFF_P_), ID($_DFFE_PN_), ID($_DFFE_PP_))) c->setParam(ID(CLKPOL), 1); else if (c->type.in(ID($_DFF_N_), ID($DFFE_NN_), ID($_DFFE_NP_), ID(FDRE_1))) c->setParam(ID(CLKPOL), 0); else log_abort(); if (c->type.in(ID($_DFFE_NP_), ID($_DFFE_PP_))) c->setParam(ID(ENPOL), 1); else if (c->type.in(ID($_DFFE_NN_), ID($_DFFE_PN_))) c->setParam(ID(ENPOL), 0); else c->setParam(ID(ENPOL), 2); if (c->type.in(ID($_DFF_N_), ID($_DFF_P_))) c->setPort(ID(E), State::S1); c->setPort(ID(L), st.shiftx->getPort(ID(B))); c->setPort(ID(Q), st.shiftx->getPort(ID(Y))); c->type = ID($__XILINX_SHREG_); } else log_abort(); log(" -> %s (%s)\n", log_id(c), log_id(c->type)); } struct XilinxSrlPass : public Pass { XilinxSrlPass() : Pass("xilinx_srl", "Xilinx shift register extraction") { } void help() YS_OVERRIDE { // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| log("\n"); log(" xilinx_srl [options] [selection]\n"); log("\n"); log("TODO.\n"); log("\n"); } void execute(std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE { log_header(design, "Executing XILINX_SRL pass (Xilinx shift register extraction).\n"); bool fixed = false; bool variable = false; int minlen = 3; size_t argidx; for (argidx = 1; argidx < args.size(); argidx++) { if (args[argidx] == "-minlen" && argidx+1 < args.size()) { minlen = atoi(args[++argidx].c_str()); continue; } if (args[argidx] == "-fixed") { fixed = true; continue; } if (args[argidx] == "-variable") { variable = true; continue; } break; } extra_args(args, argidx, design); if (!fixed && !variable) log_cmd_error("'-fixed' and/or '-variable' must be specified.\n"); for (auto module : design->selected_modules()) { bool did_something = false; if (fixed) do { auto pm = xilinx_srl_pm(module, module->selected_cells()); pm.ud_fixed.minlen = minlen; // TODO: How to get these automatically? pm.ud_fixed.default_params[std::make_pair(ID(FDRE),ID(INIT))] = State::S0; pm.ud_fixed.default_params[std::make_pair(ID(FDRE),ID(IS_C_INVERTED))] = State::S0; pm.ud_fixed.default_params[std::make_pair(ID(FDRE),ID(IS_D_INVERTED))] = State::S0; pm.ud_fixed.default_params[std::make_pair(ID(FDRE),ID(IS_R_INVERTED))] = State::S0; did_something = pm.run_fixed(run_fixed); } while (did_something); if (variable) do { auto pm = xilinx_srl_pm(module, module->selected_cells()); pm.ud_variable.minlen = minlen; // Since `nusers` does not count module ports as a user, // and since `sigmap` does not always make such ports // the canonical signal.. need to maintain a pool these // ourselves for (auto p : module->ports) { auto w = module->wire(p); if (w->port_output) for (auto b : pm.sigmap(w)) pm.ud_variable.output_bits.insert(b); } did_something = pm.run_variable(run_variable); } while (did_something); } } } XilinxSrlPass; PRIVATE_NAMESPACE_END <commit_msg>Do not run xilinx_srl_pm in fixed loop<commit_after>/* * yosys -- Yosys Open SYnthesis Suite * * Copyright (C) 2012 Clifford Wolf <clifford@clifford.at> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * */ #include "kernel/yosys.h" #include "kernel/sigtools.h" USING_YOSYS_NAMESPACE PRIVATE_NAMESPACE_BEGIN // for peepopt_pm bool did_something; #include "passes/pmgen/xilinx_srl_pm.h" #include "passes/pmgen/ice40_dsp_pm.h" #include "passes/pmgen/peepopt_pm.h" void run_fixed(xilinx_srl_pm &pm) { auto &st = pm.st_fixed; auto &ud = pm.ud_fixed; auto param_def = [&ud](Cell *cell, IdString param) { auto def = ud.default_params.at(std::make_pair(cell->type,param)); return cell->parameters.at(param, def); }; log("Found fixed chain of length %d (%s):\n", GetSize(ud.longest_chain), log_id(st.first->type)); auto last_cell = ud.longest_chain.back(); SigSpec initval; for (auto cell : ud.longest_chain) { log_debug(" %s\n", log_id(cell)); if (cell->type.in(ID($_DFF_N_), ID($_DFF_P_), ID($_DFFE_NN_), ID($_DFFE_NP_), ID($_DFFE_PN_), ID($_DFFE_PP_))) { SigBit Q = cell->getPort(ID(Q)); log_assert(Q.wire); auto it = Q.wire->attributes.find(ID(init)); if (it != Q.wire->attributes.end()) { initval.append(it->second[Q.offset]); } else initval.append(State::Sx); } else if (cell->type.in(ID(FDRE), ID(FDRE_1))) initval.append(param_def(cell, ID(INIT))); else log_abort(); if (cell != last_cell) pm.autoremove(cell); } Cell *c = last_cell; SigBit Q = st.first->getPort(ID(Q)); c->setPort(ID(Q), Q); if (c->type.in(ID($_DFF_N_), ID($_DFF_P_), ID($_DFFE_NN_), ID($_DFFE_NP_), ID($_DFFE_PN_), ID($_DFFE_PP_), ID(FDRE), ID(FDRE_1))) { c->parameters.clear(); c->setParam(ID(DEPTH), GetSize(ud.longest_chain)); c->setParam(ID(INIT), initval.as_const()); if (c->type.in(ID($_DFF_P_), ID($_DFFE_PN_), ID($_DFFE_PP_))) c->setParam(ID(CLKPOL), 1); else if (c->type.in(ID($_DFF_N_), ID($DFFE_NN_), ID($_DFFE_NP_), ID(FDRE_1))) c->setParam(ID(CLKPOL), 0); else if (c->type.in(ID(FDRE))) c->setParam(ID(CLKPOL), param_def(c, ID(IS_C_INVERTED)).as_bool() ? 0 : 1); else log_abort(); if (c->type.in(ID($_DFFE_NP_), ID($_DFFE_PP_))) c->setParam(ID(ENPOL), 1); else if (c->type.in(ID($_DFFE_NN_), ID($_DFFE_PN_))) c->setParam(ID(ENPOL), 0); else c->setParam(ID(ENPOL), 2); if (c->type.in(ID($_DFF_N_), ID($_DFF_P_))) c->setPort(ID(E), State::S1); c->setPort(ID(L), GetSize(ud.longest_chain)-1); c->type = ID($__XILINX_SHREG_); } else log_abort(); log(" -> %s (%s)\n", log_id(c), log_id(c->type)); } void run_variable(xilinx_srl_pm &pm) { auto &st = pm.st_variable; auto &ud = pm.ud_variable; log("Found variable chain of length %d (%s):\n", GetSize(ud.chain), log_id(st.first->type)); auto last_cell = ud.chain.back(); SigSpec initval; for (auto cell : ud.chain) { log_debug(" %s\n", log_id(cell)); if (cell->type.in(ID($_DFF_N_), ID($_DFF_P_), ID($_DFFE_NN_), ID($_DFFE_NP_), ID($_DFFE_PN_), ID($_DFFE_PP_))) { SigBit Q = cell->getPort(ID(Q)); log_assert(Q.wire); auto it = Q.wire->attributes.find(ID(init)); if (it != Q.wire->attributes.end()) { initval.append(it->second[Q.offset]); } else initval.append(State::Sx); } else log_abort(); if (cell != last_cell) pm.autoremove(cell); } pm.autoremove(st.shiftx); Cell *c = last_cell; SigBit Q = st.first->getPort(ID(Q)); c->setPort(ID(Q), Q); if (c->type.in(ID($_DFF_N_), ID($_DFF_P_), ID($_DFFE_NN_), ID($_DFFE_NP_), ID($_DFFE_PN_), ID($_DFFE_PP_))) { c->parameters.clear(); c->setParam(ID(DEPTH), GetSize(ud.chain)); c->setParam(ID(INIT), initval.as_const()); if (c->type.in(ID($_DFF_P_), ID($_DFFE_PN_), ID($_DFFE_PP_))) c->setParam(ID(CLKPOL), 1); else if (c->type.in(ID($_DFF_N_), ID($DFFE_NN_), ID($_DFFE_NP_), ID(FDRE_1))) c->setParam(ID(CLKPOL), 0); else log_abort(); if (c->type.in(ID($_DFFE_NP_), ID($_DFFE_PP_))) c->setParam(ID(ENPOL), 1); else if (c->type.in(ID($_DFFE_NN_), ID($_DFFE_PN_))) c->setParam(ID(ENPOL), 0); else c->setParam(ID(ENPOL), 2); if (c->type.in(ID($_DFF_N_), ID($_DFF_P_))) c->setPort(ID(E), State::S1); c->setPort(ID(L), st.shiftx->getPort(ID(B))); c->setPort(ID(Q), st.shiftx->getPort(ID(Y))); c->type = ID($__XILINX_SHREG_); } else log_abort(); log(" -> %s (%s)\n", log_id(c), log_id(c->type)); } struct XilinxSrlPass : public Pass { XilinxSrlPass() : Pass("xilinx_srl", "Xilinx shift register extraction") { } void help() YS_OVERRIDE { // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| log("\n"); log(" xilinx_srl [options] [selection]\n"); log("\n"); log("TODO.\n"); log("\n"); } void execute(std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE { log_header(design, "Executing XILINX_SRL pass (Xilinx shift register extraction).\n"); bool fixed = false; bool variable = false; int minlen = 3; size_t argidx; for (argidx = 1; argidx < args.size(); argidx++) { if (args[argidx] == "-minlen" && argidx+1 < args.size()) { minlen = atoi(args[++argidx].c_str()); continue; } if (args[argidx] == "-fixed") { fixed = true; continue; } if (args[argidx] == "-variable") { variable = true; continue; } break; } extra_args(args, argidx, design); if (!fixed && !variable) log_cmd_error("'-fixed' and/or '-variable' must be specified.\n"); for (auto module : design->selected_modules()) { auto pm = xilinx_srl_pm(module, module->selected_cells()); pm.ud_fixed.minlen = minlen; if (fixed) { // TODO: How to get these automatically? pm.ud_fixed.default_params[std::make_pair(ID(FDRE),ID(INIT))] = State::S0; pm.ud_fixed.default_params[std::make_pair(ID(FDRE),ID(IS_C_INVERTED))] = State::S0; pm.ud_fixed.default_params[std::make_pair(ID(FDRE),ID(IS_D_INVERTED))] = State::S0; pm.ud_fixed.default_params[std::make_pair(ID(FDRE),ID(IS_R_INVERTED))] = State::S0; pm.run_fixed(run_fixed); } if (variable) { // Since `nusers` does not count module ports as a user, // and since `sigmap` does not always make such ports // the canonical signal.. need to maintain a pool these // ourselves for (auto p : module->ports) { auto w = module->wire(p); if (w->port_output) for (auto b : pm.sigmap(w)) pm.ud_variable.output_bits.insert(b); } pm.run_variable(run_variable); } } } } XilinxSrlPass; PRIVATE_NAMESPACE_END <|endoftext|>
<commit_before>/* * Copyright 2019 ScyllaDB */ /* * This file is part of Scylla. * * Scylla 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. * * Scylla 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 Affero General Public License * along with Scylla. If not, see <http://www.gnu.org/licenses/>. */ #pragma once #include <seastar/http/httpd.hh> #include "seastarx.hh" namespace alternator { // api_error contains a DynamoDB error message to be returned to the user. // It can be returned by value (see executor::request_return_type) or thrown. // The DynamoDB's error messages are described in detail in // https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Programming.Errors.html // An error message has an HTTP code (almost always 400), a type, e.g., // "ResourceNotFoundException", and a human readable message. // Eventually alternator::api_handler will convert a returned or thrown // api_error into a JSON object, and that is returned to the user. class api_error final { public: using status_type = httpd::reply::status_type; status_type _http_code; std::string _type; std::string _msg; api_error(std::string type, std::string msg, status_type http_code = status_type::bad_request) : _http_code(std::move(http_code)) , _type(std::move(type)) , _msg(std::move(msg)) { } // Factory functions for some common types of DynamoDB API errors static api_error validation(std::string msg) { return api_error("ValidationException", std::move(msg)); } static api_error resource_not_found(std::string msg) { return api_error("ResourceNotFoundException", std::move(msg)); } static api_error resource_in_use(std::string msg) { return api_error("ResourceInUseException", std::move(msg)); } static api_error invalid_signature(std::string msg) { return api_error("InvalidSignatureException", std::move(msg)); } static api_error unrecognized_client(std::string msg) { return api_error("UnrecognizedClientException", std::move(msg)); } static api_error unknown_operation(std::string msg) { return api_error("UnknownOperationException", std::move(msg)); } static api_error access_denied(std::string msg) { return api_error("AccessDeniedException", std::move(msg)); } static api_error conditional_check_failed(std::string msg) { return api_error("ConditionalCheckFailedException", std::move(msg)); } static api_error internal(std::string msg) { return api_error("InternalServerError", std::move(msg), reply::status_type::internal_server_error); } }; } <commit_msg>alternator::error: Add a few dynamo exception types<commit_after>/* * Copyright 2019 ScyllaDB */ /* * This file is part of Scylla. * * Scylla 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. * * Scylla 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 Affero General Public License * along with Scylla. If not, see <http://www.gnu.org/licenses/>. */ #pragma once #include <seastar/http/httpd.hh> #include "seastarx.hh" namespace alternator { // api_error contains a DynamoDB error message to be returned to the user. // It can be returned by value (see executor::request_return_type) or thrown. // The DynamoDB's error messages are described in detail in // https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Programming.Errors.html // An error message has an HTTP code (almost always 400), a type, e.g., // "ResourceNotFoundException", and a human readable message. // Eventually alternator::api_handler will convert a returned or thrown // api_error into a JSON object, and that is returned to the user. class api_error final { public: using status_type = httpd::reply::status_type; status_type _http_code; std::string _type; std::string _msg; api_error(std::string type, std::string msg, status_type http_code = status_type::bad_request) : _http_code(std::move(http_code)) , _type(std::move(type)) , _msg(std::move(msg)) { } // Factory functions for some common types of DynamoDB API errors static api_error validation(std::string msg) { return api_error("ValidationException", std::move(msg)); } static api_error resource_not_found(std::string msg) { return api_error("ResourceNotFoundException", std::move(msg)); } static api_error resource_in_use(std::string msg) { return api_error("ResourceInUseException", std::move(msg)); } static api_error invalid_signature(std::string msg) { return api_error("InvalidSignatureException", std::move(msg)); } static api_error unrecognized_client(std::string msg) { return api_error("UnrecognizedClientException", std::move(msg)); } static api_error unknown_operation(std::string msg) { return api_error("UnknownOperationException", std::move(msg)); } static api_error access_denied(std::string msg) { return api_error("AccessDeniedException", std::move(msg)); } static api_error conditional_check_failed(std::string msg) { return api_error("ConditionalCheckFailedException", std::move(msg)); } static api_error expired_iterator(std::string msg) { return api_error("ExpiredIteratorException", std::move(msg)); } static api_error trimmed_data_access_exception(std::string msg) { return api_error("TrimmedDataAccessException", std::move(msg)); } static api_error internal(std::string msg) { return api_error("InternalServerError", std::move(msg), reply::status_type::internal_server_error); } }; } <|endoftext|>
<commit_before>/* * Implementation of graph.h. */ #include "graph.h" #define V_VISITED 1 // for marking the BFT_kmer as visited Graph::Graph(char* bftFileName) { bft = load_BFT(bftFileName); free(bftFileName); } Graph::~Graph() { free_cdbg(bft); } bool Graph::isBFTKmer(char* strKmer) const { uint32_t* colorSet = query_sequence(bft, strKmer, 0.001, false); uint32_t numColors = colorSet[0]; free(colorSet); if(numColors) { return true; } return false; } BFT_kmer* Graph::getBFTKmer(char* strKmer) const { if(isBFTKmer(strKmer)) { return get_kmer(strKmer, bft); } return NULL; } bool Graph::isValidBFTKmer(BFT_kmer* bftKmer) const { if(bftKmer != NULL) { if(is_kmer_in_cdbg(bftKmer)) { return true; } } return false; } void Graph::setMarking() { set_marking(bft); } void Graph::clearMarking() { unset_marking(bft); } void Graph::markBFTKmer(BFT_kmer* bftKmer) { set_flag_kmer(V_VISITED, bftKmer, bft); } bool Graph::isMarkedBFTKmer(BFT_kmer* bftKmer) const { if(get_flag_kmer(bftKmer, bft) == V_VISITED) { return true; } return false; } uint32_t Graph::getNumColors(BFT_kmer* bftKmer) const { uint32_t numColors = 0; BFT_annotation* bftAnno = get_annotation(bftKmer); uint32_t* temp = get_list_id_genomes(bftAnno, bft); numColors = temp[0]; free_BFT_annotation(bftAnno); free(temp); return numColors; } uint32_t Graph::getNumColors() const { return bft->nb_genomes; } uint32_t* Graph::getColors(BFT_kmer* bftKmer) const { BFT_annotation* bftAnno = get_annotation(bftKmer); return get_list_id_genomes(bftAnno, bft); } char* Graph::getColorFilePath(uint32_t colorId) const { return bft->filenames[colorId]; } BFT_kmer* Graph::getSuffixNeighbors(BFT_kmer* bftKmer) const { if(is_kmer_in_cdbg(bftKmer)) { return get_successors(bftKmer, bft); } return NULL; } bool Graph::hasSuffixNeighbors(BFT_kmer* bftKmer) const { BFT_kmer* neighbors = getSuffixNeighbors(bftKmer); if(neighbors == NULL) { return false; } bool hasNeighbors = !(checkIfEmpty(neighbors)); free_BFT_kmer(neighbors, 4); return hasNeighbors; } BFT_kmer* Graph::getPrefixNeighbors(BFT_kmer* bftKmer) const { if(is_kmer_in_cdbg(bftKmer)) { return get_predecessors(bftKmer, bft); } return NULL; } bool Graph::hasPrefixNeighbors(BFT_kmer* bftKmer) const { BFT_kmer* neighbors = getPrefixNeighbors(bftKmer); if(neighbors == NULL) { return false; } bool hasNeighbors = !(checkIfEmpty(neighbors)); free_BFT_kmer(neighbors, 4); return hasNeighbors; } bool Graph::checkIfEmpty(BFT_kmer* bftKmers) const { for(uint32_t i = 0; i < 4; i++) { if(isValidBFTKmer(bftKmers + i)) { return false; } } return true; } <commit_msg>Commented out the marking functions because they were seg-faulting.<commit_after>/* * Implementation of graph.h. */ #include "graph.h" #define V_VISITED 1 // for marking the BFT_kmer as visited Graph::Graph(char* bftFileName) { bft = load_BFT(bftFileName); free(bftFileName); //set_neighbors_traversal(bft); } Graph::~Graph() { free_cdbg(bft); } bool Graph::isBFTKmer(char* strKmer) const { uint32_t* colorSet = query_sequence(bft, strKmer, 0.001, false); if(colorSet == NULL) { return false; } uint32_t numColors = colorSet[0]; free(colorSet); if(numColors) { return true; } return false; } BFT_kmer* Graph::getBFTKmer(char* strKmer) const { if(isBFTKmer(strKmer)) { return get_kmer(strKmer, bft); } return NULL; } bool Graph::isValidBFTKmer(BFT_kmer* bftKmer) const { if(bftKmer != NULL) { if(is_kmer_in_cdbg(bftKmer)) { return true; } } return false; } void Graph::setMarking() { //set_marking(bft); } void Graph::clearMarking() { //unset_marking(bft); } void Graph::markBFTKmer(BFT_kmer* bftKmer) { //set_flag_kmer(V_VISITED, bftKmer, bft); } bool Graph::isMarkedBFTKmer(BFT_kmer* bftKmer) const { /* if(get_flag_kmer(bftKmer, bft) == V_VISITED) { return true; } */ return false; } uint32_t Graph::getNumColors(BFT_kmer* bftKmer) const { uint32_t numColors = 0; BFT_annotation* bftAnno = get_annotation(bftKmer); uint32_t* temp = get_list_id_genomes(bftAnno, bft); numColors = temp[0]; free_BFT_annotation(bftAnno); free(temp); return numColors; } uint32_t Graph::getNumColors() const { return bft->nb_genomes; } uint32_t* Graph::getColors(BFT_kmer* bftKmer) const { BFT_annotation* bftAnno = get_annotation(bftKmer); uint32_t* colors = get_list_id_genomes(bftAnno, bft); free_BFT_annotation(bftAnno); return colors; } char* Graph::getColorFilePath(uint32_t colorId) const { return bft->filenames[colorId]; } BFT_kmer* Graph::getSuffixNeighbors(BFT_kmer* bftKmer) const { if(is_kmer_in_cdbg(bftKmer)) { return get_successors(bftKmer, bft); } return NULL; } bool Graph::hasSuffixNeighbors(BFT_kmer* bftKmer) const { BFT_kmer* neighbors = getSuffixNeighbors(bftKmer); if(neighbors == NULL) { return false; } bool hasNeighbors = !(checkIfEmpty(neighbors)); free_BFT_kmer(neighbors, 4); return hasNeighbors; } BFT_kmer* Graph::getPrefixNeighbors(BFT_kmer* bftKmer) const { if(is_kmer_in_cdbg(bftKmer)) { return get_predecessors(bftKmer, bft); } return NULL; } bool Graph::hasPrefixNeighbors(BFT_kmer* bftKmer) const { BFT_kmer* neighbors = getPrefixNeighbors(bftKmer); if(neighbors == NULL) { return false; } bool hasNeighbors = !(checkIfEmpty(neighbors)); free_BFT_kmer(neighbors, 4); return hasNeighbors; } bool Graph::checkIfEmpty(BFT_kmer* bftKmers) const { for(uint32_t i = 0; i < 4; i++) { if(isValidBFTKmer(bftKmers + i)) { return false; } } return true; } <|endoftext|>
<commit_before>/* * Copyright (C) 2006,2007,2008,2009,2010,2011,2012 Olly Betts * * 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 "length.h" std::string serialise_length(size_t len) { std::string result; if (len < 255) { result += static_cast<unsigned char>(len); } else { result += '\xff'; len -= 255; while (true) { unsigned char b = static_cast<unsigned char>(len & 0x7f); len >>= 7; if (!len) { result += (b | static_cast<unsigned char>(0x80)); break; } result += b; } } return result; } size_t unserialise_length(const char **p, const char *end, bool check_remaining) { const char *pos = *p; if (pos == end) { return -1; } size_t len = static_cast<unsigned char>(*pos++); if (len == 0xff) { len = 0; unsigned char ch; int shift = 0; do { if (pos == end || shift > 28) return -1; ch = *pos++; len |= size_t(ch & 0x7f) << shift; shift += 7; } while ((ch & 0x80) == 0); len += 255; } if (check_remaining && len > size_t(end - pos)) { return -1; } *p = pos; return len; } std::string serialise_string(std::string &input) { std::string output; output.append(encode_length(input.size())); output.append(input); return output; } size_t unserialise_string(std::string &output, const char **p, const char *end) { size_t length = decode_length(p, end, true); if (length != -1) { output.append(std::string(*p, length)); *p += length; } return length; } <commit_msg>String serializer takes a constant string<commit_after>/* * Copyright (C) 2006,2007,2008,2009,2010,2011,2012 Olly Betts * * 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 "length.h" std::string serialise_length(size_t len) { std::string result; if (len < 255) { result += static_cast<unsigned char>(len); } else { result += '\xff'; len -= 255; while (true) { unsigned char b = static_cast<unsigned char>(len & 0x7f); len >>= 7; if (!len) { result += (b | static_cast<unsigned char>(0x80)); break; } result += b; } } return result; } size_t unserialise_length(const char **p, const char *end, bool check_remaining) { const char *pos = *p; if (pos == end) { return -1; } size_t len = static_cast<unsigned char>(*pos++); if (len == 0xff) { len = 0; unsigned char ch; int shift = 0; do { if (pos == end || shift > 28) return -1; ch = *pos++; len |= size_t(ch & 0x7f) << shift; shift += 7; } while ((ch & 0x80) == 0); len += 255; } if (check_remaining && len > size_t(end - pos)) { return -1; } *p = pos; return len; } std::string serialise_string(const std::string &input) { std::string output; output.append(encode_length(input.size())); output.append(input); return output; } size_t unserialise_string(std::string &output, const char **p, const char *end) { size_t length = decode_length(p, end, true); if (length != -1) { output.append(std::string(*p, length)); *p += length; } return length; } <|endoftext|>
<commit_before>// This file is auto-generated from nearest_neighbor.idl // *** DO NOT EDIT *** #ifndef JUBATUS_CLIENT_NEAREST_NEIGHBOR_CLIENT_HPP_ #define JUBATUS_CLIENT_NEAREST_NEIGHBOR_CLIENT_HPP_ #include <map> #include <string> #include <vector> #include <utility> #include <jubatus/msgpack/rpc/client.h> #include "nearest_neighbor_types.hpp" namespace jubatus { namespace nearest_neighbor { namespace client { class nearest_neighbor { public: nearest_neighbor(const std::string& host, uint64_t port, double timeout_sec) : c_(host, port) { c_.set_timeout(timeout_sec); } bool init_table(const std::string& name) { msgpack::rpc::future f = c_.call("init_table", name); return f.get<bool>(); } bool clear(const std::string& name) { msgpack::rpc::future f = c_.call("clear", name); return f.get<bool>(); } bool set_row(const std::string& name, const std::string& id, const datum& d) { msgpack::rpc::future f = c_.call("set_row", name, id, d); return f.get<bool>(); } neighbor_result neighbor_row_from_id(const std::string& name, const std::string& id, uint32_t size) { msgpack::rpc::future f = c_.call("neighbor_row_from_id", name, id, size); return f.get<neighbor_result>(); } neighbor_result neighbor_row_from_data(const std::string& name, const datum& query, uint32_t size) { msgpack::rpc::future f = c_.call("neighbor_row_from_data", name, query, size); return f.get<neighbor_result>(); } neighbor_result similar_row_from_id(const std::string& name, const std::string& id, int32_t ret_num) { msgpack::rpc::future f = c_.call("similar_row_from_id", name, id, ret_num); return f.get<neighbor_result>(); } neighbor_result similar_row_from_data(const std::string& name, const datum& query, int32_t ret_num) { msgpack::rpc::future f = c_.call("similar_row_from_data", name, query, ret_num); return f.get<neighbor_result>(); } bool save(const std::string& name, const std::string& id) { msgpack::rpc::future f = c_.call("save", name, id); return f.get<bool>(); } bool load(const std::string& name, const std::string& id) { msgpack::rpc::future f = c_.call("load", name, id); return f.get<bool>(); } std::map<std::string, std::map<std::string, std::string> > get_status( const std::string& name) { msgpack::rpc::future f = c_.call("get_status", name); return f.get<std::map<std::string, std::map<std::string, std::string> > >(); } std::string get_config(const std::string& name) { msgpack::rpc::future f = c_.call("get_config", name); return f.get<std::string>(); } msgpack::rpc::client& get_client() { return c_; } private: msgpack::rpc::client c_; }; } // namespace client } // namespace nearest_neighbor } // namespace jubatus #endif // JUBATUS_CLIENT_NEAREST_NEIGHBOR_CLIENT_HPP_ <commit_msg>Regenerate nearest_neighbor client: refs #455<commit_after>// This file is auto-generated from nearest_neighbor.idl // *** DO NOT EDIT *** #ifndef JUBATUS_CLIENT_NEAREST_NEIGHBOR_CLIENT_HPP_ #define JUBATUS_CLIENT_NEAREST_NEIGHBOR_CLIENT_HPP_ #include <map> #include <string> #include <vector> #include <utility> #include <jubatus/msgpack/rpc/client.h> #include "nearest_neighbor_types.hpp" namespace jubatus { namespace nearest_neighbor { namespace client { class nearest_neighbor { public: nearest_neighbor(const std::string& host, uint64_t port, double timeout_sec) : c_(host, port) { c_.set_timeout(timeout_sec); } bool clear(const std::string& name) { msgpack::rpc::future f = c_.call("clear", name); return f.get<bool>(); } bool set_row(const std::string& name, const std::string& id, const datum& d) { msgpack::rpc::future f = c_.call("set_row", name, id, d); return f.get<bool>(); } neighbor_result neighbor_row_from_id(const std::string& name, const std::string& id, uint32_t size) { msgpack::rpc::future f = c_.call("neighbor_row_from_id", name, id, size); return f.get<neighbor_result>(); } neighbor_result neighbor_row_from_data(const std::string& name, const datum& query, uint32_t size) { msgpack::rpc::future f = c_.call("neighbor_row_from_data", name, query, size); return f.get<neighbor_result>(); } neighbor_result similar_row_from_id(const std::string& name, const std::string& id, int32_t ret_num) { msgpack::rpc::future f = c_.call("similar_row_from_id", name, id, ret_num); return f.get<neighbor_result>(); } neighbor_result similar_row_from_data(const std::string& name, const datum& query, int32_t ret_num) { msgpack::rpc::future f = c_.call("similar_row_from_data", name, query, ret_num); return f.get<neighbor_result>(); } bool save(const std::string& name, const std::string& id) { msgpack::rpc::future f = c_.call("save", name, id); return f.get<bool>(); } bool load(const std::string& name, const std::string& id) { msgpack::rpc::future f = c_.call("load", name, id); return f.get<bool>(); } std::map<std::string, std::map<std::string, std::string> > get_status( const std::string& name) { msgpack::rpc::future f = c_.call("get_status", name); return f.get<std::map<std::string, std::map<std::string, std::string> > >(); } std::string get_config(const std::string& name) { msgpack::rpc::future f = c_.call("get_config", name); return f.get<std::string>(); } msgpack::rpc::client& get_client() { return c_; } private: msgpack::rpc::client c_; }; } // namespace client } // namespace nearest_neighbor } // namespace jubatus #endif // JUBATUS_CLIENT_NEAREST_NEIGHBOR_CLIENT_HPP_ <|endoftext|>
<commit_before>/* This file is part of KContactManager. Copyright (c) 2009 Tobias Koenig <tokoe@kde.org> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. 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 "collectionselectiondialog.h" #include "collectioncombobox.h" #include <akonadi_next/descendantsproxymodel.h> #include <akonadi_next/entityfilterproxymodel.h> #include <akonadi/item.h> #include <kabc/addressee.h> #include <klocale.h> #include <QtGui/QLabel> #include <QtGui/QVBoxLayout> CollectionSelectionDialog::CollectionSelectionDialog( QAbstractItemModel *collectionModel, QWidget *parent ) : KDialog( parent ) { setCaption( i18n( "Select Address Book" ) ); setButtons( Ok | Cancel ); QWidget *mainWidget = new QWidget( this ); setMainWidget( mainWidget ); QVBoxLayout *layout = new QVBoxLayout( mainWidget ); // flatten the collection tree structure to a collection list Akonadi::DescendantsProxyModel *descendantModel = new Akonadi::DescendantsProxyModel( this ); descendantModel->setSourceModel( collectionModel ); /* Akonadi::CollectionFilterProxyModel *filterModel = new Akonadi::CollectionFilterProxyModel( this ); filterModel->addMimeTypeFilter( KABC::Addressee::mimeType() ); filterModel->setSourceModel( collectionModel ); */ mCollectionCombo = new KABC::CollectionComboBox( mainWidget ); mCollectionCombo->setModel( descendantModel ); layout->addWidget( new QLabel( i18n( "Select the address book" ) ) ); layout->addWidget( mCollectionCombo ); } CollectionSelectionDialog::~CollectionSelectionDialog() { } Akonadi::Collection CollectionSelectionDialog::selectedCollection() const { return mCollectionCombo->selectedCollection(); } <commit_msg>Fix include.<commit_after>/* This file is part of KContactManager. Copyright (c) 2009 Tobias Koenig <tokoe@kde.org> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. 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 "collectionselectiondialog.h" #include "collectioncombobox.h" #include <akonadi/descendantsproxymodel.h> #include <akonadi_next/entityfilterproxymodel.h> #include <akonadi/item.h> #include <kabc/addressee.h> #include <klocale.h> #include <QtGui/QLabel> #include <QtGui/QVBoxLayout> CollectionSelectionDialog::CollectionSelectionDialog( QAbstractItemModel *collectionModel, QWidget *parent ) : KDialog( parent ) { setCaption( i18n( "Select Address Book" ) ); setButtons( Ok | Cancel ); QWidget *mainWidget = new QWidget( this ); setMainWidget( mainWidget ); QVBoxLayout *layout = new QVBoxLayout( mainWidget ); // flatten the collection tree structure to a collection list Akonadi::DescendantsProxyModel *descendantModel = new Akonadi::DescendantsProxyModel( this ); descendantModel->setSourceModel( collectionModel ); /* Akonadi::CollectionFilterProxyModel *filterModel = new Akonadi::CollectionFilterProxyModel( this ); filterModel->addMimeTypeFilter( KABC::Addressee::mimeType() ); filterModel->setSourceModel( collectionModel ); */ mCollectionCombo = new KABC::CollectionComboBox( mainWidget ); mCollectionCombo->setModel( descendantModel ); layout->addWidget( new QLabel( i18n( "Select the address book" ) ) ); layout->addWidget( mCollectionCombo ); } CollectionSelectionDialog::~CollectionSelectionDialog() { } Akonadi::Collection CollectionSelectionDialog::selectedCollection() const { return mCollectionCombo->selectedCollection(); } <|endoftext|>
<commit_before>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: entrylisthelper.cxx,v $ * $Revision: 1.7 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_forms.hxx" #include "entrylisthelper.hxx" #include <osl/diagnose.h> #include <comphelper/sequence.hxx> #include <comphelper/property.hxx> #include <algorithm> //......................................................................... namespace frm { //......................................................................... using namespace ::com::sun::star::uno; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::form::binding; //===================================================================== //= OEntryListHelper //===================================================================== //--------------------------------------------------------------------- OEntryListHelper::OEntryListHelper( ::osl::Mutex& _rMutex ) :m_rMutex( _rMutex ) { } //--------------------------------------------------------------------- OEntryListHelper::OEntryListHelper( const OEntryListHelper& _rSource, ::osl::Mutex& _rMutex ) :m_rMutex( _rMutex ) ,m_xListSource ( _rSource.m_xListSource ) ,m_aStringItems( _rSource.m_aStringItems ) { } //--------------------------------------------------------------------- OEntryListHelper::~OEntryListHelper( ) { } //--------------------------------------------------------------------- void SAL_CALL OEntryListHelper::setListEntrySource( const Reference< XListEntrySource >& _rxSource ) throw (RuntimeException) { ::osl::MutexGuard aGuard( m_rMutex ); // disconnect from the current external list source disconnectExternalListSource(); // and connect to the new one if ( _rxSource.is() ) connectExternalListSource( _rxSource ); } //--------------------------------------------------------------------- Reference< XListEntrySource > SAL_CALL OEntryListHelper::getListEntrySource( ) throw (RuntimeException) { return m_xListSource; } //--------------------------------------------------------------------- void SAL_CALL OEntryListHelper::entryChanged( const ListEntryEvent& _rEvent ) throw (RuntimeException) { ::osl::MutexGuard aGuard( m_rMutex ); OSL_ENSURE( _rEvent.Source == m_xListSource, "OEntryListHelper::entryChanged: where did this come from?" ); OSL_ENSURE( ( _rEvent.Position >= 0 ) && ( _rEvent.Position < m_aStringItems.getLength() ), "OEntryListHelper::entryChanged: invalid index!" ); OSL_ENSURE( _rEvent.Entries.getLength() == 1, "OEntryListHelper::entryChanged: invalid string list!" ); if ( ( _rEvent.Position >= 0 ) && ( _rEvent.Position < m_aStringItems.getLength() ) && ( _rEvent.Entries.getLength() > 0 ) ) { m_aStringItems[ _rEvent.Position ] = _rEvent.Entries[ 0 ]; stringItemListChanged(); } } //--------------------------------------------------------------------- void SAL_CALL OEntryListHelper::entryRangeInserted( const ListEntryEvent& _rEvent ) throw (RuntimeException) { ::osl::MutexGuard aGuard( m_rMutex ); OSL_ENSURE( _rEvent.Source == m_xListSource, "OEntryListHelper::entryRangeInserted: where did this come from?" ); OSL_ENSURE( ( _rEvent.Position > 0 ) && ( _rEvent.Position < m_aStringItems.getLength() ) && ( _rEvent.Entries.getLength() > 0 ), "OEntryListHelper::entryRangeRemoved: invalid count and/or position!" ); if ( ( _rEvent.Position > 0 ) && ( _rEvent.Position < m_aStringItems.getLength() ) && ( _rEvent.Entries.getLength() > 0 ) ) { // the entries *before* the insertion pos Sequence< ::rtl::OUString > aKeepEntries( m_aStringItems.getConstArray(), _rEvent.Position ); // the entries *behind* the insertion pos Sequence< ::rtl::OUString > aMovedEntries( m_aStringItems.getConstArray() + _rEvent.Position, m_aStringItems.getLength() - _rEvent.Position ); // concat all three parts m_aStringItems = ::comphelper::concatSequences( aKeepEntries, _rEvent.Entries, aMovedEntries ); stringItemListChanged(); } } //--------------------------------------------------------------------- void SAL_CALL OEntryListHelper::entryRangeRemoved( const ListEntryEvent& _rEvent ) throw (RuntimeException) { ::osl::MutexGuard aGuard( m_rMutex ); OSL_ENSURE( _rEvent.Source == m_xListSource, "OEntryListHelper::entryRangeRemoved: where did this come from?" ); OSL_ENSURE( ( _rEvent.Position > 0 ) && ( _rEvent.Count > 0 ) && ( _rEvent.Position + _rEvent.Count <= m_aStringItems.getLength() ), "OEntryListHelper::entryRangeRemoved: invalid count and/or position!" ); if ( ( _rEvent.Position > 0 ) && ( _rEvent.Count > 0 ) && ( _rEvent.Position + _rEvent.Count <= m_aStringItems.getLength() ) ) { // copy all items after the removed ones ::std::copy( m_aStringItems.getConstArray() + _rEvent.Position + _rEvent.Count, m_aStringItems.getConstArray() + m_aStringItems.getLength(), m_aStringItems.getArray( ) + _rEvent.Position ); // shrink the array m_aStringItems.realloc( m_aStringItems.getLength() - _rEvent.Count ); stringItemListChanged(); } } //--------------------------------------------------------------------- void SAL_CALL OEntryListHelper::allEntriesChanged( const EventObject& _rEvent ) throw (RuntimeException) { ::osl::MutexGuard aGuard( m_rMutex ); OSL_ENSURE( _rEvent.Source == m_xListSource, "OEntryListHelper::allEntriesChanged: where did this come from?" ); Reference< XListEntrySource > xSource( _rEvent.Source, UNO_QUERY ); if ( xSource.is() ) { m_aStringItems = xSource->getAllListEntries( ); stringItemListChanged(); } } //--------------------------------------------------------------------- bool OEntryListHelper::handleDisposing( const EventObject& _rEvent ) { if ( m_xListSource .is() && ( _rEvent.Source == m_xListSource ) ) { disconnectExternalListSource( ); return true; } return false; } //--------------------------------------------------------------------- void OEntryListHelper::disposing( ) { if ( hasExternalListSource( ) ) disconnectExternalListSource( ); } //--------------------------------------------------------------------- void OEntryListHelper::disconnectExternalListSource( ) { if ( m_xListSource.is() ) m_xListSource->removeListEntryListener( this ); m_xListSource.clear(); disconnectedExternalListSource(); } //--------------------------------------------------------------------- void OEntryListHelper::connectedExternalListSource( ) { // nothing to do here } //--------------------------------------------------------------------- void OEntryListHelper::disconnectedExternalListSource( ) { // nothing to do here } //--------------------------------------------------------------------- void OEntryListHelper::connectExternalListSource( const Reference< XListEntrySource >& _rxSource ) { OSL_ENSURE( !hasExternalListSource(), "OEntryListHelper::connectExternalListSource: only to be called if no external source is active!" ); OSL_ENSURE( _rxSource.is(), "OEntryListHelper::connectExternalListSource: invalid list source!" ); // remember it m_xListSource = _rxSource; // initially fill our item list if ( m_xListSource.is() ) { // be notified when the list changes ... m_xListSource->addListEntryListener( this ); m_aStringItems = m_xListSource->getAllListEntries( ); stringItemListChanged(); // let derivees react on the new list source connectedExternalListSource(); } } //--------------------------------------------------------------------- sal_Bool OEntryListHelper::convertNewListSourceProperty( Any& _rConvertedValue, Any& _rOldValue, const Any& _rValue ) SAL_THROW( ( IllegalArgumentException ) ) { if ( hasExternalListSource() ) throw IllegalArgumentException( ); // TODO: error message return ::comphelper::tryPropertyValue( _rConvertedValue, _rOldValue, _rValue, m_aStringItems ); } //--------------------------------------------------------------------- void OEntryListHelper::setNewStringItemList( const ::com::sun::star::uno::Any& _rValue ) { OSL_PRECOND( !hasExternalListSource(), "OEntryListHelper::setNewStringItemList: this should never have survived convertNewListSourceProperty!" ); OSL_VERIFY( _rValue >>= m_aStringItems ); stringItemListChanged( ); } //......................................................................... } // namespace frm //......................................................................... <commit_msg>INTEGRATION: CWS dba241b_DEV300 (1.6.136); FILE MERGED 2008/04/01 19:41:30 fs 1.6.136.1: #i87690# (proper) support for XRefreshable<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: entrylisthelper.cxx,v $ * $Revision: 1.8 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_forms.hxx" #include "entrylisthelper.hxx" #include <osl/diagnose.h> #include <comphelper/sequence.hxx> #include <comphelper/property.hxx> #include <algorithm> //......................................................................... namespace frm { //......................................................................... using namespace ::com::sun::star::uno; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::util; using namespace ::com::sun::star::form::binding; //===================================================================== //= OEntryListHelper //===================================================================== //--------------------------------------------------------------------- OEntryListHelper::OEntryListHelper( ::osl::Mutex& _rMutex ) :m_rMutex( _rMutex ) ,m_aRefreshListeners( _rMutex ) { } //--------------------------------------------------------------------- OEntryListHelper::OEntryListHelper( const OEntryListHelper& _rSource, ::osl::Mutex& _rMutex ) :m_rMutex( _rMutex ) ,m_xListSource ( _rSource.m_xListSource ) ,m_aStringItems( _rSource.m_aStringItems ) ,m_aRefreshListeners( _rMutex ) { } //--------------------------------------------------------------------- OEntryListHelper::~OEntryListHelper( ) { } //--------------------------------------------------------------------- void SAL_CALL OEntryListHelper::setListEntrySource( const Reference< XListEntrySource >& _rxSource ) throw (RuntimeException) { ::osl::MutexGuard aGuard( m_rMutex ); // disconnect from the current external list source disconnectExternalListSource(); // and connect to the new one if ( _rxSource.is() ) connectExternalListSource( _rxSource ); } //--------------------------------------------------------------------- Reference< XListEntrySource > SAL_CALL OEntryListHelper::getListEntrySource( ) throw (RuntimeException) { return m_xListSource; } //--------------------------------------------------------------------- void SAL_CALL OEntryListHelper::entryChanged( const ListEntryEvent& _rEvent ) throw (RuntimeException) { ::osl::MutexGuard aGuard( m_rMutex ); OSL_ENSURE( _rEvent.Source == m_xListSource, "OEntryListHelper::entryChanged: where did this come from?" ); OSL_ENSURE( ( _rEvent.Position >= 0 ) && ( _rEvent.Position < m_aStringItems.getLength() ), "OEntryListHelper::entryChanged: invalid index!" ); OSL_ENSURE( _rEvent.Entries.getLength() == 1, "OEntryListHelper::entryChanged: invalid string list!" ); if ( ( _rEvent.Position >= 0 ) && ( _rEvent.Position < m_aStringItems.getLength() ) && ( _rEvent.Entries.getLength() > 0 ) ) { m_aStringItems[ _rEvent.Position ] = _rEvent.Entries[ 0 ]; stringItemListChanged(); } } //--------------------------------------------------------------------- void SAL_CALL OEntryListHelper::entryRangeInserted( const ListEntryEvent& _rEvent ) throw (RuntimeException) { ::osl::MutexGuard aGuard( m_rMutex ); OSL_ENSURE( _rEvent.Source == m_xListSource, "OEntryListHelper::entryRangeInserted: where did this come from?" ); OSL_ENSURE( ( _rEvent.Position > 0 ) && ( _rEvent.Position < m_aStringItems.getLength() ) && ( _rEvent.Entries.getLength() > 0 ), "OEntryListHelper::entryRangeRemoved: invalid count and/or position!" ); if ( ( _rEvent.Position > 0 ) && ( _rEvent.Position < m_aStringItems.getLength() ) && ( _rEvent.Entries.getLength() > 0 ) ) { // the entries *before* the insertion pos Sequence< ::rtl::OUString > aKeepEntries( m_aStringItems.getConstArray(), _rEvent.Position ); // the entries *behind* the insertion pos Sequence< ::rtl::OUString > aMovedEntries( m_aStringItems.getConstArray() + _rEvent.Position, m_aStringItems.getLength() - _rEvent.Position ); // concat all three parts m_aStringItems = ::comphelper::concatSequences( aKeepEntries, _rEvent.Entries, aMovedEntries ); stringItemListChanged(); } } //--------------------------------------------------------------------- void SAL_CALL OEntryListHelper::entryRangeRemoved( const ListEntryEvent& _rEvent ) throw (RuntimeException) { ::osl::MutexGuard aGuard( m_rMutex ); OSL_ENSURE( _rEvent.Source == m_xListSource, "OEntryListHelper::entryRangeRemoved: where did this come from?" ); OSL_ENSURE( ( _rEvent.Position > 0 ) && ( _rEvent.Count > 0 ) && ( _rEvent.Position + _rEvent.Count <= m_aStringItems.getLength() ), "OEntryListHelper::entryRangeRemoved: invalid count and/or position!" ); if ( ( _rEvent.Position > 0 ) && ( _rEvent.Count > 0 ) && ( _rEvent.Position + _rEvent.Count <= m_aStringItems.getLength() ) ) { // copy all items after the removed ones ::std::copy( m_aStringItems.getConstArray() + _rEvent.Position + _rEvent.Count, m_aStringItems.getConstArray() + m_aStringItems.getLength(), m_aStringItems.getArray( ) + _rEvent.Position ); // shrink the array m_aStringItems.realloc( m_aStringItems.getLength() - _rEvent.Count ); stringItemListChanged(); } } //--------------------------------------------------------------------- void SAL_CALL OEntryListHelper::allEntriesChanged( const EventObject& _rEvent ) throw (RuntimeException) { ::osl::MutexGuard aGuard( m_rMutex ); OSL_ENSURE( _rEvent.Source == m_xListSource, "OEntryListHelper::allEntriesChanged: where did this come from?" ); Reference< XListEntrySource > xSource( _rEvent.Source, UNO_QUERY ); if ( _rEvent.Source == m_xListSource ) { impl_lock_refreshList(); } } // XRefreshable //------------------------------------------------------------------------------ void SAL_CALL OEntryListHelper::addRefreshListener(const Reference<XRefreshListener>& _rxListener) throw(RuntimeException) { if ( _rxListener.is() ) m_aRefreshListeners.addInterface( _rxListener ); } //------------------------------------------------------------------------------ void SAL_CALL OEntryListHelper::removeRefreshListener(const Reference<XRefreshListener>& _rxListener) throw(RuntimeException) { if ( _rxListener.is() ) m_aRefreshListeners.removeInterface( _rxListener ); } //------------------------------------------------------------------------------ void SAL_CALL OEntryListHelper::refresh() throw(RuntimeException) { { ::osl::MutexGuard aGuard( m_rMutex ); impl_lock_refreshList(); } EventObject aEvt( static_cast< XRefreshable* >( this ) ); m_aRefreshListeners.notifyEach( &XRefreshListener::refreshed, aEvt ); } //--------------------------------------------------------------------- void OEntryListHelper::impl_lock_refreshList() { if ( hasExternalListSource() ) { m_aStringItems = m_xListSource->getAllListEntries( ); stringItemListChanged(); } else refreshInternalEntryList(); } //--------------------------------------------------------------------- bool OEntryListHelper::handleDisposing( const EventObject& _rEvent ) { if ( m_xListSource .is() && ( _rEvent.Source == m_xListSource ) ) { disconnectExternalListSource( ); return true; } return false; } //--------------------------------------------------------------------- void OEntryListHelper::disposing( ) { EventObject aEvt( static_cast< XRefreshable* >( this ) ); m_aRefreshListeners.disposeAndClear(aEvt); if ( hasExternalListSource( ) ) disconnectExternalListSource( ); } //--------------------------------------------------------------------- void OEntryListHelper::disconnectExternalListSource( ) { if ( m_xListSource.is() ) m_xListSource->removeListEntryListener( this ); m_xListSource.clear(); disconnectedExternalListSource(); } //--------------------------------------------------------------------- void OEntryListHelper::connectedExternalListSource( ) { // nothing to do here } //--------------------------------------------------------------------- void OEntryListHelper::disconnectedExternalListSource( ) { // nothing to do here } //--------------------------------------------------------------------- void OEntryListHelper::connectExternalListSource( const Reference< XListEntrySource >& _rxSource ) { OSL_ENSURE( !hasExternalListSource(), "OEntryListHelper::connectExternalListSource: only to be called if no external source is active!" ); OSL_ENSURE( _rxSource.is(), "OEntryListHelper::connectExternalListSource: invalid list source!" ); // remember it m_xListSource = _rxSource; // initially fill our item list if ( m_xListSource.is() ) { // be notified when the list changes ... m_xListSource->addListEntryListener( this ); m_aStringItems = m_xListSource->getAllListEntries( ); stringItemListChanged(); // let derivees react on the new list source connectedExternalListSource(); } } //--------------------------------------------------------------------- sal_Bool OEntryListHelper::convertNewListSourceProperty( Any& _rConvertedValue, Any& _rOldValue, const Any& _rValue ) SAL_THROW( ( IllegalArgumentException ) ) { if ( hasExternalListSource() ) throw IllegalArgumentException( ); // TODO: error message return ::comphelper::tryPropertyValue( _rConvertedValue, _rOldValue, _rValue, m_aStringItems ); } //--------------------------------------------------------------------- void OEntryListHelper::setNewStringItemList( const ::com::sun::star::uno::Any& _rValue ) { OSL_PRECOND( !hasExternalListSource(), "OEntryListHelper::setNewStringItemList: this should never have survived convertNewListSourceProperty!" ); OSL_VERIFY( _rValue >>= m_aStringItems ); stringItemListChanged( ); } //......................................................................... } // namespace frm //......................................................................... <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: entrylisthelper.hxx,v $ * * $Revision: 1.5 $ * * last change: $Author: rt $ $Date: 2005-09-08 22:48:23 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef FORMS_ENTRYLISTHELPER_HXX #define FORMS_ENTRYLISTHELPER_HXX #ifndef _COM_SUN_STAR_FORM_BINDING_XLISTENTRYSINK_HDL_ #include <com/sun/star/form/binding/XListEntrySink.hpp> #endif #ifndef _COM_SUN_STAR_FORM_BINDING_XLISTENTRYLISTENER_HDL_ #include <com/sun/star/form/binding/XListEntryListener.hpp> #endif #ifndef _COM_SUN_STAR_LANG_ILLEGALARGUMENTEXCEPTION_HPP_ #include <com/sun/star/lang/IllegalArgumentException.hpp> #endif #ifndef _CPPUHELPER_IMPLBASE2_HXX_ #include <cppuhelper/implbase2.hxx> #endif //......................................................................... namespace frm { //......................................................................... //===================================================================== //= OEntryListHelper //===================================================================== typedef ::cppu::ImplHelper2 < ::com::sun::star::form::binding::XListEntrySink , ::com::sun::star::form::binding::XListEntryListener > OEntryListHelper_BASE; class OEntryListHelper : public OEntryListHelper_BASE { private: ::osl::Mutex& m_rMutex; ::com::sun::star::uno::Reference< ::com::sun::star::form::binding::XListEntrySource > m_xListSource; /// our external list source ::com::sun::star::uno::Sequence< ::rtl::OUString > m_aStringItems; /// "overridden" StringItemList property value protected: OEntryListHelper( ::osl::Mutex& _rMutex ); OEntryListHelper( const OEntryListHelper& _rSource, ::osl::Mutex& _rMutex ); ~OEntryListHelper( ); /// returns the current string item list inline const ::com::sun::star::uno::Sequence< ::rtl::OUString >& getStringItemList() const { return m_aStringItems; } inline const ::com::sun::star::uno::Reference< ::com::sun::star::form::binding::XListEntrySource >& getExternalListEntrySource() const { return m_xListSource; } /// determines whether we actually have an external list source inline bool hasExternalListSource( ) const { return m_xListSource.is(); } /** handling the XEventListener::disposing call for the case where our list source is being disposed @return <TRUE/> if and only if the disposed object was our list source, and so the event was handled */ bool handleDisposing( const ::com::sun::star::lang::EventObject& _rEvent ); /** to be called by derived classes' instances when they're being disposed */ void disposing( ); /** helper for implementing convertFastPropertyValue( StringItemList ) <p>The signature of this method and the return type have the same semantics as convertFastPropertyValue.</p> */ sal_Bool convertNewListSourceProperty( ::com::sun::star::uno::Any& _rConvertedValue, ::com::sun::star::uno::Any& _rOldValue, const ::com::sun::star::uno::Any& _rValue ) SAL_THROW( ( ::com::sun::star::lang::IllegalArgumentException ) ); /** helper for implementing setFastPropertyValueNoBroadcast <p>Will internally call stringItemListChanged after the new item list has been set.</p> @precond not to be called when we have an external list source @see hasExternalListSource */ void setNewStringItemList( const ::com::sun::star::uno::Any& _rValue ); /** announces that the list of entries has changed. <p>Derived classes have to override this. Most probably, they'll set the new as model property.</p> @pure @see getStringItemList */ virtual void stringItemListChanged( ) = 0; /** called whenever a connection to a new external list source has been established */ virtual void connectedExternalListSource( ); /** called whenever a connection to a new external list source has been revoked */ virtual void disconnectedExternalListSource( ); private: // XListEntrySink virtual void SAL_CALL setListEntrySource( const ::com::sun::star::uno::Reference< ::com::sun::star::form::binding::XListEntrySource >& _rxSource ) throw (::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Reference< ::com::sun::star::form::binding::XListEntrySource > SAL_CALL getListEntrySource( ) throw (::com::sun::star::uno::RuntimeException); // XListEntryListener virtual void SAL_CALL entryChanged( const ::com::sun::star::form::binding::ListEntryEvent& _rSource ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL entryRangeInserted( const ::com::sun::star::form::binding::ListEntryEvent& _rSource ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL entryRangeRemoved( const ::com::sun::star::form::binding::ListEntryEvent& _rSource ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL allEntriesChanged( const ::com::sun::star::lang::EventObject& _rSource ) throw (::com::sun::star::uno::RuntimeException); private: /** disconnects from the active external list source, if present @see connectExternalListSource */ void disconnectExternalListSource( ); /** connects to a new external list source @param _rxSource the new list source. Must not be <NULL/> @see disconnectExternalListSource */ void connectExternalListSource( const ::com::sun::star::uno::Reference< ::com::sun::star::form::binding::XListEntrySource >& _rxSource ); private: OEntryListHelper(); // never implemented OEntryListHelper( const OEntryListHelper& ); // never implemented OEntryListHelper& operator=( const OEntryListHelper& ); // never implemented }; //......................................................................... } // namespace frm //......................................................................... #endif // FORMS_ENTRYLISTHELPER_HXX <commit_msg>INTEGRATION: CWS warnings01 (1.5.68); FILE MERGED 2006/03/15 07:55:38 fs 1.5.68.1: #i57457# warning-free code (unxsols4)<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: entrylisthelper.hxx,v $ * * $Revision: 1.6 $ * * last change: $Author: hr $ $Date: 2006-06-19 12:54:08 $ * * 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 FORMS_ENTRYLISTHELPER_HXX #define FORMS_ENTRYLISTHELPER_HXX #ifndef _COM_SUN_STAR_FORM_BINDING_XLISTENTRYSINK_HDL_ #include <com/sun/star/form/binding/XListEntrySink.hpp> #endif #ifndef _COM_SUN_STAR_FORM_BINDING_XLISTENTRYLISTENER_HDL_ #include <com/sun/star/form/binding/XListEntryListener.hpp> #endif #ifndef _COM_SUN_STAR_LANG_ILLEGALARGUMENTEXCEPTION_HPP_ #include <com/sun/star/lang/IllegalArgumentException.hpp> #endif #ifndef _CPPUHELPER_IMPLBASE2_HXX_ #include <cppuhelper/implbase2.hxx> #endif //......................................................................... namespace frm { //......................................................................... //===================================================================== //= OEntryListHelper //===================================================================== typedef ::cppu::ImplHelper2 < ::com::sun::star::form::binding::XListEntrySink , ::com::sun::star::form::binding::XListEntryListener > OEntryListHelper_BASE; class OEntryListHelper : public OEntryListHelper_BASE { private: ::osl::Mutex& m_rMutex; ::com::sun::star::uno::Reference< ::com::sun::star::form::binding::XListEntrySource > m_xListSource; /// our external list source ::com::sun::star::uno::Sequence< ::rtl::OUString > m_aStringItems; /// "overridden" StringItemList property value protected: OEntryListHelper( ::osl::Mutex& _rMutex ); OEntryListHelper( const OEntryListHelper& _rSource, ::osl::Mutex& _rMutex ); ~OEntryListHelper( ); /// returns the current string item list inline const ::com::sun::star::uno::Sequence< ::rtl::OUString >& getStringItemList() const { return m_aStringItems; } inline const ::com::sun::star::uno::Reference< ::com::sun::star::form::binding::XListEntrySource >& getExternalListEntrySource() const { return m_xListSource; } /// determines whether we actually have an external list source inline bool hasExternalListSource( ) const { return m_xListSource.is(); } /** handling the XEventListener::disposing call for the case where our list source is being disposed @return <TRUE/> if and only if the disposed object was our list source, and so the event was handled */ bool handleDisposing( const ::com::sun::star::lang::EventObject& _rEvent ); /** to be called by derived classes' instances when they're being disposed */ void disposing( ); // prevent method hiding virtual void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& Source ) throw (::com::sun::star::uno::RuntimeException) = 0; /** helper for implementing convertFastPropertyValue( StringItemList ) <p>The signature of this method and the return type have the same semantics as convertFastPropertyValue.</p> */ sal_Bool convertNewListSourceProperty( ::com::sun::star::uno::Any& _rConvertedValue, ::com::sun::star::uno::Any& _rOldValue, const ::com::sun::star::uno::Any& _rValue ) SAL_THROW( ( ::com::sun::star::lang::IllegalArgumentException ) ); /** helper for implementing setFastPropertyValueNoBroadcast <p>Will internally call stringItemListChanged after the new item list has been set.</p> @precond not to be called when we have an external list source @see hasExternalListSource */ void setNewStringItemList( const ::com::sun::star::uno::Any& _rValue ); /** announces that the list of entries has changed. <p>Derived classes have to override this. Most probably, they'll set the new as model property.</p> @pure @see getStringItemList */ virtual void stringItemListChanged( ) = 0; /** called whenever a connection to a new external list source has been established */ virtual void connectedExternalListSource( ); /** called whenever a connection to a new external list source has been revoked */ virtual void disconnectedExternalListSource( ); private: // XListEntrySink virtual void SAL_CALL setListEntrySource( const ::com::sun::star::uno::Reference< ::com::sun::star::form::binding::XListEntrySource >& _rxSource ) throw (::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Reference< ::com::sun::star::form::binding::XListEntrySource > SAL_CALL getListEntrySource( ) throw (::com::sun::star::uno::RuntimeException); // XListEntryListener virtual void SAL_CALL entryChanged( const ::com::sun::star::form::binding::ListEntryEvent& _rSource ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL entryRangeInserted( const ::com::sun::star::form::binding::ListEntryEvent& _rSource ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL entryRangeRemoved( const ::com::sun::star::form::binding::ListEntryEvent& _rSource ) throw (::com::sun::star::uno::RuntimeException); virtual void SAL_CALL allEntriesChanged( const ::com::sun::star::lang::EventObject& _rSource ) throw (::com::sun::star::uno::RuntimeException); private: /** disconnects from the active external list source, if present @see connectExternalListSource */ void disconnectExternalListSource( ); /** connects to a new external list source @param _rxSource the new list source. Must not be <NULL/> @see disconnectExternalListSource */ void connectExternalListSource( const ::com::sun::star::uno::Reference< ::com::sun::star::form::binding::XListEntrySource >& _rxSource ); private: OEntryListHelper(); // never implemented OEntryListHelper( const OEntryListHelper& ); // never implemented OEntryListHelper& operator=( const OEntryListHelper& ); // never implemented }; //......................................................................... } // namespace frm //......................................................................... #endif // FORMS_ENTRYLISTHELPER_HXX <|endoftext|>
<commit_before>/* This file is part of the Kate project. * * Copyright (C) 2012 Christoph Cullmann <cullmann@kde.org> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "kateprojectworker.h" #include <QDir> #include <QDirIterator> #include <QFile> #include <QFileInfo> #include <QProcess> #include <QSet> KateProjectWorker::KateProjectWorker (QObject *project) : QObject () , m_project (project) { } KateProjectWorker::~KateProjectWorker () { } void KateProjectWorker::loadProject (QString fileName, QVariantMap projectMap) { /** * setup project file name * name should be FIX after initial setting */ Q_ASSERT (m_fileName.isEmpty() || (m_fileName == fileName)); m_fileName = fileName; /** * Create dummy top level parent item and load the project recursively */ QStandardItem *topLevel = new QStandardItem (); QMap<QString, QStandardItem *> *file2Item = new QMap<QString, QStandardItem *> (); loadProject (topLevel, projectMap, *file2Item); /** * create some local backup of some data we need for further processing! */ QStringList files = file2Item->keys (); /** * feed back our results */ QMetaObject::invokeMethod (m_project, "loadProjectDone", Qt::QueuedConnection, Q_ARG(void *, topLevel), Q_ARG(void *, file2Item)); /** * trigger more updates */ loadCtags (files); } void KateProjectWorker::loadProject (QStandardItem *parent, const QVariantMap &project, QMap<QString, QStandardItem *> &file2Item) { /** * recurse to sub-projects FIRST */ QVariantList subGroups = project["projects"].toList (); foreach (const QVariant &subGroupVariant, subGroups) { /** * convert to map and get name, else skip */ QVariantMap subProject = subGroupVariant.toMap (); if (subProject["name"].toString().isEmpty()) continue; /** * recurse */ QStandardItem *subProjectItem = new KateProjectItem (KateProjectItem::Project, subProject["name"].toString()); loadProject (subProjectItem, subProject, file2Item); parent->appendRow (subProjectItem); } /** * load all specified files */ QVariantList files = project["files"].toList (); foreach (const QVariant &fileVariant, files) loadFilesEntry (parent, fileVariant.toMap (), file2Item); } /** * small helper to construct directory parent items * @param dir2Item map for path => item * @param path current path we need item for * @return correct parent item for given path, will reuse existing ones */ static QStandardItem *directoryParent (QMap<QString, QStandardItem *> &dir2Item, QString path) { /** * throw away simple / */ if (path == "/") path = ""; /** * quick check: dir already seen? */ if (dir2Item.contains (path)) return dir2Item[path]; /** * else: construct recursively */ int slashIndex = path.lastIndexOf ('/'); /** * no slash? * simple, no recursion, append new item toplevel */ if (slashIndex < 0) { dir2Item[path] = new KateProjectItem (KateProjectItem::Directory, path); dir2Item[""]->appendRow (dir2Item[path]); return dir2Item[path]; } /** * else, split and recurse */ QString leftPart = path.left (slashIndex); QString rightPart = path.right (path.size() - (slashIndex + 1)); /** * special handling if / with nothing on one side are found */ if (leftPart.isEmpty() || rightPart.isEmpty ()) return directoryParent (dir2Item, leftPart.isEmpty() ? rightPart : leftPart); /** * else: recurse on left side */ dir2Item[path] = new KateProjectItem (KateProjectItem::Directory, rightPart); directoryParent (dir2Item, leftPart)->appendRow (dir2Item[path]); return dir2Item[path]; } void KateProjectWorker::loadFilesEntry (QStandardItem *parent, const QVariantMap &filesEntry, QMap<QString, QStandardItem *> &file2Item) { /** * get directory to open or skip */ QDir dir (QFileInfo (m_fileName).absoluteDir()); if (!dir.cd (filesEntry["directory"].toString())) return; /** * get recursive attribute, default is TRUE */ const bool recursive = !filesEntry.contains ("recursive") || filesEntry["recursive"].toBool(); /** * now: choose between different methodes to get files in the directory */ QStringList files; /** * use GIT */ if (filesEntry["git"].toBool()) { /** * try to run git with ls-files for this directory */ QProcess git; git.setWorkingDirectory (dir.absolutePath()); QStringList args; args << "ls-files" << "."; git.start("git", args); if (!git.waitForStarted() || !git.waitForFinished()) return; /** * get output and split up into files */ QStringList relFiles = QString::fromLocal8Bit (git.readAllStandardOutput ()).split (QRegExp("[\n\r]"), QString::SkipEmptyParts); /** * prepend the directory path */ foreach (QString relFile, relFiles) { /** * skip non-direct files if not recursive */ if (!recursive && (relFile.indexOf ("/") != -1)) continue; files.append (dir.absolutePath() + "/" + relFile); } } /** * use SVN */ else if (filesEntry["svn"].toBool()) { /** * try to run git with ls-files for this directory */ QProcess svn; svn.setWorkingDirectory (dir.absolutePath()); QStringList args; args << "list" << "."; if (recursive) args << "--depth=infinity"; svn.start("svn", args); if (!svn.waitForStarted() || !svn.waitForFinished()) return; /** * get output and split up into files */ QStringList relFiles = QString::fromLocal8Bit (svn.readAllStandardOutput ()).split (QRegExp("[\n\r]"), QString::SkipEmptyParts); /** * prepend the directory path */ foreach (QString relFile, relFiles) files.append (dir.absolutePath() + "/" + relFile); } /** * fallback to use QDirIterator and search files ourself! */ else { /** * default filter: only files! */ dir.setFilter (QDir::Files); /** * set name filters, if any */ QStringList filters = filesEntry["filters"].toStringList(); if (!filters.isEmpty()) dir.setNameFilters (filters); /** * construct flags for iterator */ QDirIterator::IteratorFlags flags = QDirIterator::NoIteratorFlags; if (recursive) flags = flags | QDirIterator::Subdirectories; /** * create iterator and collect all files */ QDirIterator dirIterator (dir, flags); while (dirIterator.hasNext()) { dirIterator.next(); files.append (dirIterator.filePath()); } } /** * sort them */ files.sort (); /** * construct paths first in tree and items in a map */ QMap<QString, QStandardItem *> dir2Item; dir2Item[""] = parent; QList<QPair<QStandardItem *, QStandardItem *> > item2ParentPath; foreach (QString filePath, files) { /** * get file info and skip NON-files */ QFileInfo fileInfo (filePath); if (!fileInfo.isFile()) continue; /** * skip dupes */ if (file2Item.contains(filePath)) continue; /** * construct the item with right directory prefix * already hang in directories in tree */ QStandardItem *fileItem = new KateProjectItem (KateProjectItem::File, fileInfo.fileName()); item2ParentPath.append (QPair<QStandardItem *, QStandardItem *>(fileItem, directoryParent(dir2Item, dir.relativeFilePath (fileInfo.absolutePath())))); fileItem->setData (filePath, Qt::UserRole); file2Item[filePath] = fileItem; } /** * plug in the file items to the tree */ QList<QPair<QStandardItem *, QStandardItem *> >::const_iterator i = item2ParentPath.constBegin(); while (i != item2ParentPath.constEnd()) { i->second->appendRow (i->first); ++i; } } void KateProjectWorker::loadCtags (const QStringList &files) { /** * try to run ctags for all files in this project */ QProcess ctags; QStringList args; args << "-L" << "-" << "-f" << "-" << "--fields=+z"; ctags.start("ctags", args); if (!ctags.waitForStarted()) return; /** * write files list and close write channel */ ctags.write(files.join("\n").toLocal8Bit()); ctags.closeWriteChannel(); /** * wait for done */ if (!ctags.waitForFinished()) return; /** * get results and parse them */ QStringList tagLines = QString::fromLocal8Bit (ctags.readAllStandardOutput ()).split (QRegExp("[\n\r]"), QString::SkipEmptyParts); QStringList *completionInfo = new QStringList (); QSet<QString> dupes; foreach (QString tagLine, tagLines) { /** * search first three separators */ int firstTab = tagLine.indexOf ("\t", 0); if (firstTab < 0) continue; int secondTab = tagLine.indexOf ("\t", firstTab+1); if (secondTab < 0) continue; int endOfEx = tagLine.indexOf (";\"\t", secondTab+1); if (endOfEx < 0) continue; /** * get infos */ QString tagName = tagLine.left (firstTab); QString fileName = tagLine.mid (firstTab+1, secondTab-(firstTab+1)); QString exCmd = tagLine.mid (secondTab+1, endOfEx-(secondTab+1)); if (!dupes.contains (tagName)) completionInfo->append (tagName); dupes.insert (tagName); //printf ("tag line: '%s'\n", qPrintable(tagLine.replace("\t", "<TAB>"))); //printf ("parsed info: TN '%s' FN '%s' EC '%s'\n\n", qPrintable(tagName), qPrintable(fileName), qPrintable(exCmd)); } /** * feed back our results */ QMetaObject::invokeMethod (m_project, "loadCompletionDone", Qt::QueuedConnection, Q_ARG(void *, completionInfo)); } // kate: space-indent on; indent-width 2; replace-tabs on; <commit_msg>timing info for debugging, seems I reload project file to often ;)<commit_after>/* This file is part of the Kate project. * * Copyright (C) 2012 Christoph Cullmann <cullmann@kde.org> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "kateprojectworker.h" #include <QDir> #include <QDirIterator> #include <QFile> #include <QFileInfo> #include <QProcess> #include <QSet> #include <QTime> KateProjectWorker::KateProjectWorker (QObject *project) : QObject () , m_project (project) { } KateProjectWorker::~KateProjectWorker () { } void KateProjectWorker::loadProject (QString fileName, QVariantMap projectMap) { /** * setup project file name * name should be FIX after initial setting */ Q_ASSERT (m_fileName.isEmpty() || (m_fileName == fileName)); m_fileName = fileName; /** * Create dummy top level parent item and load the project recursively */ QStandardItem *topLevel = new QStandardItem (); QMap<QString, QStandardItem *> *file2Item = new QMap<QString, QStandardItem *> (); loadProject (topLevel, projectMap, *file2Item); /** * create some local backup of some data we need for further processing! */ QStringList files = file2Item->keys (); /** * feed back our results */ QMetaObject::invokeMethod (m_project, "loadProjectDone", Qt::QueuedConnection, Q_ARG(void *, topLevel), Q_ARG(void *, file2Item)); /** * trigger more updates */ loadCtags (files); } void KateProjectWorker::loadProject (QStandardItem *parent, const QVariantMap &project, QMap<QString, QStandardItem *> &file2Item) { /** * recurse to sub-projects FIRST */ QVariantList subGroups = project["projects"].toList (); foreach (const QVariant &subGroupVariant, subGroups) { /** * convert to map and get name, else skip */ QVariantMap subProject = subGroupVariant.toMap (); if (subProject["name"].toString().isEmpty()) continue; /** * recurse */ QStandardItem *subProjectItem = new KateProjectItem (KateProjectItem::Project, subProject["name"].toString()); loadProject (subProjectItem, subProject, file2Item); parent->appendRow (subProjectItem); } /** * load all specified files */ QVariantList files = project["files"].toList (); foreach (const QVariant &fileVariant, files) loadFilesEntry (parent, fileVariant.toMap (), file2Item); } /** * small helper to construct directory parent items * @param dir2Item map for path => item * @param path current path we need item for * @return correct parent item for given path, will reuse existing ones */ static QStandardItem *directoryParent (QMap<QString, QStandardItem *> &dir2Item, QString path) { /** * throw away simple / */ if (path == "/") path = ""; /** * quick check: dir already seen? */ if (dir2Item.contains (path)) return dir2Item[path]; /** * else: construct recursively */ int slashIndex = path.lastIndexOf ('/'); /** * no slash? * simple, no recursion, append new item toplevel */ if (slashIndex < 0) { dir2Item[path] = new KateProjectItem (KateProjectItem::Directory, path); dir2Item[""]->appendRow (dir2Item[path]); return dir2Item[path]; } /** * else, split and recurse */ QString leftPart = path.left (slashIndex); QString rightPart = path.right (path.size() - (slashIndex + 1)); /** * special handling if / with nothing on one side are found */ if (leftPart.isEmpty() || rightPart.isEmpty ()) return directoryParent (dir2Item, leftPart.isEmpty() ? rightPart : leftPart); /** * else: recurse on left side */ dir2Item[path] = new KateProjectItem (KateProjectItem::Directory, rightPart); directoryParent (dir2Item, leftPart)->appendRow (dir2Item[path]); return dir2Item[path]; } void KateProjectWorker::loadFilesEntry (QStandardItem *parent, const QVariantMap &filesEntry, QMap<QString, QStandardItem *> &file2Item) { /** * get directory to open or skip */ QDir dir (QFileInfo (m_fileName).absoluteDir()); if (!dir.cd (filesEntry["directory"].toString())) return; /** * get recursive attribute, default is TRUE */ const bool recursive = !filesEntry.contains ("recursive") || filesEntry["recursive"].toBool(); /** * now: choose between different methodes to get files in the directory */ QStringList files; /** * use GIT */ if (filesEntry["git"].toBool()) { /** * try to run git with ls-files for this directory */ QProcess git; git.setWorkingDirectory (dir.absolutePath()); QStringList args; args << "ls-files" << "."; git.start("git", args); if (!git.waitForStarted() || !git.waitForFinished()) return; /** * get output and split up into files */ QStringList relFiles = QString::fromLocal8Bit (git.readAllStandardOutput ()).split (QRegExp("[\n\r]"), QString::SkipEmptyParts); /** * prepend the directory path */ foreach (QString relFile, relFiles) { /** * skip non-direct files if not recursive */ if (!recursive && (relFile.indexOf ("/") != -1)) continue; files.append (dir.absolutePath() + "/" + relFile); } } /** * use SVN */ else if (filesEntry["svn"].toBool()) { /** * try to run git with ls-files for this directory */ QProcess svn; svn.setWorkingDirectory (dir.absolutePath()); QStringList args; args << "list" << "."; if (recursive) args << "--depth=infinity"; svn.start("svn", args); if (!svn.waitForStarted() || !svn.waitForFinished()) return; /** * get output and split up into files */ QStringList relFiles = QString::fromLocal8Bit (svn.readAllStandardOutput ()).split (QRegExp("[\n\r]"), QString::SkipEmptyParts); /** * prepend the directory path */ foreach (QString relFile, relFiles) files.append (dir.absolutePath() + "/" + relFile); } /** * fallback to use QDirIterator and search files ourself! */ else { /** * default filter: only files! */ dir.setFilter (QDir::Files); /** * set name filters, if any */ QStringList filters = filesEntry["filters"].toStringList(); if (!filters.isEmpty()) dir.setNameFilters (filters); /** * construct flags for iterator */ QDirIterator::IteratorFlags flags = QDirIterator::NoIteratorFlags; if (recursive) flags = flags | QDirIterator::Subdirectories; /** * create iterator and collect all files */ QDirIterator dirIterator (dir, flags); while (dirIterator.hasNext()) { dirIterator.next(); files.append (dirIterator.filePath()); } } /** * sort them */ files.sort (); /** * construct paths first in tree and items in a map */ QMap<QString, QStandardItem *> dir2Item; dir2Item[""] = parent; QList<QPair<QStandardItem *, QStandardItem *> > item2ParentPath; foreach (QString filePath, files) { /** * get file info and skip NON-files */ QFileInfo fileInfo (filePath); if (!fileInfo.isFile()) continue; /** * skip dupes */ if (file2Item.contains(filePath)) continue; /** * construct the item with right directory prefix * already hang in directories in tree */ QStandardItem *fileItem = new KateProjectItem (KateProjectItem::File, fileInfo.fileName()); item2ParentPath.append (QPair<QStandardItem *, QStandardItem *>(fileItem, directoryParent(dir2Item, dir.relativeFilePath (fileInfo.absolutePath())))); fileItem->setData (filePath, Qt::UserRole); file2Item[filePath] = fileItem; } /** * plug in the file items to the tree */ QList<QPair<QStandardItem *, QStandardItem *> >::const_iterator i = item2ParentPath.constBegin(); while (i != item2ParentPath.constEnd()) { i->second->appendRow (i->first); ++i; } } void KateProjectWorker::loadCtags (const QStringList &files) { /** * get some timing stats */ QTime timer; timer.start (); /** * try to run ctags for all files in this project */ QProcess ctags; QStringList args; args << "-L" << "-" << "-f" << "-" << "--fields=+z"; ctags.start("ctags", args); if (!ctags.waitForStarted()) return; /** * write files list and close write channel */ ctags.write(files.join("\n").toLocal8Bit()); ctags.closeWriteChannel(); /** * wait for done */ if (!ctags.waitForFinished()) return; /** * get results and parse them */ QStringList tagLines = QString::fromLocal8Bit (ctags.readAllStandardOutput ()).split (QRegExp("[\n\r]"), QString::SkipEmptyParts); QStringList *completionInfo = new QStringList (); QSet<QString> dupes; foreach (QString tagLine, tagLines) { /** * search first three separators */ int firstTab = tagLine.indexOf ("\t", 0); if (firstTab < 0) continue; int secondTab = tagLine.indexOf ("\t", firstTab+1); if (secondTab < 0) continue; int endOfEx = tagLine.indexOf (";\"\t", secondTab+1); if (endOfEx < 0) continue; /** * get infos */ QString tagName = tagLine.left (firstTab); QString fileName = tagLine.mid (firstTab+1, secondTab-(firstTab+1)); QString exCmd = tagLine.mid (secondTab+1, endOfEx-(secondTab+1)); if (!dupes.contains (tagName)) completionInfo->append (tagName); dupes.insert (tagName); //printf ("tag line: '%s'\n", qPrintable(tagLine.replace("\t", "<TAB>"))); //printf ("parsed info: TN '%s' FN '%s' EC '%s'\n\n", qPrintable(tagName), qPrintable(fileName), qPrintable(exCmd)); } qDebug ("ctags extration did take %d ms", timer.elapsed()); /** * feed back our results */ QMetaObject::invokeMethod (m_project, "loadCompletionDone", Qt::QueuedConnection, Q_ARG(void *, completionInfo)); } // kate: space-indent on; indent-width 2; replace-tabs on; <|endoftext|>
<commit_before>#ifndef LIBTG_HPP #define LIBTG_HPP #include <bits/stdc++.h> #include "uint_t.hpp" // ============================================================================= // Types // ============================================================================= enum {CONJ=1,DISJ,IMPL,EQUI,NEGA,ATOM}; struct Vertex { char type; int variable; int up; std::vector<int> down; Vertex(); void remove(); }; struct CNF_t { bool simple; CNF_t(); // statistics int size() const; // compute CNF size uint_t clauses() const; // compute number of clauses (formula must be in NNF) int symbols() const; // compute number of symbols }; // ============================================================================= // Globals // ============================================================================= extern std::string raw; // input extern std::vector<Vertex> T,G; // tree and DAG extern int nextvar; // next variable id extern std::unordered_map<int,std::string> varname; // variables' names extern std::vector<int> R; // renaming extern std::set<std::set<int>> simplified; // simplified CNF extern CNF_t CNF; // final CNF // ============================================================================= // Functions // ============================================================================= // transformation pipeline void parse(); // parse string raw to build tree T void nnf(); // put tree T in NNF void flat(); // flat tree T. (p|(q|r)|s) becomes (p|q|r|s) void dag(); // convert tree T to DAG G void mindag(); // minimize DAG G. (p|q)&(p|r|s|q) becomes (p|q)&((p|q)|r|s) void boydelatour(); // Boy de la Tour's algorithm to choose a renaming void knapsack(); // Knapsack 0-1 based algorithm to choose a renaming void rename(); // apply renaming R to DAG G void cnf(); // put DAG G in CNF (G must be in NNF) void simplecnf(); // put DAG G in CNF (G must be in NNF), removing // tautologies, repeated literals and repeated clauses // statistics int size(const std::vector<Vertex>&); // compute formula size uint_t clauses(const std::vector<Vertex>&); // compute number of clauses // (formula must be in NNF) int symbols(const std::vector<Vertex>&); // compute number of symbols // formatted output std::ostream& operator<<(std::ostream&, const std::vector<Vertex>&); std::ostream& operator<<(std::ostream&, const CNF_t&); #endif <commit_msg>Updating comments<commit_after>#ifndef LIBTG_HPP #define LIBTG_HPP #include <bits/stdc++.h> #include "uint_t.hpp" // ============================================================================= // Types // ============================================================================= enum {CONJ=1,DISJ,IMPL,EQUI,NEGA,ATOM}; struct Vertex { char type; int variable; int up; std::vector<int> down; Vertex(); void remove(); }; struct CNF_t { bool simple; CNF_t(); // statistics int size() const; // compute CNF size uint_t clauses() const; // compute number of clauses int symbols() const; // compute number of symbols }; // ============================================================================= // Globals // ============================================================================= extern std::string raw; // input extern std::vector<Vertex> T,G; // tree and DAG extern int nextvar; // next variable id extern std::unordered_map<int,std::string> varname; // variables' names extern std::vector<int> R; // renaming extern std::set<std::set<int>> simplified; // simplified CNF extern CNF_t CNF; // final CNF // ============================================================================= // Functions // ============================================================================= // transformation pipeline void parse(); // parse string raw to build tree T void nnf(); // put tree T in NNF void flat(); // flat tree T. (p|(q|r)|s) becomes (p|q|r|s) void dag(); // convert tree T to DAG G void mindag(); // minimize DAG G. (p|q)&(p|r|s|q) becomes (p|q)&((p|q)|r|s) void boydelatour(); // Boy de la Tour's algorithm to choose a renaming void knapsack(); // Knapsack 0-1 based algorithm to choose a renaming void rename(); // apply renaming R to DAG G void cnf(); // put DAG G in CNF (G must be in NNF) void simplecnf(); // put DAG G in CNF (G must be in NNF), removing // tautologies, repeated literals and repeated clauses // statistics int size(const std::vector<Vertex>&); // compute formula size uint_t clauses(const std::vector<Vertex>&); // compute number of clauses int symbols(const std::vector<Vertex>&); // compute number of symbols // formatted output std::ostream& operator<<(std::ostream&, const std::vector<Vertex>&); std::ostream& operator<<(std::ostream&, const CNF_t&); #endif <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: timemeasure.hxx,v $ * * $Revision: 1.1 $ * * last change: $Author: as $ $Date: 2001-05-21 06:12:32 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef __FRAMEWORK_MACROS_DEBUG_TIMEMEASURE_HXX_ #define __FRAMEWORK_MACROS_DEBUG_TIMEMEASURE_HXX_ //************************************************************************************************************* // special macros for time measures // 1) LOGFILE_TIMEMEASURE used it to define log file for this operations (default will be set automaticly) // 2) START_TIMEMEASURE start new measure by using given variable names // 3) START_TIMEMEASURE stop current measure by using given variable names and return time // 4) LOG_TIMEMEASURE write measured time to logfile //************************************************************************************************************* #ifdef ENABLE_TIMEMEASURE //_________________________________________________________________________________________________________________ // includes //_________________________________________________________________________________________________________________ #ifndef _RTL_STRBUF_HXX_ #include <rtl/strbuf.hxx> #endif #ifndef _OSL_TIME_H_ #include <osl/time.h> #endif /*_____________________________________________________________________________________________________________ LOGFILE_TIMEMEASURE For follow macros we need a special log file. If user forget to specify anyone, we must do it for him! _____________________________________________________________________________________________________________*/ #ifndef LOGFILE_TIMEMEASURE #define LOGFILE_TIMEMEASURE "timemeasure.log" #endif /*_____________________________________________________________________________________________________________ class TimeMeasure We need this inline class as global timer to make it possible measure times over different objects! zB. Use it as baseclass to start timer at ctor (must be first called baseclass!!!) and stop it by calling stop method. _____________________________________________________________________________________________________________*/ class DBGTimeMeasureBase { public: inline DBGTimeMeasureBase() { m_nEnd = 0 ; m_nStart = osl_getGlobalTimer(); } inline sal_Int32 stopAndGet() { m_nEnd = osl_getGlobalTimer(); return( m_nEnd-m_nStart ); } private: sal_Int32 m_nStart ; sal_Int32 m_nEnd ; }; /*_____________________________________________________________________________________________________________ START_TIMEMEASURE( NSTART, NEND ) STOP_TIMEMEASURE( NSTART, NEND, NTIME ) If you doesn't need a time measure above different classes ... you can try this macros! They initialize your given members with start end end time ... You can calculate differenz by himself. _____________________________________________________________________________________________________________*/ #define START_TIMEMEASURE( NSTART, NEND ) \ sal_Int32 NSTART = 0; \ sal_Int32 NEND = 0; \ NSTART = osl_getGlobalTimer(); #define STOP_TIMEMEASURE( NSTART, NEND, NTIME ) \ NEND = osl_getGlobalTimer(); \ sal_Int32 NTIME = NEND-NSTART; /*_____________________________________________________________________________________________________________ LOG_TIMEMEASURE( SOPERATION, NSTART ) Write measured time to logfile. _____________________________________________________________________________________________________________*/ #define LOG_TIMEMEASURE( SOPERATION, NTIME ) \ { \ ::rtl::OStringBuffer _sBuffer( 256 ); \ _sBuffer.append( SOPERATION ); \ _sBuffer.append( "\t=\t" ); \ _sBuffer.append( (sal_Int32)(NTIME) ); \ _sBuffer.append( " ms\n" ); \ WRITE_LOGFILE( LOGFILE_TIMEMEASURE, _sBuffer.makeStringAndClear().getStr() ) \ } #else // #ifdef ENABLE_TIMEMEASURE /*_____________________________________________________________________________________________________________ If right testmode is'nt set - implements these macros empty! _____________________________________________________________________________________________________________*/ #undef LOGFILE_EVENTDEBUG #define START_TIMEMEASURE( NSTART, NEND ) #define STOP_TIMEMEASURE( NSTART, NEND, NTIME ) #define LOG_TIMEMEASURE( SOPERATION, NTIME ) #endif // #ifdef ENABLE_TIMEMEASURE //***************************************************************************************************************** // end of file //***************************************************************************************************************** #endif // #ifndef __FRAMEWORK_MACROS_DEBUG_TIMEMEASURE_HXX_ <commit_msg>#86171# repair time measure macros<commit_after>/************************************************************************* * * $RCSfile: timemeasure.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: as $ $Date: 2001-06-05 10:18:30 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef __FRAMEWORK_MACROS_DEBUG_TIMEMEASURE_HXX_ #define __FRAMEWORK_MACROS_DEBUG_TIMEMEASURE_HXX_ //************************************************************************************************************* // special macros for time measures // 1) LOGFILE_TIMEMEASURE used it to define log file for this operations (default will be set automaticly) // 2) START_TIMEMEASURE start new measure by using given variable names // 3) START_TIMEMEASURE stop current measure by using given variable names and return time // 4) LOG_TIMEMEASURE write measured time to logfile //************************************************************************************************************* #ifdef ENABLE_TIMEMEASURE //_________________________________________________________________________________________________________________ // includes //_________________________________________________________________________________________________________________ #ifndef _RTL_STRBUF_HXX_ #include <rtl/strbuf.hxx> #endif #ifndef _OSL_TIME_H_ #include <osl/time.h> #endif /*_____________________________________________________________________________________________________________ LOGFILE_TIMEMEASURE For follow macros we need a special log file. If user forget to specify anyone, we must do it for him! _____________________________________________________________________________________________________________*/ #ifndef LOGFILE_TIMEMEASURE #define LOGFILE_TIMEMEASURE "timemeasure.log" #endif /*_____________________________________________________________________________________________________________ class TimeMeasure We need this inline class as global timer to make it possible measure times over different objects! zB. Use it as baseclass to start timer at ctor (must be first called baseclass!!!) and stop it by calling stop method. _____________________________________________________________________________________________________________*/ class DBGTimeMeasureBase { public: inline DBGTimeMeasureBase() { m_nEnd = 0 ; m_nStart = osl_getGlobalTimer(); } inline sal_Int32 stopAndGet() { m_nEnd = osl_getGlobalTimer(); return( m_nEnd-m_nStart ); } private: sal_Int32 m_nStart ; sal_Int32 m_nEnd ; }; /*_____________________________________________________________________________________________________________ START_TIMEMEASURE( NSTART, NEND ) STOP_TIMEMEASURE( NSTART, NEND, NTIME ) If you doesn't need a time measure above different classes ... you can try this macros! They initialize your given members with start end end time ... You can calculate differenz by himself. _____________________________________________________________________________________________________________*/ #define START_TIMEMEASURE( NSTART, NEND ) \ sal_Int32 NSTART = 0; \ sal_Int32 NEND = 0; \ NSTART = osl_getGlobalTimer(); #define STOP_TIMEMEASURE( NSTART, NEND, NTIME ) \ NEND = osl_getGlobalTimer(); \ sal_Int32 NTIME = NEND-NSTART; /*_____________________________________________________________________________________________________________ LOG_TIMEMEASURE( SOPERATION, NSTART ) Write measured time to logfile. _____________________________________________________________________________________________________________*/ #define LOG_TIMEMEASURE( SOPERATION, NTIME ) \ { \ ::rtl::OStringBuffer _sBuffer( 256 ); \ _sBuffer.append( SOPERATION ); \ _sBuffer.append( "\t=\t" ); \ _sBuffer.append( (sal_Int32)(NTIME) ); \ _sBuffer.append( " ms\n" ); \ WRITE_LOGFILE( LOGFILE_TIMEMEASURE, _sBuffer.makeStringAndClear().getStr() ) \ } #else // #ifdef ENABLE_TIMEMEASURE /*_____________________________________________________________________________________________________________ If right testmode is'nt set - implements these macros empty! _____________________________________________________________________________________________________________*/ #undef LOGFILE_TIMEMEASURE #define START_TIMEMEASURE( NSTART, NEND ) #define STOP_TIMEMEASURE( NSTART, NEND, NTIME ) #define LOG_TIMEMEASURE( SOPERATION, NTIME ) #endif // #ifdef ENABLE_TIMEMEASURE //***************************************************************************************************************** // end of file //***************************************************************************************************************** #endif // #ifndef __FRAMEWORK_MACROS_DEBUG_TIMEMEASURE_HXX_ <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/ ** ** This file is part of the test suite of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** 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. ** ** 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. ** ** 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. ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <QtTest/QtTest> #include <QtTest/QSignalSpy> #include <QtQml/qqmlengine.h> #include <QtQml/qqmlcomponent.h> #include <QtCore/qdir.h> #include <QtCore/qfile.h> #include <QtCore/qabstractitemmodel.h> #include <QDebug> #include "../../shared/util.h" #if defined (Q_OS_WIN) #include <qt_windows.h> #endif // From qquickfolderlistmodel.h const int FileNameRole = Qt::UserRole+1; const int FilePathRole = Qt::UserRole+2; enum SortField { Unsorted, Name, Time, Size, Type }; class tst_qquickfolderlistmodel : public QQmlDataTest { Q_OBJECT public: tst_qquickfolderlistmodel() : removeStart(0), removeEnd(0) {} public slots: void removed(const QModelIndex &, int start, int end) { removeStart = start; removeEnd = end; } private slots: void basicProperties(); void resetFiltering(); void refresh(); #if defined (Q_OS_WIN) void changeDrive(); #endif private: void checkNoErrors(const QQmlComponent& component); QQmlEngine engine; int removeStart; int removeEnd; }; void tst_qquickfolderlistmodel::checkNoErrors(const QQmlComponent& component) { // Wait until the component is ready QTRY_VERIFY(component.isReady() || component.isError()); if (component.isError()) { QList<QQmlError> errors = component.errors(); for (int ii = 0; ii < errors.count(); ++ii) { const QQmlError &error = errors.at(ii); QByteArray errorStr = QByteArray::number(error.line()) + ":" + QByteArray::number(error.column()) + ":" + error.description().toUtf8(); qWarning() << errorStr; } } QVERIFY(!component.isError()); } void tst_qquickfolderlistmodel::basicProperties() { QQmlComponent component(&engine, testFileUrl("basic.qml")); checkNoErrors(component); QAbstractListModel *flm = qobject_cast<QAbstractListModel*>(component.create()); QVERIFY(flm != 0); flm->setProperty("folder", dataDirectoryUrl()); QTRY_COMPARE(flm->property("count").toInt(),4); // wait for refresh QCOMPARE(flm->property("folder").toUrl(), dataDirectoryUrl()); QCOMPARE(flm->property("parentFolder").toUrl(), QUrl::fromLocalFile(QDir(directory()).canonicalPath())); QCOMPARE(flm->property("sortField").toInt(), int(Name)); QCOMPARE(flm->property("nameFilters").toStringList(), QStringList() << "*.qml"); QCOMPARE(flm->property("sortReversed").toBool(), false); QCOMPARE(flm->property("showDirs").toBool(), true); QCOMPARE(flm->property("showDotAndDotDot").toBool(), false); QCOMPARE(flm->property("showOnlyReadable").toBool(), false); QCOMPARE(flm->data(flm->index(0),FileNameRole).toString(), QLatin1String("basic.qml")); QCOMPARE(flm->data(flm->index(1),FileNameRole).toString(), QLatin1String("dummy.qml")); flm->setProperty("folder",QUrl::fromLocalFile("")); QCOMPARE(flm->property("folder").toUrl(), QUrl::fromLocalFile("")); } void tst_qquickfolderlistmodel::resetFiltering() { // see QTBUG-17837 QQmlComponent component(&engine, testFileUrl("resetFiltering.qml")); checkNoErrors(component); QAbstractListModel *flm = qobject_cast<QAbstractListModel*>(component.create()); QVERIFY(flm != 0); connect(flm, SIGNAL(rowsRemoved(const QModelIndex&,int,int)), this, SLOT(removed(const QModelIndex&,int,int))); flm->setProperty("folder", testFileUrl("resetfiltering")); QTRY_COMPARE(flm->property("count").toInt(),1); // should just be "test.txt" visible int count = flm->rowCount(); QCOMPARE(removeStart, 0); QCOMPARE(removeEnd, count-1); flm->setProperty("folder", testFileUrl("resetfiltering/innerdir")); QTRY_COMPARE(flm->property("count").toInt(),1); // should just be "test2.txt" visible count = flm->rowCount(); QCOMPARE(removeStart, 0); QCOMPARE(removeEnd, count-1); flm->setProperty("folder", testFileUrl("resetfiltering")); QTRY_COMPARE(flm->property("count").toInt(),1); // should just be "test.txt" visible count = flm->rowCount(); QCOMPARE(removeStart, 0); QCOMPARE(removeEnd, count-1); } void tst_qquickfolderlistmodel::refresh() { QQmlComponent component(&engine, testFileUrl("basic.qml")); checkNoErrors(component); QAbstractListModel *flm = qobject_cast<QAbstractListModel*>(component.create()); QVERIFY(flm != 0); flm->setProperty("folder", dataDirectoryUrl()); QTRY_COMPARE(flm->property("count").toInt(),4); // wait for refresh int count = flm->rowCount(); connect(flm, SIGNAL(rowsRemoved(const QModelIndex&,int,int)), this, SLOT(removed(const QModelIndex&,int,int))); flm->setProperty("sortReversed", true); QTRY_COMPARE(removeStart, 0); QTRY_COMPARE(removeEnd, count-1); // wait for refresh } #if defined (Q_OS_WIN) void tst_qquickfolderlistmodel::changeDrive() { class DriveMapper { public: DriveMapper(const QString &dataDir) { size_t stringLen = dataDir.length(); targetPath = new wchar_t[stringLen+1]; dataDir.toWCharArray(targetPath); targetPath[stringLen] = 0; DefineDosDevice(DDD_NO_BROADCAST_SYSTEM, L"X:", targetPath); } ~DriveMapper() { DefineDosDevice(DDD_EXACT_MATCH_ON_REMOVE | DDD_NO_BROADCAST_SYSTEM | DDD_REMOVE_DEFINITION, L"X:", targetPath); delete [] targetPath; } private: wchar_t *targetPath; }; QString dataDir = testFile(0); DriveMapper dm(dataDir); QQmlComponent component(&engine, testFileUrl("basic.qml")); QAbstractListModel *flm = qobject_cast<QAbstractListModel*>(component.create()); QVERIFY(flm != 0); QSignalSpy folderChangeSpy(flm, SIGNAL(folderChanged())); flm->setProperty("folder",QUrl::fromLocalFile(dataDir)); QCOMPARE(flm->property("folder").toUrl(), QUrl::fromLocalFile(dataDir)); QTRY_VERIFY(folderChangeSpy.count() == 1); flm->setProperty("folder",QUrl::fromLocalFile("X:/resetfiltering/")); QCOMPARE(flm->property("folder").toUrl(), QUrl::fromLocalFile("X:/resetfiltering/")); QTRY_VERIFY(folderChangeSpy.count() == 2); } #endif QTEST_MAIN(tst_qquickfolderlistmodel) #include "tst_qquickfolderlistmodel.moc" <commit_msg>Skip tst_qquickfolderlistmodel::changeDrive()<commit_after>/**************************************************************************** ** ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/ ** ** This file is part of the test suite of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** 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. ** ** 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. ** ** 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. ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <QtTest/QtTest> #include <QtTest/QSignalSpy> #include <QtQml/qqmlengine.h> #include <QtQml/qqmlcomponent.h> #include <QtCore/qdir.h> #include <QtCore/qfile.h> #include <QtCore/qabstractitemmodel.h> #include <QDebug> #include "../../shared/util.h" #if defined (Q_OS_WIN) #include <qt_windows.h> #endif // From qquickfolderlistmodel.h const int FileNameRole = Qt::UserRole+1; const int FilePathRole = Qt::UserRole+2; enum SortField { Unsorted, Name, Time, Size, Type }; class tst_qquickfolderlistmodel : public QQmlDataTest { Q_OBJECT public: tst_qquickfolderlistmodel() : removeStart(0), removeEnd(0) {} public slots: void removed(const QModelIndex &, int start, int end) { removeStart = start; removeEnd = end; } private slots: void basicProperties(); void resetFiltering(); void refresh(); #if defined (Q_OS_WIN) void changeDrive(); #endif private: void checkNoErrors(const QQmlComponent& component); QQmlEngine engine; int removeStart; int removeEnd; }; void tst_qquickfolderlistmodel::checkNoErrors(const QQmlComponent& component) { // Wait until the component is ready QTRY_VERIFY(component.isReady() || component.isError()); if (component.isError()) { QList<QQmlError> errors = component.errors(); for (int ii = 0; ii < errors.count(); ++ii) { const QQmlError &error = errors.at(ii); QByteArray errorStr = QByteArray::number(error.line()) + ":" + QByteArray::number(error.column()) + ":" + error.description().toUtf8(); qWarning() << errorStr; } } QVERIFY(!component.isError()); } void tst_qquickfolderlistmodel::basicProperties() { QQmlComponent component(&engine, testFileUrl("basic.qml")); checkNoErrors(component); QAbstractListModel *flm = qobject_cast<QAbstractListModel*>(component.create()); QVERIFY(flm != 0); flm->setProperty("folder", dataDirectoryUrl()); QTRY_COMPARE(flm->property("count").toInt(),4); // wait for refresh QCOMPARE(flm->property("folder").toUrl(), dataDirectoryUrl()); QCOMPARE(flm->property("parentFolder").toUrl(), QUrl::fromLocalFile(QDir(directory()).canonicalPath())); QCOMPARE(flm->property("sortField").toInt(), int(Name)); QCOMPARE(flm->property("nameFilters").toStringList(), QStringList() << "*.qml"); QCOMPARE(flm->property("sortReversed").toBool(), false); QCOMPARE(flm->property("showDirs").toBool(), true); QCOMPARE(flm->property("showDotAndDotDot").toBool(), false); QCOMPARE(flm->property("showOnlyReadable").toBool(), false); QCOMPARE(flm->data(flm->index(0),FileNameRole).toString(), QLatin1String("basic.qml")); QCOMPARE(flm->data(flm->index(1),FileNameRole).toString(), QLatin1String("dummy.qml")); flm->setProperty("folder",QUrl::fromLocalFile("")); QCOMPARE(flm->property("folder").toUrl(), QUrl::fromLocalFile("")); } void tst_qquickfolderlistmodel::resetFiltering() { // see QTBUG-17837 QQmlComponent component(&engine, testFileUrl("resetFiltering.qml")); checkNoErrors(component); QAbstractListModel *flm = qobject_cast<QAbstractListModel*>(component.create()); QVERIFY(flm != 0); connect(flm, SIGNAL(rowsRemoved(const QModelIndex&,int,int)), this, SLOT(removed(const QModelIndex&,int,int))); flm->setProperty("folder", testFileUrl("resetfiltering")); QTRY_COMPARE(flm->property("count").toInt(),1); // should just be "test.txt" visible int count = flm->rowCount(); QCOMPARE(removeStart, 0); QCOMPARE(removeEnd, count-1); flm->setProperty("folder", testFileUrl("resetfiltering/innerdir")); QTRY_COMPARE(flm->property("count").toInt(),1); // should just be "test2.txt" visible count = flm->rowCount(); QCOMPARE(removeStart, 0); QCOMPARE(removeEnd, count-1); flm->setProperty("folder", testFileUrl("resetfiltering")); QTRY_COMPARE(flm->property("count").toInt(),1); // should just be "test.txt" visible count = flm->rowCount(); QCOMPARE(removeStart, 0); QCOMPARE(removeEnd, count-1); } void tst_qquickfolderlistmodel::refresh() { QQmlComponent component(&engine, testFileUrl("basic.qml")); checkNoErrors(component); QAbstractListModel *flm = qobject_cast<QAbstractListModel*>(component.create()); QVERIFY(flm != 0); flm->setProperty("folder", dataDirectoryUrl()); QTRY_COMPARE(flm->property("count").toInt(),4); // wait for refresh int count = flm->rowCount(); connect(flm, SIGNAL(rowsRemoved(const QModelIndex&,int,int)), this, SLOT(removed(const QModelIndex&,int,int))); flm->setProperty("sortReversed", true); QTRY_COMPARE(removeStart, 0); QTRY_COMPARE(removeEnd, count-1); // wait for refresh } #if defined (Q_OS_WIN) void tst_qquickfolderlistmodel::changeDrive() { QSKIP("QTBUG-26728"); class DriveMapper { public: DriveMapper(const QString &dataDir) { size_t stringLen = dataDir.length(); targetPath = new wchar_t[stringLen+1]; dataDir.toWCharArray(targetPath); targetPath[stringLen] = 0; DefineDosDevice(DDD_NO_BROADCAST_SYSTEM, L"X:", targetPath); } ~DriveMapper() { DefineDosDevice(DDD_EXACT_MATCH_ON_REMOVE | DDD_NO_BROADCAST_SYSTEM | DDD_REMOVE_DEFINITION, L"X:", targetPath); delete [] targetPath; } private: wchar_t *targetPath; }; QString dataDir = testFile(0); DriveMapper dm(dataDir); QQmlComponent component(&engine, testFileUrl("basic.qml")); QAbstractListModel *flm = qobject_cast<QAbstractListModel*>(component.create()); QVERIFY(flm != 0); QSignalSpy folderChangeSpy(flm, SIGNAL(folderChanged())); flm->setProperty("folder",QUrl::fromLocalFile(dataDir)); QCOMPARE(flm->property("folder").toUrl(), QUrl::fromLocalFile(dataDir)); QTRY_VERIFY(folderChangeSpy.count() == 1); flm->setProperty("folder",QUrl::fromLocalFile("X:/resetfiltering/")); QCOMPARE(flm->property("folder").toUrl(), QUrl::fromLocalFile("X:/resetfiltering/")); QTRY_VERIFY(folderChangeSpy.count() == 2); } #endif QTEST_MAIN(tst_qquickfolderlistmodel) #include "tst_qquickfolderlistmodel.moc" <|endoftext|>
<commit_before>#include "frc971/control_loops/drivetrain/drivetrain.h" #include <stdio.h> namespace frc971 { namespace control_loops { namespace drivetrain { DrivetrainLoop *loop1296; struct DrivetrainConfig config1296; extern "C" void CheezyInit1296(void) { config1296.shifter_type = ShifterType::SIMPLE_SHIFTER; config1296.dt = 0.02; // Control loop time step. config1296.stall_torque = 0.71; // Stall torque in N m. config1296.stall_current = 134.0; // Stall current in amps. config1296.free_speed_rpm = 18100.0; // Free speed in rpm. config1296.free_current = 0.7; // Free current in amps. config1296.j = 2.8; // CIM moment of inertia in kg m^2. config1296.mass = 22.79; // Mass of the robot. config1296.robot_radius = 0.558; // Robot radius, in meters. config1296.wheel_radius = 0.152; // Wheel radius, in meters. config1296.r = (12.0 / 134.0 / 2); // Motor resistance. config1296.v = ((config1296.free_speed_rpm / 60.0 * 2.0 * 3.141519) / (12.0 - config1296.free_current * config1296.r)); // Motor velocity constant. config1296.t = (config1296.stall_torque / config1296.stall_current); // Torque constant. config1296.turn_width = (0.558 * 4.0); // Robot turn width, in meters. config1296.high_gear_ratio = 1.0; // Gear ratios, from encoder shaft to transmission output. config1296.low_gear_ratio = 1.0; loop1296 = new DrivetrainLoop(config1296); } extern "C" void CheezyIterate1296( const DrivetrainGoal *goal, const DrivetrainPosition *position, DrivetrainOutput *output, DrivetrainStatus *status) { loop1296->RunIteration(goal, position, output, status); } } // namespace drivetrain } // namespace control_loops } // namespace frc971 <commit_msg>gear ration should be the same as in python<commit_after>#include "frc971/control_loops/drivetrain/drivetrain.h" #include <stdio.h> namespace frc971 { namespace control_loops { namespace drivetrain { DrivetrainLoop *loop1296; struct DrivetrainConfig config1296; extern "C" void CheezyInit1296(void) { config1296.shifter_type = ShifterType::SIMPLE_SHIFTER; config1296.dt = 0.02; // Control loop time step. config1296.stall_torque = 0.71; // Stall torque in N m. config1296.stall_current = 134.0; // Stall current in amps. config1296.free_speed_rpm = 18100.0; // Free speed in rpm. config1296.free_current = 0.7; // Free current in amps. config1296.j = 2.8; // CIM moment of inertia in kg m^2. config1296.mass = 22.79; // Mass of the robot. config1296.robot_radius = 0.558; // Robot radius, in meters. config1296.wheel_radius = 0.152; // Wheel radius, in meters. config1296.r = (12.0 / 134.0 / 2); // Motor resistance. config1296.v = ((config1296.free_speed_rpm / 60.0 * 2.0 * 3.141519) / (12.0 - config1296.free_current * config1296.r)); // Motor velocity constant. config1296.t = (config1296.stall_torque / config1296.stall_current); // Torque constant. config1296.turn_width = (0.558 * 4.0); // Robot turn width, in meters. config1296.high_gear_ratio = 28.0; // Gear ratios config1296.low_gear_ratio = 28.0; loop1296 = new DrivetrainLoop(config1296); } extern "C" void CheezyIterate1296( const DrivetrainGoal *goal, const DrivetrainPosition *position, DrivetrainOutput *output, DrivetrainStatus *status) { loop1296->RunIteration(goal, position, output, status); } } // namespace drivetrain } // namespace control_loops } // namespace frc971 <|endoftext|>
<commit_before>// $Id: energyMinimizer.C,v 1.5 1999/12/30 20:30:44 oliver Exp $ #include <BALL/MOLMEC/MINIMIZATION/energyMinimizer.h> #include <BALL/COMMON/limits.h> using namespace std; namespace BALL { const char* EnergyMinimizer::Option::MAXIMAL_NUMBER_OF_ITERATIONS = "maximal_number_of_iterations"; const char* EnergyMinimizer::Option::ENERGY_OUTPUT_FREQUENCY = "energy_output_frequency"; const char* EnergyMinimizer::Option::SNAPSHOT_FREQUENCY = "snapshot_frequency"; const char* EnergyMinimizer::Option::NUMBER_OF_ITERATION = "number_of_iteration"; // if the current rms gradient is below this one, we are converged const char *EnergyMinimizer::Option::MAX_GRADIENT = "max_gradient"; const char* EnergyMinimizer::Option::MAXIMAL_SHIFT = "MAXIMAL_SHIFT"; // The maximum number of iteration with equal energy // If this number is reached, we assume convergence const char* EnergyMinimizer::Option::MAX_SAME_ENERGY = "max_same_energy"; // The corresponding energy difference needed for assuming 'equal energy' const char* EnergyMinimizer::Option::ENERGY_DIFFERENCE_BOUND = "energy_difference_bound"; Size EnergyMinimizer::Default::MAXIMAL_NUMBER_OF_ITERATIONS = 1000; Size EnergyMinimizer::Default::ENERGY_OUTPUT_FREQUENCY = 50; Size EnergyMinimizer::Default::SNAPSHOT_FREQUENCY = Limits<Size>::max(); Size EnergyMinimizer::Default::NUMBER_OF_ITERATION = 0; // start number Size EnergyMinimizer::Default::MAX_SAME_ENERGY = 20; float EnergyMinimizer::Default::ENERGY_DIFFERENCE_BOUND = 1e-4; // in kJ/mol float EnergyMinimizer::Default::MAX_GRADIENT = 0.0001; // in kJ/(mol A) float EnergyMinimizer::Default::MAXIMAL_SHIFT = 0.4; // Angstrom // default constructor EnergyMinimizer::EnergyMinimizer() : valid_(false), force_field_(0) { } // copy constructor EnergyMinimizer::EnergyMinimizer(const EnergyMinimizer& energy_minimizer, bool /* deep */) { // Copy the attributes force_field_ = energy_minimizer.force_field_; options = energy_minimizer.options; valid_ = energy_minimizer.valid_; // BAUSTELLE // snapshot_ = energy_minimizer.snapshot_; number_of_iteration_ = energy_minimizer.number_of_iteration_; maximal_number_of_iterations_ = energy_minimizer.maximal_number_of_iterations_ ; energy_output_frequency_ = energy_minimizer.energy_output_frequency_; snapshot_frequency_ = energy_minimizer.snapshot_frequency_; energy_difference_bound_ = energy_minimizer.energy_difference_bound_ ; max_gradient_ = energy_minimizer.max_gradient_; max_same_energy_ = energy_minimizer.max_same_energy_; maximal_shift_ = energy_minimizer.maximal_shift_; force_update_counter_ = energy_minimizer.force_update_counter_; energy_update_counter_ = energy_minimizer.energy_update_counter_; } // assignment operator EnergyMinimizer& EnergyMinimizer::operator = (const EnergyMinimizer& energy_minimizer) { // guard against self assignment if (&energy_minimizer != this) { // Copy the attributes force_field_ = energy_minimizer.force_field_; options = energy_minimizer.options; valid_ = energy_minimizer.valid_; // BAUSTELLE // snapshot_ = energy_minimizer.snapshot_; number_of_iteration_ = energy_minimizer.number_of_iteration_; maximal_number_of_iterations_ = energy_minimizer.maximal_number_of_iterations_ ; energy_output_frequency_ = energy_minimizer.energy_output_frequency_; snapshot_frequency_ = energy_minimizer.snapshot_frequency_; max_same_energy_ = energy_minimizer.max_same_energy_; energy_difference_bound_ = energy_minimizer.energy_difference_bound_ ; max_gradient_ = energy_minimizer.max_gradient_ ; maximal_shift_ = energy_minimizer.maximal_shift_; force_update_counter_ = energy_minimizer.force_update_counter_; energy_update_counter_ = energy_minimizer.energy_update_counter_; } return (*this); } // Constructor initialized with a force field EnergyMinimizer::EnergyMinimizer(ForceField& force_field) { valid_ = setup(force_field); if (!valid_) { Log.level(LogStream::ERROR) << " Energy minimizer setup failed! " << endl; } } // Constructor initialized with a force field and a set of options EnergyMinimizer::EnergyMinimizer(ForceField& force_field, const Options& new_options) { valid_ = setup(force_field, new_options); if (!valid_) { Log.level(LogStream::ERROR) << " Energy minimizer setup failed! " << endl; } } // Destructor EnergyMinimizer::~EnergyMinimizer() { } // Set the number of the current iteration void EnergyMinimizer::setNumberOfIteration(Size number_of_iteration) { number_of_iteration_ = number_of_iteration; } // Get the number of the current iteration Size EnergyMinimizer::getNumberOfIteration() const { return number_of_iteration_; } // Set the maximal number of iterations void EnergyMinimizer::setMaximalNumberOfIterations(Size maximal_number_of_iterations) { maximal_number_of_iterations_ = maximal_number_of_iterations; } // Get the maximal number of iterations Size EnergyMinimizer::getMaximalNumberOfIterations() const { return maximal_number_of_iterations_; } // Is the energy minimizer valid: did the setup work? bool EnergyMinimizer::isValid() const { return valid_; } /* BAUSTELLE // Return the trajectory of the minimization procedure Snapshot& EnergyMinimizer::getSnapshot() const { return snapshot_; } // Set the trajectory void EnergyMinimizer::setSnapshot(Snapshot& snapshot) { snapshot_ = snapshot; } */ // Set the energy output frequency void EnergyMinimizer::setEnergyOutputFrequency(Size energy_output_frequency) { energy_output_frequency_ = energy_output_frequency; } // Get the energy ouput frequency Size EnergyMinimizer::getEnergyOutputFrequency() const { return energy_output_frequency_; } // Set the energy difference bound void EnergyMinimizer::setEnergyDifferenceBound(float energy_difference_bound) { energy_difference_bound_ = energy_difference_bound; } // Set explicitly the option max_gradient_ void EnergyMinimizer::setMaxGradient(float max_gradient) { max_gradient_ = max_gradient; } // Get the current value of the maximum gradient bound float EnergyMinimizer::getMaxGradient() const { return max_gradient_; } // Set explicitly the number of iterations for detecting convergence due // to invariant energy void EnergyMinimizer::setMaxSameEnergy(Size number) { max_same_energy_ = number; } // Get the value of max_same_energy, i.e. the number // of iterations after which the algorithm is stopped when the // energy remains constant Size EnergyMinimizer::getMaxSameEnergy() const { return max_same_energy_; } // Get the energy difference bound float EnergyMinimizer::getEnergyDifferenceBound() const { return energy_difference_bound_; } // Set the maximal shift void EnergyMinimizer::setMaximalShift( float maximal_shift ) { maximal_shift_ = maximal_shift; } // Get the maximal shift float EnergyMinimizer::getMaximalShift() const { return maximal_shift_; } // Set the trajectory ouput frequency void EnergyMinimizer::setSnapshotFrequency(Size snapshot_frequency) { snapshot_frequency_ = snapshot_frequency; } // Get the trajectory ouput frequency Size EnergyMinimizer::getSnapshotFrequency() const { return snapshot_frequency_; } // Get the force field of the energy minimizer ForceField* EnergyMinimizer::getForceField() { return force_field_; } // setup methods bool EnergyMinimizer::setup(ForceField& force_field) { // Default: no snapshot manager available snapShot_ptr_ = 0; // store the specified force field force_field_ = &force_field; valid_ = force_field_->isValid(); if (!valid_) { Log.error() << "The force field of the energy minimizer is not valid! " << "Check the definition and initialization of the force field! " << endl; return valid_; } // Check options options.setDefaultInteger(EnergyMinimizer::Option::MAXIMAL_NUMBER_OF_ITERATIONS, (long)EnergyMinimizer::Default::MAXIMAL_NUMBER_OF_ITERATIONS); maximal_number_of_iterations_ = (Size)(options.getInteger(EnergyMinimizer::Option::MAXIMAL_NUMBER_OF_ITERATIONS)); options.setDefaultInteger(EnergyMinimizer::Option::ENERGY_OUTPUT_FREQUENCY, (long)EnergyMinimizer::Default::ENERGY_OUTPUT_FREQUENCY); energy_output_frequency_ = (Size)(options.getInteger(EnergyMinimizer::Option::ENERGY_OUTPUT_FREQUENCY)); options.setDefaultInteger(EnergyMinimizer::Option::SNAPSHOT_FREQUENCY, (long)EnergyMinimizer::Default::SNAPSHOT_FREQUENCY); snapshot_frequency_ = (Size)(options.getInteger(EnergyMinimizer::Option::SNAPSHOT_FREQUENCY)); options.setDefaultInteger(EnergyMinimizer::Option::NUMBER_OF_ITERATION, (long)EnergyMinimizer::Default::NUMBER_OF_ITERATION); number_of_iteration_ = (Size)(options.getInteger(EnergyMinimizer::Option::NUMBER_OF_ITERATION)); options.setDefaultInteger(EnergyMinimizer::Option::MAX_SAME_ENERGY, (long) EnergyMinimizer::Default::MAX_SAME_ENERGY); max_same_energy_ = (Size) options.getInteger(EnergyMinimizer::Option::MAX_SAME_ENERGY); options.setDefaultReal(EnergyMinimizer::Option::ENERGY_DIFFERENCE_BOUND, EnergyMinimizer::Default::ENERGY_DIFFERENCE_BOUND); energy_difference_bound_ = options.getReal(EnergyMinimizer::Option::ENERGY_DIFFERENCE_BOUND); options.setDefaultReal(EnergyMinimizer::Option::MAX_GRADIENT, EnergyMinimizer::Default::MAX_GRADIENT); max_gradient_ = options.getReal(EnergyMinimizer::Option::MAX_GRADIENT); options.setDefaultReal(EnergyMinimizer::Option::MAXIMAL_SHIFT, EnergyMinimizer::Default::MAXIMAL_SHIFT); maximal_shift_ = options.getReal(EnergyMinimizer::Option::MAXIMAL_SHIFT); energy_update_counter_ = 0; force_update_counter_ = 0; // minimizer specific parts valid_ = specificSetup(); if (!valid_) { Log.level(LogStream::ERROR) << "Energy minimizer specificSetup failed!" << endl; return valid_; } valid_ = true; return valid_; } // Setup with a force field and a snapshot manager bool EnergyMinimizer::setup(ForceField& force_field, SnapShotManager *ssm) { bool result = setup(force_field); // set a pointer to the indicated snapshot manager if(ssm->isValid()) snapShot_ptr_ = ssm; return result; } // Setup with a force field and a snapshot manager and options bool EnergyMinimizer::setup(ForceField& force_field, SnapShotManager *ssm, const Options &new_options) { bool result = setup(force_field,new_options); // set a pointer to the indicated snapshot manager if(ssm->isValid()) snapShot_ptr_ = ssm; return result; } // Setup with a force field and a set of options bool EnergyMinimizer::setup(ForceField& force_field, const Options& new_options) { options = new_options; valid_ = setup(force_field); return valid_; } // virtual function for the specific setup of derived classes bool EnergyMinimizer::specificSetup() { cout << "EnergyMinimizer::specificSetup wird ausgefuehrt" << endl; return true; } /* The minimizer optimizes the energy of the system bound to the force field. The function is virtual. */ bool EnergyMinimizer::minimize(Size /* steps */, bool /* restart */) { return true; } } // namespace Ball <commit_msg>*** empty log message ***<commit_after>// $Id: energyMinimizer.C,v 1.6 1999/12/30 20:37:18 oliver Exp $ #include <BALL/MOLMEC/MINIMIZATION/energyMinimizer.h> #include <BALL/COMMON/limits.h> using namespace std; namespace BALL { const char* EnergyMinimizer::Option::MAXIMAL_NUMBER_OF_ITERATIONS = "maximal_number_of_iterations"; const char* EnergyMinimizer::Option::ENERGY_OUTPUT_FREQUENCY = "energy_output_frequency"; const char* EnergyMinimizer::Option::SNAPSHOT_FREQUENCY = "snapshot_frequency"; const char* EnergyMinimizer::Option::NUMBER_OF_ITERATION = "number_of_iteration"; // if the current rms gradient is below this one, we are converged const char *EnergyMinimizer::Option::MAX_GRADIENT = "max_gradient"; const char* EnergyMinimizer::Option::MAXIMAL_SHIFT = "MAXIMAL_SHIFT"; // The maximum number of iteration with equal energy // If this number is reached, we assume convergence const char* EnergyMinimizer::Option::MAX_SAME_ENERGY = "max_same_energy"; // The corresponding energy difference needed for assuming 'equal energy' const char* EnergyMinimizer::Option::ENERGY_DIFFERENCE_BOUND = "energy_difference_bound"; Size EnergyMinimizer::Default::MAXIMAL_NUMBER_OF_ITERATIONS = 1000; Size EnergyMinimizer::Default::ENERGY_OUTPUT_FREQUENCY = 50; Size EnergyMinimizer::Default::SNAPSHOT_FREQUENCY = Limits<Size>::max(); Size EnergyMinimizer::Default::NUMBER_OF_ITERATION = 0; // start number Size EnergyMinimizer::Default::MAX_SAME_ENERGY = 20; float EnergyMinimizer::Default::ENERGY_DIFFERENCE_BOUND = 1e-4; // in kJ/mol float EnergyMinimizer::Default::MAX_GRADIENT = 0.0001; // in kJ/(mol A) float EnergyMinimizer::Default::MAXIMAL_SHIFT = 0.4; // Angstrom // default constructor EnergyMinimizer::EnergyMinimizer() : valid_(false), force_field_(0) { } // copy constructor EnergyMinimizer::EnergyMinimizer(const EnergyMinimizer& energy_minimizer, bool /* deep */) { // Copy the attributes force_field_ = energy_minimizer.force_field_; options = energy_minimizer.options; valid_ = energy_minimizer.valid_; // BAUSTELLE // snapshot_ = energy_minimizer.snapshot_; number_of_iteration_ = energy_minimizer.number_of_iteration_; maximal_number_of_iterations_ = energy_minimizer.maximal_number_of_iterations_ ; energy_output_frequency_ = energy_minimizer.energy_output_frequency_; snapshot_frequency_ = energy_minimizer.snapshot_frequency_; energy_difference_bound_ = energy_minimizer.energy_difference_bound_ ; max_gradient_ = energy_minimizer.max_gradient_; max_same_energy_ = energy_minimizer.max_same_energy_; maximal_shift_ = energy_minimizer.maximal_shift_; force_update_counter_ = energy_minimizer.force_update_counter_; energy_update_counter_ = energy_minimizer.energy_update_counter_; } // assignment operator EnergyMinimizer& EnergyMinimizer::operator = (const EnergyMinimizer& energy_minimizer) { // guard against self assignment if (&energy_minimizer != this) { // Copy the attributes force_field_ = energy_minimizer.force_field_; options = energy_minimizer.options; valid_ = energy_minimizer.valid_; // BAUSTELLE // snapshot_ = energy_minimizer.snapshot_; number_of_iteration_ = energy_minimizer.number_of_iteration_; maximal_number_of_iterations_ = energy_minimizer.maximal_number_of_iterations_ ; energy_output_frequency_ = energy_minimizer.energy_output_frequency_; snapshot_frequency_ = energy_minimizer.snapshot_frequency_; max_same_energy_ = energy_minimizer.max_same_energy_; energy_difference_bound_ = energy_minimizer.energy_difference_bound_ ; max_gradient_ = energy_minimizer.max_gradient_ ; maximal_shift_ = energy_minimizer.maximal_shift_; force_update_counter_ = energy_minimizer.force_update_counter_; energy_update_counter_ = energy_minimizer.energy_update_counter_; } return (*this); } // Constructor initialized with a force field EnergyMinimizer::EnergyMinimizer(ForceField& force_field) { valid_ = setup(force_field); if (!valid_) { Log.level(LogStream::ERROR) << " Energy minimizer setup failed! " << endl; } } // Constructor initialized with a force field and a set of options EnergyMinimizer::EnergyMinimizer(ForceField& force_field, const Options& new_options) { valid_ = setup(force_field, new_options); if (!valid_) { Log.level(LogStream::ERROR) << " Energy minimizer setup failed! " << endl; } } // Destructor EnergyMinimizer::~EnergyMinimizer() { } // Set the number of the current iteration void EnergyMinimizer::setNumberOfIteration(Size number_of_iteration) { number_of_iteration_ = number_of_iteration; } // Get the number of the current iteration Size EnergyMinimizer::getNumberOfIteration() const { return number_of_iteration_; } // Set the maximal number of iterations void EnergyMinimizer::setMaximalNumberOfIterations(Size maximal_number_of_iterations) { maximal_number_of_iterations_ = maximal_number_of_iterations; } // Get the maximal number of iterations Size EnergyMinimizer::getMaximalNumberOfIterations() const { return maximal_number_of_iterations_; } // Is the energy minimizer valid: did the setup work? bool EnergyMinimizer::isValid() const { return valid_; } /* BAUSTELLE // Return the trajectory of the minimization procedure Snapshot& EnergyMinimizer::getSnapShot() const { return snapshot_; } // Set the trajectory void EnergyMinimizer::setSnapShot(Snapshot& snapshot) { snapshot_ = snapshot; } */ // Set the energy output frequency void EnergyMinimizer::setEnergyOutputFrequency(Size energy_output_frequency) { energy_output_frequency_ = energy_output_frequency; } // Get the energy ouput frequency Size EnergyMinimizer::getEnergyOutputFrequency() const { return energy_output_frequency_; } // Set the energy difference bound void EnergyMinimizer::setEnergyDifferenceBound(float energy_difference_bound) { energy_difference_bound_ = energy_difference_bound; } // Set explicitly the option max_gradient_ void EnergyMinimizer::setMaxGradient(float max_gradient) { max_gradient_ = max_gradient; } // Get the current value of the maximum gradient bound float EnergyMinimizer::getMaxGradient() const { return max_gradient_; } // Set explicitly the number of iterations for detecting convergence due // to invariant energy void EnergyMinimizer::setMaxSameEnergy(Size number) { max_same_energy_ = number; } // Get the value of max_same_energy, i.e. the number // of iterations after which the algorithm is stopped when the // energy remains constant Size EnergyMinimizer::getMaxSameEnergy() const { return max_same_energy_; } // Get the energy difference bound float EnergyMinimizer::getEnergyDifferenceBound() const { return energy_difference_bound_; } // Set the maximal shift void EnergyMinimizer::setMaximalShift( float maximal_shift ) { maximal_shift_ = maximal_shift; } // Get the maximal shift float EnergyMinimizer::getMaximalShift() const { return maximal_shift_; } // Set the trajectory ouput frequency void EnergyMinimizer::setSnapShotFrequency(Size snapshot_frequency) { snapshot_frequency_ = snapshot_frequency; } // Get the trajectory ouput frequency Size EnergyMinimizer::getSnapShotFrequency() const { return snapshot_frequency_; } // Get the force field of the energy minimizer ForceField* EnergyMinimizer::getForceField() { return force_field_; } // setup methods bool EnergyMinimizer::setup(ForceField& force_field) { // Default: no snapshot manager available snapShot_ptr_ = 0; // store the specified force field force_field_ = &force_field; valid_ = force_field_->isValid(); if (!valid_) { Log.error() << "The force field of the energy minimizer is not valid! " << "Check the definition and initialization of the force field! " << endl; return valid_; } // Check options options.setDefaultInteger(EnergyMinimizer::Option::MAXIMAL_NUMBER_OF_ITERATIONS, (long)EnergyMinimizer::Default::MAXIMAL_NUMBER_OF_ITERATIONS); maximal_number_of_iterations_ = (Size)(options.getInteger(EnergyMinimizer::Option::MAXIMAL_NUMBER_OF_ITERATIONS)); options.setDefaultInteger(EnergyMinimizer::Option::ENERGY_OUTPUT_FREQUENCY, (long)EnergyMinimizer::Default::ENERGY_OUTPUT_FREQUENCY); energy_output_frequency_ = (Size)(options.getInteger(EnergyMinimizer::Option::ENERGY_OUTPUT_FREQUENCY)); options.setDefaultInteger(EnergyMinimizer::Option::SNAPSHOT_FREQUENCY, (long)EnergyMinimizer::Default::SNAPSHOT_FREQUENCY); snapshot_frequency_ = (Size)(options.getInteger(EnergyMinimizer::Option::SNAPSHOT_FREQUENCY)); options.setDefaultInteger(EnergyMinimizer::Option::NUMBER_OF_ITERATION, (long)EnergyMinimizer::Default::NUMBER_OF_ITERATION); number_of_iteration_ = (Size)(options.getInteger(EnergyMinimizer::Option::NUMBER_OF_ITERATION)); options.setDefaultInteger(EnergyMinimizer::Option::MAX_SAME_ENERGY, (long) EnergyMinimizer::Default::MAX_SAME_ENERGY); max_same_energy_ = (Size) options.getInteger(EnergyMinimizer::Option::MAX_SAME_ENERGY); options.setDefaultReal(EnergyMinimizer::Option::ENERGY_DIFFERENCE_BOUND, EnergyMinimizer::Default::ENERGY_DIFFERENCE_BOUND); energy_difference_bound_ = options.getReal(EnergyMinimizer::Option::ENERGY_DIFFERENCE_BOUND); options.setDefaultReal(EnergyMinimizer::Option::MAX_GRADIENT, EnergyMinimizer::Default::MAX_GRADIENT); max_gradient_ = options.getReal(EnergyMinimizer::Option::MAX_GRADIENT); options.setDefaultReal(EnergyMinimizer::Option::MAXIMAL_SHIFT, EnergyMinimizer::Default::MAXIMAL_SHIFT); maximal_shift_ = options.getReal(EnergyMinimizer::Option::MAXIMAL_SHIFT); energy_update_counter_ = 0; force_update_counter_ = 0; // minimizer specific parts valid_ = specificSetup(); if (!valid_) { Log.level(LogStream::ERROR) << "Energy minimizer specificSetup failed!" << endl; return valid_; } valid_ = true; return valid_; } // Setup with a force field and a snapshot manager bool EnergyMinimizer::setup(ForceField& force_field, SnapShotManager *ssm) { bool result = setup(force_field); // set a pointer to the indicated snapshot manager if(ssm->isValid()) snapShot_ptr_ = ssm; return result; } // Setup with a force field and a snapshot manager and options bool EnergyMinimizer::setup(ForceField& force_field, SnapShotManager *ssm, const Options &new_options) { bool result = setup(force_field,new_options); // set a pointer to the indicated snapshot manager if(ssm->isValid()) snapShot_ptr_ = ssm; return result; } // Setup with a force field and a set of options bool EnergyMinimizer::setup(ForceField& force_field, const Options& new_options) { options = new_options; valid_ = setup(force_field); return valid_; } // virtual function for the specific setup of derived classes bool EnergyMinimizer::specificSetup() { cout << "EnergyMinimizer::specificSetup wird ausgefuehrt" << endl; return true; } /* The minimizer optimizes the energy of the system bound to the force field. The function is virtual. */ bool EnergyMinimizer::minimize(Size /* steps */, bool /* restart */) { return true; } } // namespace Ball <|endoftext|>
<commit_before>//===-- AsmPrinterDwarf.cpp - AsmPrinter Dwarf Support --------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the Dwarf emissions parts of AsmPrinter. // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "asm-printer" #include "llvm/CodeGen/AsmPrinter.h" #include "llvm/CodeGen/MachineLocation.h" #include "llvm/MC/MCAsmInfo.h" #include "llvm/MC/MCSection.h" #include "llvm/MC/MCStreamer.h" #include "llvm/MC/MCSymbol.h" #include "llvm/Target/TargetData.h" #include "llvm/Target/TargetFrameInfo.h" #include "llvm/Target/TargetLoweringObjectFile.h" #include "llvm/Target/TargetMachine.h" #include "llvm/Target/TargetRegisterInfo.h" #include "llvm/ADT/Twine.h" #include "llvm/Support/Dwarf.h" using namespace llvm; //===----------------------------------------------------------------------===// // Dwarf Emission Helper Routines //===----------------------------------------------------------------------===// /// EmitSLEB128 - emit the specified signed leb128 value. void AsmPrinter::EmitSLEB128(int Value, const char *Desc) const { if (isVerbose() && Desc) OutStreamer.AddComment(Desc); if (MAI->hasLEB128()) { OutStreamer.EmitSLEB128IntValue(Value); return; } // If we don't have .sleb128, emit as .bytes. int Sign = Value >> (8 * sizeof(Value) - 1); bool IsMore; do { unsigned char Byte = static_cast<unsigned char>(Value & 0x7f); Value >>= 7; IsMore = Value != Sign || ((Byte ^ Sign) & 0x40) != 0; if (IsMore) Byte |= 0x80; OutStreamer.EmitIntValue(Byte, 1, /*addrspace*/0); } while (IsMore); } /// EmitULEB128 - emit the specified signed leb128 value. void AsmPrinter::EmitULEB128(unsigned Value, const char *Desc, unsigned PadTo) const { if (isVerbose() && Desc) OutStreamer.AddComment(Desc); // FIXME: Should we add a PadTo option to the streamer? if (MAI->hasLEB128() && PadTo == 0) { OutStreamer.EmitULEB128IntValue(Value); return; } // If we don't have .uleb128 or we want to emit padding, emit as .bytes. do { unsigned char Byte = static_cast<unsigned char>(Value & 0x7f); Value >>= 7; if (Value || PadTo != 0) Byte |= 0x80; OutStreamer.EmitIntValue(Byte, 1, /*addrspace*/0); } while (Value); if (PadTo) { if (PadTo > 1) OutStreamer.EmitFill(PadTo - 1, 0x80/*fillval*/, 0/*addrspace*/); OutStreamer.EmitFill(1, 0/*fillval*/, 0/*addrspace*/); } } /// EmitCFAByte - Emit a .byte 42 directive for a DW_CFA_xxx value. void AsmPrinter::EmitCFAByte(unsigned Val) const { if (isVerbose()) { if (Val >= dwarf::DW_CFA_offset && Val < dwarf::DW_CFA_offset+64) OutStreamer.AddComment("DW_CFA_offset + Reg (" + Twine(Val-dwarf::DW_CFA_offset) + ")"); else OutStreamer.AddComment(dwarf::CallFrameString(Val)); } OutStreamer.EmitIntValue(Val, 1, 0/*addrspace*/); } static const char *DecodeDWARFEncoding(unsigned Encoding) { switch (Encoding) { case dwarf::DW_EH_PE_absptr: return "absptr"; case dwarf::DW_EH_PE_omit: return "omit"; case dwarf::DW_EH_PE_pcrel: return "pcrel"; case dwarf::DW_EH_PE_udata4: return "udata4"; case dwarf::DW_EH_PE_udata8: return "udata8"; case dwarf::DW_EH_PE_sdata4: return "sdata4"; case dwarf::DW_EH_PE_sdata8: return "sdata8"; case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata4: return "pcrel udata4"; case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4: return "pcrel sdata4"; case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata8: return "pcrel udata8"; case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata8: return "pcrel sdata8"; case dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_udata4: return "indirect pcrel udata4"; case dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_sdata4: return "indirect pcrel sdata4"; case dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_udata8: return "indirect pcrel udata8"; case dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_sdata8: return "indirect pcrel sdata8"; } return "<unknown encoding>"; } /// EmitEncodingByte - Emit a .byte 42 directive that corresponds to an /// encoding. If verbose assembly output is enabled, we output comments /// describing the encoding. Desc is an optional string saying what the /// encoding is specifying (e.g. "LSDA"). void AsmPrinter::EmitEncodingByte(unsigned Val, const char *Desc) const { if (isVerbose()) { if (Desc != 0) OutStreamer.AddComment(Twine(Desc)+" Encoding = " + Twine(DecodeDWARFEncoding(Val))); else OutStreamer.AddComment(Twine("Encoding = ") + DecodeDWARFEncoding(Val)); } OutStreamer.EmitIntValue(Val, 1, 0/*addrspace*/); } /// GetSizeOfEncodedValue - Return the size of the encoding in bytes. unsigned AsmPrinter::GetSizeOfEncodedValue(unsigned Encoding) const { if (Encoding == dwarf::DW_EH_PE_omit) return 0; switch (Encoding & 0x07) { default: assert(0 && "Invalid encoded value."); case dwarf::DW_EH_PE_absptr: return TM.getTargetData()->getPointerSize(); case dwarf::DW_EH_PE_udata2: return 2; case dwarf::DW_EH_PE_udata4: return 4; case dwarf::DW_EH_PE_udata8: return 8; } } void AsmPrinter::EmitReference(const MCSymbol *Sym, unsigned Encoding) const { const TargetLoweringObjectFile &TLOF = getObjFileLowering(); const MCExpr *Exp = TLOF.getExprForDwarfReference(Sym, Mang, MMI, Encoding, OutStreamer); OutStreamer.EmitValue(Exp, GetSizeOfEncodedValue(Encoding), /*addrspace*/0); } void AsmPrinter::EmitReference(const GlobalValue *GV, unsigned Encoding)const{ const TargetLoweringObjectFile &TLOF = getObjFileLowering(); const MCExpr *Exp = TLOF.getExprForDwarfGlobalReference(GV, Mang, MMI, Encoding, OutStreamer); OutStreamer.EmitValue(Exp, GetSizeOfEncodedValue(Encoding), /*addrspace*/0); } /// EmitSectionOffset - Emit the 4-byte offset of Label from the start of its /// section. This can be done with a special directive if the target supports /// it (e.g. cygwin) or by emitting it as an offset from a label at the start /// of the section. /// /// SectionLabel is a temporary label emitted at the start of the section that /// Label lives in. void AsmPrinter::EmitSectionOffset(const MCSymbol *Label, const MCSymbol *SectionLabel) const { // On COFF targets, we have to emit the special .secrel32 directive. if (const char *SecOffDir = MAI->getDwarfSectionOffsetDirective()) { // FIXME: MCize. OutStreamer.EmitRawText(SecOffDir + Twine(Label->getName())); return; } // Get the section that we're referring to, based on SectionLabel. const MCSection &Section = SectionLabel->getSection(); // If Label has already been emitted, verify that it is in the same section as // section label for sanity. assert((!Label->isInSection() || &Label->getSection() == &Section) && "Section offset using wrong section base for label"); // If the section in question will end up with an address of 0 anyway, we can // just emit an absolute reference to save a relocation. if (Section.isBaseAddressKnownZero()) { OutStreamer.EmitSymbolValue(Label, 4, 0/*AddrSpace*/); return; } // Otherwise, emit it as a label difference from the start of the section. EmitLabelDifference(Label, SectionLabel, 4); } //===----------------------------------------------------------------------===// // Dwarf Lowering Routines //===----------------------------------------------------------------------===// /// EmitFrameMoves - Emit frame instructions to describe the layout of the /// frame. void AsmPrinter::EmitFrameMoves(const std::vector<MachineMove> &Moves, MCSymbol *BaseLabel, bool isEH) const { const TargetRegisterInfo *RI = TM.getRegisterInfo(); int stackGrowth = TM.getTargetData()->getPointerSize(); if (TM.getFrameInfo()->getStackGrowthDirection() != TargetFrameInfo::StackGrowsUp) stackGrowth *= -1; for (unsigned i = 0, N = Moves.size(); i < N; ++i) { const MachineMove &Move = Moves[i]; MCSymbol *Label = Move.getLabel(); // Throw out move if the label is invalid. if (Label && !Label->isDefined()) continue; // Not emitted, in dead code. const MachineLocation &Dst = Move.getDestination(); const MachineLocation &Src = Move.getSource(); // Advance row if new location. if (BaseLabel && Label) { MCSymbol *ThisSym = Label; if (ThisSym != BaseLabel) { EmitCFAByte(dwarf::DW_CFA_advance_loc4); EmitLabelDifference(ThisSym, BaseLabel, 4); BaseLabel = ThisSym; } } // If advancing cfa. if (Dst.isReg() && Dst.getReg() == MachineLocation::VirtualFP) { assert(!Src.isReg() && "Machine move not supported yet."); if (Src.getReg() == MachineLocation::VirtualFP) { EmitCFAByte(dwarf::DW_CFA_def_cfa_offset); } else { EmitCFAByte(dwarf::DW_CFA_def_cfa); EmitULEB128(RI->getDwarfRegNum(Src.getReg(), isEH), "Register"); } EmitULEB128(-Src.getOffset(), "Offset"); continue; } if (Src.isReg() && Src.getReg() == MachineLocation::VirtualFP) { assert(Dst.isReg() && "Machine move not supported yet."); EmitCFAByte(dwarf::DW_CFA_def_cfa_register); EmitULEB128(RI->getDwarfRegNum(Dst.getReg(), isEH), "Register"); continue; } unsigned Reg = RI->getDwarfRegNum(Src.getReg(), isEH); int Offset = Dst.getOffset() / stackGrowth; if (Offset < 0) { EmitCFAByte(dwarf::DW_CFA_offset_extended_sf); EmitULEB128(Reg, "Reg"); EmitSLEB128(Offset, "Offset"); } else if (Reg < 64) { EmitCFAByte(dwarf::DW_CFA_offset + Reg); EmitULEB128(Offset, "Offset"); } else { EmitCFAByte(dwarf::DW_CFA_offset_extended); EmitULEB128(Reg, "Reg"); EmitULEB128(Offset, "Offset"); } } } <commit_msg>Revert previous patch. Some targets don't support uleb and say they do :-(<commit_after>//===-- AsmPrinterDwarf.cpp - AsmPrinter Dwarf Support --------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the Dwarf emissions parts of AsmPrinter. // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "asm-printer" #include "llvm/CodeGen/AsmPrinter.h" #include "llvm/CodeGen/MachineLocation.h" #include "llvm/MC/MCAsmInfo.h" #include "llvm/MC/MCSection.h" #include "llvm/MC/MCStreamer.h" #include "llvm/MC/MCSymbol.h" #include "llvm/Target/TargetData.h" #include "llvm/Target/TargetFrameInfo.h" #include "llvm/Target/TargetLoweringObjectFile.h" #include "llvm/Target/TargetMachine.h" #include "llvm/Target/TargetRegisterInfo.h" #include "llvm/ADT/Twine.h" #include "llvm/Support/Dwarf.h" using namespace llvm; //===----------------------------------------------------------------------===// // Dwarf Emission Helper Routines //===----------------------------------------------------------------------===// /// EmitSLEB128 - emit the specified signed leb128 value. void AsmPrinter::EmitSLEB128(int Value, const char *Desc) const { if (isVerbose() && Desc) OutStreamer.AddComment(Desc); if (MAI->hasLEB128() && OutStreamer.hasRawTextSupport()) { // FIXME: MCize. OutStreamer.EmitRawText("\t.sleb128\t" + Twine(Value)); return; } // If we don't have .sleb128, emit as .bytes. int Sign = Value >> (8 * sizeof(Value) - 1); bool IsMore; do { unsigned char Byte = static_cast<unsigned char>(Value & 0x7f); Value >>= 7; IsMore = Value != Sign || ((Byte ^ Sign) & 0x40) != 0; if (IsMore) Byte |= 0x80; OutStreamer.EmitIntValue(Byte, 1, /*addrspace*/0); } while (IsMore); } /// EmitULEB128 - emit the specified signed leb128 value. void AsmPrinter::EmitULEB128(unsigned Value, const char *Desc, unsigned PadTo) const { if (isVerbose() && Desc) OutStreamer.AddComment(Desc); if (MAI->hasLEB128() && PadTo == 0 && OutStreamer.hasRawTextSupport()) { // FIXME: MCize. OutStreamer.EmitRawText("\t.uleb128\t" + Twine(Value)); return; } // If we don't have .uleb128 or we want to emit padding, emit as .bytes. do { unsigned char Byte = static_cast<unsigned char>(Value & 0x7f); Value >>= 7; if (Value || PadTo != 0) Byte |= 0x80; OutStreamer.EmitIntValue(Byte, 1, /*addrspace*/0); } while (Value); if (PadTo) { if (PadTo > 1) OutStreamer.EmitFill(PadTo - 1, 0x80/*fillval*/, 0/*addrspace*/); OutStreamer.EmitFill(1, 0/*fillval*/, 0/*addrspace*/); } } /// EmitCFAByte - Emit a .byte 42 directive for a DW_CFA_xxx value. void AsmPrinter::EmitCFAByte(unsigned Val) const { if (isVerbose()) { if (Val >= dwarf::DW_CFA_offset && Val < dwarf::DW_CFA_offset+64) OutStreamer.AddComment("DW_CFA_offset + Reg (" + Twine(Val-dwarf::DW_CFA_offset) + ")"); else OutStreamer.AddComment(dwarf::CallFrameString(Val)); } OutStreamer.EmitIntValue(Val, 1, 0/*addrspace*/); } static const char *DecodeDWARFEncoding(unsigned Encoding) { switch (Encoding) { case dwarf::DW_EH_PE_absptr: return "absptr"; case dwarf::DW_EH_PE_omit: return "omit"; case dwarf::DW_EH_PE_pcrel: return "pcrel"; case dwarf::DW_EH_PE_udata4: return "udata4"; case dwarf::DW_EH_PE_udata8: return "udata8"; case dwarf::DW_EH_PE_sdata4: return "sdata4"; case dwarf::DW_EH_PE_sdata8: return "sdata8"; case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata4: return "pcrel udata4"; case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4: return "pcrel sdata4"; case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata8: return "pcrel udata8"; case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata8: return "pcrel sdata8"; case dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_udata4: return "indirect pcrel udata4"; case dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_sdata4: return "indirect pcrel sdata4"; case dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_udata8: return "indirect pcrel udata8"; case dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_sdata8: return "indirect pcrel sdata8"; } return "<unknown encoding>"; } /// EmitEncodingByte - Emit a .byte 42 directive that corresponds to an /// encoding. If verbose assembly output is enabled, we output comments /// describing the encoding. Desc is an optional string saying what the /// encoding is specifying (e.g. "LSDA"). void AsmPrinter::EmitEncodingByte(unsigned Val, const char *Desc) const { if (isVerbose()) { if (Desc != 0) OutStreamer.AddComment(Twine(Desc)+" Encoding = " + Twine(DecodeDWARFEncoding(Val))); else OutStreamer.AddComment(Twine("Encoding = ") + DecodeDWARFEncoding(Val)); } OutStreamer.EmitIntValue(Val, 1, 0/*addrspace*/); } /// GetSizeOfEncodedValue - Return the size of the encoding in bytes. unsigned AsmPrinter::GetSizeOfEncodedValue(unsigned Encoding) const { if (Encoding == dwarf::DW_EH_PE_omit) return 0; switch (Encoding & 0x07) { default: assert(0 && "Invalid encoded value."); case dwarf::DW_EH_PE_absptr: return TM.getTargetData()->getPointerSize(); case dwarf::DW_EH_PE_udata2: return 2; case dwarf::DW_EH_PE_udata4: return 4; case dwarf::DW_EH_PE_udata8: return 8; } } void AsmPrinter::EmitReference(const MCSymbol *Sym, unsigned Encoding) const { const TargetLoweringObjectFile &TLOF = getObjFileLowering(); const MCExpr *Exp = TLOF.getExprForDwarfReference(Sym, Mang, MMI, Encoding, OutStreamer); OutStreamer.EmitValue(Exp, GetSizeOfEncodedValue(Encoding), /*addrspace*/0); } void AsmPrinter::EmitReference(const GlobalValue *GV, unsigned Encoding)const{ const TargetLoweringObjectFile &TLOF = getObjFileLowering(); const MCExpr *Exp = TLOF.getExprForDwarfGlobalReference(GV, Mang, MMI, Encoding, OutStreamer); OutStreamer.EmitValue(Exp, GetSizeOfEncodedValue(Encoding), /*addrspace*/0); } /// EmitSectionOffset - Emit the 4-byte offset of Label from the start of its /// section. This can be done with a special directive if the target supports /// it (e.g. cygwin) or by emitting it as an offset from a label at the start /// of the section. /// /// SectionLabel is a temporary label emitted at the start of the section that /// Label lives in. void AsmPrinter::EmitSectionOffset(const MCSymbol *Label, const MCSymbol *SectionLabel) const { // On COFF targets, we have to emit the special .secrel32 directive. if (const char *SecOffDir = MAI->getDwarfSectionOffsetDirective()) { // FIXME: MCize. OutStreamer.EmitRawText(SecOffDir + Twine(Label->getName())); return; } // Get the section that we're referring to, based on SectionLabel. const MCSection &Section = SectionLabel->getSection(); // If Label has already been emitted, verify that it is in the same section as // section label for sanity. assert((!Label->isInSection() || &Label->getSection() == &Section) && "Section offset using wrong section base for label"); // If the section in question will end up with an address of 0 anyway, we can // just emit an absolute reference to save a relocation. if (Section.isBaseAddressKnownZero()) { OutStreamer.EmitSymbolValue(Label, 4, 0/*AddrSpace*/); return; } // Otherwise, emit it as a label difference from the start of the section. EmitLabelDifference(Label, SectionLabel, 4); } //===----------------------------------------------------------------------===// // Dwarf Lowering Routines //===----------------------------------------------------------------------===// /// EmitFrameMoves - Emit frame instructions to describe the layout of the /// frame. void AsmPrinter::EmitFrameMoves(const std::vector<MachineMove> &Moves, MCSymbol *BaseLabel, bool isEH) const { const TargetRegisterInfo *RI = TM.getRegisterInfo(); int stackGrowth = TM.getTargetData()->getPointerSize(); if (TM.getFrameInfo()->getStackGrowthDirection() != TargetFrameInfo::StackGrowsUp) stackGrowth *= -1; for (unsigned i = 0, N = Moves.size(); i < N; ++i) { const MachineMove &Move = Moves[i]; MCSymbol *Label = Move.getLabel(); // Throw out move if the label is invalid. if (Label && !Label->isDefined()) continue; // Not emitted, in dead code. const MachineLocation &Dst = Move.getDestination(); const MachineLocation &Src = Move.getSource(); // Advance row if new location. if (BaseLabel && Label) { MCSymbol *ThisSym = Label; if (ThisSym != BaseLabel) { EmitCFAByte(dwarf::DW_CFA_advance_loc4); EmitLabelDifference(ThisSym, BaseLabel, 4); BaseLabel = ThisSym; } } // If advancing cfa. if (Dst.isReg() && Dst.getReg() == MachineLocation::VirtualFP) { assert(!Src.isReg() && "Machine move not supported yet."); if (Src.getReg() == MachineLocation::VirtualFP) { EmitCFAByte(dwarf::DW_CFA_def_cfa_offset); } else { EmitCFAByte(dwarf::DW_CFA_def_cfa); EmitULEB128(RI->getDwarfRegNum(Src.getReg(), isEH), "Register"); } EmitULEB128(-Src.getOffset(), "Offset"); continue; } if (Src.isReg() && Src.getReg() == MachineLocation::VirtualFP) { assert(Dst.isReg() && "Machine move not supported yet."); EmitCFAByte(dwarf::DW_CFA_def_cfa_register); EmitULEB128(RI->getDwarfRegNum(Dst.getReg(), isEH), "Register"); continue; } unsigned Reg = RI->getDwarfRegNum(Src.getReg(), isEH); int Offset = Dst.getOffset() / stackGrowth; if (Offset < 0) { EmitCFAByte(dwarf::DW_CFA_offset_extended_sf); EmitULEB128(Reg, "Reg"); EmitSLEB128(Offset, "Offset"); } else if (Reg < 64) { EmitCFAByte(dwarf::DW_CFA_offset + Reg); EmitULEB128(Offset, "Offset"); } else { EmitCFAByte(dwarf::DW_CFA_offset_extended); EmitULEB128(Reg, "Reg"); EmitULEB128(Offset, "Offset"); } } } <|endoftext|>
<commit_before>#include <unistd.h> #include <node.h> #include <QtGui> #include <QObject> #include "QmlContext.h" namespace Brig { using namespace v8; using namespace node; Persistent<Function> QmlContext::constructor; QmlContext::QmlContext() : ObjectWrap() { obj = NULL; } QmlContext::~QmlContext() { delete obj; } void QmlContext::Initialize(Handle<Object> target) { HandleScope scope; Local<String> name = String::NewSymbol("QmlContext"); /* Constructor template */ Persistent<FunctionTemplate> tpl = Persistent<FunctionTemplate>::New(FunctionTemplate::New(QmlContext::New)); tpl->InstanceTemplate()->SetInternalFieldCount(1); tpl->SetClassName(name); /* Prototype */ //NODE_SET_PROTOTYPE_METHOD(tpl, "setEngine", QmlContext::setEngine); constructor = Persistent<Function>::New(tpl->GetFunction()); target->Set(name, constructor); } // Prototype Constructor Handle<Value> QmlContext::New(const Arguments& args) { HandleScope scope; if (args.Length() == 0) return Undefined(); // Using Engine to initialize QQmlContext QmlEngineWrap *engine_wrap = ObjectWrap::Unwrap<QmlEngineWrap>(args[0]->ToObject()); QmlContext *obj_wrap = new QmlContext(); obj_wrap->obj = new QQmlContext(engine_wrap->GetObject()->rootContext()); obj_wrap->Wrap(args.This()); return args.This(); } // Method } <commit_msg>migrate QmlContext<commit_after>#include <unistd.h> #include <node.h> #include <QtGui> #include <QObject> #include "QmlContext.h" namespace Brig { using namespace v8; using namespace node; Persistent<Function> QmlContext::constructor; QmlContext::QmlContext() : ObjectWrap() { obj = NULL; } QmlContext::~QmlContext() { delete obj; } void QmlContext::Initialize(Handle<Object> target) { HandleScope scope; Local<String> name = String::NewSymbol("QmlContext"); /* Constructor template */ Persistent<FunctionTemplate> tpl = Persistent<FunctionTemplate>::New(FunctionTemplate::New(QmlContext::New)); tpl->InstanceTemplate()->SetInternalFieldCount(1); tpl->SetClassName(name); /* Prototype */ //NODE_SET_PROTOTYPE_METHOD(tpl, "setEngine", QmlContext::setEngine); constructor = Persistent<Function>::New(tpl->GetFunction()); target->Set(name, constructor); } // Prototype Constructor NAN_METHOD(QmlContext::New) { NanScope(); if (args.Length() == 0) return Undefined(); // Using Engine to initialize QQmlContext QmlEngineWrap *engine_wrap = ObjectWrap::Unwrap<QmlEngineWrap>(args[0]->ToObject()); QmlContext *obj_wrap = new QmlContext(); obj_wrap->obj = new QQmlContext(engine_wrap->GetObject()->rootContext()); obj_wrap->Wrap(args.This()); NanReturnValue(args.This()); } // Method } <|endoftext|>
<commit_before> // RCONServer.cpp // Implements the cRCONServer class representing the RCON server #include "Globals.h" #include "IniFile.h" #include "RCONServer.h" #include "Server.h" #include "Root.h" #include "CommandOutput.h" // Disable MSVC warnings: #if defined(_MSC_VER) #pragma warning(push) #pragma warning(disable:4355) // 'this' : used in base member initializer list #endif enum { // Client -> Server: RCON_PACKET_COMMAND = 2, RCON_PACKET_LOGIN = 3, // Server -> Client: RCON_PACKET_RESPONSE = 2, } ; //////////////////////////////////////////////////////////////////////////////// // cRCONListenCallbacks: class cRCONListenCallbacks: public cNetwork::cListenCallbacks { public: cRCONListenCallbacks(cRCONServer & a_RCONServer, UInt16 a_Port): m_RCONServer(a_RCONServer), m_Port(a_Port) { } protected: /** The RCON server instance that we're attached to. */ cRCONServer & m_RCONServer; /** The port for which this instance is responsible. */ UInt16 m_Port; // cNetwork::cListenCallbacks overrides: virtual cTCPLink::cCallbacksPtr OnIncomingConnection(const AString & a_RemoteIPAddress, UInt16 a_RemotePort) override { LOG("RCON Client \"%s\" connected!", a_RemoteIPAddress.c_str()); return std::make_shared<cRCONServer::cConnection>(m_RCONServer, a_RemoteIPAddress); } virtual void OnAccepted(cTCPLink & a_Link) override {} virtual void OnError(int a_ErrorCode, const AString & a_ErrorMsg) override { LOGWARNING("RCON server error on port %d: %d (%s)", m_Port, a_ErrorCode, a_ErrorMsg.c_str()); } }; //////////////////////////////////////////////////////////////////////////////// // cRCONCommandOutput: class cRCONCommandOutput : public cCommandOutputCallback { public: cRCONCommandOutput(cRCONServer::cConnection & a_Connection, UInt32 a_RequestID) : m_Connection(a_Connection), m_RequestID(a_RequestID) { } // cCommandOutputCallback overrides: virtual void Out(const AString & a_Text) override { m_Buffer.append(a_Text); } virtual void Finished(void) override { m_Connection.SendResponse(m_RequestID, RCON_PACKET_RESPONSE, static_cast<UInt32>(m_Buffer.size()), m_Buffer.c_str()); delete this; } protected: cRCONServer::cConnection & m_Connection; UInt32 m_RequestID; AString m_Buffer; } ; //////////////////////////////////////////////////////////////////////////////// // cRCONServer: cRCONServer::cRCONServer(cServer & a_Server) : m_Server(a_Server) { } cRCONServer::~cRCONServer() { for (auto srv: m_ListenServers) { srv->Close(); } } void cRCONServer::Initialize(cIniFile & a_IniFile) { if (!a_IniFile.GetValueSetB("RCON", "Enabled", false)) { return; } // Read the password, don't allow an empty one: m_Password = a_IniFile.GetValueSet("RCON", "Password", ""); if (m_Password.empty()) { LOGWARNING("RCON is requested, but the password is not set. RCON is now disabled."); return; } // Read the listening ports for RCON from config: AStringVector Ports = ReadUpgradeIniPorts(a_IniFile, "RCON", "Ports", "PortsIPv4", "PortsIPv6", "25575"); // Start listening on each specified port: for (auto port: Ports) { UInt16 PortNum; if (!StringToInteger(port, PortNum)) { LOGINFO("Invalid RCON port value: \"%s\". Ignoring.", port.c_str()); continue; } auto Handle = cNetwork::Listen(PortNum, std::make_shared<cRCONListenCallbacks>(*this, PortNum)); if (Handle->IsListening()) { m_ListenServers.push_back(Handle); } } if (m_ListenServers.empty()) { LOGWARNING("RCON is enabled but no valid ports were found. RCON is not accessible."); } } //////////////////////////////////////////////////////////////////////////////// // cRCONServer::cConnection: cRCONServer::cConnection::cConnection(cRCONServer & a_RCONServer, const AString & a_IPAddress) : m_IsAuthenticated(false), m_RCONServer(a_RCONServer), m_IPAddress(a_IPAddress) { } void cRCONServer::cConnection::OnLinkCreated(cTCPLinkPtr a_Link) { m_Link = a_Link; } void cRCONServer::cConnection::OnReceivedData(const char * a_Data, size_t a_Size) { ASSERT(m_Link != nullptr); // Append data to the buffer: m_Buffer.append(a_Data, a_Size); // Process the packets in the buffer: while (m_Buffer.size() >= 14) { UInt32 Length = UIntFromBuffer(m_Buffer.data()); if (Length > 1500) { // Too long, drop the connection LOGWARNING("Received an invalid RCON packet length (%d), dropping RCON connection to %s.", Length, m_IPAddress.c_str() ); m_Link->Close(); m_Link.reset(); return; } if (Length > static_cast<Int32>(m_Buffer.size() + 4)) { // Incomplete packet yet, wait for more data to come return; } UInt32 RequestID = UIntFromBuffer(m_Buffer.data() + 4); UInt32 PacketType = UIntFromBuffer(m_Buffer.data() + 8); if (!ProcessPacket(RequestID, PacketType, Length - 10, m_Buffer.data() + 12)) { m_Link->Close(); m_Link.reset(); return; } m_Buffer.erase(0, Length + 4); } // while (m_Buffer.size() >= 14) } void cRCONServer::cConnection::OnRemoteClosed(void) { m_Link.reset(); } void cRCONServer::cConnection::OnError(int a_ErrorCode, const AString & a_ErrorMsg) { LOGD("Error in RCON connection %s: %d (%s)", m_IPAddress.c_str(), a_ErrorCode, a_ErrorMsg.c_str()); m_Link.reset(); } bool cRCONServer::cConnection::ProcessPacket(UInt32 a_RequestID, UInt32 a_PacketType, UInt32 a_PayloadLength, const char * a_Payload) { switch (a_PacketType) { case RCON_PACKET_LOGIN: { if (strncmp(a_Payload, m_RCONServer.m_Password.c_str(), a_PayloadLength) != 0) { LOGINFO("RCON: Invalid password from client %s, dropping connection.", m_IPAddress.c_str()); SendResponse(0xffffffffU, RCON_PACKET_RESPONSE, 0, nullptr); return false; } m_IsAuthenticated = true; LOGD("RCON: Client at %s has successfully authenticated", m_IPAddress.c_str()); // Send OK response: SendResponse(a_RequestID, RCON_PACKET_RESPONSE, 0, nullptr); return true; } case RCON_PACKET_COMMAND: { if (!m_IsAuthenticated) { char AuthNeeded[] = "You need to authenticate first!"; SendResponse(a_RequestID, RCON_PACKET_RESPONSE, sizeof(AuthNeeded), AuthNeeded); return false; } AString cmd(a_Payload, a_PayloadLength); LOGD("RCON command from %s: \"%s\"", m_IPAddress.c_str(), cmd.c_str()); cRoot::Get()->ExecuteConsoleCommand(cmd, *(new cRCONCommandOutput(*this, a_RequestID))); // Send an empty response: SendResponse(a_RequestID, RCON_PACKET_RESPONSE, 0, nullptr); return true; } } // Unknown packet type, drop the connection: LOGWARNING("RCON: Client at %s has sent an unknown packet type %d, dropping connection.", m_IPAddress.c_str(), a_PacketType ); return false; } UInt32 cRCONServer::cConnection::UIntFromBuffer(const char * a_Buffer) { const Byte * Buffer = reinterpret_cast<const Byte *>(a_Buffer); return (Buffer[3] << 24) | (Buffer[2] << 16) | (Buffer[1] << 8) | Buffer[0]; } void cRCONServer::cConnection::UIntToBuffer(UInt32 a_Value, char * a_Buffer) { a_Buffer[0] = static_cast<char>(a_Value & 0xff); a_Buffer[1] = static_cast<char>((a_Value >> 8) & 0xff); a_Buffer[2] = static_cast<char>((a_Value >> 16) & 0xff); a_Buffer[3] = static_cast<char>((a_Value >> 24) & 0xff); } /// Sends a RCON packet back to the client void cRCONServer::cConnection::SendResponse(UInt32 a_RequestID, UInt32 a_PacketType, UInt32 a_PayloadLength, const char * a_Payload) { ASSERT((a_PayloadLength == 0) || (a_Payload != nullptr)); // Either zero data to send, or a valid payload ptr ASSERT(m_Link != nullptr); char Buffer[12]; UInt32 Length = a_PayloadLength + 10; UIntToBuffer(Length, Buffer); UIntToBuffer(a_RequestID, Buffer + 4); UIntToBuffer(a_PacketType, Buffer + 8); m_Link->Send(Buffer, 12); if (a_PayloadLength > 0) { m_Link->Send(a_Payload, a_PayloadLength); } m_Link->Send("\0", 2); // Send two zero chars as the padding } <commit_msg>Fix clang compile error<commit_after> // RCONServer.cpp // Implements the cRCONServer class representing the RCON server #include "Globals.h" #include "IniFile.h" #include "RCONServer.h" #include "Server.h" #include "Root.h" #include "CommandOutput.h" // Disable MSVC warnings: #if defined(_MSC_VER) #pragma warning(push) #pragma warning(disable:4355) // 'this' : used in base member initializer list #endif enum { // Client -> Server: RCON_PACKET_COMMAND = 2, RCON_PACKET_LOGIN = 3, // Server -> Client: RCON_PACKET_RESPONSE = 2, } ; //////////////////////////////////////////////////////////////////////////////// // cRCONListenCallbacks: class cRCONListenCallbacks: public cNetwork::cListenCallbacks { public: cRCONListenCallbacks(cRCONServer & a_RCONServer, UInt16 a_Port): m_RCONServer(a_RCONServer), m_Port(a_Port) { } protected: /** The RCON server instance that we're attached to. */ cRCONServer & m_RCONServer; /** The port for which this instance is responsible. */ UInt16 m_Port; // cNetwork::cListenCallbacks overrides: virtual cTCPLink::cCallbacksPtr OnIncomingConnection(const AString & a_RemoteIPAddress, UInt16 a_RemotePort) override { LOG("RCON Client \"%s\" connected!", a_RemoteIPAddress.c_str()); return std::make_shared<cRCONServer::cConnection>(m_RCONServer, a_RemoteIPAddress); } virtual void OnAccepted(cTCPLink & a_Link) override {} virtual void OnError(int a_ErrorCode, const AString & a_ErrorMsg) override { LOGWARNING("RCON server error on port %d: %d (%s)", m_Port, a_ErrorCode, a_ErrorMsg.c_str()); } }; //////////////////////////////////////////////////////////////////////////////// // cRCONCommandOutput: class cRCONCommandOutput : public cCommandOutputCallback { public: cRCONCommandOutput(cRCONServer::cConnection & a_Connection, UInt32 a_RequestID) : m_Connection(a_Connection), m_RequestID(a_RequestID) { } // cCommandOutputCallback overrides: virtual void Out(const AString & a_Text) override { m_Buffer.append(a_Text); } virtual void Finished(void) override { m_Connection.SendResponse(m_RequestID, RCON_PACKET_RESPONSE, static_cast<UInt32>(m_Buffer.size()), m_Buffer.c_str()); delete this; } protected: cRCONServer::cConnection & m_Connection; UInt32 m_RequestID; AString m_Buffer; } ; //////////////////////////////////////////////////////////////////////////////// // cRCONServer: cRCONServer::cRCONServer(cServer & a_Server) : m_Server(a_Server) { } cRCONServer::~cRCONServer() { for (auto srv: m_ListenServers) { srv->Close(); } } void cRCONServer::Initialize(cIniFile & a_IniFile) { if (!a_IniFile.GetValueSetB("RCON", "Enabled", false)) { return; } // Read the password, don't allow an empty one: m_Password = a_IniFile.GetValueSet("RCON", "Password", ""); if (m_Password.empty()) { LOGWARNING("RCON is requested, but the password is not set. RCON is now disabled."); return; } // Read the listening ports for RCON from config: AStringVector Ports = ReadUpgradeIniPorts(a_IniFile, "RCON", "Ports", "PortsIPv4", "PortsIPv6", "25575"); // Start listening on each specified port: for (auto port: Ports) { UInt16 PortNum; if (!StringToInteger(port, PortNum)) { LOGINFO("Invalid RCON port value: \"%s\". Ignoring.", port.c_str()); continue; } auto Handle = cNetwork::Listen(PortNum, std::make_shared<cRCONListenCallbacks>(*this, PortNum)); if (Handle->IsListening()) { m_ListenServers.push_back(Handle); } } if (m_ListenServers.empty()) { LOGWARNING("RCON is enabled but no valid ports were found. RCON is not accessible."); } } //////////////////////////////////////////////////////////////////////////////// // cRCONServer::cConnection: cRCONServer::cConnection::cConnection(cRCONServer & a_RCONServer, const AString & a_IPAddress) : m_IsAuthenticated(false), m_RCONServer(a_RCONServer), m_IPAddress(a_IPAddress) { } void cRCONServer::cConnection::OnLinkCreated(cTCPLinkPtr a_Link) { m_Link = a_Link; } void cRCONServer::cConnection::OnReceivedData(const char * a_Data, size_t a_Size) { ASSERT(m_Link != nullptr); // Append data to the buffer: m_Buffer.append(a_Data, a_Size); // Process the packets in the buffer: while (m_Buffer.size() >= 14) { UInt32 Length = UIntFromBuffer(m_Buffer.data()); if (Length > 1500) { // Too long, drop the connection LOGWARNING("Received an invalid RCON packet length (%d), dropping RCON connection to %s.", Length, m_IPAddress.c_str() ); m_Link->Close(); m_Link.reset(); return; } if (Length > static_cast<UInt32>(m_Buffer.size() + 4)) { // Incomplete packet yet, wait for more data to come return; } UInt32 RequestID = UIntFromBuffer(m_Buffer.data() + 4); UInt32 PacketType = UIntFromBuffer(m_Buffer.data() + 8); if (!ProcessPacket(RequestID, PacketType, Length - 10, m_Buffer.data() + 12)) { m_Link->Close(); m_Link.reset(); return; } m_Buffer.erase(0, Length + 4); } // while (m_Buffer.size() >= 14) } void cRCONServer::cConnection::OnRemoteClosed(void) { m_Link.reset(); } void cRCONServer::cConnection::OnError(int a_ErrorCode, const AString & a_ErrorMsg) { LOGD("Error in RCON connection %s: %d (%s)", m_IPAddress.c_str(), a_ErrorCode, a_ErrorMsg.c_str()); m_Link.reset(); } bool cRCONServer::cConnection::ProcessPacket(UInt32 a_RequestID, UInt32 a_PacketType, UInt32 a_PayloadLength, const char * a_Payload) { switch (a_PacketType) { case RCON_PACKET_LOGIN: { if (strncmp(a_Payload, m_RCONServer.m_Password.c_str(), a_PayloadLength) != 0) { LOGINFO("RCON: Invalid password from client %s, dropping connection.", m_IPAddress.c_str()); SendResponse(0xffffffffU, RCON_PACKET_RESPONSE, 0, nullptr); return false; } m_IsAuthenticated = true; LOGD("RCON: Client at %s has successfully authenticated", m_IPAddress.c_str()); // Send OK response: SendResponse(a_RequestID, RCON_PACKET_RESPONSE, 0, nullptr); return true; } case RCON_PACKET_COMMAND: { if (!m_IsAuthenticated) { char AuthNeeded[] = "You need to authenticate first!"; SendResponse(a_RequestID, RCON_PACKET_RESPONSE, sizeof(AuthNeeded), AuthNeeded); return false; } AString cmd(a_Payload, a_PayloadLength); LOGD("RCON command from %s: \"%s\"", m_IPAddress.c_str(), cmd.c_str()); cRoot::Get()->ExecuteConsoleCommand(cmd, *(new cRCONCommandOutput(*this, a_RequestID))); // Send an empty response: SendResponse(a_RequestID, RCON_PACKET_RESPONSE, 0, nullptr); return true; } } // Unknown packet type, drop the connection: LOGWARNING("RCON: Client at %s has sent an unknown packet type %d, dropping connection.", m_IPAddress.c_str(), a_PacketType ); return false; } UInt32 cRCONServer::cConnection::UIntFromBuffer(const char * a_Buffer) { const Byte * Buffer = reinterpret_cast<const Byte *>(a_Buffer); return (Buffer[3] << 24) | (Buffer[2] << 16) | (Buffer[1] << 8) | Buffer[0]; } void cRCONServer::cConnection::UIntToBuffer(UInt32 a_Value, char * a_Buffer) { a_Buffer[0] = static_cast<char>(a_Value & 0xff); a_Buffer[1] = static_cast<char>((a_Value >> 8) & 0xff); a_Buffer[2] = static_cast<char>((a_Value >> 16) & 0xff); a_Buffer[3] = static_cast<char>((a_Value >> 24) & 0xff); } /// Sends a RCON packet back to the client void cRCONServer::cConnection::SendResponse(UInt32 a_RequestID, UInt32 a_PacketType, UInt32 a_PayloadLength, const char * a_Payload) { ASSERT((a_PayloadLength == 0) || (a_Payload != nullptr)); // Either zero data to send, or a valid payload ptr ASSERT(m_Link != nullptr); char Buffer[12]; UInt32 Length = a_PayloadLength + 10; UIntToBuffer(Length, Buffer); UIntToBuffer(a_RequestID, Buffer + 4); UIntToBuffer(a_PacketType, Buffer + 8); m_Link->Send(Buffer, 12); if (a_PayloadLength > 0) { m_Link->Send(a_Payload, a_PayloadLength); } m_Link->Send("\0", 2); // Send two zero chars as the padding } <|endoftext|>
<commit_before><commit_msg>error: assigning to 'PrintQueueFlags' from incompatible type 'int'<commit_after><|endoftext|>
<commit_before><commit_msg>Fix merge issues<commit_after><|endoftext|>
<commit_before>//===-- XCoreLowerThreadLocal - Lower thread local variables --------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// /// \file /// \brief This file contains a pass that lowers thread local variables on the /// XCore. /// //===----------------------------------------------------------------------===// #include "XCore.h" #include "llvm/IR/Constants.h" #include "llvm/IR/DerivedTypes.h" #include "llvm/IR/GlobalVariable.h" #include "llvm/IR/Intrinsics.h" #include "llvm/IR/IRBuilder.h" #include "llvm/IR/Module.h" #include "llvm/Pass.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/NoFolder.h" #include "llvm/Support/ValueHandle.h" #define DEBUG_TYPE "xcore-lower-thread-local" using namespace llvm; static cl::opt<unsigned> MaxThreads( "xcore-max-threads", cl::Optional, cl::desc("Maximum number of threads (for emulation thread-local storage)"), cl::Hidden, cl::value_desc("number"), cl::init(8)); namespace { /// Lowers thread local variables on the XCore. Each thread local variable is /// expanded to an array of n elements indexed by the thread ID where n is the /// fixed number hardware threads supported by the device. struct XCoreLowerThreadLocal : public ModulePass { static char ID; XCoreLowerThreadLocal() : ModulePass(ID) { initializeXCoreLowerThreadLocalPass(*PassRegistry::getPassRegistry()); } bool lowerGlobal(GlobalVariable *GV); bool runOnModule(Module &M); }; } char XCoreLowerThreadLocal::ID = 0; INITIALIZE_PASS(XCoreLowerThreadLocal, "xcore-lower-thread-local", "Lower thread local variables", false, false) ModulePass *llvm::createXCoreLowerThreadLocalPass() { return new XCoreLowerThreadLocal(); } static ArrayType *createLoweredType(Type *OriginalType) { return ArrayType::get(OriginalType, MaxThreads); } static Constant * createLoweredInitializer(ArrayType *NewType, Constant *OriginalInitializer) { SmallVector<Constant *, 8> Elements(MaxThreads); for (unsigned i = 0; i != MaxThreads; ++i) { Elements[i] = OriginalInitializer; } return ConstantArray::get(NewType, Elements); } static Instruction * createReplacementInstr(ConstantExpr *CE, Instruction *Instr) { IRBuilder<true,NoFolder> Builder(Instr); unsigned OpCode = CE->getOpcode(); switch (OpCode) { case Instruction::GetElementPtr: { SmallVector<Value *,4> CEOpVec(CE->op_begin(), CE->op_end()); ArrayRef<Value *> CEOps(CEOpVec); return dyn_cast<Instruction>(Builder.CreateInBoundsGEP(CEOps[0], CEOps.slice(1))); } case Instruction::Add: case Instruction::Sub: case Instruction::Mul: case Instruction::UDiv: case Instruction::SDiv: case Instruction::FDiv: case Instruction::URem: case Instruction::SRem: case Instruction::FRem: case Instruction::Shl: case Instruction::LShr: case Instruction::AShr: case Instruction::And: case Instruction::Or: case Instruction::Xor: return dyn_cast<Instruction>( Builder.CreateBinOp((Instruction::BinaryOps)OpCode, CE->getOperand(0), CE->getOperand(1), CE->getName())); case Instruction::Trunc: case Instruction::ZExt: case Instruction::SExt: case Instruction::FPToUI: case Instruction::FPToSI: case Instruction::UIToFP: case Instruction::SIToFP: case Instruction::FPTrunc: case Instruction::FPExt: case Instruction::PtrToInt: case Instruction::IntToPtr: case Instruction::BitCast: return dyn_cast<Instruction>( Builder.CreateCast((Instruction::CastOps)OpCode, CE->getOperand(0), CE->getType(), CE->getName())); default: assert(0 && "Unhandled constant expression!\n"); } } static bool replaceConstantExprOp(ConstantExpr *CE) { do { SmallVector<WeakVH,8> WUsers; for (Value::use_iterator I = CE->use_begin(), E = CE->use_end(); I != E; ++I) WUsers.push_back(WeakVH(*I)); while (!WUsers.empty()) if (WeakVH WU = WUsers.pop_back_val()) { if (Instruction *Instr = dyn_cast<Instruction>(WU)) { Instruction *NewInst = createReplacementInstr(CE, Instr); assert(NewInst && "Must build an instruction\n"); // If NewInst uses a CE being handled in an earlier recursion the // earlier recursion's do-while-hasNUsesOrMore(1) will run again. Instr->replaceUsesOfWith(CE, NewInst); } else { ConstantExpr *CExpr = dyn_cast<ConstantExpr>(WU); if (!CExpr || !replaceConstantExprOp(CExpr)) return false; } } } while (CE->hasNUsesOrMore(1)); // Does a recursion's NewInst use CE? CE->destroyConstant(); return true; } static bool rewriteNonInstructionUses(GlobalVariable *GV) { SmallVector<WeakVH,8> WUsers; for (Value::use_iterator I = GV->use_begin(), E = GV->use_end(); I != E; ++I) if (!isa<Instruction>(*I)) WUsers.push_back(WeakVH(*I)); while (!WUsers.empty()) if (WeakVH WU = WUsers.pop_back_val()) { ConstantExpr *CE = dyn_cast<ConstantExpr>(WU); if (!CE || !replaceConstantExprOp(CE)) return false; } return true; } static bool isZeroLengthArray(Type *Ty) { ArrayType *AT = dyn_cast<ArrayType>(Ty); return AT && (AT->getNumElements() == 0); } bool XCoreLowerThreadLocal::lowerGlobal(GlobalVariable *GV) { Module *M = GV->getParent(); LLVMContext &Ctx = M->getContext(); if (!GV->isThreadLocal()) return false; // Skip globals that we can't lower and leave it for the backend to error. if (!rewriteNonInstructionUses(GV) || !GV->getType()->isSized() || isZeroLengthArray(GV->getType())) return false; // Create replacement global. ArrayType *NewType = createLoweredType(GV->getType()->getElementType()); Constant *NewInitializer = 0; if (GV->hasInitializer()) NewInitializer = createLoweredInitializer(NewType, GV->getInitializer()); GlobalVariable *NewGV = new GlobalVariable(*M, NewType, GV->isConstant(), GV->getLinkage(), NewInitializer, "", 0, GlobalVariable::NotThreadLocal, GV->getType()->getAddressSpace(), GV->isExternallyInitialized()); // Update uses. SmallVector<User *, 16> Users(GV->use_begin(), GV->use_end()); for (unsigned I = 0, E = Users.size(); I != E; ++I) { User *U = Users[I]; Instruction *Inst = cast<Instruction>(U); IRBuilder<> Builder(Inst); Function *GetID = Intrinsic::getDeclaration(GV->getParent(), Intrinsic::xcore_getid); Value *ThreadID = Builder.CreateCall(GetID); SmallVector<Value *, 2> Indices; Indices.push_back(Constant::getNullValue(Type::getInt64Ty(Ctx))); Indices.push_back(ThreadID); Value *Addr = Builder.CreateInBoundsGEP(NewGV, Indices); U->replaceUsesOfWith(GV, Addr); } // Remove old global. NewGV->takeName(GV); GV->eraseFromParent(); return true; } bool XCoreLowerThreadLocal::runOnModule(Module &M) { // Find thread local globals. bool MadeChange = false; SmallVector<GlobalVariable *, 16> ThreadLocalGlobals; for (Module::global_iterator GVI = M.global_begin(), E = M.global_end(); GVI != E; ++GVI) { GlobalVariable *GV = GVI; if (GV->isThreadLocal()) ThreadLocalGlobals.push_back(GV); } for (unsigned I = 0, E = ThreadLocalGlobals.size(); I != E; ++I) { MadeChange |= lowerGlobal(ThreadLocalGlobals[I]); } return MadeChange; } <commit_msg>Silencing a warning about control flow reaching the end of a non-void function.<commit_after>//===-- XCoreLowerThreadLocal - Lower thread local variables --------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// /// \file /// \brief This file contains a pass that lowers thread local variables on the /// XCore. /// //===----------------------------------------------------------------------===// #include "XCore.h" #include "llvm/IR/Constants.h" #include "llvm/IR/DerivedTypes.h" #include "llvm/IR/GlobalVariable.h" #include "llvm/IR/Intrinsics.h" #include "llvm/IR/IRBuilder.h" #include "llvm/IR/Module.h" #include "llvm/Pass.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/NoFolder.h" #include "llvm/Support/ValueHandle.h" #define DEBUG_TYPE "xcore-lower-thread-local" using namespace llvm; static cl::opt<unsigned> MaxThreads( "xcore-max-threads", cl::Optional, cl::desc("Maximum number of threads (for emulation thread-local storage)"), cl::Hidden, cl::value_desc("number"), cl::init(8)); namespace { /// Lowers thread local variables on the XCore. Each thread local variable is /// expanded to an array of n elements indexed by the thread ID where n is the /// fixed number hardware threads supported by the device. struct XCoreLowerThreadLocal : public ModulePass { static char ID; XCoreLowerThreadLocal() : ModulePass(ID) { initializeXCoreLowerThreadLocalPass(*PassRegistry::getPassRegistry()); } bool lowerGlobal(GlobalVariable *GV); bool runOnModule(Module &M); }; } char XCoreLowerThreadLocal::ID = 0; INITIALIZE_PASS(XCoreLowerThreadLocal, "xcore-lower-thread-local", "Lower thread local variables", false, false) ModulePass *llvm::createXCoreLowerThreadLocalPass() { return new XCoreLowerThreadLocal(); } static ArrayType *createLoweredType(Type *OriginalType) { return ArrayType::get(OriginalType, MaxThreads); } static Constant * createLoweredInitializer(ArrayType *NewType, Constant *OriginalInitializer) { SmallVector<Constant *, 8> Elements(MaxThreads); for (unsigned i = 0; i != MaxThreads; ++i) { Elements[i] = OriginalInitializer; } return ConstantArray::get(NewType, Elements); } static Instruction * createReplacementInstr(ConstantExpr *CE, Instruction *Instr) { IRBuilder<true,NoFolder> Builder(Instr); unsigned OpCode = CE->getOpcode(); switch (OpCode) { case Instruction::GetElementPtr: { SmallVector<Value *,4> CEOpVec(CE->op_begin(), CE->op_end()); ArrayRef<Value *> CEOps(CEOpVec); return dyn_cast<Instruction>(Builder.CreateInBoundsGEP(CEOps[0], CEOps.slice(1))); } case Instruction::Add: case Instruction::Sub: case Instruction::Mul: case Instruction::UDiv: case Instruction::SDiv: case Instruction::FDiv: case Instruction::URem: case Instruction::SRem: case Instruction::FRem: case Instruction::Shl: case Instruction::LShr: case Instruction::AShr: case Instruction::And: case Instruction::Or: case Instruction::Xor: return dyn_cast<Instruction>( Builder.CreateBinOp((Instruction::BinaryOps)OpCode, CE->getOperand(0), CE->getOperand(1), CE->getName())); case Instruction::Trunc: case Instruction::ZExt: case Instruction::SExt: case Instruction::FPToUI: case Instruction::FPToSI: case Instruction::UIToFP: case Instruction::SIToFP: case Instruction::FPTrunc: case Instruction::FPExt: case Instruction::PtrToInt: case Instruction::IntToPtr: case Instruction::BitCast: return dyn_cast<Instruction>( Builder.CreateCast((Instruction::CastOps)OpCode, CE->getOperand(0), CE->getType(), CE->getName())); default: assert(0 && "Unhandled constant expression!\n"); } llvm_unreachable("Unhandled constant expression!\n"); } static bool replaceConstantExprOp(ConstantExpr *CE) { do { SmallVector<WeakVH,8> WUsers; for (Value::use_iterator I = CE->use_begin(), E = CE->use_end(); I != E; ++I) WUsers.push_back(WeakVH(*I)); while (!WUsers.empty()) if (WeakVH WU = WUsers.pop_back_val()) { if (Instruction *Instr = dyn_cast<Instruction>(WU)) { Instruction *NewInst = createReplacementInstr(CE, Instr); assert(NewInst && "Must build an instruction\n"); // If NewInst uses a CE being handled in an earlier recursion the // earlier recursion's do-while-hasNUsesOrMore(1) will run again. Instr->replaceUsesOfWith(CE, NewInst); } else { ConstantExpr *CExpr = dyn_cast<ConstantExpr>(WU); if (!CExpr || !replaceConstantExprOp(CExpr)) return false; } } } while (CE->hasNUsesOrMore(1)); // Does a recursion's NewInst use CE? CE->destroyConstant(); return true; } static bool rewriteNonInstructionUses(GlobalVariable *GV) { SmallVector<WeakVH,8> WUsers; for (Value::use_iterator I = GV->use_begin(), E = GV->use_end(); I != E; ++I) if (!isa<Instruction>(*I)) WUsers.push_back(WeakVH(*I)); while (!WUsers.empty()) if (WeakVH WU = WUsers.pop_back_val()) { ConstantExpr *CE = dyn_cast<ConstantExpr>(WU); if (!CE || !replaceConstantExprOp(CE)) return false; } return true; } static bool isZeroLengthArray(Type *Ty) { ArrayType *AT = dyn_cast<ArrayType>(Ty); return AT && (AT->getNumElements() == 0); } bool XCoreLowerThreadLocal::lowerGlobal(GlobalVariable *GV) { Module *M = GV->getParent(); LLVMContext &Ctx = M->getContext(); if (!GV->isThreadLocal()) return false; // Skip globals that we can't lower and leave it for the backend to error. if (!rewriteNonInstructionUses(GV) || !GV->getType()->isSized() || isZeroLengthArray(GV->getType())) return false; // Create replacement global. ArrayType *NewType = createLoweredType(GV->getType()->getElementType()); Constant *NewInitializer = 0; if (GV->hasInitializer()) NewInitializer = createLoweredInitializer(NewType, GV->getInitializer()); GlobalVariable *NewGV = new GlobalVariable(*M, NewType, GV->isConstant(), GV->getLinkage(), NewInitializer, "", 0, GlobalVariable::NotThreadLocal, GV->getType()->getAddressSpace(), GV->isExternallyInitialized()); // Update uses. SmallVector<User *, 16> Users(GV->use_begin(), GV->use_end()); for (unsigned I = 0, E = Users.size(); I != E; ++I) { User *U = Users[I]; Instruction *Inst = cast<Instruction>(U); IRBuilder<> Builder(Inst); Function *GetID = Intrinsic::getDeclaration(GV->getParent(), Intrinsic::xcore_getid); Value *ThreadID = Builder.CreateCall(GetID); SmallVector<Value *, 2> Indices; Indices.push_back(Constant::getNullValue(Type::getInt64Ty(Ctx))); Indices.push_back(ThreadID); Value *Addr = Builder.CreateInBoundsGEP(NewGV, Indices); U->replaceUsesOfWith(GV, Addr); } // Remove old global. NewGV->takeName(GV); GV->eraseFromParent(); return true; } bool XCoreLowerThreadLocal::runOnModule(Module &M) { // Find thread local globals. bool MadeChange = false; SmallVector<GlobalVariable *, 16> ThreadLocalGlobals; for (Module::global_iterator GVI = M.global_begin(), E = M.global_end(); GVI != E; ++GVI) { GlobalVariable *GV = GVI; if (GV->isThreadLocal()) ThreadLocalGlobals.push_back(GV); } for (unsigned I = 0, E = ThreadLocalGlobals.size(); I != E; ++I) { MadeChange |= lowerGlobal(ThreadLocalGlobals[I]); } return MadeChange; } <|endoftext|>
<commit_before>// Copyright 2004-present Facebook. All Rights Reserved. #include <gflags/gflags.h> #include <glog/logging.h> #include "osquery/core.h" DEFINE_string(query, "", "query to execute"); int main(int argc, char* argv[]) { osquery::core::initOsquery(argc, argv); if (FLAGS_query != "") { int err; LOG(INFO) << "Executing: " << FLAGS_query; osquery::core::aggregateQuery(FLAGS_query, err); if (err != 0) { LOG(ERROR) << "Query failed: " << err; return 1; } LOG(INFO) << "Query succedded"; } else { LOG(ERROR) << "Usage: run --query=\"<query>\""; return 1; } return 0; } <commit_msg>adding an 'iterations' flag to the run tool to look at memory usage trends<commit_after>// Copyright 2004-present Facebook. All Rights Reserved. #include <gflags/gflags.h> #include <glog/logging.h> #include "osquery/core.h" DEFINE_string(query, "", "query to execute"); DEFINE_int32(iterations, 1, "times to run the query in question"); int main(int argc, char* argv[]) { osquery::core::initOsquery(argc, argv); if (FLAGS_query != "") { for (int i = 0; i < FLAGS_iterations; ++i) { int err; LOG(INFO) << "Executing: " << FLAGS_query; osquery::core::aggregateQuery(FLAGS_query, err); if (err != 0) { LOG(ERROR) << "Query failed: " << err; return 1; } LOG(INFO) << "Query succedded"; } } else { LOG(ERROR) << "Usage: run --query=\"<query>\""; return 1; } return 0; } <|endoftext|>
<commit_before>/******************************************************************************* GPU OPTIMIZED MONTE CARLO (GOMC) 2.60 Copyright (C) 2018 GOMC Group A copy of the GNU General Public License can be found in the COPYRIGHT.txt along with this program, also can be found at <http://www.gnu.org/licenses/>. ********************************************************************************/ #include "Simulation.h" #include "Setup.h" //For setup object #include "EnergyTypes.h" #include "PSFOutput.h" #include <iostream> #include <iomanip> #include "CUDAMemoryManager.cuh" #define EPSILON 0.001 Simulation::Simulation(char const*const configFileName, MultiSim const*const& multisim):ms(multisim) { startStep = 0; //NOTE: //IMPORTANT! Keep this order... //as system depends on staticValues, and cpu sometimes depends on both. set.Init(configFileName, multisim); totalSteps = set.config.sys.step.total; staticValues = new StaticVals(set); system = new System(*staticValues); staticValues->Init(set, *system); system->Init(set, startStep); //recal Init for static value for initializing ewald since ewald is //initialized in system staticValues->InitOver(set, *system); cpu = new CPUSide(*system, *staticValues); cpu->Init(set.pdb, set.config.out, set.config.sys.step.equil, totalSteps, startStep); //Dump combined PSF PSFOutput psfOut(staticValues->mol, *system, set.mol.kindMap, set.pdb.atoms.resKindNames); psfOut.PrintPSF(set.config.out.state.files.psf.name); std::cout << "Printed combined psf to file " << set.config.out.state.files.psf.name << '\n'; if(totalSteps == 0) { frameSteps = set.pdb.GetFrameSteps(set.config.in.files.pdb.name); } #if GOMC_LIB_MPI PTUtils = set.config.sys.step.parallelTemp ? new ParallelTemperingUtilities(ms, *system, *staticValues, set.config.sys.step.parallelTempFreq, set.config.sys.step.parallelTemperingAttemptsPerExchange): NULL; exchangeResults.resize(ms->worldSize, false); #endif } Simulation::~Simulation() { delete cpu; delete system; delete staticValues; #ifdef GOMC_CUDA CUDAMemoryManager::isFreed(); #endif } void Simulation::RunSimulation(void) { double startEnergy = system->potential.totalEnergy.total; if(totalSteps == 0) { for(int i = 0; i < frameSteps.size(); i++) { if(i == 0) { cpu->Output(frameSteps[0] - 1); continue; } system->RecalculateTrajectory(set, i + 1); cpu->Output(frameSteps[i] - 1); } } for (ulong step = startStep; step < totalSteps; step++) { system->moveSettings.AdjustMoves(step); system->ChooseAndRunMove(step); cpu->Output(step); if((step + 1) == cpu->equilSteps) { double currEnergy = system->potential.totalEnergy.total; if(std::abs(currEnergy - startEnergy) > 1.0e+10) { printf("Info: Recalculating the total energies to insure the accuracy" " of the computed \n" " running energies.\n\n"); system->calcEwald->Init(); system->potential = system->calcEnergy.SystemTotal(); } } #if GOMC_LIB_MPI // if(staticValues->simEventFreq.parallelTemp && step > cpu->equilSteps && step % staticValues->simEventFreq.parallelTempFreq == 0){ int maxSwap = 0; /* Number of rounds of exchanges needed to deal with any multiple * exchanges. */ /* Where each replica ends up after the exchange attempt(s). */ /* The order in which multiple exchanges will occur. */ bool bThisReplicaExchanged = false; system->potential = system->calcEnergy.SystemTotal(); PTUtils->evaluateExchangeCriteria(step); PTUtils->prepareToDoExchange(ms->worldRank, &maxSwap, &bThisReplicaExchanged); PTUtils->conductExchanges(system->coordinates, system->com, ms, maxSwap, bThisReplicaExchanged); system->cellList.GridAll(system->boxDimRef, system->coordinates, system->molLookup); if (staticValues->forcefield.ewald){ for(int box = 0; box < BOX_TOTAL; box++){ system->calcEwald->BoxReciprocalSetup(box, system->coordinates); system->potential.boxEnergy[box].recip = system->calcEwald->BoxReciprocal(box); system->calcEwald->UpdateRecip(box); } } system->potential = system->calcEnergy.SystemTotal(); } #endif #ifndef NDEBUG if((step + 1) % 1000 == 0) RunningCheck(step); #endif } if(!RecalculateAndCheck()) { std::cerr << "Warning: Updated energy differs from Recalculated Energy!\n"; } system->PrintAcceptance(); system->PrintTime(); #if GOMC_LIB_MPI if (staticValues->simEventFreq.parallelTemp) PTUtils->print_replica_exchange_statistics(ms->fplog); #endif } bool Simulation::RecalculateAndCheck(void) { system->calcEwald->UpdateVectorsAndRecipTerms(false); SystemPotential pot = system->calcEnergy.SystemTotal(); bool compare = true; compare &= std::abs(system->potential.totalEnergy.intraBond - pot.totalEnergy.intraBond) < EPSILON; compare &= std::abs(system->potential.totalEnergy.intraNonbond - pot.totalEnergy.intraNonbond) < EPSILON; compare &= std::abs(system->potential.totalEnergy.inter - pot.totalEnergy.inter) < EPSILON; compare &= std::abs(system->potential.totalEnergy.tc - pot.totalEnergy.tc) < EPSILON; compare &= std::abs(system->potential.totalEnergy.real - pot.totalEnergy.real) < EPSILON; compare &= std::abs(system->potential.totalEnergy.self - pot.totalEnergy.self) < EPSILON; compare &= std::abs(system->potential.totalEnergy.correction - pot.totalEnergy.correction) < EPSILON; compare &= std::abs(system->potential.totalEnergy.recip - pot.totalEnergy.recip) < EPSILON; if(!compare) { std::cout << "=================================================================\n" << "Energy INTRA B | INTRA NB | INTER | TC | REAL | SELF | CORRECTION | RECIP" << std::endl << "System: " << std::setw(12) << system->potential.totalEnergy.intraBond << " | " << std::setw(12) << system->potential.totalEnergy.intraNonbond << " | " << std::setw(12) << system->potential.totalEnergy.inter << " | " << std::setw(12) << system->potential.totalEnergy.tc << " | " << std::setw(12) << system->potential.totalEnergy.real << " | " << std::setw(12) << system->potential.totalEnergy.self << " | " << std::setw(12) << system->potential.totalEnergy.correction << " | " << std::setw(12) << system->potential.totalEnergy.recip << std::endl << "Recalc: " << std::setw(12) << pot.totalEnergy.intraBond << " | " << std::setw(12) << pot.totalEnergy.intraNonbond << " | " << std::setw(12) << pot.totalEnergy.inter << " | " << std::setw(12) << pot.totalEnergy.tc << " | " << std::setw(12) << pot.totalEnergy.real << " | " << std::setw(12) << pot.totalEnergy.self << " | " << std::setw(12) << pot.totalEnergy.correction << " | " << std::setw(12) << pot.totalEnergy.recip << std::endl << "================================================================" << std::endl << std::endl; } return compare; } #ifndef NDEBUG void Simulation::RunningCheck(const uint step) { system->calcEwald->UpdateVectorsAndRecipTerms(false); SystemPotential pot = system->calcEnergy.SystemTotal(); std::cout << "=================================================================" << std::endl << "-------------------------" << std::endl << " STEP: " << step + 1 << std::endl << "-------------------------" << std::endl << "Energy INTRA B | INTRA NB | INTER | TC | REAL | SELF | CORRECTION | RECIP" << std::endl << "System: " << std::setw(12) << system->potential.totalEnergy.intraBond << " | " << std::setw(12) << system->potential.totalEnergy.intraNonbond << " | " << std::setw(12) << system->potential.totalEnergy.inter << " | " << std::setw(12) << system->potential.totalEnergy.tc << " | " << std::setw(12) << system->potential.totalEnergy.real << " | " << std::setw(12) << system->potential.totalEnergy.self << " | " << std::setw(12) << system->potential.totalEnergy.correction << " | " << std::setw(12) << system->potential.totalEnergy.recip << std::endl << "Recalc: " << std::setw(12) << pot.totalEnergy.intraBond << " | " << std::setw(12) << pot.totalEnergy.intraNonbond << " | " << std::setw(12) << pot.totalEnergy.inter << " | " << std::setw(12) << pot.totalEnergy.tc << " | " << std::setw(12) << pot.totalEnergy.real << " | " << std::setw(12) << pot.totalEnergy.self << " | " << std::setw(12) << pot.totalEnergy.correction << " | " << std::setw(12) << pot.totalEnergy.recip << std::endl << "================================================================" << std::endl << std::endl; } #endif <commit_msg>Fixed #207 to recalculcate system energy corrected at equilibrium<commit_after>/******************************************************************************* GPU OPTIMIZED MONTE CARLO (GOMC) 2.60 Copyright (C) 2018 GOMC Group A copy of the GNU General Public License can be found in the COPYRIGHT.txt along with this program, also can be found at <http://www.gnu.org/licenses/>. ********************************************************************************/ #include "Simulation.h" #include "Setup.h" //For setup object #include "EnergyTypes.h" #include "PSFOutput.h" #include <iostream> #include <iomanip> #include "CUDAMemoryManager.cuh" #define EPSILON 0.001 Simulation::Simulation(char const*const configFileName, MultiSim const*const& multisim):ms(multisim) { startStep = 0; //NOTE: //IMPORTANT! Keep this order... //as system depends on staticValues, and cpu sometimes depends on both. set.Init(configFileName, multisim); totalSteps = set.config.sys.step.total; staticValues = new StaticVals(set); system = new System(*staticValues); staticValues->Init(set, *system); system->Init(set, startStep); //recal Init for static value for initializing ewald since ewald is //initialized in system staticValues->InitOver(set, *system); cpu = new CPUSide(*system, *staticValues); cpu->Init(set.pdb, set.config.out, set.config.sys.step.equil, totalSteps, startStep); //Dump combined PSF PSFOutput psfOut(staticValues->mol, *system, set.mol.kindMap, set.pdb.atoms.resKindNames); psfOut.PrintPSF(set.config.out.state.files.psf.name); std::cout << "Printed combined psf to file " << set.config.out.state.files.psf.name << '\n'; if(totalSteps == 0) { frameSteps = set.pdb.GetFrameSteps(set.config.in.files.pdb.name); } #if GOMC_LIB_MPI PTUtils = set.config.sys.step.parallelTemp ? new ParallelTemperingUtilities(ms, *system, *staticValues, set.config.sys.step.parallelTempFreq, set.config.sys.step.parallelTemperingAttemptsPerExchange): NULL; exchangeResults.resize(ms->worldSize, false); #endif } Simulation::~Simulation() { delete cpu; delete system; delete staticValues; #ifdef GOMC_CUDA CUDAMemoryManager::isFreed(); #endif } void Simulation::RunSimulation(void) { double startEnergy = system->potential.totalEnergy.total; if(totalSteps == 0) { for(int i = 0; i < frameSteps.size(); i++) { if(i == 0) { cpu->Output(frameSteps[0] - 1); continue; } system->RecalculateTrajectory(set, i + 1); cpu->Output(frameSteps[i] - 1); } } for (ulong step = startStep; step < totalSteps; step++) { system->moveSettings.AdjustMoves(step); system->ChooseAndRunMove(step); cpu->Output(step); if((step + 1) == cpu->equilSteps) { double currEnergy = system->potential.totalEnergy.total; if(std::abs(currEnergy - startEnergy) > 1.0e+10) { printf("Info: Recalculating the total energies to insure the accuracy" " of the computed \n" " running energies.\n\n"); system->calcEwald->UpdateVectorsAndRecipTerms(true); system->potential = system->calcEnergy.SystemTotal(); } } #if GOMC_LIB_MPI // if(staticValues->simEventFreq.parallelTemp && step > cpu->equilSteps && step % staticValues->simEventFreq.parallelTempFreq == 0){ int maxSwap = 0; /* Number of rounds of exchanges needed to deal with any multiple * exchanges. */ /* Where each replica ends up after the exchange attempt(s). */ /* The order in which multiple exchanges will occur. */ bool bThisReplicaExchanged = false; system->potential = system->calcEnergy.SystemTotal(); PTUtils->evaluateExchangeCriteria(step); PTUtils->prepareToDoExchange(ms->worldRank, &maxSwap, &bThisReplicaExchanged); PTUtils->conductExchanges(system->coordinates, system->com, ms, maxSwap, bThisReplicaExchanged); system->cellList.GridAll(system->boxDimRef, system->coordinates, system->molLookup); if (staticValues->forcefield.ewald){ for(int box = 0; box < BOX_TOTAL; box++){ system->calcEwald->BoxReciprocalSetup(box, system->coordinates); system->potential.boxEnergy[box].recip = system->calcEwald->BoxReciprocal(box); system->calcEwald->UpdateRecip(box); } } system->potential = system->calcEnergy.SystemTotal(); } #endif #ifndef NDEBUG if((step + 1) % 1000 == 0) RunningCheck(step); #endif } if(!RecalculateAndCheck()) { std::cerr << "Warning: Updated energy differs from Recalculated Energy!\n"; } system->PrintAcceptance(); system->PrintTime(); #if GOMC_LIB_MPI if (staticValues->simEventFreq.parallelTemp) PTUtils->print_replica_exchange_statistics(ms->fplog); #endif } bool Simulation::RecalculateAndCheck(void) { system->calcEwald->UpdateVectorsAndRecipTerms(false); SystemPotential pot = system->calcEnergy.SystemTotal(); bool compare = true; compare &= std::abs(system->potential.totalEnergy.intraBond - pot.totalEnergy.intraBond) < EPSILON; compare &= std::abs(system->potential.totalEnergy.intraNonbond - pot.totalEnergy.intraNonbond) < EPSILON; compare &= std::abs(system->potential.totalEnergy.inter - pot.totalEnergy.inter) < EPSILON; compare &= std::abs(system->potential.totalEnergy.tc - pot.totalEnergy.tc) < EPSILON; compare &= std::abs(system->potential.totalEnergy.real - pot.totalEnergy.real) < EPSILON; compare &= std::abs(system->potential.totalEnergy.self - pot.totalEnergy.self) < EPSILON; compare &= std::abs(system->potential.totalEnergy.correction - pot.totalEnergy.correction) < EPSILON; compare &= std::abs(system->potential.totalEnergy.recip - pot.totalEnergy.recip) < EPSILON; if(!compare) { std::cout << "=================================================================\n" << "Energy INTRA B | INTRA NB | INTER | TC | REAL | SELF | CORRECTION | RECIP" << std::endl << "System: " << std::setw(12) << system->potential.totalEnergy.intraBond << " | " << std::setw(12) << system->potential.totalEnergy.intraNonbond << " | " << std::setw(12) << system->potential.totalEnergy.inter << " | " << std::setw(12) << system->potential.totalEnergy.tc << " | " << std::setw(12) << system->potential.totalEnergy.real << " | " << std::setw(12) << system->potential.totalEnergy.self << " | " << std::setw(12) << system->potential.totalEnergy.correction << " | " << std::setw(12) << system->potential.totalEnergy.recip << std::endl << "Recalc: " << std::setw(12) << pot.totalEnergy.intraBond << " | " << std::setw(12) << pot.totalEnergy.intraNonbond << " | " << std::setw(12) << pot.totalEnergy.inter << " | " << std::setw(12) << pot.totalEnergy.tc << " | " << std::setw(12) << pot.totalEnergy.real << " | " << std::setw(12) << pot.totalEnergy.self << " | " << std::setw(12) << pot.totalEnergy.correction << " | " << std::setw(12) << pot.totalEnergy.recip << std::endl << "================================================================" << std::endl << std::endl; } return compare; } #ifndef NDEBUG void Simulation::RunningCheck(const uint step) { system->calcEwald->UpdateVectorsAndRecipTerms(false); SystemPotential pot = system->calcEnergy.SystemTotal(); std::cout << "=================================================================" << std::endl << "-------------------------" << std::endl << " STEP: " << step + 1 << std::endl << "-------------------------" << std::endl << "Energy INTRA B | INTRA NB | INTER | TC | REAL | SELF | CORRECTION | RECIP" << std::endl << "System: " << std::setw(12) << system->potential.totalEnergy.intraBond << " | " << std::setw(12) << system->potential.totalEnergy.intraNonbond << " | " << std::setw(12) << system->potential.totalEnergy.inter << " | " << std::setw(12) << system->potential.totalEnergy.tc << " | " << std::setw(12) << system->potential.totalEnergy.real << " | " << std::setw(12) << system->potential.totalEnergy.self << " | " << std::setw(12) << system->potential.totalEnergy.correction << " | " << std::setw(12) << system->potential.totalEnergy.recip << std::endl << "Recalc: " << std::setw(12) << pot.totalEnergy.intraBond << " | " << std::setw(12) << pot.totalEnergy.intraNonbond << " | " << std::setw(12) << pot.totalEnergy.inter << " | " << std::setw(12) << pot.totalEnergy.tc << " | " << std::setw(12) << pot.totalEnergy.real << " | " << std::setw(12) << pot.totalEnergy.self << " | " << std::setw(12) << pot.totalEnergy.correction << " | " << std::setw(12) << pot.totalEnergy.recip << std::endl << "================================================================" << std::endl << std::endl; } #endif <|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2006 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ // mapnik #include <mapnik/global.hpp> #include <mapnik/utils.hpp> #include <mapnik/unicode.hpp> #include "dbffile.hpp" // boost #include <boost/algorithm/string.hpp> #include <boost/spirit/include/qi.hpp> // stl #include <string> dbf_file::dbf_file() : num_records_(0), num_fields_(0), record_length_(0), record_(0) {} dbf_file::dbf_file(std::string const& file_name) :num_records_(0), num_fields_(0), record_length_(0), #ifdef SHAPE_MEMORY_MAPPED_FILE file_(file_name), #else file_(file_name,std::ios::in | std::ios::binary), #endif record_(0) { if (file_.is_open()) { read_header(); } } dbf_file::~dbf_file() { ::operator delete(record_); } bool dbf_file::is_open() { return file_.is_open(); } void dbf_file::close() { if (file_ && file_.is_open()) file_.close(); } int dbf_file::num_records() const { return num_records_; } int dbf_file::num_fields() const { return num_fields_; } void dbf_file::move_to(int index) { if (index>0 && index<=num_records_) { long pos=(num_fields_<<5)+34+(index-1)*(record_length_+1); file_.seekg(pos,std::ios::beg); file_.read(record_,record_length_); } } std::string dbf_file::string_value(int col) const { if (col>=0 && col<num_fields_) { return std::string(record_+fields_[col].offset_,fields_[col].length_); } return ""; } const field_descriptor& dbf_file::descriptor(int col) const { assert(col>=0 && col<num_fields_); return fields_[col]; } void dbf_file::add_attribute(int col, mapnik::transcoder const& tr, Feature const& f) const throw() { using namespace boost::spirit; if (col>=0 && col<num_fields_) { std::string name=fields_[col].name_; switch (fields_[col].type_) { case 'C': case 'D'://todo handle date? case 'M': case 'L': { // FIXME - avoid constructing std::string in stack std::string str(record_+fields_[col].offset_,fields_[col].length_); boost::trim(str); f[name] = tr.transcode(str.c_str()); break; } case 'N': case 'F': { if (record_[fields_[col].offset_] == '*') { boost::put(f,name,0); break; } if ( fields_[col].dec_>0 ) { double val = 0.0; qi::phrase_parse(record_+fields_[col].offset_,record_+fields_[col].offset_ + fields_[col].length_, double_,ascii::space,val); boost::put(f,name,val); } else { int val = 0; qi::phrase_parse(record_+fields_[col].offset_,record_+fields_[col].offset_ + fields_[col].length_, int_,ascii::space,val); boost::put(f,name,val); } break; } } } } void dbf_file::read_header() { char c=file_.get(); if (c=='\3' || c=='\131') { skip(3); num_records_=read_int(); assert(num_records_>=0); num_fields_=read_short(); assert(num_fields_>0); num_fields_=(num_fields_-33)/32; skip(22); int offset=0; char name[11]; memset(&name,0,11); fields_.reserve(num_fields_); for (int i=0;i<num_fields_;++i) { field_descriptor desc; desc.index_=i; file_.read(name,10); desc.name_=boost::trim_left_copy(std::string(name)); skip(1); desc.type_=file_.get(); skip(4); desc.length_=file_.get(); desc.dec_=file_.get(); skip(14); desc.offset_=offset; offset+=desc.length_; fields_.push_back(desc); } record_length_=offset; if (record_length_>0) { record_=static_cast<char*>(::operator new (sizeof(char)*record_length_)); } } } int dbf_file::read_short() { char b[2]; file_.read(b,2); boost::int16_t val; mapnik::read_int16_ndr(b,val); return val; } int dbf_file::read_int() { char b[4]; file_.read(b,4); boost::int32_t val; mapnik::read_int32_ndr(b,val); return val; } void dbf_file::skip(int bytes) { file_.seekg(bytes,std::ios::cur); } <commit_msg>pass iterators as const to qi::phrase_parse allowing compile on linux g++ (rhel)<commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2006 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ // mapnik #include <mapnik/global.hpp> #include <mapnik/utils.hpp> #include <mapnik/unicode.hpp> #include "dbffile.hpp" // boost #include <boost/algorithm/string.hpp> #include <boost/spirit/include/qi.hpp> // stl #include <string> dbf_file::dbf_file() : num_records_(0), num_fields_(0), record_length_(0), record_(0) {} dbf_file::dbf_file(std::string const& file_name) :num_records_(0), num_fields_(0), record_length_(0), #ifdef SHAPE_MEMORY_MAPPED_FILE file_(file_name), #else file_(file_name,std::ios::in | std::ios::binary), #endif record_(0) { if (file_.is_open()) { read_header(); } } dbf_file::~dbf_file() { ::operator delete(record_); } bool dbf_file::is_open() { return file_.is_open(); } void dbf_file::close() { if (file_ && file_.is_open()) file_.close(); } int dbf_file::num_records() const { return num_records_; } int dbf_file::num_fields() const { return num_fields_; } void dbf_file::move_to(int index) { if (index>0 && index<=num_records_) { long pos=(num_fields_<<5)+34+(index-1)*(record_length_+1); file_.seekg(pos,std::ios::beg); file_.read(record_,record_length_); } } std::string dbf_file::string_value(int col) const { if (col>=0 && col<num_fields_) { return std::string(record_+fields_[col].offset_,fields_[col].length_); } return ""; } const field_descriptor& dbf_file::descriptor(int col) const { assert(col>=0 && col<num_fields_); return fields_[col]; } void dbf_file::add_attribute(int col, mapnik::transcoder const& tr, Feature const& f) const throw() { using namespace boost::spirit; if (col>=0 && col<num_fields_) { std::string name=fields_[col].name_; switch (fields_[col].type_) { case 'C': case 'D'://todo handle date? case 'M': case 'L': { // FIXME - avoid constructing std::string in stack std::string str(record_+fields_[col].offset_,fields_[col].length_); boost::trim(str); f[name] = tr.transcode(str.c_str()); break; } case 'N': case 'F': { if (record_[fields_[col].offset_] == '*') { boost::put(f,name,0); break; } if ( fields_[col].dec_>0 ) { double val = 0.0; const char *itr = record_+fields_[col].offset_; const char *end = itr + fields_[col].length_; qi::phrase_parse(itr,end,double_,ascii::space,val); boost::put(f,name,val); } else { int val = 0; const char *itr = record_+fields_[col].offset_; const char *end = itr + fields_[col].length_; qi::phrase_parse(itr,end,int_,ascii::space,val); boost::put(f,name,val); } break; } } } } void dbf_file::read_header() { char c=file_.get(); if (c=='\3' || c=='\131') { skip(3); num_records_=read_int(); assert(num_records_>=0); num_fields_=read_short(); assert(num_fields_>0); num_fields_=(num_fields_-33)/32; skip(22); int offset=0; char name[11]; memset(&name,0,11); fields_.reserve(num_fields_); for (int i=0;i<num_fields_;++i) { field_descriptor desc; desc.index_=i; file_.read(name,10); desc.name_=boost::trim_left_copy(std::string(name)); skip(1); desc.type_=file_.get(); skip(4); desc.length_=file_.get(); desc.dec_=file_.get(); skip(14); desc.offset_=offset; offset+=desc.length_; fields_.push_back(desc); } record_length_=offset; if (record_length_>0) { record_=static_cast<char*>(::operator new (sizeof(char)*record_length_)); } } } int dbf_file::read_short() { char b[2]; file_.read(b,2); boost::int16_t val; mapnik::read_int16_ndr(b,val); return val; } int dbf_file::read_int() { char b[4]; file_.read(b,4); boost::int32_t val; mapnik::read_int32_ndr(b,val); return val; } void dbf_file::skip(int bytes) { file_.seekg(bytes,std::ios::cur); } <|endoftext|>
<commit_before>/************************************************************************* * * Copyright (c) 2008-2010 Kohei Yoshida * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. * ************************************************************************/ #ifndef __MDDS_NODE_HXX__ #define __MDDS_NODE_HXX__ #include <iostream> #include <list> #include <cassert> #include <boost/intrusive_ptr.hpp> namespace mdds { #ifdef DEBUG_NODE_BASE size_t node_instance_count = 0; #endif template<typename _NodePtr, typename _NodeType> struct node_base { static size_t get_instance_count() { #ifdef DEBUG_NODE_BASE return node_instance_count; #else return 0; #endif } size_t refcount; _NodePtr parent; /// parent node _NodePtr left; /// left child node or previous sibling if it's a leaf node. _NodePtr right; /// right child node or next sibling if it's aleaf node. bool is_leaf; node_base(bool _is_leaf) : refcount(0), is_leaf(_is_leaf) { #ifdef DEBUG_NODE_BASE ++node_instance_count; #endif } /** * When copying node, only the stored values should be copied. * Connections to the parent, left and right nodes must not be copied. */ node_base(const node_base& r) : refcount(0), is_leaf(r.is_leaf) { #ifdef DEBUG_NODE_BASE ++node_instance_count; #endif } /** * Like the copy constructor, only the stored values should be copied. */ node_base& operator=(const node_base& r) { if (this == &r) // assignment to self. return *this; is_leaf = r.is_leaf; return *this; } ~node_base() { #ifdef DEBUG_NODE_BASE --node_instance_count; #endif static_cast<_NodeType*>(this)->dispose(); } }; template<typename _NodePtr> inline void intrusive_ptr_add_ref(_NodePtr p) { ++p->refcount; } template<typename _NodePtr> inline void intrusive_ptr_release(_NodePtr p) { --p->refcount; if (!p->refcount) delete p; } template<typename _NodePtr> void disconnect_node(_NodePtr p) { if (!p) return; p->left.reset(); p->right.reset(); p->parent.reset(); } template<typename _NodePtr> void disconnect_leaf_nodes(_NodePtr left_node, _NodePtr right_node) { if (!left_node || !right_node) return; // Go through all leaf nodes, and disconnect their links. _NodePtr cur_node = left_node; do { _NodePtr next_node = cur_node->right.get(); disconnect_node(cur_node); cur_node = next_node; } while (cur_node != right_node); disconnect_node(right_node); } template<typename _NodePtr> void link_nodes(_NodePtr& left, _NodePtr& right) { left->right = right; right->left = left; } /** * Disconnect all non-leaf nodes so that their ref-counted instances will * all get destroyed afterwards. */ template<typename _NodePtr> void clear_tree(_NodePtr node) { if (!node) // Nothing to do. return; if (node->is_leaf) { node->parent.reset(); return; } clear_tree(node->left.get()); clear_tree(node->right.get()); disconnect_node(node); } template<typename _NodePtr, typename _NodeType> _NodePtr make_parent_node(const _NodePtr& node1, const _NodePtr& node2) { _NodePtr parent_node(new _NodeType(false)); node1->parent = parent_node; parent_node->left = node1; if (node2) { node2->parent = parent_node; parent_node->right = node2; } parent_node->fill_nonleaf_value(node1, node2); return parent_node; } template<typename _NodePtr, typename _NodeType> _NodePtr build_tree_non_leaf(const ::std::list<_NodePtr>& node_list) { size_t node_count = node_list.size(); if (node_count == 1) { return node_list.front(); } else if (node_count == 0) return _NodePtr(); ::std::list<_NodePtr> new_node_list; _NodePtr node_pair[2]; typename ::std::list<_NodePtr>::const_iterator itr = node_list.begin(); typename ::std::list<_NodePtr>::const_iterator itrEnd = node_list.end(); for (bool even_itr = false; itr != itrEnd; ++itr, even_itr = !even_itr) { node_pair[even_itr] = *itr; if (even_itr) { _NodePtr parent_node = make_parent_node<_NodePtr, _NodeType>(node_pair[0], node_pair[1]); node_pair[0].reset(); node_pair[1].reset(); new_node_list.push_back(parent_node); } } if (node_pair[0]) { // Un-paired node still needs a parent... _NodePtr parent_node = make_parent_node<_NodePtr, _NodeType>(node_pair[0], _NodePtr()); node_pair[0].reset(); node_pair[1].reset(); new_node_list.push_back(parent_node); } // Move up one level, and do the same procedure until the root node is reached. return build_tree_non_leaf<_NodePtr, _NodeType>(new_node_list); } template<typename _NodePtr, typename _NodeType> _NodePtr build_tree(const _NodePtr& left_leaf_node) { if (!left_leaf_node) // The left leaf node is empty. Nothing to build. return _NodePtr(); _NodePtr node1, node2; node1 = left_leaf_node; ::std::list<_NodePtr> node_list; while (true) { node2 = node1->right; _NodePtr parent_node = make_parent_node<_NodePtr, _NodeType>(node1, node2); node_list.push_back(parent_node); if (!node2 || !node2->right) // no more nodes. Break out of the loop. break; node1 = node2->right; } return build_tree_non_leaf<_NodePtr, _NodeType>(node_list); } #ifdef UNIT_TEST template<typename _NodePtr> size_t dump_tree_layer(const ::std::list<_NodePtr>& node_list, unsigned int level) { using ::std::cout; using ::std::endl; if (node_list.empty()) return 0; size_t node_count = node_list.size(); bool isLeaf = node_list.front()->is_leaf; cout << "level " << level << " (" << (isLeaf?"leaf":"non-leaf") << ")" << endl; ::std::list<_NodePtr> newList; typename ::std::list<_NodePtr>::const_iterator itr = node_list.begin(), itrEnd = node_list.end(); for (; itr != itrEnd; ++itr) { const _NodePtr& p = *itr; if (!p) { cout << "(x) "; continue; } p->dump_value(); if (p->is_leaf) continue; if (p->left) { newList.push_back(p->left.get()); if (p->right) newList.push_back(p->right.get()); } } cout << endl; if (!newList.empty()) node_count += dump_tree_layer(newList, level+1); return node_count; } template<typename _NodePtr> size_t dump_tree(_NodePtr root_node) { if (!root_node) return 0; ::std::list<_NodePtr> node_list; node_list.push_back(root_node); return dump_tree_layer(node_list, 0); } #endif } #endif <commit_msg>changed variable name for naming consistency.<commit_after>/************************************************************************* * * Copyright (c) 2008-2010 Kohei Yoshida * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. * ************************************************************************/ #ifndef __MDDS_NODE_HXX__ #define __MDDS_NODE_HXX__ #include <iostream> #include <list> #include <cassert> #include <boost/intrusive_ptr.hpp> namespace mdds { #ifdef DEBUG_NODE_BASE size_t node_instance_count = 0; #endif template<typename _NodePtr, typename _NodeType> struct node_base { static size_t get_instance_count() { #ifdef DEBUG_NODE_BASE return node_instance_count; #else return 0; #endif } size_t refcount; _NodePtr parent; /// parent node _NodePtr left; /// left child node or previous sibling if it's a leaf node. _NodePtr right; /// right child node or next sibling if it's aleaf node. bool is_leaf; node_base(bool _is_leaf) : refcount(0), is_leaf(_is_leaf) { #ifdef DEBUG_NODE_BASE ++node_instance_count; #endif } /** * When copying node, only the stored values should be copied. * Connections to the parent, left and right nodes must not be copied. */ node_base(const node_base& r) : refcount(0), is_leaf(r.is_leaf) { #ifdef DEBUG_NODE_BASE ++node_instance_count; #endif } /** * Like the copy constructor, only the stored values should be copied. */ node_base& operator=(const node_base& r) { if (this == &r) // assignment to self. return *this; is_leaf = r.is_leaf; return *this; } ~node_base() { #ifdef DEBUG_NODE_BASE --node_instance_count; #endif static_cast<_NodeType*>(this)->dispose(); } }; template<typename _NodePtr> inline void intrusive_ptr_add_ref(_NodePtr p) { ++p->refcount; } template<typename _NodePtr> inline void intrusive_ptr_release(_NodePtr p) { --p->refcount; if (!p->refcount) delete p; } template<typename _NodePtr> void disconnect_node(_NodePtr p) { if (!p) return; p->left.reset(); p->right.reset(); p->parent.reset(); } template<typename _NodePtr> void disconnect_leaf_nodes(_NodePtr left_node, _NodePtr right_node) { if (!left_node || !right_node) return; // Go through all leaf nodes, and disconnect their links. _NodePtr cur_node = left_node; do { _NodePtr next_node = cur_node->right.get(); disconnect_node(cur_node); cur_node = next_node; } while (cur_node != right_node); disconnect_node(right_node); } template<typename _NodePtr> void link_nodes(_NodePtr& left, _NodePtr& right) { left->right = right; right->left = left; } /** * Disconnect all non-leaf nodes so that their ref-counted instances will * all get destroyed afterwards. */ template<typename _NodePtr> void clear_tree(_NodePtr node) { if (!node) // Nothing to do. return; if (node->is_leaf) { node->parent.reset(); return; } clear_tree(node->left.get()); clear_tree(node->right.get()); disconnect_node(node); } template<typename _NodePtr, typename _NodeType> _NodePtr make_parent_node(const _NodePtr& node1, const _NodePtr& node2) { _NodePtr parent_node(new _NodeType(false)); node1->parent = parent_node; parent_node->left = node1; if (node2) { node2->parent = parent_node; parent_node->right = node2; } parent_node->fill_nonleaf_value(node1, node2); return parent_node; } template<typename _NodePtr, typename _NodeType> _NodePtr build_tree_non_leaf(const ::std::list<_NodePtr>& node_list) { size_t node_count = node_list.size(); if (node_count == 1) { return node_list.front(); } else if (node_count == 0) return _NodePtr(); ::std::list<_NodePtr> new_node_list; _NodePtr node_pair[2]; typename ::std::list<_NodePtr>::const_iterator itr = node_list.begin(); typename ::std::list<_NodePtr>::const_iterator itr_end = node_list.end(); for (bool even_itr = false; itr != itr_end; ++itr, even_itr = !even_itr) { node_pair[even_itr] = *itr; if (even_itr) { _NodePtr parent_node = make_parent_node<_NodePtr, _NodeType>(node_pair[0], node_pair[1]); node_pair[0].reset(); node_pair[1].reset(); new_node_list.push_back(parent_node); } } if (node_pair[0]) { // Un-paired node still needs a parent... _NodePtr parent_node = make_parent_node<_NodePtr, _NodeType>(node_pair[0], _NodePtr()); node_pair[0].reset(); node_pair[1].reset(); new_node_list.push_back(parent_node); } // Move up one level, and do the same procedure until the root node is reached. return build_tree_non_leaf<_NodePtr, _NodeType>(new_node_list); } template<typename _NodePtr, typename _NodeType> _NodePtr build_tree(const _NodePtr& left_leaf_node) { if (!left_leaf_node) // The left leaf node is empty. Nothing to build. return _NodePtr(); _NodePtr node1, node2; node1 = left_leaf_node; ::std::list<_NodePtr> node_list; while (true) { node2 = node1->right; _NodePtr parent_node = make_parent_node<_NodePtr, _NodeType>(node1, node2); node_list.push_back(parent_node); if (!node2 || !node2->right) // no more nodes. Break out of the loop. break; node1 = node2->right; } return build_tree_non_leaf<_NodePtr, _NodeType>(node_list); } #ifdef UNIT_TEST template<typename _NodePtr> size_t dump_tree_layer(const ::std::list<_NodePtr>& node_list, unsigned int level) { using ::std::cout; using ::std::endl; if (node_list.empty()) return 0; size_t node_count = node_list.size(); bool isLeaf = node_list.front()->is_leaf; cout << "level " << level << " (" << (isLeaf?"leaf":"non-leaf") << ")" << endl; ::std::list<_NodePtr> newList; typename ::std::list<_NodePtr>::const_iterator itr = node_list.begin(), itrEnd = node_list.end(); for (; itr != itrEnd; ++itr) { const _NodePtr& p = *itr; if (!p) { cout << "(x) "; continue; } p->dump_value(); if (p->is_leaf) continue; if (p->left) { newList.push_back(p->left.get()); if (p->right) newList.push_back(p->right.get()); } } cout << endl; if (!newList.empty()) node_count += dump_tree_layer(newList, level+1); return node_count; } template<typename _NodePtr> size_t dump_tree(_NodePtr root_node) { if (!root_node) return 0; ::std::list<_NodePtr> node_list; node_list.push_back(root_node); return dump_tree_layer(node_list, 0); } #endif } #endif <|endoftext|>
<commit_before>/* * Copyright (c) 2011 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "webrtc/system_wrappers/interface/cpu_info.h" #if defined(_WIN32) #include <Windows.h> #elif defined(WEBRTC_MAC) #include <sys/sysctl.h> #include <sys/types.h> #elif defined(WEBRTC_ANDROID) // Not implemented yet, might be possible to use Linux implementation #else // defined(WEBRTC_LINUX) #include <sys/sysinfo.h> #include <unistd.h> // required for get_nprocs() with uClibc #endif #include "webrtc/system_wrappers/interface/trace.h" namespace webrtc { uint32_t CpuInfo::number_of_cores_ = 0; uint32_t CpuInfo::DetectNumberOfCores() { if (!number_of_cores_) { #if defined(_WIN32) SYSTEM_INFO si; GetSystemInfo(&si); number_of_cores_ = static_cast<uint32_t>(si.dwNumberOfProcessors); WEBRTC_TRACE(kTraceStateInfo, kTraceUtility, -1, "Available number of cores:%d", number_of_cores_); #elif defined(WEBRTC_LINUX) && !defined(WEBRTC_ANDROID) number_of_cores_ = get_nprocs(); WEBRTC_TRACE(kTraceStateInfo, kTraceUtility, -1, "Available number of cores:%d", number_of_cores_); #elif defined(WEBRTC_MAC) int name[] = {CTL_HW, HW_AVAILCPU}; int ncpu; size_t size = sizeof(ncpu); if (0 == sysctl(name, 2, &ncpu, &size, NULL, 0)) { number_of_cores_ = static_cast<uint32_t>(ncpu); WEBRTC_TRACE(kTraceStateInfo, kTraceUtility, -1, "Available number of cores:%d", number_of_cores_); } else { WEBRTC_TRACE(kTraceError, kTraceUtility, -1, "Failed to get number of cores"); number_of_cores_ = 1; } #else WEBRTC_TRACE(kTraceWarning, kTraceUtility, -1, "No function to get number of cores"); number_of_cores_ = 1; #endif } return number_of_cores_; } } // namespace webrtc <commit_msg>Implement DetectNumberOfCores on Android and make it consistent on Linux and Android<commit_after>/* * Copyright (c) 2011 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "webrtc/system_wrappers/interface/cpu_info.h" #if defined(_WIN32) #include <Windows.h> #elif defined(WEBRTC_MAC) #include <sys/sysctl.h> #include <sys/types.h> #else // defined(WEBRTC_LINUX) or defined(WEBRTC_ANDROID) #include <unistd.h> #endif #include "webrtc/system_wrappers/interface/trace.h" namespace webrtc { uint32_t CpuInfo::number_of_cores_ = 0; uint32_t CpuInfo::DetectNumberOfCores() { if (!number_of_cores_) { #if defined(_WIN32) SYSTEM_INFO si; GetSystemInfo(&si); number_of_cores_ = static_cast<uint32_t>(si.dwNumberOfProcessors); WEBRTC_TRACE(kTraceStateInfo, kTraceUtility, -1, "Available number of cores:%d", number_of_cores_); #elif defined(WEBRTC_LINUX) || defined(WEBRTC_ANDROID) number_of_cores_ = static_cast<uint32_t>(sysconf(_SC_NPROCESSORS_ONLN)); WEBRTC_TRACE(kTraceStateInfo, kTraceUtility, -1, "Available number of cores:%d", number_of_cores_); #elif defined(WEBRTC_MAC) int name[] = {CTL_HW, HW_AVAILCPU}; int ncpu; size_t size = sizeof(ncpu); if (0 == sysctl(name, 2, &ncpu, &size, NULL, 0)) { number_of_cores_ = static_cast<uint32_t>(ncpu); WEBRTC_TRACE(kTraceStateInfo, kTraceUtility, -1, "Available number of cores:%d", number_of_cores_); } else { WEBRTC_TRACE(kTraceError, kTraceUtility, -1, "Failed to get number of cores"); number_of_cores_ = 1; } #else WEBRTC_TRACE(kTraceWarning, kTraceUtility, -1, "No function to get number of cores"); number_of_cores_ = 1; #endif } return number_of_cores_; } } // namespace webrtc <|endoftext|>
<commit_before>//------------------------------------------------------------------------------ // CLING - the C++ LLVM-based InterpreterG :) // // This file is dual-licensed: you can choose to license it under the University // of Illinois Open Source License or the GNU Lesser General Public License. See // LICENSE.TXT for details. //------------------------------------------------------------------------------ // RUN: cat %s | %cling -I%S -Xclang -verify 2>&1 | FileCheck %s // FIXME: When printing can be properly unloaded don't force it here "BEGIN" // CHECK: (const char [6]) "BEGIN" #pragma cling load("P0.h", "P1.h","P2.h") ValueA // CHECK-NEXT: (const char *) "ValueA" ValueB // CHECK-NEXT: (const char *) "ValueB" ValueC // CHECK-NEXT: (const char *) "ValueC" .undo .undo .undo .undo ValueA // expected-error {{use of undeclared identifier 'ValueA'}} #pragma cling load "P0.h" "P1.h" "P2.h" ValueA // CHECK-NEXT: (const char *) "ValueA" ValueB // CHECK-NEXT: (const char *) "ValueB" ValueC // CHECK-NEXT: (const char *) "ValueC" .undo .undo .undo .undo ValueB // expected-error {{use of undeclared identifier 'ValueB'}} #pragma cling(load, "P0.h", "P1.h", "P2.h") ValueA // CHECK-NEXT: (const char *) "ValueA" ValueB // CHECK-NEXT: (const char *) "ValueB" ValueC // CHECK-NEXT: (const char *) "ValueC" #pragma cling load "P0.h P1.h P2.h" ValueD // CHECK-NEXT: (const char *) "ValueD" .q <commit_msg>Revert "Fix test for CERN/master."<commit_after>//------------------------------------------------------------------------------ // CLING - the C++ LLVM-based InterpreterG :) // // This file is dual-licensed: you can choose to license it under the University // of Illinois Open Source License or the GNU Lesser General Public License. See // LICENSE.TXT for details. //------------------------------------------------------------------------------ // RUN: cat %s | %cling -I%S -Xclang -verify 2>&1 | FileCheck %s #pragma cling load("P0.h", "P1.h","P2.h") ValueA // CHECK: (const char *) "ValueA" ValueB // CHECK-NEXT: (const char *) "ValueB" ValueC // CHECK-NEXT: (const char *) "ValueC" .undo .undo .undo .undo ValueA // expected-error {{use of undeclared identifier 'ValueA'}} #pragma cling load "P0.h" "P1.h" "P2.h" ValueA // CHECK-NEXT: (const char *) "ValueA" ValueB // CHECK-NEXT: (const char *) "ValueB" ValueC // CHECK-NEXT: (const char *) "ValueC" .undo .undo .undo .undo ValueB // expected-error {{use of undeclared identifier 'ValueB'}} #pragma cling(load, "P0.h", "P1.h", "P2.h") ValueA // CHECK-NEXT: (const char *) "ValueA" ValueB // CHECK-NEXT: (const char *) "ValueB" ValueC // CHECK-NEXT: (const char *) "ValueC" #pragma cling load "P0.h P1.h P2.h" ValueD // CHECK-NEXT: (const char *) "ValueD" .q <|endoftext|>
<commit_before>/* * Copyright 2014 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "gl/GrGLInterface.h" #include "gl/GrGLAssembleInterface.h" #include "gl/GrGLUtil.h" #include <GL/glx.h> static GrGLFuncPtr glx_get(void* ctx, const char name[]) { // Avoid calling glXGetProcAddress() for EGL procs. // We don't expect it to ever succeed, but somtimes it returns non-null anyway. if (0 == strncmp(name, "egl", 3)) { return nullptr; } SkASSERT(nullptr == ctx); SkASSERT(glXGetCurrentContext()); return glXGetProcAddress(reinterpret_cast<const GLubyte*>(name)); } const GrGLInterface* GrGLCreateNativeInterface() { if (nullptr == glXGetCurrentContext()) { return nullptr; } return GrGLAssembleInterface(nullptr, glx_get); } <commit_msg>Ensure glxGetProcAddress is declared<commit_after>/* * Copyright 2014 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "gl/GrGLInterface.h" #include "gl/GrGLAssembleInterface.h" #include "gl/GrGLUtil.h" // Define this to get a prototype for glXGetProcAddress on some systems #define GLX_GLXEXT_PROTOTYPES 1 #include <GL/glx.h> static GrGLFuncPtr glx_get(void* ctx, const char name[]) { // Avoid calling glXGetProcAddress() for EGL procs. // We don't expect it to ever succeed, but somtimes it returns non-null anyway. if (0 == strncmp(name, "egl", 3)) { return nullptr; } SkASSERT(nullptr == ctx); SkASSERT(glXGetCurrentContext()); return glXGetProcAddress(reinterpret_cast<const GLubyte*>(name)); } const GrGLInterface* GrGLCreateNativeInterface() { if (nullptr == glXGetCurrentContext()) { return nullptr; } return GrGLAssembleInterface(nullptr, glx_get); } <|endoftext|>
<commit_before> /* * Copyright 2011 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "gl/GrGLInterface.h" #include "gl/GrGLExtensions.h" #include "GrGLUtil.h" #include <OpenGL/gl.h> #include <OpenGL/glext.h> #include <dlfcn.h> static void* GetProcAddress(const char* name) { return dlsym(RTLD_DEFAULT, name); } #define GET_PROC(name) (interface->f ## name = ((GrGL ## name ## Proc) GetProcAddress("gl" #name))) #define GET_PROC_SUFFIX(name, suffix) (interface->f ## name = ((GrGL ## name ## Proc) GetProcAddress("gl" #name #suffix))) const GrGLInterface* GrGLCreateNativeInterface() { // The gl functions are not context-specific so we create one global // interface static SkAutoTUnref<GrGLInterface> glInterface; if (!glInterface.get()) { GrGLInterface* interface = new GrGLInterface; glInterface.reset(interface); const char* verStr = (const char*) glGetString(GL_VERSION); GrGLVersion ver = GrGLGetVersionFromString(verStr); GrGLExtensions extensions; GrGLGetStringiProc glGetStringi = (GrGLGetStringiProc) GetProcAddress("glGetStringi"); if (!extensions.init(kDesktop_GrGLBinding, glGetString, glGetStringi, glGetIntegerv)) { glInterface.reset(NULL); return NULL; } interface->fBindingsExported = kDesktop_GrGLBinding; interface->fActiveTexture = glActiveTexture; interface->fAttachShader = glAttachShader; interface->fBeginQuery = glBeginQuery; interface->fBindAttribLocation = glBindAttribLocation; interface->fBindBuffer = glBindBuffer; if (ver >= GR_GL_VER(3,0)) { #if GL_VERSION_3_0 interface->fBindFragDataLocation = glBindFragDataLocation; #else GET_PROC(BindFragDataLocation); #endif } interface->fBindTexture = glBindTexture; interface->fBlendFunc = glBlendFunc; if (ver >= GR_GL_VER(1,4)) { interface->fBlendColor = glBlendColor; } else if (extensions.has("GL_ARB_imaging") || extensions.has("GL_EXT_blend_color")) { GET_PROC(BlendColor); } interface->fBufferData = glBufferData; interface->fBufferSubData = glBufferSubData; interface->fClear = glClear; interface->fClearColor = glClearColor; interface->fClearStencil = glClearStencil; interface->fColorMask = glColorMask; interface->fCompileShader = glCompileShader; interface->fCompressedTexImage2D = glCompressedTexImage2D; interface->fCreateProgram = glCreateProgram; interface->fCreateShader = glCreateShader; interface->fCullFace = glCullFace; interface->fDeleteBuffers = glDeleteBuffers; interface->fDeleteProgram = glDeleteProgram; interface->fDeleteQueries = glDeleteQueries; interface->fDeleteShader = glDeleteShader; interface->fDeleteTextures = glDeleteTextures; interface->fDepthMask = glDepthMask; interface->fDisable = glDisable; interface->fDisableVertexAttribArray = glDisableVertexAttribArray; interface->fDrawArrays = glDrawArrays; interface->fDrawBuffer = glDrawBuffer; interface->fDrawBuffers = glDrawBuffers; interface->fDrawElements = glDrawElements; interface->fEnable = glEnable; interface->fEnableVertexAttribArray = glEnableVertexAttribArray; interface->fEndQuery = glEndQuery; interface->fFinish = glFinish; interface->fFlush = glFlush; interface->fFrontFace = glFrontFace; interface->fGenBuffers = glGenBuffers; interface->fGenQueries = glGenQueries; interface->fGetBufferParameteriv = glGetBufferParameteriv; interface->fGetError = glGetError; interface->fGetIntegerv = glGetIntegerv; interface->fGetProgramInfoLog = glGetProgramInfoLog; interface->fGetProgramiv = glGetProgramiv; interface->fGetQueryiv = glGetQueryiv; interface->fGetQueryObjectiv = glGetQueryObjectiv; interface->fGetQueryObjectuiv = glGetQueryObjectuiv; interface->fGetShaderInfoLog = glGetShaderInfoLog; interface->fGetShaderiv = glGetShaderiv; interface->fGetString = glGetString; interface->fGetStringi = glGetStringi; interface->fGetTexLevelParameteriv = glGetTexLevelParameteriv; interface->fGenTextures = glGenTextures; interface->fGetUniformLocation = glGetUniformLocation; interface->fLineWidth = glLineWidth; interface->fLinkProgram = glLinkProgram; interface->fMapBuffer = glMapBuffer; interface->fPixelStorei = glPixelStorei; interface->fReadBuffer = glReadBuffer; interface->fReadPixels = glReadPixels; interface->fScissor = glScissor; // The new OpenGLES2 header has an extra "const" in it. :( #if GR_GL_USE_NEW_SHADER_SOURCE_SIGNATURE interface->fShaderSource = (GrGLShaderSourceProc) glShaderSource; #else interface->fShaderSource = glShaderSource; #endif interface->fStencilFunc = glStencilFunc; interface->fStencilFuncSeparate = glStencilFuncSeparate; interface->fStencilMask = glStencilMask; interface->fStencilMaskSeparate = glStencilMaskSeparate; interface->fStencilOp = glStencilOp; interface->fStencilOpSeparate = glStencilOpSeparate; // mac uses GLenum for internalFormat param (non-standard) // amounts to int vs. uint. interface->fTexImage2D = (GrGLTexImage2DProc)glTexImage2D; interface->fTexParameteri = glTexParameteri; interface->fTexParameteriv = glTexParameteriv; #if GL_ARB_texture_storage || GL_VERSION_4_2 interface->fTexStorage2D = glTexStorage2D #elif GL_EXT_texture_storage interface->fTexStorage2D = glTexStorage2DEXT; #else if (ver >= GR_GL_VER(4,2) || extensions.has("GL_ARB_texture_storage")) { GET_PROC(TexStorage2D); } else if (extensions.has("GL_EXT_texture_storage")) { GET_PROC_SUFFIX(TexStorage2D, EXT); } #endif interface->fTexSubImage2D = glTexSubImage2D; interface->fUniform1f = glUniform1f; interface->fUniform1i = glUniform1i; interface->fUniform1fv = glUniform1fv; interface->fUniform1iv = glUniform1iv; interface->fUniform2f = glUniform2f; interface->fUniform2i = glUniform2i; interface->fUniform2fv = glUniform2fv; interface->fUniform2iv = glUniform2iv; interface->fUniform3f = glUniform3f; interface->fUniform3i = glUniform3i; interface->fUniform3fv = glUniform3fv; interface->fUniform3iv = glUniform3iv; interface->fUniform4f = glUniform4f; interface->fUniform4i = glUniform4i; interface->fUniform4fv = glUniform4fv; interface->fUniform4iv = glUniform4iv; interface->fUniform4fv = glUniform4fv; interface->fUniformMatrix2fv = glUniformMatrix2fv; interface->fUniformMatrix3fv = glUniformMatrix3fv; interface->fUniformMatrix4fv = glUniformMatrix4fv; interface->fUnmapBuffer = glUnmapBuffer; interface->fUseProgram = glUseProgram; interface->fVertexAttrib4fv = glVertexAttrib4fv; interface->fVertexAttribPointer = glVertexAttribPointer; interface->fViewport = glViewport; if (ver >= GR_GL_VER(3,0) || extensions.has("GL_ARB_vertex_array_object")) { // no ARB suffix for GL_ARB_vertex_array_object #if GL_ARB_vertex_array_object || GL_VERSION_3_0 interface->fBindVertexArray = glBindVertexArray; interface->fDeleteVertexArrays = glDeleteVertexArrays; interface->fGenVertexArrays = glGenVertexArrays; #else GET_PROC(BindVertexArray); GET_PROC(DeleteVertexArrays); GET_PROC(GenVertexArrays); #endif } if (ver >= GR_GL_VER(3,3) || extensions.has("GL_ARB_timer_query")) { // ARB extension doesn't use the ARB suffix on the function name #if GL_ARB_timer_query || GL_VERSION_3_3 interface->fQueryCounter = glQueryCounter; interface->fGetQueryObjecti64v = glGetQueryObjecti64v; interface->fGetQueryObjectui64v = glGetQueryObjectui64v; #else GET_PROC(QueryCounter); GET_PROC(GetQueryObjecti64v); GET_PROC(GetQueryObjectui64v); #endif } else if (extensions.has("GL_EXT_timer_query")) { #if GL_EXT_timer_query interface->fGetQueryObjecti64v = glGetQueryObjecti64vEXT; interface->fGetQueryObjectui64v = glGetQueryObjectui64vEXT; #else GET_PROC_SUFFIX(GetQueryObjecti64v, EXT); GET_PROC_SUFFIX(GetQueryObjectui64v, EXT); #endif } if (ver >= GR_GL_VER(3,0) || extensions.has("GL_ARB_framebuffer_object")) { // ARB extension doesn't use the ARB suffix on the function names #if GL_VERSION_3_0 || GL_ARB_framebuffer_object interface->fGenFramebuffers = glGenFramebuffers; interface->fGetFramebufferAttachmentParameteriv = glGetFramebufferAttachmentParameteriv; interface->fGetRenderbufferParameteriv = glGetRenderbufferParameteriv; interface->fBindFramebuffer = glBindFramebuffer; interface->fFramebufferTexture2D = glFramebufferTexture2D; interface->fCheckFramebufferStatus = glCheckFramebufferStatus; interface->fDeleteFramebuffers = glDeleteFramebuffers; interface->fRenderbufferStorage = glRenderbufferStorage; interface->fGenRenderbuffers = glGenRenderbuffers; interface->fDeleteRenderbuffers = glDeleteRenderbuffers; interface->fFramebufferRenderbuffer = glFramebufferRenderbuffer; interface->fBindRenderbuffer = glBindRenderbuffer; interface->fRenderbufferStorageMultisample = glRenderbufferStorageMultisample; interface->fBlitFramebuffer = glBlitFramebuffer; #else GET_PROC(GenFramebuffers); GET_PROC(GetFramebufferAttachmentParameteriv); GET_PROC(GetRenderbufferParameteriv); GET_PROC(BindFramebuffer); GET_PROC(FramebufferTexture2D); GET_PROC(CheckFramebufferStatus); GET_PROC(DeleteFramebuffers); GET_PROC(RenderbufferStorage); GET_PROC(GenRenderbuffers); GET_PROC(DeleteRenderbuffers); GET_PROC(FramebufferRenderbuffer); GET_PROC(BindRenderbuffer); GET_PROC(RenderbufferStorageMultisample); GET_PROC(BlitFramebuffer); #endif } else { if (extensions.has("GL_EXT_framebuffer_object")) { #if GL_EXT_framebuffer_object interface->fGenFramebuffers = glGenFramebuffersEXT; interface->fGetFramebufferAttachmentParameteriv = glGetFramebufferAttachmentParameterivEXT; interface->fGetRenderbufferParameteriv = glGetRenderbufferParameterivEXT; interface->fBindFramebuffer = glBindFramebufferEXT; interface->fFramebufferTexture2D = glFramebufferTexture2DEXT; interface->fCheckFramebufferStatus = glCheckFramebufferStatusEXT; interface->fDeleteFramebuffers = glDeleteFramebuffersEXT; interface->fRenderbufferStorage = glRenderbufferStorageEXT; interface->fGenRenderbuffers = glGenRenderbuffersEXT; interface->fDeleteRenderbuffers = glDeleteRenderbuffersEXT; interface->fFramebufferRenderbuffer = glFramebufferRenderbufferEXT; interface->fBindRenderbuffer = glBindRenderbufferEXT; #else GET_PROC_SUFFIX(GenFramebuffers, EXT); GET_PROC_SUFFIX(GetFramebufferAttachmentParameteriv, EXT); GET_PROC_SUFFIX(GetRenderbufferParameteriv, EXT); GET_PROC_SUFFIX(BindFramebuffer, EXT); GET_PROC_SUFFIX(FramebufferTexture2D, EXT); GET_PROC_SUFFIX(CheckFramebufferStatus, EXT); GET_PROC_SUFFIX(DeleteFramebuffers, EXT); GET_PROC_SUFFIX(RenderbufferStorage, EXT); GET_PROC_SUFFIX(GenRenderbuffers, EXT); GET_PROC_SUFFIX(DeleteRenderbuffers, EXT); GET_PROC_SUFFIX(FramebufferRenderbuffer, EXT); GET_PROC_SUFFIX(BindRenderbuffer, EXT); #endif } if (extensions.has("GL_EXT_framebuffer_multisample")) { #if GL_EXT_framebuffer_multisample interface->fRenderbufferStorageMultisample = glRenderbufferStorageMultisampleEXT; #else GET_PROC_SUFFIX(RenderbufferStorageMultisample, EXT); #endif } if (extensions.has("GL_EXT_framebuffer_blit")) { #if GL_EXT_framebuffer_blit interface->fBlitFramebuffer = glBlitFramebufferEXT; #else GET_PROC_SUFFIX(BlitFramebuffer, EXT); #endif } } if (ver >= GR_GL_VER(3,3) || extensions.has("GL_ARB_blend_func_extended")) { // ARB extension doesn't use the ARB suffix on the function name #if GL_VERSION_3_3 || GL_ARB_blend_func_extended interface->fBindFragDataLocationIndexed = glBindFragDataLocationIndexed; #else GET_PROC(BindFragDataLocationIndexed); #endif } } glInterface.get()->ref(); return glInterface.get(); } <commit_msg>fix mac build<commit_after> /* * Copyright 2011 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "gl/GrGLInterface.h" #include "gl/GrGLExtensions.h" #include "../GrGLUtil.h" #include <OpenGL/gl.h> #include <OpenGL/glext.h> #include <dlfcn.h> static void* GetProcAddress(const char* name) { return dlsym(RTLD_DEFAULT, name); } #define GET_PROC(name) (interface->f ## name = ((GrGL ## name ## Proc) GetProcAddress("gl" #name))) #define GET_PROC_SUFFIX(name, suffix) (interface->f ## name = ((GrGL ## name ## Proc) GetProcAddress("gl" #name #suffix))) const GrGLInterface* GrGLCreateNativeInterface() { // The gl functions are not context-specific so we create one global // interface static SkAutoTUnref<GrGLInterface> glInterface; if (!glInterface.get()) { GrGLInterface* interface = new GrGLInterface; glInterface.reset(interface); const char* verStr = (const char*) glGetString(GL_VERSION); GrGLVersion ver = GrGLGetVersionFromString(verStr); GrGLExtensions extensions; GrGLGetStringiProc glGetStringi = (GrGLGetStringiProc) GetProcAddress("glGetStringi"); if (!extensions.init(kDesktop_GrGLBinding, glGetString, glGetStringi, glGetIntegerv)) { glInterface.reset(NULL); return NULL; } interface->fBindingsExported = kDesktop_GrGLBinding; interface->fActiveTexture = glActiveTexture; interface->fAttachShader = glAttachShader; interface->fBeginQuery = glBeginQuery; interface->fBindAttribLocation = glBindAttribLocation; interface->fBindBuffer = glBindBuffer; if (ver >= GR_GL_VER(3,0)) { #if GL_VERSION_3_0 interface->fBindFragDataLocation = glBindFragDataLocation; #else GET_PROC(BindFragDataLocation); #endif } interface->fBindTexture = glBindTexture; interface->fBlendFunc = glBlendFunc; if (ver >= GR_GL_VER(1,4)) { interface->fBlendColor = glBlendColor; } else if (extensions.has("GL_ARB_imaging") || extensions.has("GL_EXT_blend_color")) { GET_PROC(BlendColor); } interface->fBufferData = glBufferData; interface->fBufferSubData = glBufferSubData; interface->fClear = glClear; interface->fClearColor = glClearColor; interface->fClearStencil = glClearStencil; interface->fColorMask = glColorMask; interface->fCompileShader = glCompileShader; interface->fCompressedTexImage2D = glCompressedTexImage2D; interface->fCreateProgram = glCreateProgram; interface->fCreateShader = glCreateShader; interface->fCullFace = glCullFace; interface->fDeleteBuffers = glDeleteBuffers; interface->fDeleteProgram = glDeleteProgram; interface->fDeleteQueries = glDeleteQueries; interface->fDeleteShader = glDeleteShader; interface->fDeleteTextures = glDeleteTextures; interface->fDepthMask = glDepthMask; interface->fDisable = glDisable; interface->fDisableVertexAttribArray = glDisableVertexAttribArray; interface->fDrawArrays = glDrawArrays; interface->fDrawBuffer = glDrawBuffer; interface->fDrawBuffers = glDrawBuffers; interface->fDrawElements = glDrawElements; interface->fEnable = glEnable; interface->fEnableVertexAttribArray = glEnableVertexAttribArray; interface->fEndQuery = glEndQuery; interface->fFinish = glFinish; interface->fFlush = glFlush; interface->fFrontFace = glFrontFace; interface->fGenBuffers = glGenBuffers; interface->fGenQueries = glGenQueries; interface->fGetBufferParameteriv = glGetBufferParameteriv; interface->fGetError = glGetError; interface->fGetIntegerv = glGetIntegerv; interface->fGetProgramInfoLog = glGetProgramInfoLog; interface->fGetProgramiv = glGetProgramiv; interface->fGetQueryiv = glGetQueryiv; interface->fGetQueryObjectiv = glGetQueryObjectiv; interface->fGetQueryObjectuiv = glGetQueryObjectuiv; interface->fGetShaderInfoLog = glGetShaderInfoLog; interface->fGetShaderiv = glGetShaderiv; interface->fGetString = glGetString; interface->fGetStringi = glGetStringi; interface->fGetTexLevelParameteriv = glGetTexLevelParameteriv; interface->fGenTextures = glGenTextures; interface->fGetUniformLocation = glGetUniformLocation; interface->fLineWidth = glLineWidth; interface->fLinkProgram = glLinkProgram; interface->fMapBuffer = glMapBuffer; interface->fPixelStorei = glPixelStorei; interface->fReadBuffer = glReadBuffer; interface->fReadPixels = glReadPixels; interface->fScissor = glScissor; // The new OpenGLES2 header has an extra "const" in it. :( #if GR_GL_USE_NEW_SHADER_SOURCE_SIGNATURE interface->fShaderSource = (GrGLShaderSourceProc) glShaderSource; #else interface->fShaderSource = glShaderSource; #endif interface->fStencilFunc = glStencilFunc; interface->fStencilFuncSeparate = glStencilFuncSeparate; interface->fStencilMask = glStencilMask; interface->fStencilMaskSeparate = glStencilMaskSeparate; interface->fStencilOp = glStencilOp; interface->fStencilOpSeparate = glStencilOpSeparate; // mac uses GLenum for internalFormat param (non-standard) // amounts to int vs. uint. interface->fTexImage2D = (GrGLTexImage2DProc)glTexImage2D; interface->fTexParameteri = glTexParameteri; interface->fTexParameteriv = glTexParameteriv; #if GL_ARB_texture_storage || GL_VERSION_4_2 interface->fTexStorage2D = glTexStorage2D #elif GL_EXT_texture_storage interface->fTexStorage2D = glTexStorage2DEXT; #else if (ver >= GR_GL_VER(4,2) || extensions.has("GL_ARB_texture_storage")) { GET_PROC(TexStorage2D); } else if (extensions.has("GL_EXT_texture_storage")) { GET_PROC_SUFFIX(TexStorage2D, EXT); } #endif interface->fTexSubImage2D = glTexSubImage2D; interface->fUniform1f = glUniform1f; interface->fUniform1i = glUniform1i; interface->fUniform1fv = glUniform1fv; interface->fUniform1iv = glUniform1iv; interface->fUniform2f = glUniform2f; interface->fUniform2i = glUniform2i; interface->fUniform2fv = glUniform2fv; interface->fUniform2iv = glUniform2iv; interface->fUniform3f = glUniform3f; interface->fUniform3i = glUniform3i; interface->fUniform3fv = glUniform3fv; interface->fUniform3iv = glUniform3iv; interface->fUniform4f = glUniform4f; interface->fUniform4i = glUniform4i; interface->fUniform4fv = glUniform4fv; interface->fUniform4iv = glUniform4iv; interface->fUniform4fv = glUniform4fv; interface->fUniformMatrix2fv = glUniformMatrix2fv; interface->fUniformMatrix3fv = glUniformMatrix3fv; interface->fUniformMatrix4fv = glUniformMatrix4fv; interface->fUnmapBuffer = glUnmapBuffer; interface->fUseProgram = glUseProgram; interface->fVertexAttrib4fv = glVertexAttrib4fv; interface->fVertexAttribPointer = glVertexAttribPointer; interface->fViewport = glViewport; if (ver >= GR_GL_VER(3,0) || extensions.has("GL_ARB_vertex_array_object")) { // no ARB suffix for GL_ARB_vertex_array_object #if GL_ARB_vertex_array_object || GL_VERSION_3_0 interface->fBindVertexArray = glBindVertexArray; interface->fDeleteVertexArrays = glDeleteVertexArrays; interface->fGenVertexArrays = glGenVertexArrays; #else GET_PROC(BindVertexArray); GET_PROC(DeleteVertexArrays); GET_PROC(GenVertexArrays); #endif } if (ver >= GR_GL_VER(3,3) || extensions.has("GL_ARB_timer_query")) { // ARB extension doesn't use the ARB suffix on the function name #if GL_ARB_timer_query || GL_VERSION_3_3 interface->fQueryCounter = glQueryCounter; interface->fGetQueryObjecti64v = glGetQueryObjecti64v; interface->fGetQueryObjectui64v = glGetQueryObjectui64v; #else GET_PROC(QueryCounter); GET_PROC(GetQueryObjecti64v); GET_PROC(GetQueryObjectui64v); #endif } else if (extensions.has("GL_EXT_timer_query")) { #if GL_EXT_timer_query interface->fGetQueryObjecti64v = glGetQueryObjecti64vEXT; interface->fGetQueryObjectui64v = glGetQueryObjectui64vEXT; #else GET_PROC_SUFFIX(GetQueryObjecti64v, EXT); GET_PROC_SUFFIX(GetQueryObjectui64v, EXT); #endif } if (ver >= GR_GL_VER(3,0) || extensions.has("GL_ARB_framebuffer_object")) { // ARB extension doesn't use the ARB suffix on the function names #if GL_VERSION_3_0 || GL_ARB_framebuffer_object interface->fGenFramebuffers = glGenFramebuffers; interface->fGetFramebufferAttachmentParameteriv = glGetFramebufferAttachmentParameteriv; interface->fGetRenderbufferParameteriv = glGetRenderbufferParameteriv; interface->fBindFramebuffer = glBindFramebuffer; interface->fFramebufferTexture2D = glFramebufferTexture2D; interface->fCheckFramebufferStatus = glCheckFramebufferStatus; interface->fDeleteFramebuffers = glDeleteFramebuffers; interface->fRenderbufferStorage = glRenderbufferStorage; interface->fGenRenderbuffers = glGenRenderbuffers; interface->fDeleteRenderbuffers = glDeleteRenderbuffers; interface->fFramebufferRenderbuffer = glFramebufferRenderbuffer; interface->fBindRenderbuffer = glBindRenderbuffer; interface->fRenderbufferStorageMultisample = glRenderbufferStorageMultisample; interface->fBlitFramebuffer = glBlitFramebuffer; #else GET_PROC(GenFramebuffers); GET_PROC(GetFramebufferAttachmentParameteriv); GET_PROC(GetRenderbufferParameteriv); GET_PROC(BindFramebuffer); GET_PROC(FramebufferTexture2D); GET_PROC(CheckFramebufferStatus); GET_PROC(DeleteFramebuffers); GET_PROC(RenderbufferStorage); GET_PROC(GenRenderbuffers); GET_PROC(DeleteRenderbuffers); GET_PROC(FramebufferRenderbuffer); GET_PROC(BindRenderbuffer); GET_PROC(RenderbufferStorageMultisample); GET_PROC(BlitFramebuffer); #endif } else { if (extensions.has("GL_EXT_framebuffer_object")) { #if GL_EXT_framebuffer_object interface->fGenFramebuffers = glGenFramebuffersEXT; interface->fGetFramebufferAttachmentParameteriv = glGetFramebufferAttachmentParameterivEXT; interface->fGetRenderbufferParameteriv = glGetRenderbufferParameterivEXT; interface->fBindFramebuffer = glBindFramebufferEXT; interface->fFramebufferTexture2D = glFramebufferTexture2DEXT; interface->fCheckFramebufferStatus = glCheckFramebufferStatusEXT; interface->fDeleteFramebuffers = glDeleteFramebuffersEXT; interface->fRenderbufferStorage = glRenderbufferStorageEXT; interface->fGenRenderbuffers = glGenRenderbuffersEXT; interface->fDeleteRenderbuffers = glDeleteRenderbuffersEXT; interface->fFramebufferRenderbuffer = glFramebufferRenderbufferEXT; interface->fBindRenderbuffer = glBindRenderbufferEXT; #else GET_PROC_SUFFIX(GenFramebuffers, EXT); GET_PROC_SUFFIX(GetFramebufferAttachmentParameteriv, EXT); GET_PROC_SUFFIX(GetRenderbufferParameteriv, EXT); GET_PROC_SUFFIX(BindFramebuffer, EXT); GET_PROC_SUFFIX(FramebufferTexture2D, EXT); GET_PROC_SUFFIX(CheckFramebufferStatus, EXT); GET_PROC_SUFFIX(DeleteFramebuffers, EXT); GET_PROC_SUFFIX(RenderbufferStorage, EXT); GET_PROC_SUFFIX(GenRenderbuffers, EXT); GET_PROC_SUFFIX(DeleteRenderbuffers, EXT); GET_PROC_SUFFIX(FramebufferRenderbuffer, EXT); GET_PROC_SUFFIX(BindRenderbuffer, EXT); #endif } if (extensions.has("GL_EXT_framebuffer_multisample")) { #if GL_EXT_framebuffer_multisample interface->fRenderbufferStorageMultisample = glRenderbufferStorageMultisampleEXT; #else GET_PROC_SUFFIX(RenderbufferStorageMultisample, EXT); #endif } if (extensions.has("GL_EXT_framebuffer_blit")) { #if GL_EXT_framebuffer_blit interface->fBlitFramebuffer = glBlitFramebufferEXT; #else GET_PROC_SUFFIX(BlitFramebuffer, EXT); #endif } } if (ver >= GR_GL_VER(3,3) || extensions.has("GL_ARB_blend_func_extended")) { // ARB extension doesn't use the ARB suffix on the function name #if GL_VERSION_3_3 || GL_ARB_blend_func_extended interface->fBindFragDataLocationIndexed = glBindFragDataLocationIndexed; #else GET_PROC(BindFragDataLocationIndexed); #endif } } glInterface.get()->ref(); return glInterface.get(); } <|endoftext|>
<commit_before>/*- * Copyright (c) 2015 Masayoshi Mizutani <mizutani@sfc.wide.ad.jp> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <sstream> #include <sys/time.h> #include <time.h> #include <math.h> #include <unistd.h> #include "./fluent/logger.hpp" #include "./fluent/message.hpp" #include "./fluent/emitter.hpp" #include "./debug.h" namespace fluent { Logger::Logger() { } Logger::~Logger() { // delete not used messages. for (auto it = this->msg_set_.begin(); it != this->msg_set_.end(); it++) { delete *it; } for (size_t i = 0; i < this->emitter_.size(); i++) { delete this->emitter_[i]; } } void Logger::new_forward(const std::string &host, int port) { Emitter *e = new InetEmitter(host, port); this->emitter_.push_back(e); } void Logger::new_dumpfile(const std::string &fname) { Emitter *e = new FileEmitter(fname); this->emitter_.push_back(e); } Message* Logger::retain_message(const std::string &tag) { Message *msg = new Message(tag); this->msg_set_.insert(msg); return msg; } bool Logger::emit(Message *msg) { if (this->msg_set_.find(msg) == this->msg_set_.end()) { this->errmsg_ = "invalid Message instance, " "should be got by Logger::retain_message()"; return false; } this->msg_set_.erase(msg); bool rc = true; for (size_t i = 0; i < this->emitter_.size(); i++) { rc &= this->emitter_[i]->emit(msg); } return rc; } void Logger::set_queue_limit(size_t limit) { for (size_t i = 0; i < this->emitter_.size(); i++) { this->emitter_[i]->set_queue_limit(limit); } } } <commit_msg>clone the Message that will be sent before push to Emitter<commit_after>/*- * Copyright (c) 2015 Masayoshi Mizutani <mizutani@sfc.wide.ad.jp> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <sstream> #include <sys/time.h> #include <time.h> #include <math.h> #include <unistd.h> #include "./fluent/logger.hpp" #include "./fluent/message.hpp" #include "./fluent/emitter.hpp" #include "./debug.h" namespace fluent { Logger::Logger() { } Logger::~Logger() { // delete not used messages. for (auto it = this->msg_set_.begin(); it != this->msg_set_.end(); it++) { delete *it; } for (size_t i = 0; i < this->emitter_.size(); i++) { delete this->emitter_[i]; } } void Logger::new_forward(const std::string &host, int port) { Emitter *e = new InetEmitter(host, port); this->emitter_.push_back(e); } void Logger::new_dumpfile(const std::string &fname) { Emitter *e = new FileEmitter(fname); this->emitter_.push_back(e); } Message* Logger::retain_message(const std::string &tag) { Message *msg = new Message(tag); this->msg_set_.insert(msg); return msg; } bool Logger::emit(Message *msg) { if (this->msg_set_.find(msg) == this->msg_set_.end()) { this->errmsg_ = "invalid Message instance, " "should be got by Logger::retain_message()"; return false; } this->msg_set_.erase(msg); bool rc = true; if (this->emitter_.size() == 1) { rc = this->emitter_[0]->emit(msg); } else if (this->emitter_.size() > 1) { for (size_t i = 0; i < this->emitter_.size() - 1; i++) { Message *cloned_msg = msg->clone(); rc &= this->emitter_[i]->emit(cloned_msg); } rc &= this->emitter_[this->emitter_.size() - 1]->emit(msg); } return rc; } void Logger::set_queue_limit(size_t limit) { for (size_t i = 0; i < this->emitter_.size(); i++) { this->emitter_[i]->set_queue_limit(limit); } } } <|endoftext|>
<commit_before>#include "TrackLayer.h" #include "PathUtil.h" #include "Projection.h" #include "Types.h" #include "ViewCtx.h" #define PARTICLE_RADIUS 12.0 #define MEDIUM_LOD_RES 10.0 #define LO_LOD_RES 20.0 using namespace cinder; const Color TrackLayer::RunColor = Color( 1, 0, 0 ); const Color TrackLayer::OtherColor = Color( 0.3, 0.3, 1 ); const Color TrackLayer::SelectedColor = Color( 1, 1, 0 ); QOpenGLShaderProgram* TrackLayer::_shader; bool TrackLayer::_isSetup = false; bool TrackLayer::_particlesDrawn = false; bool TrackLayer::_selectedParticlesDrawn = false; QList<Vec2d> TrackLayer::_particleDrawList; QList<Vec2d> TrackLayer::_selectedParticleDrawList; float TrackLayer::_particleRadius = PARTICLE_RADIUS; void TrackLayer::_setup() { _shader = new QOpenGLShaderProgram(); // shaders from http://www.geeks3d.com/20130705/shader-library-circle-disc-fake-sphere-in-glsl-opengl-glslhacker/3/ _shader->addShaderFromSourceCode(QOpenGLShader::Vertex, "#version 120\n" "void main()\n" "{\n" " gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;\n" " gl_TexCoord[0] = gl_MultiTexCoord0;\n" "}\n"); _shader->addShaderFromSourceCode(QOpenGLShader::Fragment, "#version 120\n" "uniform sampler2D tex0;\n" "uniform float border_size; // 0.01\n" "uniform float disc_radius; // 0.5\n" "uniform vec4 disc_color; // vec4(1.0, 1.0, 1.0, 1.0)\n" "uniform vec2 disc_center; // vec2(0.5, 0.5)\n" "void main (void)\n" "{\n" " vec2 uv = gl_TexCoord[0].xy;\n\n" " vec4 bkg_color = texture2D(tex0,uv * vec2(1.0, -1.0));\n" " // Offset uv with the center of the circle.\n" " uv -= disc_center;\n" " float dist = sqrt(dot(uv, uv));\n" " float t = smoothstep(disc_radius+border_size, disc_radius-border_size, dist);\n" " gl_FragColor = mix(bkg_color, disc_color, t);\n" "}\n"); _isSetup = true; } TrackLayer::TrackLayer(const Track *track) : Layer(), _mediumLodRes(MEDIUM_LOD_RES), _loLodRes(LO_LOD_RES), _track(track), _duration(0) { if (!_isSetup) _setup(); int numPts = track->points.size(); if (numPts > 0) _startTime = QDateTime::fromTime_t(track->points[0].time); if (numPts > 1) _duration = track->points[numPts-1].time - track->points[0].time; _pathBuffer = (float*)malloc(sizeof(float)*4*numPts); } TrackLayer::~TrackLayer() { free(_pathBuffer); _pathBuffer = NULL; delete _track; } QString TrackLayer::name() const { return _track->name; } QString TrackLayer::sport() const { return _track->sport; } QDateTime TrackLayer::startTime() const { return _startTime; } PassMap TrackLayer::passes() const { PassMap layers; layers.insert(Pass_UnselectedPath); layers.insert(Pass_SelectedPath); layers.insert(Pass_Particles); return layers; } /* * Linear interpolate between a and b by the fractional f. */ double lerp(double a, double b, double f) { return a + f * (b - a); } MapPoint lerp(const MapPoint& a, const MapPoint& b, double f) { return MapPoint(lerp(a.x, b.x, f), lerp(a.y, b.y, f)); } unsigned int TrackLayer::duration() const { return _duration; } void TrackLayer::project(const Projection &projection) { // Project the track into the hi-res path and compute the bounding box int startTime = 0; for(size_t i=0; i < _track->points.size(); i++) { TrackPoint pt = _track->points[i]; if (i == 0) startTime = pt.time; PathPoint newPt; newPt.pos = projection.toProjection(pt.pos); newPt.time = pt.time - startTime; _path_hi.push_back(newPt); _bounds += newPt.pos; } _particleRadius *= projection.getScaleMultiplier(); _mediumLodRes *= projection.getScaleMultiplier(); _loLodRes *= projection.getScaleMultiplier(); qDebug("med: %f, lo: %f", _mediumLodRes, _loLodRes); qDebug("hi: %d points", _path_hi.count()); // Make the medium res path _path_med = PathUtil::DouglasPeucker(_path_hi, _mediumLodRes); qDebug("med: %d points", _path_med.count()); // Make the low res path _path_lo = PathUtil::DouglasPeucker(_path_med, _loLodRes); qDebug("lo: %d points", _path_lo.count()); } void TrackLayer::draw(uint pass, const ViewCtx &viewCtx, const TimeCtx &timeCtx) { if (!visible() || !_bounds.overlaps(viewCtx.getBoundingBox())) return; bool selected = viewCtx.isSelected(id()); switch (pass) { case Pass_UnselectedPath: if (!selected) _drawPath(viewCtx, timeCtx); _pushParticle(viewCtx); break; case Pass_SelectedPath: if (selected) _drawPath(viewCtx, timeCtx); break; case Pass_Particles: _drawParticles(viewCtx); break; }; } void TrackLayer::_drawPath(const ViewCtx &viewCtx, const TimeCtx &timeCtx) { // Choose which path to display Path *currentPath = &_path_hi; double res = viewCtx.getResolution(); if (res >= _mediumLodRes && res < _loLodRes) currentPath = &_path_med; else if (res >= _loLodRes) currentPath = &_path_lo; if (viewCtx.isSelected(id())) gl::color( SelectedColor ); else if (_track->sport == "Running") gl::color( RunColor ); else gl::color( OtherColor ); MapPoint w2c = viewCtx.getWorldToCamera(); PathPoint *lastPathPt; MapPoint *lastMapPt; int bufferIndex = 0; bool lastInbounds = false; for(int i=0; i < currentPath->count(); i++) { PathPoint *pt = &(*currentPath)[i]; MapPoint *thisMapPt = &(pt->pos); bool inbounds = viewCtx.getBoundingBox().contains(*thisMapPt); if (i == 0 || pt->time < timeCtx.getMapSeconds()) { if (i > 0 && (inbounds || lastInbounds)) { _pathBuffer[bufferIndex++] = w2c.x + lastMapPt->x; _pathBuffer[bufferIndex++] = w2c.y + lastMapPt->y; _pathBuffer[bufferIndex++] = w2c.x + thisMapPt->x; _pathBuffer[bufferIndex++] = w2c.y + thisMapPt->y; } lastMapPt = thisMapPt; lastPathPt = pt; _particlePos = *lastMapPt; } else { double elapsed = timeCtx.getMapSeconds() - double(lastPathPt->time); int trkElapsed = pt->time - lastPathPt->time; double f = (trkElapsed == 0) ? 0. : elapsed / double(trkElapsed); if (f > 0.0 && (inbounds || lastInbounds)) { MapPoint finalPt = lerp(*lastMapPt, *thisMapPt, f); _pathBuffer[bufferIndex++] = w2c.x + lastMapPt->x; _pathBuffer[bufferIndex++] = w2c.y + lastMapPt->y; _pathBuffer[bufferIndex++] = w2c.x + finalPt.x; _pathBuffer[bufferIndex++] = w2c.y + finalPt.y; _particlePos = finalPt; } break; } lastInbounds = inbounds; } glEnableClientState( GL_VERTEX_ARRAY ); glVertexPointer( 2, GL_FLOAT, 0, _pathBuffer ); glDrawArrays( GL_LINES, 0, bufferIndex/2 ); glDisableClientState( GL_VERTEX_ARRAY ); } void TrackLayer::_pushParticle(const ViewCtx &viewCtx) const { _particlesDrawn = false; // transform to camera space const Vec2d particlePosCamera = viewCtx.getWorldToCamera() + _particlePos; if (viewCtx.isSelected(id())) _selectedParticleDrawList.append(particlePosCamera); else _particleDrawList.append(particlePosCamera); /* gl::drawSolidCircle( particlePosCamera, radius); if (viewCtx.isSelected(id())) { gl::drawStrokedCircle(particlePosCamera, radius*1.5); gl::drawStrokedCircle(particlePosCamera, radius*2.0); } gl::color( Color( 0.3, 0.3, 0.3 ) ); gl::drawStrokedCircle(particlePosCamera, radius); */ } BoundingBox TrackLayer::getBoundingBox() const { return _bounds; } MapPoint TrackLayer::position() const { return _particlePos; } bool TrackLayer::ephemeral() const { return false; } void TrackLayer::_drawParticles(const ViewCtx &viewCtx) { _particlesDrawn = true; Vec2d particle; size_t numParticles = _particleDrawList.count(); float *_particleBuffer = (float*)malloc(sizeof(float)*2*numParticles); size_t bufferIndex = 0; foreach(particle, _particleDrawList) { _particleBuffer[bufferIndex++] = particle.x; _particleBuffer[bufferIndex++] = particle.y; } float radius = _particleRadius; if (radius < viewCtx.getResolution()*2.) radius = viewCtx.getResolution()*2.; _shader->bind(); glEnableClientState( GL_VERTEX_ARRAY ); glVertexPointer( 2, GL_FLOAT, 0, _particleBuffer ); glDrawArrays( GL_POINTS, 0, bufferIndex/2 ); glDisableClientState( GL_VERTEX_ARRAY ); _shader->release(); free(_particleBuffer); } void TrackLayer::_drawSelectedParticles(const ViewCtx &viewCtx) { _selectedParticlesDrawn = true; } <commit_msg>And don’t forget to clear the particle drawlist after drawing the particles.<commit_after>#include "TrackLayer.h" #include "PathUtil.h" #include "Projection.h" #include "Types.h" #include "ViewCtx.h" #define PARTICLE_RADIUS 12.0 #define MEDIUM_LOD_RES 10.0 #define LO_LOD_RES 20.0 using namespace cinder; const Color TrackLayer::RunColor = Color( 1, 0, 0 ); const Color TrackLayer::OtherColor = Color( 0.3, 0.3, 1 ); const Color TrackLayer::SelectedColor = Color( 1, 1, 0 ); QOpenGLShaderProgram* TrackLayer::_shader; bool TrackLayer::_isSetup = false; bool TrackLayer::_particlesDrawn = false; bool TrackLayer::_selectedParticlesDrawn = false; QList<Vec2d> TrackLayer::_particleDrawList; QList<Vec2d> TrackLayer::_selectedParticleDrawList; float TrackLayer::_particleRadius = PARTICLE_RADIUS; void TrackLayer::_setup() { _shader = new QOpenGLShaderProgram(); // shaders from http://www.geeks3d.com/20130705/shader-library-circle-disc-fake-sphere-in-glsl-opengl-glslhacker/3/ _shader->addShaderFromSourceCode(QOpenGLShader::Vertex, "#version 120\n" "void main()\n" "{\n" " gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;\n" " gl_TexCoord[0] = gl_MultiTexCoord0;\n" "}\n"); _shader->addShaderFromSourceCode(QOpenGLShader::Fragment, "#version 120\n" "uniform sampler2D tex0;\n" "uniform float border_size; // 0.01\n" "uniform float disc_radius; // 0.5\n" "uniform vec4 disc_color; // vec4(1.0, 1.0, 1.0, 1.0)\n" "uniform vec2 disc_center; // vec2(0.5, 0.5)\n" "void main (void)\n" "{\n" " vec2 uv = gl_TexCoord[0].xy;\n\n" " vec4 bkg_color = texture2D(tex0,uv * vec2(1.0, -1.0));\n" " // Offset uv with the center of the circle.\n" " uv -= disc_center;\n" " float dist = sqrt(dot(uv, uv));\n" " float t = smoothstep(disc_radius+border_size, disc_radius-border_size, dist);\n" " gl_FragColor = mix(bkg_color, disc_color, t);\n" "}\n"); _isSetup = true; } TrackLayer::TrackLayer(const Track *track) : Layer(), _mediumLodRes(MEDIUM_LOD_RES), _loLodRes(LO_LOD_RES), _track(track), _duration(0) { if (!_isSetup) _setup(); int numPts = track->points.size(); if (numPts > 0) _startTime = QDateTime::fromTime_t(track->points[0].time); if (numPts > 1) _duration = track->points[numPts-1].time - track->points[0].time; _pathBuffer = (float*)malloc(sizeof(float)*4*numPts); } TrackLayer::~TrackLayer() { free(_pathBuffer); _pathBuffer = NULL; delete _track; } QString TrackLayer::name() const { return _track->name; } QString TrackLayer::sport() const { return _track->sport; } QDateTime TrackLayer::startTime() const { return _startTime; } PassMap TrackLayer::passes() const { PassMap layers; layers.insert(Pass_UnselectedPath); layers.insert(Pass_SelectedPath); layers.insert(Pass_Particles); return layers; } /* * Linear interpolate between a and b by the fractional f. */ double lerp(double a, double b, double f) { return a + f * (b - a); } MapPoint lerp(const MapPoint& a, const MapPoint& b, double f) { return MapPoint(lerp(a.x, b.x, f), lerp(a.y, b.y, f)); } unsigned int TrackLayer::duration() const { return _duration; } void TrackLayer::project(const Projection &projection) { // Project the track into the hi-res path and compute the bounding box int startTime = 0; for(size_t i=0; i < _track->points.size(); i++) { TrackPoint pt = _track->points[i]; if (i == 0) startTime = pt.time; PathPoint newPt; newPt.pos = projection.toProjection(pt.pos); newPt.time = pt.time - startTime; _path_hi.push_back(newPt); _bounds += newPt.pos; } _particleRadius *= projection.getScaleMultiplier(); _mediumLodRes *= projection.getScaleMultiplier(); _loLodRes *= projection.getScaleMultiplier(); qDebug("med: %f, lo: %f", _mediumLodRes, _loLodRes); qDebug("hi: %d points", _path_hi.count()); // Make the medium res path _path_med = PathUtil::DouglasPeucker(_path_hi, _mediumLodRes); qDebug("med: %d points", _path_med.count()); // Make the low res path _path_lo = PathUtil::DouglasPeucker(_path_med, _loLodRes); qDebug("lo: %d points", _path_lo.count()); } void TrackLayer::draw(uint pass, const ViewCtx &viewCtx, const TimeCtx &timeCtx) { if (!visible() || !_bounds.overlaps(viewCtx.getBoundingBox())) return; bool selected = viewCtx.isSelected(id()); switch (pass) { case Pass_UnselectedPath: if (!selected) _drawPath(viewCtx, timeCtx); _pushParticle(viewCtx); break; case Pass_SelectedPath: if (selected) _drawPath(viewCtx, timeCtx); break; case Pass_Particles: _drawParticles(viewCtx); break; }; } void TrackLayer::_drawPath(const ViewCtx &viewCtx, const TimeCtx &timeCtx) { // Choose which path to display Path *currentPath = &_path_hi; double res = viewCtx.getResolution(); if (res >= _mediumLodRes && res < _loLodRes) currentPath = &_path_med; else if (res >= _loLodRes) currentPath = &_path_lo; if (viewCtx.isSelected(id())) gl::color( SelectedColor ); else if (_track->sport == "Running") gl::color( RunColor ); else gl::color( OtherColor ); MapPoint w2c = viewCtx.getWorldToCamera(); PathPoint *lastPathPt; MapPoint *lastMapPt; int bufferIndex = 0; bool lastInbounds = false; for(int i=0; i < currentPath->count(); i++) { PathPoint *pt = &(*currentPath)[i]; MapPoint *thisMapPt = &(pt->pos); bool inbounds = viewCtx.getBoundingBox().contains(*thisMapPt); if (i == 0 || pt->time < timeCtx.getMapSeconds()) { if (i > 0 && (inbounds || lastInbounds)) { _pathBuffer[bufferIndex++] = w2c.x + lastMapPt->x; _pathBuffer[bufferIndex++] = w2c.y + lastMapPt->y; _pathBuffer[bufferIndex++] = w2c.x + thisMapPt->x; _pathBuffer[bufferIndex++] = w2c.y + thisMapPt->y; } lastMapPt = thisMapPt; lastPathPt = pt; _particlePos = *lastMapPt; } else { double elapsed = timeCtx.getMapSeconds() - double(lastPathPt->time); int trkElapsed = pt->time - lastPathPt->time; double f = (trkElapsed == 0) ? 0. : elapsed / double(trkElapsed); if (f > 0.0 && (inbounds || lastInbounds)) { MapPoint finalPt = lerp(*lastMapPt, *thisMapPt, f); _pathBuffer[bufferIndex++] = w2c.x + lastMapPt->x; _pathBuffer[bufferIndex++] = w2c.y + lastMapPt->y; _pathBuffer[bufferIndex++] = w2c.x + finalPt.x; _pathBuffer[bufferIndex++] = w2c.y + finalPt.y; _particlePos = finalPt; } break; } lastInbounds = inbounds; } glEnableClientState( GL_VERTEX_ARRAY ); glVertexPointer( 2, GL_FLOAT, 0, _pathBuffer ); glDrawArrays( GL_LINES, 0, bufferIndex/2 ); glDisableClientState( GL_VERTEX_ARRAY ); } void TrackLayer::_pushParticle(const ViewCtx &viewCtx) const { _particlesDrawn = false; // transform to camera space const Vec2d particlePosCamera = viewCtx.getWorldToCamera() + _particlePos; if (viewCtx.isSelected(id())) _selectedParticleDrawList.append(particlePosCamera); else _particleDrawList.append(particlePosCamera); /* gl::drawSolidCircle( particlePosCamera, radius); if (viewCtx.isSelected(id())) { gl::drawStrokedCircle(particlePosCamera, radius*1.5); gl::drawStrokedCircle(particlePosCamera, radius*2.0); } gl::color( Color( 0.3, 0.3, 0.3 ) ); gl::drawStrokedCircle(particlePosCamera, radius); */ } BoundingBox TrackLayer::getBoundingBox() const { return _bounds; } MapPoint TrackLayer::position() const { return _particlePos; } bool TrackLayer::ephemeral() const { return false; } void TrackLayer::_drawParticles(const ViewCtx &viewCtx) { _particlesDrawn = true; Vec2d particle; size_t numParticles = _particleDrawList.count(); float *_particleBuffer = (float*)malloc(sizeof(float)*2*numParticles); size_t bufferIndex = 0; foreach(particle, _particleDrawList) { _particleBuffer[bufferIndex++] = particle.x; _particleBuffer[bufferIndex++] = particle.y; } float radius = _particleRadius; if (radius < viewCtx.getResolution()*2.) radius = viewCtx.getResolution()*2.; _shader->bind(); glEnableClientState( GL_VERTEX_ARRAY ); glVertexPointer( 2, GL_FLOAT, 0, _particleBuffer ); glDrawArrays( GL_POINTS, 0, bufferIndex/2 ); glDisableClientState( GL_VERTEX_ARRAY ); _shader->release(); free(_particleBuffer); _particleDrawList.clear(); } void TrackLayer::_drawSelectedParticles(const ViewCtx &viewCtx) { _selectedParticlesDrawn = true; } <|endoftext|>
<commit_before>// // File: Actor.hpp // Class: Actor // Author: John Barbero Unenge // All code is my own except where credited to others. // // Copyright (c) 2012 Catch22. All Rights Reserved. // // Date: 2/10/12 // // Description: // This class is used to graphically represent some part of // the game model. It has a set of animations which it can // switch between. // #ifndef __CatchiOS__Actor__ #define __CatchiOS__Actor__ #include "IRenderable.hpp" #include "Animation.hpp" #include "../GameModel/Physics/PBody.hpp" // A structure used keep track of animations and // the current number of animations. struct AnimationArray { Animation** m_animationArray; int m_size; AnimationArray(Animation** animations, int size) { m_animationArray = animations; m_size = size; } }; class Actor : public IRenderable { private: AnimationArray* m_animations; Animation* m_currentAnimation; PBody* m_pBody; public: Actor(AnimationArray* animations, Animation* currentAnimation); Actor(Actor* actor); ~Actor(); void setPBody(PBody* pBody); // Inherited from IRenderable virtual const Vertex* getVertexData(); virtual const Vertex* getTextureVertexData(); virtual int getTextureID(); virtual void update(float dt); }; #endif /* defined(__CatchiOS__Actor__) */ <commit_msg>Created a copy constructor and destructor for struct AnimationArray.<commit_after>// // File: Actor.hpp // Class: Actor // Author: John Barbero Unenge // All code is my own except where credited to others. // // Copyright (c) 2012 Catch22. All Rights Reserved. // // Date: 2/10/12 // // Description: // This class is used to graphically represent some part of // the game model. It has a set of animations which it can // switch between. // #ifndef __CatchiOS__Actor__ #define __CatchiOS__Actor__ #include "IRenderable.hpp" #include "Animation.hpp" #include "../GameModel/Physics/PBody.hpp" // A structure used keep track of animations and // the current number of animations. struct AnimationArray { Animation** m_animationArray; int m_size; AnimationArray(Animation** animations, int size) { m_animationArray = animations; m_size = size; } AnimationArray(AnimationArray* anim) { this->m_size = anim->m_size; this->m_animationArray = new Animation*[this->m_size]; for (int i = 0; i < this->m_size; i++) { this->m_animationArray[i] = new Animation(anim->m_animationArray[i]); } } ~AnimationArray() { for (int i = 0; i < m_size; i++) { delete m_animationArray[i]; } delete m_animationArray; m_animationArray = 0; } }; class Actor : public IRenderable { private: AnimationArray* m_animations; Animation* m_currentAnimation; PBody* m_pBody; public: Actor(AnimationArray* animations, Animation* currentAnimation); Actor(Actor* actor); ~Actor(); void setPBody(PBody* pBody); // Inherited from IRenderable virtual const Vertex* getVertexData(); virtual const Vertex* getTextureVertexData(); virtual int getTextureID(); virtual void update(float dt); }; #endif /* defined(__CatchiOS__Actor__) */ <|endoftext|>
<commit_before>#pragma once #include <memory> #include <cstring> #include <boost/lockfree/queue.hpp> #include <sqlite3.h> #include <iod/sio.hh> #include <iod/callable_traits.hh> namespace iod { void free_sqlite3_statement(void* s) { sqlite3_finalize((sqlite3_stmt*) s); } struct sqlite_statement { typedef std::shared_ptr<sqlite3_stmt> stmt_sptr; sqlite_statement(sqlite3* db, sqlite3_stmt* s) : db_(db), stmt_(s), stmt_sptr_(stmt_sptr(s, free_sqlite3_statement)) { } template <typename... A> void row_to_sio(iod::sio<A...>& o) { int ncols = sqlite3_column_count(stmt_); int filled[sizeof...(A)]; for (unsigned i = 0; i < sizeof...(A); i++) filled[i] = 0; for (int i = 0; i < ncols; i++) { const char* cname = sqlite3_column_name(stmt_, i); bool found = false; int j = 0; foreach(o) | [&] (auto& m) { if (!found and !filled[j] and !strcmp(cname, m.symbol().name())) { this->read_column(i, m.value()); found = true; filled[j] = 1; } j++; }; } } template <typename... A> int operator>>(iod::sio<A...>& o) { if (sqlite3_step(stmt_) != SQLITE_ROW) return false; row_to_sio(o); return true; } template <typename T> int operator>>(T& o) { if (sqlite3_step(stmt_) != SQLITE_ROW) return false; this->read_column(0, o); return true; } int exec() { int ret = sqlite3_step(stmt_); if (ret != SQLITE_ROW and ret != SQLITE_DONE) throw std::runtime_error(sqlite3_errstr(ret)); return ret == SQLITE_ROW or ret == SQLITE_DONE; } int last_insert_rowid() { return sqlite3_last_insert_rowid(db_); } int exists() { return sqlite3_step(stmt_) == SQLITE_ROW; } template <typename F> void operator|(F f) { while (sqlite3_step(stmt_) == SQLITE_ROW) { typedef callable_arguments_tuple_t<F> tp; typedef std::remove_reference_t<std::tuple_element_t<0, tp>> T; T o; row_to_sio(o); f(o); } } template <typename V> void append_to(V& v) { (*this) | [&v] (typename V::value_type& o) { v.push_back(o); }; } template <typename T> struct typed_iterator { template <typename F> void operator|(F f) const { (*_this) | [&f] (T& t) { f(t); }; } sqlite_statement* _this; }; template <typename... A> auto operator()(A&&... typeinfo) { return typed_iterator<decltype(iod::D(typeinfo...))>{this}; } void read_column(int pos, int& v) { v = sqlite3_column_int(stmt_, pos); } void read_column(int pos, float& v) { v = sqlite3_column_double(stmt_, pos); } void read_column(int pos, double& v) { v = sqlite3_column_double(stmt_, pos); } void read_column(int pos, int64_t& v) { v = sqlite3_column_int64(stmt_, pos); } void read_column(int pos, std::string& v) { auto str = sqlite3_column_text(stmt_, pos); auto n = sqlite3_column_bytes(stmt_, pos); v = std::move(std::string((const char*) str, n)); } sqlite3* db_; sqlite3_stmt* stmt_; stmt_sptr stmt_sptr_; }; void free_sqlite3_db(void* db) { sqlite3_close_v2((sqlite3*) db); } struct sqlite_middleware; struct sqlite_connection { typedef sqlite_middleware middleware_type; typedef std::shared_ptr<sqlite3> db_sptr; sqlite_connection() : db_(nullptr) { } void connect(const std::string& filename, int flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE) { int r = sqlite3_open_v2(filename.c_str(), &db_, flags, nullptr); if (r != SQLITE_OK) throw std::runtime_error(std::string("Cannot open database ") + filename + " " + sqlite3_errstr(r)); db_sptr_ = db_sptr(db_, free_sqlite3_db); } int bind(sqlite3_stmt* stmt, int pos, double d) const { return sqlite3_bind_double(stmt, pos, d); } int bind(sqlite3_stmt* stmt, int pos, int d) const { return sqlite3_bind_int(stmt, pos, d); } //void bind(sqlite3_stmt* stmt, int pos, null_t) { sqlite3_bind_null(stmt, pos); } int bind(sqlite3_stmt* stmt, int pos, const std::string& s) const { return sqlite3_bind_text(stmt, pos, s.data(), s.size(), nullptr); } template <typename E> inline void format_error(E& err) const {} template <typename E, typename T1, typename... T> inline void format_error(E& err, T1 a, T... args) const { err << a; format_error(err, args...); } int last_insert_rowid() { return sqlite3_last_insert_rowid(db_); } template <typename... A> sqlite_statement operator()(const std::string& req, A&&... args) const { sqlite3_stmt* stmt; int err = sqlite3_prepare_v2(db_, req.c_str(), req.size(), &stmt, nullptr); if (err != SQLITE_OK) throw std::runtime_error(std::string("Sqlite error during prepare: ") + sqlite3_errstr(err) + " statement was: " + req); int i = 1; foreach(std::forward_as_tuple(args...)) | [&] (auto& m) { int err; if ((err = this->bind(stmt, i, m)) != SQLITE_OK) throw std::runtime_error(std::string("Sqlite error during binding: ") + sqlite3_errstr(err)); i++; }; return sqlite_statement(db_, stmt); } sqlite3* db_; db_sptr db_sptr_; }; struct sqlite_database { sqlite_database() {} sqlite_connection& get_connection() { return con_; } void init(const std::string& path) { path_ = path; con_.connect(path, SQLITE_OPEN_FULLMUTEX | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE); con_("PRAGMA synchronous=0").exec(); } sqlite_connection con_; std::string path_; }; struct sqlite_middleware { sqlite_middleware(const std::string& database_path) { db_.init(database_path); } sqlite_connection& instantiate() { return db_.get_connection(); } sqlite_database db_; }; } <commit_msg>Handle binary blobs in sqlite.<commit_after>#pragma once #include <memory> #include <cstring> #include <boost/lockfree/queue.hpp> #include <sqlite3.h> #include <iod/sio.hh> #include <iod/callable_traits.hh> namespace iod { struct blob : public std::string { blob(const std::string& s) : std::string(s) {} }; void free_sqlite3_statement(void* s) { sqlite3_finalize((sqlite3_stmt*) s); } struct sqlite_statement { typedef std::shared_ptr<sqlite3_stmt> stmt_sptr; sqlite_statement(sqlite3* db, sqlite3_stmt* s) : db_(db), stmt_(s), stmt_sptr_(stmt_sptr(s, free_sqlite3_statement)) { } template <typename... A> void row_to_sio(iod::sio<A...>& o) { int ncols = sqlite3_column_count(stmt_); int filled[sizeof...(A)]; for (unsigned i = 0; i < sizeof...(A); i++) filled[i] = 0; for (int i = 0; i < ncols; i++) { const char* cname = sqlite3_column_name(stmt_, i); bool found = false; int j = 0; foreach(o) | [&] (auto& m) { if (!found and !filled[j] and !strcmp(cname, m.symbol().name())) { this->read_column(i, m.value()); found = true; filled[j] = 1; } j++; }; } } template <typename... A> int operator>>(iod::sio<A...>& o) { if (sqlite3_step(stmt_) != SQLITE_ROW) return false; row_to_sio(o); return true; } template <typename T> int operator>>(T& o) { if (sqlite3_step(stmt_) != SQLITE_ROW) return false; this->read_column(0, o); return true; } int exec() { int ret = sqlite3_step(stmt_); if (ret != SQLITE_ROW and ret != SQLITE_DONE) throw std::runtime_error(sqlite3_errstr(ret)); return ret == SQLITE_ROW or ret == SQLITE_DONE; } int last_insert_rowid() { return sqlite3_last_insert_rowid(db_); } int exists() { return sqlite3_step(stmt_) == SQLITE_ROW; } template <typename F> void operator|(F f) { while (sqlite3_step(stmt_) == SQLITE_ROW) { typedef callable_arguments_tuple_t<F> tp; typedef std::remove_reference_t<std::tuple_element_t<0, tp>> T; T o; row_to_sio(o); f(o); } } template <typename V> void append_to(V& v) { (*this) | [&v] (typename V::value_type& o) { v.push_back(o); }; } template <typename T> struct typed_iterator { template <typename F> void operator|(F f) const { (*_this) | [&f] (T& t) { f(t); }; } sqlite_statement* _this; }; template <typename... A> auto operator()(A&&... typeinfo) { return typed_iterator<decltype(iod::D(typeinfo...))>{this}; } void read_column(int pos, int& v) { v = sqlite3_column_int(stmt_, pos); } void read_column(int pos, float& v) { v = sqlite3_column_double(stmt_, pos); } void read_column(int pos, double& v) { v = sqlite3_column_double(stmt_, pos); } void read_column(int pos, int64_t& v) { v = sqlite3_column_int64(stmt_, pos); } void read_column(int pos, std::string& v) { auto str = sqlite3_column_text(stmt_, pos); auto n = sqlite3_column_bytes(stmt_, pos); v = std::move(std::string((const char*) str, n)); } sqlite3* db_; sqlite3_stmt* stmt_; stmt_sptr stmt_sptr_; }; void free_sqlite3_db(void* db) { sqlite3_close_v2((sqlite3*) db); } struct sqlite_middleware; struct sqlite_connection { typedef sqlite_middleware middleware_type; typedef std::shared_ptr<sqlite3> db_sptr; sqlite_connection() : db_(nullptr) { } void connect(const std::string& filename, int flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE) { int r = sqlite3_open_v2(filename.c_str(), &db_, flags, nullptr); if (r != SQLITE_OK) throw std::runtime_error(std::string("Cannot open database ") + filename + " " + sqlite3_errstr(r)); db_sptr_ = db_sptr(db_, free_sqlite3_db); } int bind(sqlite3_stmt* stmt, int pos, double d) const { return sqlite3_bind_double(stmt, pos, d); } int bind(sqlite3_stmt* stmt, int pos, int d) const { return sqlite3_bind_int(stmt, pos, d); } //void bind(sqlite3_stmt* stmt, int pos, null_t) { sqlite3_bind_null(stmt, pos); } int bind(sqlite3_stmt* stmt, int pos, const std::string& s) const { return sqlite3_bind_text(stmt, pos, s.data(), s.size(), nullptr); } int bind(sqlite3_stmt* stmt, int pos, const blob& b) const { return sqlite3_bind_blob(stmt, pos, b.data(), b.size(), nullptr); } template <typename E> inline void format_error(E& err) const {} template <typename E, typename T1, typename... T> inline void format_error(E& err, T1 a, T... args) const { err << a; format_error(err, args...); } int last_insert_rowid() { return sqlite3_last_insert_rowid(db_); } template <typename... A> sqlite_statement operator()(const std::string& req, A&&... args) const { sqlite3_stmt* stmt; int err = sqlite3_prepare_v2(db_, req.c_str(), req.size(), &stmt, nullptr); if (err != SQLITE_OK) throw std::runtime_error(std::string("Sqlite error during prepare: ") + sqlite3_errmsg(db_) + " statement was: " + req); int i = 1; foreach(std::forward_as_tuple(args...)) | [&] (auto& m) { int err; if ((err = this->bind(stmt, i, m)) != SQLITE_OK) throw std::runtime_error(std::string("Sqlite error during binding: ") + sqlite3_errmsg(db_)); i++; }; return sqlite_statement(db_, stmt); } sqlite3* db_; db_sptr db_sptr_; }; struct sqlite_database { sqlite_database() {} sqlite_connection& get_connection() { return con_; } void init(const std::string& path) { path_ = path; con_.connect(path, SQLITE_OPEN_FULLMUTEX | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE); con_("PRAGMA synchronous=0").exec(); } sqlite_connection con_; std::string path_; }; struct sqlite_middleware { sqlite_middleware(const std::string& database_path) { db_.init(database_path); } sqlite_connection& instantiate() { return db_.get_connection(); } sqlite_database db_; }; } <|endoftext|>
<commit_before>/* The MIT License Copyright (c) 2016 Adrian Tan <atks@umich.edu> 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 "info2tab.h" namespace { class Igor : Program { public: /////////// //options// /////////// std::string input_vcf_file; std::string output_text_file; std::vector<GenomeInterval> intervals; std::vector<std::string> info_tags; bool print_variant; bool debug; /////// //i/o// /////// BCFOrderedReader *odr; ////////// //filter// ////////// std::string fexp; Filter filter; bool filter_exists; ///////// //stats// ///////// uint32_t no_variants; ///////// //tools// ///////// VariantManip *vm; Igor(int argc, char **argv) { version = "0.5"; ////////////////////////// //options initialization// ////////////////////////// try { std::string desc = "extracts info fields to a tab delimited file."; TCLAP::CmdLine cmd(desc, ' ', version); VTOutput my; cmd.setOutput(&my); TCLAP::ValueArg<std::string> arg_intervals("i", "i", "intervals []", false, "", "str", cmd); TCLAP::ValueArg<std::string> arg_interval_list("I", "I", "file containing list of intervals []", false, "", "file", cmd); TCLAP::ValueArg<std::string> arg_output_text_file("o", "o", "output tab delimited file [-]", false, "-", "str", cmd); TCLAP::ValueArg<std::string> arg_info_tags("t", "t", "list of info tags to be extracted []", true, "", "str", cmd); TCLAP::ValueArg<std::string> arg_fexp("f", "f", "filter expression []", false, "", "str", cmd); TCLAP::SwitchArg arg_debug("d", "d", "debug [false]", cmd, false); TCLAP::SwitchArg arg_print_variant("v", "v", "print variant CHROM,POS,REF,ALT [false]", cmd, false); TCLAP::UnlabeledValueArg<std::string> arg_input_vcf_file("<in.vcf>", "input VCF file", true, "","file", cmd); cmd.parse(argc, argv); input_vcf_file = arg_input_vcf_file.getValue(); output_text_file = arg_output_text_file.getValue(); fexp = arg_fexp.getValue(); std::cerr << arg_info_tags.getValue() << "\n"; parse_string_list(info_tags, arg_info_tags.getValue()); print_variant = arg_print_variant.getValue(); debug = arg_debug.getValue(); parse_intervals(intervals, arg_interval_list.getValue(), arg_intervals.getValue()); } catch (TCLAP::ArgException &e) { std::cerr << "error: " << e.error() << " for arg " << e.argId() << "\n"; abort(); } }; void initialize() { ////////////////////// //i/o initialization// ////////////////////// odr = new BCFOrderedReader(input_vcf_file, intervals); ///////////////////////// //filter initialization// ///////////////////////// filter.parse(fexp.c_str(), false); filter_exists = fexp=="" ? false : true; //////////////////////// //stats initialization// //////////////////////// no_variants = 0; //////////////////////// //tools initialization// //////////////////////// vm = new VariantManip(); } void info2tab() { bcf_hdr_t* h = odr->hdr; bcf1_t* v = bcf_init(); Variant variant; FILE *out = NULL; if (output_text_file=="-") { out = stdout; } else { out = fopen(output_text_file.c_str(), "w"); } //get the types of each info field std::vector<std::string> info_tag_str; std::vector<int32_t> info_tag_id; std::vector<int32_t> info_tag_vlen; std::vector<int32_t> info_tag_type; std::vector<int32_t> info_tag_num; if (print_variant) { fprintf(out, "CHROM\tPOS\tREF\tALT\tN_ALLELE\t"); } for (uint32_t i=0; i<info_tags.size(); ++i) { int32_t id = bcf_hdr_id2int(h, BCF_DT_ID, info_tags[i].c_str()); if (id==-1) { notice("%s info tag does not exist", info_tags[i].c_str()); continue; } int32_t vlen = bcf_hdr_id2length(h, BCF_HL_INFO, id); int32_t type = bcf_hdr_id2type(h, BCF_HL_INFO, id); int32_t num = bcf_hdr_id2number(h, BCF_HL_INFO, id); if (vlen==BCF_VL_FIXED) { info_tag_str.push_back(info_tags[i]); info_tag_id.push_back(id); info_tag_vlen.push_back(vlen); info_tag_type.push_back(type); info_tag_num.push_back(num); // notice("Adding id:%s, vlen=%s, type=%s, num=%d", // info_tag_str[i].c_str(), bcf_hdr_vl2str(vlen).c_str(), bcf_hdr_ht2str(type).c_str(), num); if (type==BCF_HT_FLAG) { if (info_tag_str.size()>0) fprintf(out, "\t"); fprintf(out, "%s", info_tags[i].c_str()); } else if (type==BCF_HT_INT) { for (uint32_t j=0; j<num; ++j) { if (info_tag_str.size()!=1 || j!=0) fprintf(out, "\t"); if (num>1) { fprintf(out, "%s_%d", info_tags[i].c_str(), j+1); } else { fprintf(out, "%s", info_tags[i].c_str()); } } } } else { notice("info2tab does not support id:%s, vlen=%s, type=%s, num=%d", info_tags[i].c_str(), bcf_hdr_vl2str(vlen).c_str(), bcf_hdr_ht2str(type).c_str(), num); } } fprintf(out, "\n"); while (odr->read(v)) { bcf_unpack(v, BCF_UN_INFO); if (filter_exists) { vm->classify_variant(h, v, variant); if (!filter.apply(h, v, &variant, false)) { continue; } } if (print_variant) { fprintf(out, "%s\t%d\t", bcf_get_chrom(h, v), bcf_get_pos1(v)); char** alleles = bcf_get_allele(v); fprintf(out, "\t%s", alleles[0]); int32_t no_alleles = bcf_get_n_allele(v); for (uint32_t i=1; i<no_alleles; ++i) { fprintf(out, "%c", i==1?'\t':','); fprintf(out, "%s", alleles[i]); } fprintf(out, "\t"); } // bcf_print(h, v); for (uint32_t i=0; i<info_tag_str.size(); ++i) { if (i) { fprintf(out, "\t"); } int32_t id = info_tag_id[i]; int32_t vlen = info_tag_vlen[i]; int32_t type = info_tag_type[i]; int32_t num = info_tag_num[i]; // notice("processing id:%s, vlen=%s, type=%s, num=%d", // info_tag_str[i].c_str(), bcf_hdr_vl2str(vlen).c_str(), bcf_hdr_ht2str(type).c_str(), num); if (vlen==BCF_VL_FIXED) { if (type==BCF_HT_FLAG) { bool present = bcf_get_info_flg(h, v, info_tag_str[i].c_str()); fprintf(out, "%d", (present ? 1 : 0)); } else if (type==BCF_HT_INT) { for (uint32_t j=0; j<num; ++j) { if (j) fprintf(out, "\t"); int32_t val = bcf_get_info_int(h, v, info_tag_str[i].c_str()); fprintf(out, "%d", val); } } else if (type==BCF_HT_REAL) { for (uint32_t j=0; j<num; ++j) { if (j) fprintf(out, "\t"); float val = bcf_get_info_flt(h, v, info_tag_str[i].c_str()); fprintf(out, "%f", val); } } else if (type==BCF_HT_STR) { for (uint32_t j=0; j<num; ++j) { if (j) fprintf(out, "\t"); std::string val = bcf_get_info_str(h, v, info_tag_str[i].c_str()); fprintf(out, "%s", val.c_str()); } } } else if (vlen == BCF_VL_VAR) { } else if (vlen==BCF_VL_G) { } else if (vlen == BCF_VL_A) { } else if (vlen == BCF_VL_R) { } } fprintf(out, "\n"); ++no_variants; } if (output_text_file!="-") fclose(out); odr->close(); }; void print_options() { std::clog << "info2tab v" << version << "\n"; std::clog << "\n"; std::clog << "options: input VCF file " << input_vcf_file << "\n"; std::clog << " [o] output text file " << output_text_file << "\n"; print_boo_op(" [v] print variant ", print_variant); print_strvec(" [t] info tags ", info_tags); print_int_op(" [i] intervals ", intervals); std::clog << "\n"; } void print_stats() { std::clog << "\n"; std::clog << "stats: no. variants : " << no_variants << "\n"; std::clog << "\n"; }; ~Igor() {}; private: }; } void info2tab(int argc, char ** argv) { Igor igor(argc, argv); igor.print_options(); igor.initialize(); igor.info2tab(); igor.print_stats(); }; <commit_msg>fixed variant output<commit_after>/* The MIT License Copyright (c) 2016 Adrian Tan <atks@umich.edu> 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 "info2tab.h" namespace { class Igor : Program { public: /////////// //options// /////////// std::string input_vcf_file; std::string output_text_file; std::vector<GenomeInterval> intervals; std::vector<std::string> info_tags; bool print_variant; bool debug; /////// //i/o// /////// BCFOrderedReader *odr; ////////// //filter// ////////// std::string fexp; Filter filter; bool filter_exists; ///////// //stats// ///////// uint32_t no_variants; ///////// //tools// ///////// VariantManip *vm; Igor(int argc, char **argv) { version = "0.5"; ////////////////////////// //options initialization// ////////////////////////// try { std::string desc = "extracts info fields to a tab delimited file."; TCLAP::CmdLine cmd(desc, ' ', version); VTOutput my; cmd.setOutput(&my); TCLAP::ValueArg<std::string> arg_intervals("i", "i", "intervals []", false, "", "str", cmd); TCLAP::ValueArg<std::string> arg_interval_list("I", "I", "file containing list of intervals []", false, "", "file", cmd); TCLAP::ValueArg<std::string> arg_output_text_file("o", "o", "output tab delimited file [-]", false, "-", "str", cmd); TCLAP::ValueArg<std::string> arg_info_tags("t", "t", "list of info tags to be extracted []", true, "", "str", cmd); TCLAP::ValueArg<std::string> arg_fexp("f", "f", "filter expression []", false, "", "str", cmd); TCLAP::SwitchArg arg_debug("d", "d", "debug [false]", cmd, false); TCLAP::SwitchArg arg_print_variant("v", "v", "print variant CHROM,POS,REF,ALT,N_ALLELE [false]", cmd, false); TCLAP::UnlabeledValueArg<std::string> arg_input_vcf_file("<in.vcf>", "input VCF file", true, "","file", cmd); cmd.parse(argc, argv); input_vcf_file = arg_input_vcf_file.getValue(); output_text_file = arg_output_text_file.getValue(); fexp = arg_fexp.getValue(); std::cerr << arg_info_tags.getValue() << "\n"; parse_string_list(info_tags, arg_info_tags.getValue()); print_variant = arg_print_variant.getValue(); debug = arg_debug.getValue(); parse_intervals(intervals, arg_interval_list.getValue(), arg_intervals.getValue()); } catch (TCLAP::ArgException &e) { std::cerr << "error: " << e.error() << " for arg " << e.argId() << "\n"; abort(); } }; void initialize() { ////////////////////// //i/o initialization// ////////////////////// odr = new BCFOrderedReader(input_vcf_file, intervals); ///////////////////////// //filter initialization// ///////////////////////// filter.parse(fexp.c_str(), false); filter_exists = fexp=="" ? false : true; //////////////////////// //stats initialization// //////////////////////// no_variants = 0; //////////////////////// //tools initialization// //////////////////////// vm = new VariantManip(); } void info2tab() { bcf_hdr_t* h = odr->hdr; bcf1_t* v = bcf_init(); Variant variant; FILE *out = NULL; if (output_text_file=="-") { out = stdout; } else { out = fopen(output_text_file.c_str(), "w"); } //get the types of each info field std::vector<std::string> info_tag_str; std::vector<int32_t> info_tag_id; std::vector<int32_t> info_tag_vlen; std::vector<int32_t> info_tag_type; std::vector<int32_t> info_tag_num; if (print_variant) { fprintf(out, "CHROM\tPOS\tREF\tALT\tN_ALLELE\t"); } for (uint32_t i=0; i<info_tags.size(); ++i) { int32_t id = bcf_hdr_id2int(h, BCF_DT_ID, info_tags[i].c_str()); if (id==-1) { notice("%s info tag does not exist", info_tags[i].c_str()); continue; } int32_t vlen = bcf_hdr_id2length(h, BCF_HL_INFO, id); int32_t type = bcf_hdr_id2type(h, BCF_HL_INFO, id); int32_t num = bcf_hdr_id2number(h, BCF_HL_INFO, id); if (vlen==BCF_VL_FIXED) { info_tag_str.push_back(info_tags[i]); info_tag_id.push_back(id); info_tag_vlen.push_back(vlen); info_tag_type.push_back(type); info_tag_num.push_back(num); // notice("Adding id:%s, vlen=%s, type=%s, num=%d", // info_tag_str[i].c_str(), bcf_hdr_vl2str(vlen).c_str(), bcf_hdr_ht2str(type).c_str(), num); if (type==BCF_HT_FLAG) { if (info_tag_str.size()>0) fprintf(out, "\t"); fprintf(out, "%s", info_tags[i].c_str()); } else if (type==BCF_HT_INT) { for (uint32_t j=0; j<num; ++j) { if (info_tag_str.size()!=1 || j!=0) fprintf(out, "\t"); if (num>1) { fprintf(out, "%s_%d", info_tags[i].c_str(), j+1); } else { fprintf(out, "%s", info_tags[i].c_str()); } } } } else { notice("info2tab does not support id:%s, vlen=%s, type=%s, num=%d", info_tags[i].c_str(), bcf_hdr_vl2str(vlen).c_str(), bcf_hdr_ht2str(type).c_str(), num); } } fprintf(out, "\n"); while (odr->read(v)) { bcf_unpack(v, BCF_UN_INFO); if (filter_exists) { vm->classify_variant(h, v, variant); if (!filter.apply(h, v, &variant, false)) { continue; } } if (print_variant) { fprintf(out, "%s\t%d", bcf_get_chrom(h, v), bcf_get_pos1(v)); char** alleles = bcf_get_allele(v); fprintf(out, "\t%s", alleles[0]); int32_t no_alleles = bcf_get_n_allele(v); for (uint32_t i=1; i<no_alleles; ++i) { fprintf(out, "%c", i==1?'\t':','); fprintf(out, "%s", alleles[i]); } fprintf(out, "\t%d\t", no_alleles); } // bcf_print(h, v); for (uint32_t i=0; i<info_tag_str.size(); ++i) { if (i) { fprintf(out, "\t"); } int32_t id = info_tag_id[i]; int32_t vlen = info_tag_vlen[i]; int32_t type = info_tag_type[i]; int32_t num = info_tag_num[i]; // notice("processing id:%s, vlen=%s, type=%s, num=%d", // info_tag_str[i].c_str(), bcf_hdr_vl2str(vlen).c_str(), bcf_hdr_ht2str(type).c_str(), num); if (vlen==BCF_VL_FIXED) { if (type==BCF_HT_FLAG) { bool present = bcf_get_info_flg(h, v, info_tag_str[i].c_str()); fprintf(out, "%d", (present ? 1 : 0)); } else if (type==BCF_HT_INT) { for (uint32_t j=0; j<num; ++j) { if (j) fprintf(out, "\t"); int32_t val = bcf_get_info_int(h, v, info_tag_str[i].c_str()); fprintf(out, "%d", val); } } else if (type==BCF_HT_REAL) { for (uint32_t j=0; j<num; ++j) { if (j) fprintf(out, "\t"); float val = bcf_get_info_flt(h, v, info_tag_str[i].c_str()); fprintf(out, "%f", val); } } else if (type==BCF_HT_STR) { for (uint32_t j=0; j<num; ++j) { if (j) fprintf(out, "\t"); std::string val = bcf_get_info_str(h, v, info_tag_str[i].c_str()); fprintf(out, "%s", val.c_str()); } } } else if (vlen == BCF_VL_VAR) { } else if (vlen==BCF_VL_G) { } else if (vlen == BCF_VL_A) { } else if (vlen == BCF_VL_R) { } } fprintf(out, "\n"); ++no_variants; } if (output_text_file!="-") fclose(out); odr->close(); }; void print_options() { std::clog << "info2tab v" << version << "\n"; std::clog << "\n"; std::clog << "options: input VCF file " << input_vcf_file << "\n"; std::clog << " [o] output text file " << output_text_file << "\n"; print_boo_op(" [v] print variant ", print_variant); print_strvec(" [t] info tags ", info_tags); print_int_op(" [i] intervals ", intervals); std::clog << "\n"; } void print_stats() { std::clog << "\n"; std::clog << "stats: no. variants : " << no_variants << "\n"; std::clog << "\n"; }; ~Igor() {}; private: }; } void info2tab(int argc, char ** argv) { Igor igor(argc, argv); igor.print_options(); igor.initialize(); igor.info2tab(); igor.print_stats(); }; <|endoftext|>
<commit_before>/*******************************************************************************/ /* */ /* Copyright (c) 2007-2009: Peter Schregle, */ /* All rights reserved. */ /* */ /* This file is part of the Fixed Point Math Library. */ /* */ /* Redistribution of the Fixed Point Math Library 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 of Peter Schregle nor the names of other contributors */ /* may be used to endorse or promote products derived from this software */ /* without specific prior written permission. */ /* */ /* THIS SOFTWARE IS PROVIDED BY PETER SCHREGLE 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 PETER SCHREGLE 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 "../../include/fpml/fixed_point.h" #include "intrin.h" #include <iostream> /******************************************************************************/ /* */ /* cpu_clocks_32 */ /* */ /******************************************************************************/ /// Return the number of clocks since the processor was powered up. //! //! With modern processors there are a few gotchas related to this function. //! //! The function internally uses the RDTSC assembler instruction, which has the //! following limitations you should know about: //! - The timing information is locked to the cycle counter of the processor. //! - Dual core or multi core processors do not guarantee synchronization //! between cycle counters. //! - CPU frequency is not fixed. //! //! Nevertheless, the function is a good measurement tool if you want to judge //! the relative performance of an algorithm in some measurement such as //! clocks per pixel. //! //! \return The number of clocks since the processor was powered up. The //! result is returned in a 32 bit unsigned integer. It can count up to //! 4294967296 counts, which - on a 3 MHz CPU - translates to 1.3 seconds //! before it wraps. //! //! Wrap around may lead to incorrect measurements since the difference between //! a counter value and a wrapped around counter value is meaningless. With the //! 32bit counter wrap around occurs very often. inline unsigned int cpu_clocks_32() { // The RDTSC statement returns the number of clocks since the processor was // powered up in eax/edx. The intrinsic is used, because the 64bit compiler // does not support inline assembly, like: // _asm { // RDTSC // } // the return statement can be omitted, since the data is already in eax return (unsigned int)__rdtsc(); } int main() { std::cout << "Benchmark" << std::endl; std::cout << "---------" << std::endl << std::endl; std::cout << "Function\tfloat\tdouble\t15.16" << std::endl; int loops = 1000000; volatile int g; float af = 1.0; float bf = 2.0; float cf; unsigned __int64 start = cpu_clocks_32(); for (int i=0; i<loops; ++i) { g = 0; cf = af+bf; } double clocks_per_addition_float = (cpu_clocks_32() - start) / (double)loops; double ad = 1.0; double bd = 2.0; double cd; start = cpu_clocks_32(); for (int i=0; i<loops; ++i) { g = 0; cd = ad+bd; } double clocks_per_addition_double = (cpu_clocks_32() - start) / (double)loops; fpml::fixed_point<int, 15> afp = 1.0; fpml::fixed_point<int, 15> bfp = 2.0; fpml::fixed_point<int, 15> cfp; start = cpu_clocks_32(); for (int i=0; i<loops; ++i) { g = 0; cfp = afp+bfp; } double clocks_per_addition_fp15_16 = (cpu_clocks_32() - start) / (double)loops; std::cout << "Addition\t" << clocks_per_addition_float << "\t" << clocks_per_addition_double << "\t" << clocks_per_addition_fp15_16 << std::endl; start = cpu_clocks_32(); for (int i=0; i<loops; ++i) { g = 0; cf = af*bf; } double clocks_per_multiplication_float = (cpu_clocks_32() - start) / (double)loops; start = cpu_clocks_32(); for (int i=0; i<loops; ++i) { g = 0; cd = ad*bd; } double clocks_per_multiplication_double = (cpu_clocks_32() - start) / (double)loops; start = cpu_clocks_32(); for (int i=0; i<loops; ++i) { g = 0; cfp = afp*bfp; } double clocks_per_multiplication_fp15_16 = (cpu_clocks_32() - start) / (double)loops; std::cout << "Multiplication\t" << clocks_per_multiplication_float << "\t" << clocks_per_multiplication_double << "\t" << clocks_per_multiplication_fp15_16 << std::endl; start = cpu_clocks_32(); for (int i=0; i<loops; ++i) { g = 0; cf = af/bf; } double clocks_per_division_float = (cpu_clocks_32() - start) / (double)loops; start = cpu_clocks_32(); for (int i=0; i<loops; ++i) { g = 0; cd = ad/bd; } double clocks_per_division_double = (cpu_clocks_32() - start) / (double)loops; start = cpu_clocks_32(); for (int i=0; i<loops; ++i) { g = 0; cfp = afp/bfp; } double clocks_per_division_fp15_16 = (cpu_clocks_32() - start) / (double)loops; std::cout << "Division\t" << clocks_per_division_float << "\t" << clocks_per_division_double << "\t" << clocks_per_division_fp15_16 << std::endl; start = cpu_clocks_32(); for (int i=0; i<loops; ++i) { g = 0; cf = sqrt(af); } double clocks_per_sqrt_float = (cpu_clocks_32() - start) / (double)loops; start = cpu_clocks_32(); for (int i=0; i<loops; ++i) { g = 0; cd = sqrt(ad); } double clocks_per_sqrt_double = (cpu_clocks_32() - start) / (double)loops; start = cpu_clocks_32(); for (int i=0; i<loops; ++i) { g = 0; cfp = sqrt(afp); } double clocks_per_sqrt_fp15_16 = (cpu_clocks_32() - start) / (double)loops; std::cout << "Sqrt\t" << clocks_per_sqrt_float << "\t" << clocks_per_sqrt_double << "\t" << clocks_per_sqrt_fp15_16 << std::endl; start = cpu_clocks_32(); for (int i=0; i<loops; ++i) { g = 0; cf = sin(af); } double clocks_per_sine_float = (cpu_clocks_32() - start) / (double)loops; start = cpu_clocks_32(); for (int i=0; i<loops; ++i) { g = 0; cd = sin(ad); } double clocks_per_sine_double = (cpu_clocks_32() - start) / (double)loops; start = cpu_clocks_32(); for (int i=0; i<loops; ++i) { g = 0; cfp = sin(afp); } double clocks_per_sine_fp15_16 = (cpu_clocks_32() - start) / (double)loops; std::cout << "Sine\t" << clocks_per_sine_float << "\t" << clocks_per_sine_double << "\t" << clocks_per_sine_fp15_16 << std::endl; } <commit_msg>Porting to gcc.<commit_after>/*******************************************************************************/ /* */ /* Copyright (c) 2007-2009: Peter Schregle, */ /* All rights reserved. */ /* */ /* This file is part of the Fixed Point Math Library. */ /* */ /* Redistribution of the Fixed Point Math Library 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 of Peter Schregle nor the names of other contributors */ /* may be used to endorse or promote products derived from this software */ /* without specific prior written permission. */ /* */ /* THIS SOFTWARE IS PROVIDED BY PETER SCHREGLE 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 PETER SCHREGLE 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 "../../include/fpml/fixed_point.h" #include "intrin.h" #include <iostream> /******************************************************************************/ /* */ /* cpu_clocks_32 */ /* */ /******************************************************************************/ /// Return the number of clocks since the processor was powered up. //! //! With modern processors there are a few gotchas related to this function. //! //! The function internally uses the RDTSC assembler instruction, which has the //! following limitations you should know about: //! - The timing information is locked to the cycle counter of the processor. //! - Dual core or multi core processors do not guarantee synchronization //! between cycle counters. //! - CPU frequency is not fixed. //! //! Nevertheless, the function is a good measurement tool if you want to judge //! the relative performance of an algorithm in some measurement such as //! clocks per pixel. //! //! \return The number of clocks since the processor was powered up. The //! result is returned in a 32 bit unsigned integer. It can count up to //! 4294967296 counts, which - on a 3 MHz CPU - translates to 1.3 seconds //! before it wraps. //! //! Wrap around may lead to incorrect measurements since the difference between //! a counter value and a wrapped around counter value is meaningless. With the //! 32bit counter wrap around occurs very often. inline unsigned int cpu_clocks_32() { // The RDTSC statement returns the number of clocks since the processor was // powered up in eax/edx. The intrinsic is used, because the 64bit compiler // does not support inline assembly, like: // _asm { // RDTSC // } // the return statement can be omitted, since the data is already in eax return (unsigned int)__rdtsc(); } int main() { std::cout << "Benchmark" << std::endl; std::cout << "---------" << std::endl << std::endl; std::cout << "Function\tfloat\tdouble\t15.16" << std::endl; int loops = 1000000; volatile int g; float af = 1.0; float bf = 2.0; float cf; unsigned int start = cpu_clocks_32(); for (int i=0; i<loops; ++i) { g = 0; cf = af+bf; } double clocks_per_addition_float = (cpu_clocks_32() - start) / (double)loops; double ad = 1.0; double bd = 2.0; double cd; start = cpu_clocks_32(); for (int i=0; i<loops; ++i) { g = 0; cd = ad+bd; } double clocks_per_addition_double = (cpu_clocks_32() - start) / (double)loops; fpml::fixed_point<int, 15> afp = 1.0; fpml::fixed_point<int, 15> bfp = 2.0; fpml::fixed_point<int, 15> cfp; start = cpu_clocks_32(); for (int i=0; i<loops; ++i) { g = 0; cfp = afp+bfp; } double clocks_per_addition_fp15_16 = (cpu_clocks_32() - start) / (double)loops; std::cout << "Addition\t" << clocks_per_addition_float << "\t" << clocks_per_addition_double << "\t" << clocks_per_addition_fp15_16 << std::endl; start = cpu_clocks_32(); for (int i=0; i<loops; ++i) { g = 0; cf = af*bf; } double clocks_per_multiplication_float = (cpu_clocks_32() - start) / (double)loops; start = cpu_clocks_32(); for (int i=0; i<loops; ++i) { g = 0; cd = ad*bd; } double clocks_per_multiplication_double = (cpu_clocks_32() - start) / (double)loops; start = cpu_clocks_32(); for (int i=0; i<loops; ++i) { g = 0; cfp = afp*bfp; } double clocks_per_multiplication_fp15_16 = (cpu_clocks_32() - start) / (double)loops; std::cout << "Multiplication\t" << clocks_per_multiplication_float << "\t" << clocks_per_multiplication_double << "\t" << clocks_per_multiplication_fp15_16 << std::endl; start = cpu_clocks_32(); for (int i=0; i<loops; ++i) { g = 0; cf = af/bf; } double clocks_per_division_float = (cpu_clocks_32() - start) / (double)loops; start = cpu_clocks_32(); for (int i=0; i<loops; ++i) { g = 0; cd = ad/bd; } double clocks_per_division_double = (cpu_clocks_32() - start) / (double)loops; start = cpu_clocks_32(); for (int i=0; i<loops; ++i) { g = 0; cfp = afp/bfp; } double clocks_per_division_fp15_16 = (cpu_clocks_32() - start) / (double)loops; std::cout << "Division\t" << clocks_per_division_float << "\t" << clocks_per_division_double << "\t" << clocks_per_division_fp15_16 << std::endl; start = cpu_clocks_32(); for (int i=0; i<loops; ++i) { g = 0; cf = sqrt(af); } double clocks_per_sqrt_float = (cpu_clocks_32() - start) / (double)loops; start = cpu_clocks_32(); for (int i=0; i<loops; ++i) { g = 0; cd = sqrt(ad); } double clocks_per_sqrt_double = (cpu_clocks_32() - start) / (double)loops; start = cpu_clocks_32(); for (int i=0; i<loops; ++i) { g = 0; cfp = sqrt(afp); } double clocks_per_sqrt_fp15_16 = (cpu_clocks_32() - start) / (double)loops; std::cout << "Sqrt\t" << clocks_per_sqrt_float << "\t" << clocks_per_sqrt_double << "\t" << clocks_per_sqrt_fp15_16 << std::endl; start = cpu_clocks_32(); for (int i=0; i<loops; ++i) { g = 0; cf = sin(af); } double clocks_per_sine_float = (cpu_clocks_32() - start) / (double)loops; start = cpu_clocks_32(); for (int i=0; i<loops; ++i) { g = 0; cd = sin(ad); } double clocks_per_sine_double = (cpu_clocks_32() - start) / (double)loops; start = cpu_clocks_32(); for (int i=0; i<loops; ++i) { g = 0; cfp = sin(afp); } double clocks_per_sine_fp15_16 = (cpu_clocks_32() - start) / (double)loops; std::cout << "Sine\t" << clocks_per_sine_float << "\t" << clocks_per_sine_double << "\t" << clocks_per_sine_fp15_16 << std::endl; } <|endoftext|>
<commit_before>/* This file is part of the Grantlee template system. Copyright (c) 2009 Stephen Kelly <steveire@gmail.com> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License version 3 only, 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 version 3 for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see <http://www.gnu.org/licenses/>. */ #include "filterexpression.h" #include "parser.h" #include "grantlee.h" #include "filter.h" #include "util_p.h" namespace Grantlee { class FilterExpressionPrivate { FilterExpressionPrivate( FilterExpression *fe ) : q_ptr( fe ) { } Variable m_variable; QList<ArgFilter> m_filters; QStringList m_filterNames; Q_DECLARE_PUBLIC( FilterExpression ) FilterExpression *q_ptr; }; } static const char * FILTER_SEPARATOR = "|"; static const char * FILTER_ARGUMENT_SEPARATOR = ":"; static const char * VARIABLE_ATTRIBUTE_SEPARATOR = "."; static const char * ALLOWED_VARIABLE_CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_\\."; static const char * varChars = "\\w\\." ; static const char * numChars = "[-+\\.]?\\d[\\d\\.e]*"; static const QString filterSep( QRegExp::escape( FILTER_SEPARATOR ) ); static const QString argSep( QRegExp::escape( FILTER_ARGUMENT_SEPARATOR ) ); static const QString i18nOpen( QRegExp::escape( "_(" ) ); static const QString i18nClose( QRegExp::escape( ")" ) ); static const QString constantString = QString( "(?:%3%1%4|" "%3%2%4|" "%1|" "%2)" ) .arg( "\"[^\"\\\\]*(?:\\\\.[^\"\\\\]*)*\"" ) .arg( "\'[^\'\\\\]*(?:\\\\.[^\'\\\\]*)*\'" ) .arg( i18nOpen ) .arg( i18nClose ); static const QString filterRawString = QString( "^%1|" /* Match "strings" and 'strings' incl i18n */ "^[%2]+|" /* Match variables */ "%3|" /* Match numbers */ "%4\\w+|" /* Match filters */ "%5(?:%1|[%2]+|%3|%4\\w+)" /* Match arguments to filters, which may be strings, */ ) /* variables, numbers or another filter in the chain */ /* 1 */ .arg( constantString ) /* 2 */ .arg( varChars ) /* 3 */ .arg( numChars ) /* 4 */ .arg( filterSep ) /* 5 */ .arg( argSep ); static const QRegExp sFilterRe( filterRawString ); FilterExpression::FilterExpression( const QString &varString, Parser *parser ) : d_ptr( new FilterExpressionPrivate( this ) ) { Q_D( FilterExpression ); int pos = 0; int lastPos = 0; int len; QString subString; QString vs = varString; while ( ( pos = sFilterRe.indexIn( vs, pos ) ) != -1 ) { len = sFilterRe.matchedLength(); subString = vs.mid( pos, len ); int ssSize = subString.size(); if ( pos != lastPos ) { throw Grantlee::Exception( TagSyntaxError, QString( "Could not parse some characters: \"%1\"" ).arg( vs.mid( lastPos, pos ) ) ); } if ( subString.startsWith( FILTER_SEPARATOR ) ) { subString = subString.right( ssSize - 1 ); Filter *f = parser->getFilter( subString ); Q_ASSERT( f ); d->m_filterNames << subString; d->m_filters << qMakePair<Filter*, Variable>( f, Variable() ); } else if ( subString.startsWith( FILTER_ARGUMENT_SEPARATOR ) ) { subString = subString.right( ssSize - 1 ); int lastFilter = d->m_filters.size(); if ( subString.isEmpty() ) throw Grantlee::Exception( EmptyVariableError, QString( "Missing argument to filter: %1" ).arg( d->m_filterNames[lastFilter -1] ) ); d->m_filters[lastFilter -1].second = Variable( subString ); } else { if ( subString.contains( "._" ) || ( subString.startsWith( "_" ) && !subString.startsWith( "_(" ) ) ) { throw Grantlee::Exception( TagSyntaxError, QString( "Variables and attributes may not begin with underscores: %1" ).arg( subString ) ); } // Token is _("translated"), or "constant", or a variable; d->m_variable = Variable( subString ); } pos += len; lastPos = pos; } QString remainder = vs.right( vs.size() - lastPos ); if ( !remainder.isEmpty() ) { throw Grantlee::Exception( TagSyntaxError, QString( "Could not parse the remainder, %1 from %2" ).arg( remainder ).arg( varString ) ); } } FilterExpression::FilterExpression( const FilterExpression &other ) : d_ptr( new FilterExpressionPrivate( this ) ) { d_ptr->m_variable = other.d_ptr->m_variable; d_ptr->m_filters = other.d_ptr->m_filters; } FilterExpression::FilterExpression() : d_ptr( new FilterExpressionPrivate( this ) ) { Q_D( FilterExpression ); } bool FilterExpression::isValid() const { Q_D( const FilterExpression ); return d->m_variable.isValid(); } FilterExpression::~FilterExpression() { delete d_ptr; } Variable FilterExpression::variable() const { Q_D( const FilterExpression ); return d->m_variable; } FilterExpression &FilterExpression::operator=( const FilterExpression & other ) { d_ptr->m_variable = other.d_ptr->m_variable; d_ptr->m_filters = other.d_ptr->m_filters; return *this; } QVariant FilterExpression::resolve( Context *c ) const { Q_D( const FilterExpression ); QVariant var = d->m_variable.resolve( c ); foreach( ArgFilter argfilter, d->m_filters ) { Filter *filter = argfilter.first; Variable argVar = argfilter.second; QVariant arg = argVar.resolve( c ); Grantlee::SafeString argString; if ( arg.userType() == qMetaTypeId<Grantlee::SafeString>() ) { argString = arg.value<Grantlee::SafeString>(); } else if ( arg.canConvert( QVariant::String ) ) { arg.convert( QVariant::String ); argString = Grantlee::SafeString( arg.toString() ); } else if ( arg.isValid() ) { throw Grantlee::Exception( TagSyntaxError, "Argument to Filter must be string-like" ); } Grantlee::SafeString nextVar; if ( argVar.isConstant() ) { argString = Util::markSafe( argString ); } if ( filter->needsAutoescape() ) { nextVar = filter->doFilter( var, argString, c->autoescape() ); } else { nextVar = filter->doFilter( var, argString ); } if ( filter->isSafe() && argString.isSafe() ) { var = QVariant::fromValue<Grantlee::SafeString>( Util::markSafe( nextVar ) ); } else if ( argString.needsEscape() ) { var = QVariant::fromValue<Grantlee::SafeString>( Util::markForEscaping( nextVar ) ); } else { var = QVariant::fromValue<Grantlee::SafeString>( nextVar ); } } return var; } QVariantList FilterExpression::toList( Context *c ) const { QVariant var = resolve( c ); return Util::variantToList( var ); } bool FilterExpression::isTrue( Context *c ) const { return Util::variantIsTrue( resolve( c ) ); } bool FilterExpression::isConstant() const { Q_D( const FilterExpression ); return d->m_variable.isConstant(); } QStringList FilterExpression::filters() const { Q_D( const FilterExpression ); return d->m_filterNames; } <commit_msg>Examine the correct variable when deciding whether to mark a string for escaping or as safe.<commit_after>/* This file is part of the Grantlee template system. Copyright (c) 2009 Stephen Kelly <steveire@gmail.com> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License version 3 only, 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 version 3 for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see <http://www.gnu.org/licenses/>. */ #include "filterexpression.h" #include "parser.h" #include "grantlee.h" #include "filter.h" #include "util_p.h" namespace Grantlee { class FilterExpressionPrivate { FilterExpressionPrivate( FilterExpression *fe ) : q_ptr( fe ) { } Variable m_variable; QList<ArgFilter> m_filters; QStringList m_filterNames; Q_DECLARE_PUBLIC( FilterExpression ) FilterExpression *q_ptr; }; } static const char * FILTER_SEPARATOR = "|"; static const char * FILTER_ARGUMENT_SEPARATOR = ":"; static const char * VARIABLE_ATTRIBUTE_SEPARATOR = "."; static const char * ALLOWED_VARIABLE_CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_\\."; static const char * varChars = "\\w\\." ; static const char * numChars = "[-+\\.]?\\d[\\d\\.e]*"; static const QString filterSep( QRegExp::escape( FILTER_SEPARATOR ) ); static const QString argSep( QRegExp::escape( FILTER_ARGUMENT_SEPARATOR ) ); static const QString i18nOpen( QRegExp::escape( "_(" ) ); static const QString i18nClose( QRegExp::escape( ")" ) ); static const QString constantString = QString( "(?:%3%1%4|" "%3%2%4|" "%1|" "%2)" ) .arg( "\"[^\"\\\\]*(?:\\\\.[^\"\\\\]*)*\"" ) .arg( "\'[^\'\\\\]*(?:\\\\.[^\'\\\\]*)*\'" ) .arg( i18nOpen ) .arg( i18nClose ); static const QString filterRawString = QString( "^%1|" /* Match "strings" and 'strings' incl i18n */ "^[%2]+|" /* Match variables */ "%3|" /* Match numbers */ "%4\\w+|" /* Match filters */ "%5(?:%1|[%2]+|%3|%4\\w+)" /* Match arguments to filters, which may be strings, */ ) /* variables, numbers or another filter in the chain */ /* 1 */ .arg( constantString ) /* 2 */ .arg( varChars ) /* 3 */ .arg( numChars ) /* 4 */ .arg( filterSep ) /* 5 */ .arg( argSep ); static const QRegExp sFilterRe( filterRawString ); FilterExpression::FilterExpression( const QString &varString, Parser *parser ) : d_ptr( new FilterExpressionPrivate( this ) ) { Q_D( FilterExpression ); int pos = 0; int lastPos = 0; int len; QString subString; QString vs = varString; while ( ( pos = sFilterRe.indexIn( vs, pos ) ) != -1 ) { len = sFilterRe.matchedLength(); subString = vs.mid( pos, len ); int ssSize = subString.size(); if ( pos != lastPos ) { throw Grantlee::Exception( TagSyntaxError, QString( "Could not parse some characters: \"%1\"" ).arg( vs.mid( lastPos, pos ) ) ); } if ( subString.startsWith( FILTER_SEPARATOR ) ) { subString = subString.right( ssSize - 1 ); Filter *f = parser->getFilter( subString ); Q_ASSERT( f ); d->m_filterNames << subString; d->m_filters << qMakePair<Filter*, Variable>( f, Variable() ); } else if ( subString.startsWith( FILTER_ARGUMENT_SEPARATOR ) ) { subString = subString.right( ssSize - 1 ); int lastFilter = d->m_filters.size(); if ( subString.isEmpty() ) throw Grantlee::Exception( EmptyVariableError, QString( "Missing argument to filter: %1" ).arg( d->m_filterNames[lastFilter -1] ) ); d->m_filters[lastFilter -1].second = Variable( subString ); } else { if ( subString.contains( "._" ) || ( subString.startsWith( "_" ) && !subString.startsWith( "_(" ) ) ) { throw Grantlee::Exception( TagSyntaxError, QString( "Variables and attributes may not begin with underscores: %1" ).arg( subString ) ); } // Token is _("translated"), or "constant", or a variable; d->m_variable = Variable( subString ); } pos += len; lastPos = pos; } QString remainder = vs.right( vs.size() - lastPos ); if ( !remainder.isEmpty() ) { throw Grantlee::Exception( TagSyntaxError, QString( "Could not parse the remainder, %1 from %2" ).arg( remainder ).arg( varString ) ); } } FilterExpression::FilterExpression( const FilterExpression &other ) : d_ptr( new FilterExpressionPrivate( this ) ) { d_ptr->m_variable = other.d_ptr->m_variable; d_ptr->m_filters = other.d_ptr->m_filters; } FilterExpression::FilterExpression() : d_ptr( new FilterExpressionPrivate( this ) ) { Q_D( FilterExpression ); } bool FilterExpression::isValid() const { Q_D( const FilterExpression ); return d->m_variable.isValid(); } FilterExpression::~FilterExpression() { delete d_ptr; } Variable FilterExpression::variable() const { Q_D( const FilterExpression ); return d->m_variable; } FilterExpression &FilterExpression::operator=( const FilterExpression & other ) { d_ptr->m_variable = other.d_ptr->m_variable; d_ptr->m_filters = other.d_ptr->m_filters; return *this; } QVariant FilterExpression::resolve( Context *c ) const { Q_D( const FilterExpression ); QVariant var = d->m_variable.resolve( c ); foreach( ArgFilter argfilter, d->m_filters ) { Filter *filter = argfilter.first; Variable argVar = argfilter.second; QVariant arg = argVar.resolve( c ); Grantlee::SafeString argString; SafeString varString = Util::getSafeString( var ); if ( arg.userType() == qMetaTypeId<Grantlee::SafeString>() ) { argString = arg.value<Grantlee::SafeString>(); } else if ( arg.canConvert( QVariant::String ) ) { arg.convert( QVariant::String ); argString = Grantlee::SafeString( arg.toString() ); } else if ( arg.isValid() ) { throw Grantlee::Exception( TagSyntaxError, "Argument to Filter must be string-like" ); } Grantlee::SafeString nextVar; if ( argVar.isConstant() ) { argString = Util::markSafe( argString ); } if ( filter->needsAutoescape() ) { nextVar = filter->doFilter( var, argString, c->autoescape() ); } else { nextVar = filter->doFilter( var, argString ); } if ( filter->isSafe() && varString.isSafe() ) { var = QVariant::fromValue<Grantlee::SafeString>( Util::markSafe( nextVar ) ); } else if ( varString.needsEscape() ) { var = QVariant::fromValue<Grantlee::SafeString>( Util::markForEscaping( nextVar ) ); } else { var = QVariant::fromValue<Grantlee::SafeString>( nextVar ); } } return var; } QVariantList FilterExpression::toList( Context *c ) const { QVariant var = resolve( c ); return Util::variantToList( var ); } bool FilterExpression::isTrue( Context *c ) const { return Util::variantIsTrue( resolve( c ) ); } bool FilterExpression::isConstant() const { Q_D( const FilterExpression ); return d->m_variable.isConstant(); } QStringList FilterExpression::filters() const { Q_D( const FilterExpression ); return d->m_filterNames; } <|endoftext|>
<commit_before>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "operator.h" #include <vespa/vespalib/util/regexp.h> #include <vespa/vespalib/stllike/asciistream.h> #include <vespa/vespalib/stllike/hash_map.hpp> #include <cassert> #include <vespa/log/log.h> LOG_SETUP(".document.select.operator"); namespace document::select { Operator::OperatorMap Operator::_operators; Operator::Operator(vespalib::stringref name) : _name(name) { OperatorMap::iterator it = _operators.find(name); if (it != _operators.end()) { LOG_ABORT("unknown operator, should not happen"); } _operators[_name] = this; } const Operator& Operator::get(vespalib::stringref name) { OperatorMap::iterator it = _operators.find(name); if (it == _operators.end()) { LOG_ABORT("unknown operator, should not happen"); } return *it->second; } void Operator::print(std::ostream& out, bool verbose, const std::string& indent) const { (void) verbose; (void) indent; out << _name; } ResultList FunctionOperator::compare(const Value& a, const Value& b) const { return (a.*_comparator)(b); } ResultList FunctionOperator::trace(const Value& a, const Value& b, std::ostream& out) const { ResultList result = (a.*_comparator)(b); out << "Operator(" << getName() << ") - Result was " << result << ".\n"; return result; } const FunctionOperator FunctionOperator::GT(">", &Value::operator>); const FunctionOperator FunctionOperator::GEQ(">=", &Value::operator>=); const FunctionOperator FunctionOperator::EQ("==", &Value::operator==); const FunctionOperator FunctionOperator::LEQ("<=", &Value::operator<=); const FunctionOperator FunctionOperator::LT("<", &Value::operator<); const FunctionOperator FunctionOperator::NE("!=", &Value::operator!=); RegexOperator::RegexOperator(vespalib::stringref name) : Operator(name) { } ResultList RegexOperator::compare(const Value& a, const Value& b) const { return a.regexCompare(b); } ResultList RegexOperator::trace(const Value& a, const Value& b, std::ostream& out) const { return a.regexTrace(b, out); } ResultList RegexOperator::compareImpl(const Value& a, const Value& b) const { const StringValue* left(dynamic_cast<const StringValue*>(&a)); const StringValue* right(dynamic_cast<const StringValue*>(&b)); if (left == 0 || right == 0) return ResultList(Result::Invalid); return match(left->getValue(), right->getValue()); } ResultList RegexOperator::traceImpl(const Value& a, const Value& b, std::ostream& out) const { const StringValue* left(dynamic_cast<const StringValue*>(&a)); const StringValue* right(dynamic_cast<const StringValue*>(&b)); if (left == 0) { out << "Operator(" << getName() << ") - Left value not a string. " << "Returning invalid.\n"; return ResultList(Result::Invalid); } if (right == 0) { out << "Operator(" << getName() << ") - Right value not a string. " << "Returning invalid.\n"; return ResultList(Result::Invalid); } ResultList result = match(left->getValue(), right->getValue()); out << "Operator(" << getName() << ")(" << left->getValue() << ", " << right->getValue() << ") - Result was " << result << "\n"; return result; } ResultList RegexOperator::match(const vespalib::string& val, vespalib::stringref expr) const { // Should we catch this in parsing? if (expr.size() == 0) return ResultList(Result::True); vespalib::Regexp expression(expr); return ResultList(Result::get(expression.match(val))); } const RegexOperator RegexOperator::REGEX("=~"); GlobOperator::GlobOperator(vespalib::stringref name) : RegexOperator(name) { } ResultList GlobOperator::compare(const Value& a, const Value& b) const { return a.globCompare(b); } ResultList GlobOperator::trace(const Value& a, const Value& b, std::ostream& out) const { return a.globTrace(b, out); } ResultList GlobOperator::compareImpl(const Value& a, const Value& b) const { const StringValue* right(dynamic_cast<const StringValue*>(&b)); // Fall back to operator== if it isn't string matching if (right == 0) { return FunctionOperator::EQ.compare(a, b); } const StringValue* left(dynamic_cast<const StringValue*>(&a)); if (left == 0) return ResultList(Result::Invalid); vespalib::string regex(convertToRegex(right->getValue())); return match(left->getValue(), regex); } ResultList GlobOperator::traceImpl(const Value& a, const Value& b, std::ostream& ost) const { const StringValue* right(dynamic_cast<const StringValue*>(&b)); // Fall back to operator== if it isn't string matching if (right == 0) { ost << "Operator(" << getName() << ") - Right val not a string, " << "falling back to == behavior.\n"; return FunctionOperator::EQ.trace(a, b, ost); } const StringValue* left(dynamic_cast<const StringValue*>(&a)); if (left == 0) { ost << "Operator(" << getName() << ") - Left value is not a string, " << "returning invalid.\n"; return ResultList(Result::Invalid); } vespalib::string regex(convertToRegex(right->getValue())); ost << "Operator(" << getName() << ") - Converted glob expression '" << right->getValue() << "' to regex '" << regex << "'.\n"; return match(left->getValue(), regex); } vespalib::string GlobOperator::convertToRegex(vespalib::stringref globpattern) const { vespalib::asciistream ost; ost << '^'; for(uint32_t i=0, n=globpattern.size(); i<n; ++i) { switch(globpattern[i]) { case '*': ost << ".*"; break; case '?': ost << "."; break; case '^': case '$': case '|': case '{': case '}': case '(': case ')': case '[': case ']': case '\\': case '+': case '.': ost << '\\' << globpattern[i]; break; // Are there other regex special chars we need to escape? default: ost << globpattern[i]; } } ost << '$'; return ost.str(); } bool GlobOperator::containsVariables(vespalib::stringref expression) { for (size_t i=0, n=expression.size(); i<n; ++i) { if (expression[i] == '*' || expression[i] == '?') { return true; } } return false; } const GlobOperator GlobOperator::GLOB("="); } <commit_msg>Use std::basic_regex in document module.<commit_after>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "operator.h" #include <regex> #include <vespa/vespalib/stllike/asciistream.h> #include <vespa/vespalib/stllike/hash_map.hpp> #include <cassert> #include <vespa/log/log.h> LOG_SETUP(".document.select.operator"); namespace document::select { Operator::OperatorMap Operator::_operators; Operator::Operator(vespalib::stringref name) : _name(name) { OperatorMap::iterator it = _operators.find(name); if (it != _operators.end()) { LOG_ABORT("unknown operator, should not happen"); } _operators[_name] = this; } const Operator& Operator::get(vespalib::stringref name) { OperatorMap::iterator it = _operators.find(name); if (it == _operators.end()) { LOG_ABORT("unknown operator, should not happen"); } return *it->second; } void Operator::print(std::ostream& out, bool verbose, const std::string& indent) const { (void) verbose; (void) indent; out << _name; } ResultList FunctionOperator::compare(const Value& a, const Value& b) const { return (a.*_comparator)(b); } ResultList FunctionOperator::trace(const Value& a, const Value& b, std::ostream& out) const { ResultList result = (a.*_comparator)(b); out << "Operator(" << getName() << ") - Result was " << result << ".\n"; return result; } const FunctionOperator FunctionOperator::GT(">", &Value::operator>); const FunctionOperator FunctionOperator::GEQ(">=", &Value::operator>=); const FunctionOperator FunctionOperator::EQ("==", &Value::operator==); const FunctionOperator FunctionOperator::LEQ("<=", &Value::operator<=); const FunctionOperator FunctionOperator::LT("<", &Value::operator<); const FunctionOperator FunctionOperator::NE("!=", &Value::operator!=); RegexOperator::RegexOperator(vespalib::stringref name) : Operator(name) { } ResultList RegexOperator::compare(const Value& a, const Value& b) const { return a.regexCompare(b); } ResultList RegexOperator::trace(const Value& a, const Value& b, std::ostream& out) const { return a.regexTrace(b, out); } ResultList RegexOperator::compareImpl(const Value& a, const Value& b) const { const StringValue* left(dynamic_cast<const StringValue*>(&a)); const StringValue* right(dynamic_cast<const StringValue*>(&b)); if (left == 0 || right == 0) return ResultList(Result::Invalid); return match(left->getValue(), right->getValue()); } ResultList RegexOperator::traceImpl(const Value& a, const Value& b, std::ostream& out) const { const StringValue* left(dynamic_cast<const StringValue*>(&a)); const StringValue* right(dynamic_cast<const StringValue*>(&b)); if (left == 0) { out << "Operator(" << getName() << ") - Left value not a string. " << "Returning invalid.\n"; return ResultList(Result::Invalid); } if (right == 0) { out << "Operator(" << getName() << ") - Right value not a string. " << "Returning invalid.\n"; return ResultList(Result::Invalid); } ResultList result = match(left->getValue(), right->getValue()); out << "Operator(" << getName() << ")(" << left->getValue() << ", " << right->getValue() << ") - Result was " << result << "\n"; return result; } ResultList RegexOperator::match(const vespalib::string& val, vespalib::stringref expr) const { // Should we catch this in parsing? if (expr.size() == 0) return ResultList(Result::True); try { std::basic_regex<char> expression(expr.data(), expr.size()); return ResultList(Result::get(std::regex_search(val.c_str(), val.c_str() + val.size(), expression))); } catch (std::regex_error &) { return ResultList(Result::False); } } const RegexOperator RegexOperator::REGEX("=~"); GlobOperator::GlobOperator(vespalib::stringref name) : RegexOperator(name) { } ResultList GlobOperator::compare(const Value& a, const Value& b) const { return a.globCompare(b); } ResultList GlobOperator::trace(const Value& a, const Value& b, std::ostream& out) const { return a.globTrace(b, out); } ResultList GlobOperator::compareImpl(const Value& a, const Value& b) const { const StringValue* right(dynamic_cast<const StringValue*>(&b)); // Fall back to operator== if it isn't string matching if (right == 0) { return FunctionOperator::EQ.compare(a, b); } const StringValue* left(dynamic_cast<const StringValue*>(&a)); if (left == 0) return ResultList(Result::Invalid); vespalib::string regex(convertToRegex(right->getValue())); return match(left->getValue(), regex); } ResultList GlobOperator::traceImpl(const Value& a, const Value& b, std::ostream& ost) const { const StringValue* right(dynamic_cast<const StringValue*>(&b)); // Fall back to operator== if it isn't string matching if (right == 0) { ost << "Operator(" << getName() << ") - Right val not a string, " << "falling back to == behavior.\n"; return FunctionOperator::EQ.trace(a, b, ost); } const StringValue* left(dynamic_cast<const StringValue*>(&a)); if (left == 0) { ost << "Operator(" << getName() << ") - Left value is not a string, " << "returning invalid.\n"; return ResultList(Result::Invalid); } vespalib::string regex(convertToRegex(right->getValue())); ost << "Operator(" << getName() << ") - Converted glob expression '" << right->getValue() << "' to regex '" << regex << "'.\n"; return match(left->getValue(), regex); } vespalib::string GlobOperator::convertToRegex(vespalib::stringref globpattern) const { vespalib::asciistream ost; ost << '^'; for(uint32_t i=0, n=globpattern.size(); i<n; ++i) { switch(globpattern[i]) { case '*': ost << ".*"; break; case '?': ost << "."; break; case '^': case '$': case '|': case '{': case '}': case '(': case ')': case '[': case ']': case '\\': case '+': case '.': ost << '\\' << globpattern[i]; break; // Are there other regex special chars we need to escape? default: ost << globpattern[i]; } } ost << '$'; return ost.str(); } bool GlobOperator::containsVariables(vespalib::stringref expression) { for (size_t i=0, n=expression.size(); i<n; ++i) { if (expression[i] == '*' || expression[i] == '?') { return true; } } return false; } const GlobOperator GlobOperator::GLOB("="); } <|endoftext|>
<commit_before>// Convert DMD CodeView debug information to PDB files // Copyright (c) 2009-2010 by Rainer Schuetze, All Rights Reserved // // License for redistribution is given by the Artistic License 2.0 // see file LICENSE for further details #include "mspdb.h" #include <windows.h> #pragma comment(lib, "rpcrt4.lib") HMODULE modMsPdb; mspdb::fnPDBOpen2W *pPDBOpen2W; char* mspdb80_dll = "mspdb80.dll"; char* mspdb100_dll = "mspdb100.dll"; char* mspdb110_dll = "mspdb110.dll"; char* mspdb120_dll = "mspdb120.dll"; char* mspdb140_dll = "mspdb140.dll"; // char* mspdb110shell_dll = "mspdbst.dll"; // the VS 2012 Shell uses this file instead of mspdb110.dll, but is missing mspdbsrv.exe int mspdb::vsVersion = 8; // verify mspdbsrv.exe is found in the same path void tryLoadLibrary(const char* mspdb) { if (modMsPdb) return; modMsPdb = LoadLibraryA(mspdb); if (!modMsPdb) return; char modpath[260]; if(GetModuleFileNameA(modMsPdb, modpath, 260) < 260) { char* p = modpath + strlen(modpath); while(p > modpath && p[-1] != '\\') p--; strcpy(p, "mspdbsrv.exe"); if(GetFileAttributesA(modpath) != INVALID_FILE_ATTRIBUTES) return; } FreeLibrary(modMsPdb); modMsPdb = NULL; } bool getInstallDir(const char* version, char* installDir, DWORD size) { char key[260] = "SOFTWARE\\Microsoft\\"; strcat(key, version); HKEY hkey; if (RegOpenKeyExA(HKEY_LOCAL_MACHINE, key, 0, KEY_QUERY_VALUE #if _M_X64 | KEY_WOW64_32KEY #endif , &hkey) != ERROR_SUCCESS) return false; bool rc = RegQueryValueExA(hkey, "InstallDir", 0, 0, (LPBYTE)installDir, &size) == ERROR_SUCCESS; RegCloseKey(hkey); return rc; } bool tryLoadMsPdb(const char* version, const char* mspdb, const char* path = 0) { char installDir[260]; if (!getInstallDir(version, installDir, sizeof(installDir))) return false; char* p = installDir + strlen(installDir); if (p[-1] != '\\' && p[-1] != '/') *p++ = '\\'; if(path) p += strlen(strcpy(p, path)); #ifdef _M_X64 p += strlen(strcpy(p, "amd64\\")); #endif strcpy(p, mspdb); tryLoadLibrary(installDir); return modMsPdb != 0; } void tryLoadMsPdb80(bool throughPath) { if (!modMsPdb && throughPath) tryLoadLibrary(mspdb80_dll); if (!modMsPdb && !throughPath) tryLoadMsPdb("VisualStudio\\9.0", mspdb80_dll); if (!modMsPdb && !throughPath) tryLoadMsPdb("VisualStudio\\8.0", mspdb80_dll); if (!modMsPdb && !throughPath) tryLoadMsPdb("VCExpress\\9.0", mspdb80_dll); if (!modMsPdb && !throughPath) tryLoadMsPdb("VCExpress\\8.0", mspdb80_dll); } void tryLoadMsPdb100(bool throughPath) { if (!modMsPdb) { if(throughPath) modMsPdb = LoadLibraryA(mspdb100_dll); if (!modMsPdb && !throughPath) tryLoadMsPdb("VisualStudio\\10.0", mspdb100_dll); if (!modMsPdb && !throughPath) tryLoadMsPdb("VCExpress\\10.0", mspdb100_dll); if (modMsPdb) mspdb::vsVersion = 10; } } void tryLoadMsPdb110(bool throughPath) { if (!modMsPdb) { if (throughPath) modMsPdb = LoadLibraryA(mspdb110_dll); if (!modMsPdb && !throughPath) tryLoadMsPdb("VisualStudio\\11.0", mspdb110_dll); if (!modMsPdb && !throughPath) tryLoadMsPdb("VSWinExpress\\11.0", mspdb110_dll); if (modMsPdb) mspdb::vsVersion = 11; } } void tryLoadMsPdb120(bool throughPath) { if (!modMsPdb) { if(throughPath) modMsPdb = LoadLibraryA(mspdb120_dll); if (!modMsPdb && !throughPath) tryLoadMsPdb("VisualStudio\\12.0", mspdb120_dll, "..\\..\\VC\\bin\\"); if (!modMsPdb && !throughPath) tryLoadMsPdb("VSWinExpress\\12.0", mspdb120_dll, "..\\..\\VC\\bin\\"); if (modMsPdb) mspdb::vsVersion = 12; } } void tryLoadMsPdb140(bool throughPath) { if (!modMsPdb) { if(throughPath) modMsPdb = LoadLibraryA(mspdb140_dll); if (!modMsPdb && !throughPath) tryLoadMsPdb("VisualStudio\\14.0", mspdb140_dll, "..\\..\\VC\\bin\\"); if (!modMsPdb && !throughPath) tryLoadMsPdb("VSWinExpress\\14.0", mspdb140_dll, "..\\..\\VC\\bin\\"); if (modMsPdb) mspdb::vsVersion = 14; } } bool initMsPdb() { #if 0 // might cause problems when combining VS Shell 2010 with VS 2008 or similar if(const char* p = getenv("VisualStudioDir")) { // guess from environment variable from which version of VS we are invoked and prefer a correspondig mspdb DLL if (strstr(p, "2010")) tryLoadMsPdb100(); if (strstr(p, "2012")) tryLoadMsPdb110(); // VS2008 tried next anyway } #endif // try loading through the PATH first to best match current setup tryLoadMsPdb140(true); tryLoadMsPdb120(true); tryLoadMsPdb110(true); tryLoadMsPdb100(true); tryLoadMsPdb80(true); tryLoadMsPdb140(false); tryLoadMsPdb120(false); tryLoadMsPdb110(false); tryLoadMsPdb100(false); tryLoadMsPdb80(false); if (!modMsPdb) return false; if (!pPDBOpen2W) pPDBOpen2W = (mspdb::fnPDBOpen2W*) GetProcAddress(modMsPdb, "PDBOpen2W"); if (!pPDBOpen2W) return false; return true; } bool exitMsPdb() { pPDBOpen2W = 0; if (modMsPdb) FreeLibrary(modMsPdb); modMsPdb = 0; return true; } mspdb::PDB* CreatePDB(const wchar_t* pdbname) { if (!initMsPdb ()) return 0; mspdb::PDB* pdb = 0; long data[194] = { 193, 0 }; wchar_t ext[256] = L".exe"; if (!((*pPDBOpen2W) (pdbname, "wf", data, ext, 0x400, &pdb))) return 0; return pdb; } <commit_msg>fixes #11 (fix for different paths on older VS versions on amd64)<commit_after>// Convert DMD CodeView debug information to PDB files // Copyright (c) 2009-2010 by Rainer Schuetze, All Rights Reserved // // License for redistribution is given by the Artistic License 2.0 // see file LICENSE for further details #include "mspdb.h" #include <windows.h> #pragma comment(lib, "rpcrt4.lib") HMODULE modMsPdb; mspdb::fnPDBOpen2W *pPDBOpen2W; char* mspdb80_dll = "mspdb80.dll"; char* mspdb100_dll = "mspdb100.dll"; char* mspdb110_dll = "mspdb110.dll"; char* mspdb120_dll = "mspdb120.dll"; char* mspdb140_dll = "mspdb140.dll"; // char* mspdb110shell_dll = "mspdbst.dll"; // the VS 2012 Shell uses this file instead of mspdb110.dll, but is missing mspdbsrv.exe int mspdb::vsVersion = 8; // verify mspdbsrv.exe is found in the same path void tryLoadLibrary(const char* mspdb) { if (modMsPdb) return; modMsPdb = LoadLibraryA(mspdb); if (!modMsPdb) return; char modpath[260]; if(GetModuleFileNameA(modMsPdb, modpath, 260) < 260) { char* p = modpath + strlen(modpath); while(p > modpath && p[-1] != '\\') p--; strcpy(p, "mspdbsrv.exe"); if(GetFileAttributesA(modpath) != INVALID_FILE_ATTRIBUTES) return; } FreeLibrary(modMsPdb); modMsPdb = NULL; } bool getInstallDir(const char* version, char* installDir, DWORD size) { char key[260] = "SOFTWARE\\Microsoft\\"; strcat(key, version); HKEY hkey; if (RegOpenKeyExA(HKEY_LOCAL_MACHINE, key, 0, KEY_QUERY_VALUE #if _M_X64 | KEY_WOW64_32KEY #endif , &hkey) != ERROR_SUCCESS) return false; bool rc = RegQueryValueExA(hkey, "InstallDir", 0, 0, (LPBYTE)installDir, &size) == ERROR_SUCCESS; RegCloseKey(hkey); return rc; } bool tryLoadMsPdb(const char* version, const char* mspdb, const char* path = 0) { char installDir[260]; if (!getInstallDir(version, installDir, sizeof(installDir))) return false; char* p = installDir + strlen(installDir); if (p[-1] != '\\' && p[-1] != '/') *p++ = '\\'; if(path) p += strlen(strcpy(p, path)); strcpy(p, mspdb); tryLoadLibrary(installDir); return modMsPdb != 0; } #ifdef _M_X64 #define MSPDB_DIR_NEW "..\\..\\VC\\bin\\amd64\\" #define MSPDB_DIR_OLD MSPDB_DIR_NEW #else #define MSPDB_DIR_NEW "..\\..\\VC\\bin\\" #define MSPDB_DIR_OLD 0 #endif void tryLoadMsPdb80(bool throughPath) { if (!modMsPdb && throughPath) tryLoadLibrary(mspdb80_dll); if (!modMsPdb && !throughPath) tryLoadMsPdb("VisualStudio\\9.0", mspdb80_dll, MSPDB_DIR_OLD); if (!modMsPdb && !throughPath) tryLoadMsPdb("VisualStudio\\8.0", mspdb80_dll, MSPDB_DIR_OLD); if (!modMsPdb && !throughPath) tryLoadMsPdb("VCExpress\\9.0", mspdb80_dll, MSPDB_DIR_OLD); if (!modMsPdb && !throughPath) tryLoadMsPdb("VCExpress\\8.0", mspdb80_dll, MSPDB_DIR_OLD); } void tryLoadMsPdb100(bool throughPath) { if (!modMsPdb) { if(throughPath) modMsPdb = LoadLibraryA(mspdb100_dll); if (!modMsPdb && !throughPath) tryLoadMsPdb("VisualStudio\\10.0", mspdb100_dll, MSPDB_DIR_OLD); if (!modMsPdb && !throughPath) tryLoadMsPdb("VCExpress\\10.0", mspdb100_dll, MSPDB_DIR_OLD); if (modMsPdb) mspdb::vsVersion = 10; } } void tryLoadMsPdb110(bool throughPath) { if (!modMsPdb) { if (throughPath) modMsPdb = LoadLibraryA(mspdb110_dll); if (!modMsPdb && !throughPath) tryLoadMsPdb("VisualStudio\\11.0", mspdb110_dll, MSPDB_DIR_OLD); if (!modMsPdb && !throughPath) tryLoadMsPdb("VSWinExpress\\11.0", mspdb110_dll, MSPDB_DIR_OLD); if (modMsPdb) mspdb::vsVersion = 11; } } void tryLoadMsPdb120(bool throughPath) { if (!modMsPdb) { if(throughPath) modMsPdb = LoadLibraryA(mspdb120_dll); if (!modMsPdb && !throughPath) tryLoadMsPdb("VisualStudio\\12.0", mspdb120_dll, MSPDB_DIR_NEW); if (!modMsPdb && !throughPath) tryLoadMsPdb("VSWinExpress\\12.0", mspdb120_dll, MSPDB_DIR_NEW); if (modMsPdb) mspdb::vsVersion = 12; } } void tryLoadMsPdb140(bool throughPath) { if (!modMsPdb) { if(throughPath) modMsPdb = LoadLibraryA(mspdb140_dll); if (!modMsPdb && !throughPath) tryLoadMsPdb("VisualStudio\\14.0", mspdb140_dll, MSPDB_DIR_NEW); if (!modMsPdb && !throughPath) tryLoadMsPdb("VSWinExpress\\14.0", mspdb140_dll, MSPDB_DIR_NEW); if (modMsPdb) mspdb::vsVersion = 14; } } bool initMsPdb() { #if 0 // might cause problems when combining VS Shell 2010 with VS 2008 or similar if(const char* p = getenv("VisualStudioDir")) { // guess from environment variable from which version of VS we are invoked and prefer a correspondig mspdb DLL if (strstr(p, "2010")) tryLoadMsPdb100(); if (strstr(p, "2012")) tryLoadMsPdb110(); // VS2008 tried next anyway } #endif // try loading through the PATH first to best match current setup tryLoadMsPdb140(true); tryLoadMsPdb120(true); tryLoadMsPdb110(true); tryLoadMsPdb100(true); tryLoadMsPdb80(true); tryLoadMsPdb140(false); tryLoadMsPdb120(false); tryLoadMsPdb110(false); tryLoadMsPdb100(false); tryLoadMsPdb80(false); if (!modMsPdb) return false; if (!pPDBOpen2W) pPDBOpen2W = (mspdb::fnPDBOpen2W*) GetProcAddress(modMsPdb, "PDBOpen2W"); if (!pPDBOpen2W) return false; return true; } bool exitMsPdb() { pPDBOpen2W = 0; if (modMsPdb) FreeLibrary(modMsPdb); modMsPdb = 0; return true; } mspdb::PDB* CreatePDB(const wchar_t* pdbname) { if (!initMsPdb ()) return 0; mspdb::PDB* pdb = 0; long data[194] = { 193, 0 }; wchar_t ext[256] = L".exe"; if (!((*pPDBOpen2W) (pdbname, "wf", data, ext, 0x400, &pdb))) return 0; return pdb; } <|endoftext|>
<commit_before>#include "music.h" #include <string> #include <iostream> #include "globals.h" // #include "defs.h" #include <pthread.h> #include "util/funcs.h" #include "util/file-system.h" #include "util/music-player.h" using namespace std; static Music * instance = NULL; static double volume = 1.0; // static bool muted = false; static pthread_t musicThread; static pthread_mutex_t musicMutex; static bool alive = true; static void * playMusic( void * ); #define synchronized for( int __l( ! pthread_mutex_lock( &musicMutex ) ); __l; __l = 0, pthread_mutex_unlock( &musicMutex ) ) #define LOCK pthread_mutex_lock( &musicMutex ); #define UNLOCK pthread_mutex_unlock( &musicMutex ); /* #undef LOCK #undef UNLOCK #define LOCK #define UNLOCK */ static void * bogus_thread( void * x){ return NULL; } Music::Music( bool on ): playing(false), fading(0), musicPlayer(NULL), currentSong(""){ if ( instance != NULL ){ cerr << "Trying to instantiate music object twice!" << endl; return; } instance = this; pthread_mutex_init( &musicMutex, NULL ); if ( on ){ pthread_create( &musicThread, NULL, playMusic, (void *)instance ); } else { pthread_create( &musicThread, NULL, bogus_thread, NULL ); } } /* static bool isAlive(){ bool f = false; synchronized{ f = alive; } return f; } */ static void * playMusic( void * _music ){ Music * music = (Music *) _music; Global::debug( 1 ) << "Playing music" << endl; /* unsigned int tick = 0; unsigned int counter; */ bool playing = true; while ( playing ){ LOCK;{ playing = alive; music->doPlay(); } UNLOCK; Util::rest( 10 ); // Util::YIELD(); // pthread_yield(); } // cout << "Done with music thread" << endl; return NULL; } double Music::getVolume(){ double vol = 0; LOCK;{ vol = volume; } UNLOCK; return vol; } void Music::doPlay(){ if ( this->playing ){ double f = fading / 500.0; switch ( fading ){ case -1 : { if ( volume + f < 0 ){ fading = 0; volume = 0; } else { volume += f; this->_setVolume( volume ); } break; } case 1 : { if ( volume + f > 1.0 ){ fading = 0; volume = 1.0; } else { volume += f; this->_setVolume( volume ); } break; } } musicPlayer->poll(); } } /* Music::Music( const char * song ): volume( 1.0 ), muted( false ), player( NULL ), music_file( NULL ){ loadSong( song ); } Music::Music( const string & song ): volume( 1.0 ), muted( false ), player( NULL ), music_file( NULL ){ loadSong( song ); } */ void Music::fadeIn( double vol ){ LOCK;{ volume = vol; instance->_fadeIn(); } UNLOCK; } void Music::fadeOut( double vol ){ LOCK;{ volume = vol; instance->_fadeOut(); } UNLOCK; } void Music::_fadeIn(){ fading = 1; } void Music::_fadeOut(){ fading = -1; } bool Music::loadSong( const char * song ){ bool loaded = false; LOCK;{ loaded = instance->internal_loadSong( song ); } UNLOCK; return loaded; // muted = false; } /* remove an element from a vector at index 'pos' and return it */ template< class Tx_ > static Tx_ removeVectorElement( vector< Tx_ > & toRemove, int pos ){ int count = 0; typename vector< Tx_ >::iterator it; for ( it = toRemove.begin(); it != toRemove.end() && count < pos; count++, it++ ); if ( it == toRemove.end() ){ /* this isnt right, but whatever */ return toRemove.front(); } const Tx_ & removed = toRemove[ pos ]; toRemove.erase( it ); return removed; } void Music::loadSong( const vector< string > & Songs ){ /* cout << "Songs = " << &Songs << endl; if ( ! loadSong( "music/song5.xm" ) ){ cerr << "Could not load music/song5.xm" << endl; } return; */ vector< string > _songs = Songs; vector< string > songs; while ( ! _songs.empty() ){ int i = Util::rnd( _songs.size() ); songs.push_back( removeVectorElement< string >( _songs, i ) ); } /* songs.clear(); songs.push_back( "music/song3.xm" ); */ for ( vector< string >::iterator it = songs.begin(); it != songs.end(); it++ ){ Global::debug( 1 ) << "Trying to load song " << *it << endl; if (loadSong(*it)){ break; } } } bool Music::loadSong( const string & song ){ return loadSong( song.c_str() ); } void Music::_play(){ if ( playing == false && musicPlayer != NULL ){ musicPlayer->play(); playing = true; } } void Music::play(){ LOCK;{ instance->_play(); } UNLOCK; } void Music::_pause(){ playing = false; if (musicPlayer != NULL){ musicPlayer->pause(); } } void Music::pause(){ LOCK;{ instance->_pause(); } UNLOCK; } void Music::soften(){ LOCK;{ instance->_soften(); } UNLOCK; } void Music::_soften(){ if ( volume > 0.1 ){ volume -= 0.1; } else { volume = 0.0; } _setVolume( volume ); } void Music::louden(){ LOCK;{ instance->_louden(); } UNLOCK; } void Music::_louden(){ if ( volume < 0.9 ){ volume += 0.1; } else { volume = 1.0; } _setVolume( volume ); } void Music::mute(){ setVolume( 0 ); } void Music::setVolume( double vol ){ LOCK;{ volume = vol; if ( volume > 1.0 ){ volume = 1.0; } if ( volume < 0 ){ volume = 0; } instance->_setVolume( volume ); } UNLOCK; } void Music::_setVolume( double vol ){ if (musicPlayer){ musicPlayer->setVolume(vol); } } Music::~Music(){ LOCK;{ if (musicPlayer){ delete musicPlayer; } alive = false; playing = false; } UNLOCK; Global::debug( 1 ) << "Waiting for music thread to die" << endl; pthread_join( musicThread, NULL ); } static string getExtension(const char * path_){ string path(path_); if (path.rfind('.') != string::npos){ return path.substr(path.rfind('.') + 1); } return ""; } /* true if the file extension is something DUMB will probably recognize */ static bool isDumbFile(const char * path){ string extension = getExtension(path); return extension == "mod" || extension == "s3m" || extension == "it" || extension == "xm"; } static bool isGMEFile(const char * path){ string extension = getExtension(path); return extension == "nsf"; } bool Music::internal_loadSong( const char * path ){ // cout << "Trying to load '" << path << "'" << endl; // Check current song and/or set it if (currentSong.compare(std::string(path))==0){ return true; } else { currentSong = std::string(path); } if (musicPlayer != NULL){ delete musicPlayer; musicPlayer = NULL; } if (isDumbFile(path)){ musicPlayer = new Util::DumbPlayer(path); musicPlayer->play(); playing = true; } else if (isGMEFile(path)){ musicPlayer = new Util::GMEPlayer(path); musicPlayer->play(); playing = true; } else { return false; } return true; } void Music::changeSong(){ pause(); fadeIn(0.3); loadSong(Util::getFiles(Filesystem::find(Filesystem::RelativePath("music/")), "*")); play(); } #undef synchronized #undef LOCK #undef UNLOCK <commit_msg>set gme as track 0. can play spc and gym<commit_after>#include "music.h" #include <string> #include <iostream> #include "globals.h" // #include "defs.h" #include <pthread.h> #include "util/funcs.h" #include "util/file-system.h" #include "util/music-player.h" using namespace std; static Music * instance = NULL; static double volume = 1.0; // static bool muted = false; static pthread_t musicThread; static pthread_mutex_t musicMutex; static bool alive = true; static void * playMusic( void * ); #define synchronized for( int __l( ! pthread_mutex_lock( &musicMutex ) ); __l; __l = 0, pthread_mutex_unlock( &musicMutex ) ) #define LOCK pthread_mutex_lock( &musicMutex ); #define UNLOCK pthread_mutex_unlock( &musicMutex ); /* #undef LOCK #undef UNLOCK #define LOCK #define UNLOCK */ static void * bogus_thread( void * x){ return NULL; } Music::Music( bool on ): playing(false), fading(0), musicPlayer(NULL), currentSong(""){ if ( instance != NULL ){ cerr << "Trying to instantiate music object twice!" << endl; return; } instance = this; pthread_mutex_init( &musicMutex, NULL ); if ( on ){ pthread_create( &musicThread, NULL, playMusic, (void *)instance ); } else { pthread_create( &musicThread, NULL, bogus_thread, NULL ); } } /* static bool isAlive(){ bool f = false; synchronized{ f = alive; } return f; } */ static void * playMusic( void * _music ){ Music * music = (Music *) _music; Global::debug( 1 ) << "Playing music" << endl; /* unsigned int tick = 0; unsigned int counter; */ bool playing = true; while ( playing ){ LOCK;{ playing = alive; music->doPlay(); } UNLOCK; Util::rest( 10 ); // Util::YIELD(); // pthread_yield(); } // cout << "Done with music thread" << endl; return NULL; } double Music::getVolume(){ double vol = 0; LOCK;{ vol = volume; } UNLOCK; return vol; } void Music::doPlay(){ if ( this->playing ){ double f = fading / 500.0; switch ( fading ){ case -1 : { if ( volume + f < 0 ){ fading = 0; volume = 0; } else { volume += f; this->_setVolume( volume ); } break; } case 1 : { if ( volume + f > 1.0 ){ fading = 0; volume = 1.0; } else { volume += f; this->_setVolume( volume ); } break; } } musicPlayer->poll(); } } /* Music::Music( const char * song ): volume( 1.0 ), muted( false ), player( NULL ), music_file( NULL ){ loadSong( song ); } Music::Music( const string & song ): volume( 1.0 ), muted( false ), player( NULL ), music_file( NULL ){ loadSong( song ); } */ void Music::fadeIn( double vol ){ LOCK;{ volume = vol; instance->_fadeIn(); } UNLOCK; } void Music::fadeOut( double vol ){ LOCK;{ volume = vol; instance->_fadeOut(); } UNLOCK; } void Music::_fadeIn(){ fading = 1; } void Music::_fadeOut(){ fading = -1; } bool Music::loadSong( const char * song ){ bool loaded = false; LOCK;{ loaded = instance->internal_loadSong( song ); } UNLOCK; return loaded; // muted = false; } /* remove an element from a vector at index 'pos' and return it */ template< class Tx_ > static Tx_ removeVectorElement( vector< Tx_ > & toRemove, int pos ){ int count = 0; typename vector< Tx_ >::iterator it; for ( it = toRemove.begin(); it != toRemove.end() && count < pos; count++, it++ ); if ( it == toRemove.end() ){ /* this isnt right, but whatever */ return toRemove.front(); } const Tx_ & removed = toRemove[ pos ]; toRemove.erase( it ); return removed; } void Music::loadSong( const vector< string > & Songs ){ /* cout << "Songs = " << &Songs << endl; if ( ! loadSong( "music/song5.xm" ) ){ cerr << "Could not load music/song5.xm" << endl; } return; */ vector< string > _songs = Songs; vector< string > songs; while ( ! _songs.empty() ){ int i = Util::rnd( _songs.size() ); songs.push_back( removeVectorElement< string >( _songs, i ) ); } /* songs.clear(); songs.push_back( "music/song3.xm" ); */ for ( vector< string >::iterator it = songs.begin(); it != songs.end(); it++ ){ Global::debug( 1 ) << "Trying to load song " << *it << endl; if (loadSong(*it)){ break; } } } bool Music::loadSong( const string & song ){ return loadSong( song.c_str() ); } void Music::_play(){ if ( playing == false && musicPlayer != NULL ){ musicPlayer->play(); playing = true; } } void Music::play(){ LOCK;{ instance->_play(); } UNLOCK; } void Music::_pause(){ playing = false; if (musicPlayer != NULL){ musicPlayer->pause(); } } void Music::pause(){ LOCK;{ instance->_pause(); } UNLOCK; } void Music::soften(){ LOCK;{ instance->_soften(); } UNLOCK; } void Music::_soften(){ if ( volume > 0.1 ){ volume -= 0.1; } else { volume = 0.0; } _setVolume( volume ); } void Music::louden(){ LOCK;{ instance->_louden(); } UNLOCK; } void Music::_louden(){ if ( volume < 0.9 ){ volume += 0.1; } else { volume = 1.0; } _setVolume( volume ); } void Music::mute(){ setVolume( 0 ); } void Music::setVolume( double vol ){ LOCK;{ volume = vol; if ( volume > 1.0 ){ volume = 1.0; } if ( volume < 0 ){ volume = 0; } instance->_setVolume( volume ); } UNLOCK; } void Music::_setVolume( double vol ){ if (musicPlayer){ musicPlayer->setVolume(vol); } } Music::~Music(){ LOCK;{ if (musicPlayer){ delete musicPlayer; } alive = false; playing = false; } UNLOCK; Global::debug( 1 ) << "Waiting for music thread to die" << endl; pthread_join( musicThread, NULL ); } static string getExtension(const char * path_){ string path(path_); if (path.rfind('.') != string::npos){ return path.substr(path.rfind('.') + 1); } return ""; } /* true if the file extension is something DUMB will probably recognize */ static bool isDumbFile(const char * path){ string extension = getExtension(path); return extension == "mod" || extension == "s3m" || extension == "it" || extension == "xm"; } static bool isGMEFile(const char * path){ string extension = getExtension(path); return extension == "nsf" || extension == "spc" || extension == "gym"; } bool Music::internal_loadSong( const char * path ){ // cout << "Trying to load '" << path << "'" << endl; // Check current song and/or set it if (currentSong.compare(std::string(path))==0){ return true; } else { currentSong = std::string(path); } if (musicPlayer != NULL){ delete musicPlayer; musicPlayer = NULL; } if (isDumbFile(path)){ musicPlayer = new Util::DumbPlayer(path); musicPlayer->play(); playing = true; } else if (isGMEFile(path)){ musicPlayer = new Util::GMEPlayer(path); musicPlayer->play(); playing = true; } else { return false; } return true; } void Music::changeSong(){ pause(); fadeIn(0.3); loadSong(Util::getFiles(Filesystem::find(Filesystem::RelativePath("music/")), "*")); play(); } #undef synchronized #undef LOCK #undef UNLOCK <|endoftext|>
<commit_before>#include "builtin/nativemethod.hpp" #include "objectmemory.hpp" #include "gc/baker.hpp" #include "capi/capi.hpp" #include "capi/handles.hpp" namespace rubinius { namespace capi { Handle* Handles::allocate(STATE, Object* obj) { bool needs_gc = false; Handle* handle = allocator_->allocate(&needs_gc); handle->set_object(obj); handle->validate(); if(needs_gc) { state->memory()->collect_mature_now = true; } atomic::memory_barrier(); return handle; } uintptr_t Handles::allocate_index(STATE, Object* obj) { bool needs_gc = false; uintptr_t handle_index = allocator_->allocate_index(&needs_gc); Handle* handle = allocator_->from_index(handle_index); handle->set_object(obj); handle->validate(); if(needs_gc) { state->memory()->collect_mature_now = true; } atomic::memory_barrier(); return handle_index; } Handle* Handles::find_index(STATE, uintptr_t index) { Handle* handle = allocator_->from_index(index); assert(validate(handle)); return handle; } bool Handles::validate(Handle* handle) { return allocator_->validate(handle); } Handles::~Handles() { for(std::vector<int>::size_type i = 0; i < allocator_->chunks_.size(); ++i) { Handle* chunk = allocator_->chunks_[i]; for(size_t j = 0; j < allocator_->cChunkSize; j++) { Handle* handle = &chunk[j]; if(handle->in_use_p()) { handle->clear(); } } } delete allocator_; } void Handles::deallocate_handles(std::list<Handle*>* cached, int mark, BakerGC* young) { std::vector<bool> chunk_marks(allocator_->chunks_.size(), false); for(std::vector<int>::size_type i = 0; i < allocator_->chunks_.size(); ++i) { Handle* chunk = allocator_->chunks_[i]; for(size_t j = 0; j < allocator_->cChunkSize; j++) { Handle* handle = &chunk[j]; Object* obj = handle->object(); if(!handle->in_use_p()) { continue; } // Strong references will already have been updated. if(!handle->weak_p()) { chunk_marks[i] = true; continue; } if(young) { if(obj->young_object_p()) { // A weakref pointing to a valid young object // // TODO this only works because we run prune_handles right after // a collection. In this state, valid objects are only in current. if(young->in_current_p(obj)) { chunk_marks[i] = true; // A weakref pointing to a forwarded young object } else if(obj->forwarded_p()) { handle->set_object(obj->forward()); chunk_marks[i] = true; // A weakref pointing to a dead young object } else { handle->clear(); } } else { // Not a young object, so won't be GC'd so mark // chunk as still active chunk_marks[i] = true; } // A weakref pointing to a dead mature object } else if(!obj->marked_p(mark)) { handle->clear(); } else { chunk_marks[i] = true; } } } // Cleanup cached handles for(std::list<Handle*>::iterator it = cached->begin(); it != cached->end();) { Handle* handle = *it; if(handle->in_use_p()) { ++it; } else { it = cached->erase(it); } } allocator_->rebuild_freelist(&chunk_marks); } } } <commit_msg>Removed debugging assert for Handles::find_index.<commit_after>#include "builtin/nativemethod.hpp" #include "objectmemory.hpp" #include "gc/baker.hpp" #include "capi/capi.hpp" #include "capi/handles.hpp" namespace rubinius { namespace capi { Handle* Handles::allocate(STATE, Object* obj) { bool needs_gc = false; Handle* handle = allocator_->allocate(&needs_gc); handle->set_object(obj); handle->validate(); if(needs_gc) { state->memory()->collect_mature_now = true; } atomic::memory_barrier(); return handle; } uintptr_t Handles::allocate_index(STATE, Object* obj) { bool needs_gc = false; uintptr_t handle_index = allocator_->allocate_index(&needs_gc); Handle* handle = allocator_->from_index(handle_index); handle->set_object(obj); handle->validate(); if(needs_gc) { state->memory()->collect_mature_now = true; } atomic::memory_barrier(); return handle_index; } Handle* Handles::find_index(STATE, uintptr_t index) { return allocator_->from_index(index); } bool Handles::validate(Handle* handle) { return allocator_->validate(handle); } Handles::~Handles() { for(std::vector<int>::size_type i = 0; i < allocator_->chunks_.size(); ++i) { Handle* chunk = allocator_->chunks_[i]; for(size_t j = 0; j < allocator_->cChunkSize; j++) { Handle* handle = &chunk[j]; if(handle->in_use_p()) { handle->clear(); } } } delete allocator_; } void Handles::deallocate_handles(std::list<Handle*>* cached, int mark, BakerGC* young) { std::vector<bool> chunk_marks(allocator_->chunks_.size(), false); for(std::vector<int>::size_type i = 0; i < allocator_->chunks_.size(); ++i) { Handle* chunk = allocator_->chunks_[i]; for(size_t j = 0; j < allocator_->cChunkSize; j++) { Handle* handle = &chunk[j]; Object* obj = handle->object(); if(!handle->in_use_p()) { continue; } // Strong references will already have been updated. if(!handle->weak_p()) { chunk_marks[i] = true; continue; } if(young) { if(obj->young_object_p()) { // A weakref pointing to a valid young object // // TODO this only works because we run prune_handles right after // a collection. In this state, valid objects are only in current. if(young->in_current_p(obj)) { chunk_marks[i] = true; // A weakref pointing to a forwarded young object } else if(obj->forwarded_p()) { handle->set_object(obj->forward()); chunk_marks[i] = true; // A weakref pointing to a dead young object } else { handle->clear(); } } else { // Not a young object, so won't be GC'd so mark // chunk as still active chunk_marks[i] = true; } // A weakref pointing to a dead mature object } else if(!obj->marked_p(mark)) { handle->clear(); } else { chunk_marks[i] = true; } } } // Cleanup cached handles for(std::list<Handle*>::iterator it = cached->begin(); it != cached->end();) { Handle* handle = *it; if(handle->in_use_p()) { ++it; } else { it = cached->erase(it); } } allocator_->rebuild_freelist(&chunk_marks); } } } <|endoftext|>
<commit_before>/* Copyright (c) 2010, Antonie Jovanoski * * All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see <http://www.gnu.org/licenses/>. * * Contact e-mail: Antonie Jovanoski <minimoog77_at_gmail.com> */ #include <QDateTime> #include <QtAlgorithms> #include <QCryptographicHash> #include <QtDebug> #include "oauth.h" #ifndef CONSUMER_KEY #define CONSUMER_KEY "" #endif //CONSUMER_KEY #ifndef CONSUMER_SECRET #define CONSUMER_SECRET "" #endif //CONSUMER_SECRET /** * Generates HMAC-SHA1 signature * @param message for which to create signature * @param key */ static QByteArray hmacSha1(const QByteArray& message, const QByteArray& key) { QByteArray normKey; if (key.size() > 64) { normKey = QCryptographicHash::hash(key, QCryptographicHash::Sha1); } else { normKey = key; // no need for zero padding ipad and opad are filled with zeros } unsigned char* K = (unsigned char *)normKey.constData(); unsigned char ipad[65]; unsigned char opad[65]; memset(ipad, 0, 65); memset(opad, 0, 65); memcpy(ipad, K, normKey.size()); memcpy(opad, K, normKey.size()); for (int i = 0; i < 64; ++i) { ipad[i] ^= 0x36; opad[i] ^= 0x5c; } QByteArray context; context.append((const char *)ipad, 64); context.append(message); QByteArray sha1 = QCryptographicHash::hash(context, QCryptographicHash::Sha1); context.clear(); context.append((const char *)opad, 64); context.append(sha1); sha1.clear(); sha1 = QCryptographicHash::hash(context, QCryptographicHash::Sha1); return sha1; } /** * Generates time stamp * @return time stamp in epoch time */ static QByteArray generateTimeStamp() { //OAuth spec. 8 http://oauth.net/core/1.0/#nonce QDateTime current = QDateTime::currentDateTime(); uint seconds = current.toTime_t(); return QString("%1").arg(seconds).toUtf8(); } /** * Generates random 16 length string * @return random string */ static QByteArray generateNonce() { //OAuth spec. 8 http://oauth.net/core/1.0/#nonce QByteArray chars("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"); int max = chars.size(); int len = 16; QByteArray nonce; for(int i = 0; i < len; ++i){ nonce.append( chars[qrand() % max] ); } return nonce; } /** * Constructor * @param parent parent QObject */ OAuth::OAuth(QObject *parent) : QObject(parent), m_oauthConsumerKey(CONSUMER_KEY), m_oauthConsumerSecret(CONSUMER_SECRET) { QDateTime current = QDateTime::currentDateTime(); qsrand(current.toTime_t()); } /** * Constructor * @param consumerKey oauth consumer key * @param consumerSecret oauth consumer secret * @param parent parent QObject */ OAuth::OAuth(const QByteArray &consumerKey, const QByteArray &consumerSecret, QObject *parent) : QObject(parent), m_oauthConsumerKey(consumerKey), m_oauthConsumerSecret(consumerSecret) { QDateTime current = QDateTime::currentDateTime(); qsrand(current.toTime_t()); } /** * Parses oauth_token and oauth_token_secret from response of the service provider * and sets m_oauthToken and m_oauthTokenSecret accordingly * @param response response from service provider */ void OAuth::parseTokens(const QByteArray& response) { //OAuth spec 5.3, 6.1.2, 6.3.2 //use QUrl for parsing QByteArray parseQuery("http://parse.com?"); QUrl parseUrl = QUrl::fromEncoded(parseQuery + response); m_oauthToken = parseUrl.encodedQueryItemValue("oauth_token"); m_oauthTokenSecret = parseUrl.encodedQueryItemValue("oauth_token_secret"); } /** * Sets oauth token * @param token OAuth token */ void OAuth::setOAuthToken(const QByteArray& token) { m_oauthToken = token; } /** * Sets OAauth token secret * @param tokenSecret OAuth token secret */ void OAuth::setOAuthTokenSecret(const QByteArray& tokenSecret) { m_oauthTokenSecret = tokenSecret; } /** * Gets oauth_token * @return OAuth token */ QByteArray OAuth::oauthToken() const { return m_oauthToken; } /** * Gets oauth_token_secret * @return OAuth token secret */ QByteArray OAuth::oauthTokenSecret() const { return m_oauthTokenSecret; } /** * Clears the oauth tokens */ void OAuth::clearTokens() { m_oauthToken.clear(); m_oauthTokenSecret.clear(); } /** * Generates HMAC-SHA1 signature * @param signatureBase signature base * @return HMAC-SHA1 signature */ QByteArray OAuth::generateSignatureHMACSHA1(const QByteArray& signatureBase) { //OAuth spec. 9.2 http://oauth.net/core/1.0/#anchor16 QByteArray key = m_oauthConsumerSecret + '&' + m_oauthTokenSecret; QByteArray result = hmacSha1(signatureBase, key); QByteArray resultBE64 = result.toBase64(); QByteArray resultPE = resultBE64.toPercentEncoding(); return resultPE; } /** * Generates OAuth signature base * @param url Url with encoded parameters * @param method Http method * @param timestamp timestamp * @param nonce random string * @return signature base */ QByteArray OAuth::generateSignatureBase(const QUrl& url, HttpMethod method, const QByteArray& timestamp, const QByteArray& nonce) { //OAuth spec. 9.1 http://oauth.net/core/1.0/#anchor14 //OAuth spec. 9.1.1 QList<QPair<QByteArray, QByteArray> > urlParameters = url.encodedQueryItems(); QList<QByteArray> normParameters; QListIterator<QPair<QByteArray, QByteArray> > i(urlParameters); while(i.hasNext()){ QPair<QByteArray, QByteArray> queryItem = i.next(); QByteArray normItem = queryItem.first + '=' + queryItem.second; normParameters.append(normItem); } //consumer key normParameters.append(QByteArray("oauth_consumer_key=") + m_oauthConsumerKey); //token if(!m_oauthToken.isEmpty()){ normParameters.append(QByteArray("oauth_token=") + m_oauthToken); } //signature method, only HMAC_SHA1 normParameters.append(QByteArray("oauth_signature_method=HMAC-SHA1")); //time stamp normParameters.append(QByteArray("oauth_timestamp=") + timestamp); //nonce normParameters.append(QByteArray("oauth_nonce=") + nonce); //version normParameters.append(QByteArray("oauth_version=1.0")); //OAuth spec. 9.1.1.1 qSort(normParameters); //OAuth spec. 9.1.1.2 //QByteArray normString; //QListIterator<QByteArray> j(normParameters); //while(j.hasNext()){ // normString += j.next(); // normString += '&'; //} //normString.chop(1); QByteArray normString; QListIterator<QByteArray> j(normParameters); while (j.hasNext()) { normString += j.next().toPercentEncoding(); normString += "%26"; } normString.chop(3); //OAuth spec. 9.1.2 QString urlScheme = url.scheme(); QString urlPath = url.path(); QString urlHost = url.host(); QByteArray normUrl = urlScheme.toUtf8() + "://" + urlHost.toUtf8() + urlPath.toUtf8(); QByteArray httpm; switch (method) { case OAuth::GET: httpm = "GET"; break; case OAuth::POST: httpm = "POST"; break; case OAuth::DELETE: httpm = "DELETE"; break; case OAuth::PUT: httpm = "PUT"; break; } //OAuth spec. 9.1.3 return httpm + '&' + normUrl.toPercentEncoding() + '&' + normString; } /** * Generates Authorization Header * @param url url with query items embedded * @param method type of http method * @remarks If HttpMethod is POST put query items in url (QUrl::addEncodedQueryItem) */ QByteArray OAuth::generateAuthorizationHeader( const QUrl& url, HttpMethod method ) { if (m_oauthToken.isEmpty() && m_oauthTokenSecret.isEmpty()) qDebug() << "OAuth tokens are empty!"; QByteArray timeStamp = generateTimeStamp(); QByteArray nonce = generateNonce(); QByteArray sigBase = generateSignatureBase(url, method, timeStamp, nonce); QByteArray signature = generateSignatureHMACSHA1(sigBase); QByteArray header; header += "OAuth "; header += "oauth_consumer_key=\"" + m_oauthConsumerKey + "\","; if(!m_oauthToken.isEmpty()) header += "oauth_token=\"" + m_oauthToken + "\","; header += "oauth_signature_method=\"HMAC-SHA1\","; header += "oauth_signature=\"" + signature + "\","; header += "oauth_timestamp=\"" + timeStamp + "\","; header += "oauth_nonce=\"" + nonce + "\","; header += "oauth_version=\"1.0\""; return header; } <commit_msg>Fixed tabs.<commit_after>/* Copyright (c) 2010, Antonie Jovanoski * * All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see <http://www.gnu.org/licenses/>. * * Contact e-mail: Antonie Jovanoski <minimoog77_at_gmail.com> */ #include <QDateTime> #include <QtAlgorithms> #include <QCryptographicHash> #include <QtDebug> #include "oauth.h" #ifndef CONSUMER_KEY #define CONSUMER_KEY "" #endif //CONSUMER_KEY #ifndef CONSUMER_SECRET #define CONSUMER_SECRET "" #endif //CONSUMER_SECRET /** * Generates HMAC-SHA1 signature * @param message for which to create signature * @param key */ static QByteArray hmacSha1(const QByteArray& message, const QByteArray& key) { QByteArray normKey; if (key.size() > 64) { normKey = QCryptographicHash::hash(key, QCryptographicHash::Sha1); } else { normKey = key; // no need for zero padding ipad and opad are filled with zeros } unsigned char* K = (unsigned char *)normKey.constData(); unsigned char ipad[65]; unsigned char opad[65]; memset(ipad, 0, 65); memset(opad, 0, 65); memcpy(ipad, K, normKey.size()); memcpy(opad, K, normKey.size()); for (int i = 0; i < 64; ++i) { ipad[i] ^= 0x36; opad[i] ^= 0x5c; } QByteArray context; context.append((const char *)ipad, 64); context.append(message); QByteArray sha1 = QCryptographicHash::hash(context, QCryptographicHash::Sha1); context.clear(); context.append((const char *)opad, 64); context.append(sha1); sha1.clear(); sha1 = QCryptographicHash::hash(context, QCryptographicHash::Sha1); return sha1; } /** * Generates time stamp * @return time stamp in epoch time */ static QByteArray generateTimeStamp() { //OAuth spec. 8 http://oauth.net/core/1.0/#nonce QDateTime current = QDateTime::currentDateTime(); uint seconds = current.toTime_t(); return QString("%1").arg(seconds).toUtf8(); } /** * Generates random 16 length string * @return random string */ static QByteArray generateNonce() { //OAuth spec. 8 http://oauth.net/core/1.0/#nonce QByteArray chars("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"); int max = chars.size(); int len = 16; QByteArray nonce; for(int i = 0; i < len; ++i){ nonce.append( chars[qrand() % max] ); } return nonce; } /** * Constructor * @param parent parent QObject */ OAuth::OAuth(QObject *parent) : QObject(parent), m_oauthConsumerKey(CONSUMER_KEY), m_oauthConsumerSecret(CONSUMER_SECRET) { QDateTime current = QDateTime::currentDateTime(); qsrand(current.toTime_t()); } /** * Constructor * @param consumerKey oauth consumer key * @param consumerSecret oauth consumer secret * @param parent parent QObject */ OAuth::OAuth(const QByteArray &consumerKey, const QByteArray &consumerSecret, QObject *parent) : QObject(parent), m_oauthConsumerKey(consumerKey), m_oauthConsumerSecret(consumerSecret) { QDateTime current = QDateTime::currentDateTime(); qsrand(current.toTime_t()); } /** * Parses oauth_token and oauth_token_secret from response of the service provider * and sets m_oauthToken and m_oauthTokenSecret accordingly * @param response response from service provider */ void OAuth::parseTokens(const QByteArray& response) { //OAuth spec 5.3, 6.1.2, 6.3.2 //use QUrl for parsing QByteArray parseQuery("http://parse.com?"); QUrl parseUrl = QUrl::fromEncoded(parseQuery + response); m_oauthToken = parseUrl.encodedQueryItemValue("oauth_token"); m_oauthTokenSecret = parseUrl.encodedQueryItemValue("oauth_token_secret"); } /** * Sets oauth token * @param token OAuth token */ void OAuth::setOAuthToken(const QByteArray& token) { m_oauthToken = token; } /** * Sets OAauth token secret * @param tokenSecret OAuth token secret */ void OAuth::setOAuthTokenSecret(const QByteArray& tokenSecret) { m_oauthTokenSecret = tokenSecret; } /** * Gets oauth_token * @return OAuth token */ QByteArray OAuth::oauthToken() const { return m_oauthToken; } /** * Gets oauth_token_secret * @return OAuth token secret */ QByteArray OAuth::oauthTokenSecret() const { return m_oauthTokenSecret; } /** * Clears the oauth tokens */ void OAuth::clearTokens() { m_oauthToken.clear(); m_oauthTokenSecret.clear(); } /** * Generates HMAC-SHA1 signature * @param signatureBase signature base * @return HMAC-SHA1 signature */ QByteArray OAuth::generateSignatureHMACSHA1(const QByteArray& signatureBase) { //OAuth spec. 9.2 http://oauth.net/core/1.0/#anchor16 QByteArray key = m_oauthConsumerSecret + '&' + m_oauthTokenSecret; QByteArray result = hmacSha1(signatureBase, key); QByteArray resultBE64 = result.toBase64(); QByteArray resultPE = resultBE64.toPercentEncoding(); return resultPE; } /** * Generates OAuth signature base * @param url Url with encoded parameters * @param method Http method * @param timestamp timestamp * @param nonce random string * @return signature base */ QByteArray OAuth::generateSignatureBase(const QUrl& url, HttpMethod method, const QByteArray& timestamp, const QByteArray& nonce) { //OAuth spec. 9.1 http://oauth.net/core/1.0/#anchor14 //OAuth spec. 9.1.1 QList<QPair<QByteArray, QByteArray> > urlParameters = url.encodedQueryItems(); QList<QByteArray> normParameters; QListIterator<QPair<QByteArray, QByteArray> > i(urlParameters); while(i.hasNext()){ QPair<QByteArray, QByteArray> queryItem = i.next(); QByteArray normItem = queryItem.first + '=' + queryItem.second; normParameters.append(normItem); } //consumer key normParameters.append(QByteArray("oauth_consumer_key=") + m_oauthConsumerKey); //token if(!m_oauthToken.isEmpty()){ normParameters.append(QByteArray("oauth_token=") + m_oauthToken); } //signature method, only HMAC_SHA1 normParameters.append(QByteArray("oauth_signature_method=HMAC-SHA1")); //time stamp normParameters.append(QByteArray("oauth_timestamp=") + timestamp); //nonce normParameters.append(QByteArray("oauth_nonce=") + nonce); //version normParameters.append(QByteArray("oauth_version=1.0")); //OAuth spec. 9.1.1.1 qSort(normParameters); //OAuth spec. 9.1.1.2 //QByteArray normString; //QListIterator<QByteArray> j(normParameters); //while(j.hasNext()){ // normString += j.next(); // normString += '&'; //} //normString.chop(1); QByteArray normString; QListIterator<QByteArray> j(normParameters); while (j.hasNext()) { normString += j.next().toPercentEncoding(); normString += "%26"; } normString.chop(3); //OAuth spec. 9.1.2 QString urlScheme = url.scheme(); QString urlPath = url.path(); QString urlHost = url.host(); QByteArray normUrl = urlScheme.toUtf8() + "://" + urlHost.toUtf8() + urlPath.toUtf8(); QByteArray httpm; switch (method) { case OAuth::GET: httpm = "GET"; break; case OAuth::POST: httpm = "POST"; break; case OAuth::DELETE: httpm = "DELETE"; break; case OAuth::PUT: httpm = "PUT"; break; } //OAuth spec. 9.1.3 return httpm + '&' + normUrl.toPercentEncoding() + '&' + normString; } /** * Generates Authorization Header * @param url url with query items embedded * @param method type of http method * @remarks If HttpMethod is POST put query items in url (QUrl::addEncodedQueryItem) */ QByteArray OAuth::generateAuthorizationHeader( const QUrl& url, HttpMethod method ) { if (m_oauthToken.isEmpty() && m_oauthTokenSecret.isEmpty()) qDebug() << "OAuth tokens are empty!"; QByteArray timeStamp = generateTimeStamp(); QByteArray nonce = generateNonce(); QByteArray sigBase = generateSignatureBase(url, method, timeStamp, nonce); QByteArray signature = generateSignatureHMACSHA1(sigBase); QByteArray header; header += "OAuth "; header += "oauth_consumer_key=\"" + m_oauthConsumerKey + "\","; if(!m_oauthToken.isEmpty()) header += "oauth_token=\"" + m_oauthToken + "\","; header += "oauth_signature_method=\"HMAC-SHA1\","; header += "oauth_signature=\"" + signature + "\","; header += "oauth_timestamp=\"" + timeStamp + "\","; header += "oauth_nonce=\"" + nonce + "\","; header += "oauth_version=\"1.0\""; return header; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: pipe.cxx,v $ * * $Revision: 1.6 $ * * last change: $Author: hr $ $Date: 2006-06-20 04:07:03 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #include <vos/pipe.hxx> #include <vos/diagnose.hxx> using namespace vos; /////////////////////////////////////////////////////////////////////////////// // Pipe VOS_IMPLEMENT_CLASSINFO(VOS_CLASSNAME(OPipe, vos), VOS_NAMESPACE(OPipe, vos), VOS_NAMESPACE(OObject, vos), 0); /*****************************************************************************/ // OPipe() /*****************************************************************************/ OPipe::OPipe() { m_pPipeRef= 0; } /*****************************************************************************/ // OPipe() /*****************************************************************************/ OPipe::OPipe( const rtl::OUString& strName, TPipeOption Options) { m_pPipeRef = new PipeRef( osl_createPipe(strName.pData, (oslPipeOptions)Options, NULL) ); VOS_POSTCOND(m_pPipeRef != 0, "OPipe(): new failed.\n"); VOS_POSTCOND((*m_pPipeRef)(), "OPipe(): creation of pipe failed!\n"); } /*****************************************************************************/ // OPipe() /*****************************************************************************/ OPipe::OPipe( const rtl::OUString& strName, TPipeOption Options, const OSecurity& rSecurity) { m_pPipeRef= new PipeRef(osl_createPipe(strName.pData, (oslPipeOptions)Options, (oslSecurity)rSecurity)); VOS_POSTCOND(m_pPipeRef != 0, "OPipe(): new failed.\n"); VOS_POSTCOND((*m_pPipeRef)(), "OPipe(): creation of pipe failed!\n"); } /*****************************************************************************/ // OPipe() /*****************************************************************************/ OPipe::OPipe(const OPipe& pipe) : OReference(), OObject() { VOS_ASSERT(pipe.m_pPipeRef != 0); m_pPipeRef= pipe.m_pPipeRef; m_pPipeRef->acquire(); } /*****************************************************************************/ // OPipe() /*****************************************************************************/ OPipe::OPipe(oslPipe Pipe) { m_pPipeRef = new PipeRef(Pipe); } /*****************************************************************************/ // ~OPipe() /*****************************************************************************/ OPipe::~OPipe() { close(); } /*****************************************************************************/ // create /*****************************************************************************/ sal_Bool OPipe::create( const rtl::OUString& strName, TPipeOption Options ) { // if this was a valid pipe, decrease reference if ((m_pPipeRef) && (m_pPipeRef->release() == 0)) { osl_releasePipe((*m_pPipeRef)()); delete m_pPipeRef; m_pPipeRef= 0; } m_pPipeRef= new PipeRef(osl_createPipe(strName.pData, (oslPipeOptions)Options, NULL)); VOS_POSTCOND(m_pPipeRef != 0, "OPipe(): new failed.\n"); return (*m_pPipeRef)() != 0; } /*****************************************************************************/ // create /*****************************************************************************/ sal_Bool OPipe::create( const rtl::OUString& strName, TPipeOption Options, const NAMESPACE_VOS(OSecurity)& rSecurity ) { // if this was a valid pipe, decrease reference if ((m_pPipeRef) && (m_pPipeRef->release() == 0)) { osl_releasePipe((*m_pPipeRef)()); delete m_pPipeRef; m_pPipeRef= 0; } m_pPipeRef= new PipeRef(osl_createPipe(strName.pData, (oslPipeOptions)Options, (oslSecurity)rSecurity)); VOS_POSTCOND(m_pPipeRef != 0, "OPipe(): new failed.\n"); return (*m_pPipeRef)() != 0; } /*****************************************************************************/ // operator= /*****************************************************************************/ OPipe& OPipe::operator= (const OPipe& pipe) { VOS_PRECOND(pipe.m_pPipeRef != 0, "OPipe::operator=: tried to assign an empty/invalid pipe\n"); if (m_pPipeRef == pipe.m_pPipeRef) return *this; // if this was a valid pipe, decrease reference if ((m_pPipeRef) && (m_pPipeRef->release() == 0)) { osl_releasePipe((*m_pPipeRef)()); delete m_pPipeRef; m_pPipeRef= 0; } m_pPipeRef= pipe.m_pPipeRef; m_pPipeRef->acquire(); return *this; } /*****************************************************************************/ // operator oslPipe() /*****************************************************************************/ OPipe::operator oslPipe() const { VOS_ASSERT(m_pPipeRef); return (*m_pPipeRef)(); } /*****************************************************************************/ // isValid() /*****************************************************************************/ sal_Bool OPipe::isValid() const { return m_pPipeRef != 0 && (*m_pPipeRef)() != 0; } /*****************************************************************************/ // close /*****************************************************************************/ void OPipe::close() { if (m_pPipeRef && (m_pPipeRef->release() == 0)) { osl_releasePipe((*m_pPipeRef)()); delete m_pPipeRef; } m_pPipeRef= 0; } /*****************************************************************************/ // accept /*****************************************************************************/ OPipe::TPipeError OPipe::accept(OStreamPipe& Connection) { if ( isValid() ) { Connection = osl_acceptPipe((*m_pPipeRef)()); if(Connection.isValid()) return E_None; } return getError(); } /*****************************************************************************/ // recv /*****************************************************************************/ sal_Int32 OPipe::recv(void* pBuffer, sal_uInt32 BytesToRead) { if ( isValid() ) return osl_receivePipe((*m_pPipeRef)(), pBuffer, BytesToRead); else return -1; } /*****************************************************************************/ // send /*****************************************************************************/ sal_Int32 OPipe::send(const void* pBuffer, sal_uInt32 BytesToSend) { if ( isValid() ) return osl_sendPipe((*m_pPipeRef)(), pBuffer, BytesToSend); else return -1; } /*****************************************************************************/ // getError /*****************************************************************************/ OPipe::TPipeError OPipe::getError() const { if (m_pPipeRef) return (TPipeError)osl_getLastPipeError((*m_pPipeRef)()); else return (TPipeError)osl_getLastPipeError(NULL); } VOS_IMPLEMENT_CLASSINFO(VOS_CLASSNAME(OStreamPipe, vos), VOS_NAMESPACE(OStreamPipe, vos), VOS_NAMESPACE(OPipe, vos), 0); /*****************************************************************************/ // OStreamPipe /*****************************************************************************/ OStreamPipe::OStreamPipe() { } /*****************************************************************************/ // OStreamPipe /*****************************************************************************/ OStreamPipe::OStreamPipe(oslPipe Pipe) : OPipe(Pipe) { } /*****************************************************************************/ // OStreamPipe // copy constructor /*****************************************************************************/ OStreamPipe::OStreamPipe(const OStreamPipe& pipe) : OPipe(), IStream() { VOS_ASSERT(pipe.m_pPipeRef != 0); m_pPipeRef= pipe.m_pPipeRef; m_pPipeRef->acquire(); } /*****************************************************************************/ // ~OStreamPipe /*****************************************************************************/ OStreamPipe::~OStreamPipe() { } /*****************************************************************************/ // operator=(oslPipe) /*****************************************************************************/ OStreamPipe& OStreamPipe::operator=(oslPipe Pipe) { // if this was a valid pipe, decrease reference if (m_pPipeRef && (m_pPipeRef->release() == 0)) { osl_releasePipe((*m_pPipeRef)()); delete m_pPipeRef; m_pPipeRef= 0; } m_pPipeRef= new PipeRef(Pipe); VOS_POSTCOND(m_pPipeRef != 0, "OPipe(): new failed.\n"); return *this; } /*****************************************************************************/ // operator=OPipe /*****************************************************************************/ OStreamPipe& OStreamPipe::operator= (const OPipe& pipe) { OPipe::operator= ( pipe ); return *this; } /*****************************************************************************/ // read /*****************************************************************************/ sal_Int32 OStreamPipe::read(void* pBuffer, sal_uInt32 n) const { VOS_ASSERT(m_pPipeRef && (*m_pPipeRef)()); /* loop until all desired bytes were read or an error occured */ sal_Int32 BytesRead= 0; sal_Int32 BytesToRead= n; while (BytesToRead > 0) { sal_Int32 RetVal; RetVal= osl_receivePipe((*m_pPipeRef)(), pBuffer, BytesToRead); /* error occured? */ if(RetVal <= 0) { break; } BytesToRead -= RetVal; BytesRead += RetVal; pBuffer= (sal_Char*)pBuffer + RetVal; } return BytesRead; } /*****************************************************************************/ // write /*****************************************************************************/ sal_Int32 OStreamPipe::write(const void* pBuffer, sal_uInt32 n) { VOS_ASSERT(m_pPipeRef && (*m_pPipeRef)()); /* loop until all desired bytes were send or an error occured */ sal_Int32 BytesSend= 0; sal_Int32 BytesToSend= n; while (BytesToSend > 0) { sal_Int32 RetVal; RetVal= osl_sendPipe((*m_pPipeRef)(), pBuffer, BytesToSend); /* error occured? */ if(RetVal <= 0) { break; } BytesToSend -= RetVal; BytesSend += RetVal; pBuffer= (sal_Char*)pBuffer + RetVal; } return BytesSend; } sal_Bool OStreamPipe::isEof() const { return isValid(); } <commit_msg>INTEGRATION: CWS changefileheader (1.6.38); FILE MERGED 2008/03/31 07:26:56 rt 1.6.38.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: pipe.cxx,v $ * $Revision: 1.7 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #include <vos/pipe.hxx> #include <vos/diagnose.hxx> using namespace vos; /////////////////////////////////////////////////////////////////////////////// // Pipe VOS_IMPLEMENT_CLASSINFO(VOS_CLASSNAME(OPipe, vos), VOS_NAMESPACE(OPipe, vos), VOS_NAMESPACE(OObject, vos), 0); /*****************************************************************************/ // OPipe() /*****************************************************************************/ OPipe::OPipe() { m_pPipeRef= 0; } /*****************************************************************************/ // OPipe() /*****************************************************************************/ OPipe::OPipe( const rtl::OUString& strName, TPipeOption Options) { m_pPipeRef = new PipeRef( osl_createPipe(strName.pData, (oslPipeOptions)Options, NULL) ); VOS_POSTCOND(m_pPipeRef != 0, "OPipe(): new failed.\n"); VOS_POSTCOND((*m_pPipeRef)(), "OPipe(): creation of pipe failed!\n"); } /*****************************************************************************/ // OPipe() /*****************************************************************************/ OPipe::OPipe( const rtl::OUString& strName, TPipeOption Options, const OSecurity& rSecurity) { m_pPipeRef= new PipeRef(osl_createPipe(strName.pData, (oslPipeOptions)Options, (oslSecurity)rSecurity)); VOS_POSTCOND(m_pPipeRef != 0, "OPipe(): new failed.\n"); VOS_POSTCOND((*m_pPipeRef)(), "OPipe(): creation of pipe failed!\n"); } /*****************************************************************************/ // OPipe() /*****************************************************************************/ OPipe::OPipe(const OPipe& pipe) : OReference(), OObject() { VOS_ASSERT(pipe.m_pPipeRef != 0); m_pPipeRef= pipe.m_pPipeRef; m_pPipeRef->acquire(); } /*****************************************************************************/ // OPipe() /*****************************************************************************/ OPipe::OPipe(oslPipe Pipe) { m_pPipeRef = new PipeRef(Pipe); } /*****************************************************************************/ // ~OPipe() /*****************************************************************************/ OPipe::~OPipe() { close(); } /*****************************************************************************/ // create /*****************************************************************************/ sal_Bool OPipe::create( const rtl::OUString& strName, TPipeOption Options ) { // if this was a valid pipe, decrease reference if ((m_pPipeRef) && (m_pPipeRef->release() == 0)) { osl_releasePipe((*m_pPipeRef)()); delete m_pPipeRef; m_pPipeRef= 0; } m_pPipeRef= new PipeRef(osl_createPipe(strName.pData, (oslPipeOptions)Options, NULL)); VOS_POSTCOND(m_pPipeRef != 0, "OPipe(): new failed.\n"); return (*m_pPipeRef)() != 0; } /*****************************************************************************/ // create /*****************************************************************************/ sal_Bool OPipe::create( const rtl::OUString& strName, TPipeOption Options, const NAMESPACE_VOS(OSecurity)& rSecurity ) { // if this was a valid pipe, decrease reference if ((m_pPipeRef) && (m_pPipeRef->release() == 0)) { osl_releasePipe((*m_pPipeRef)()); delete m_pPipeRef; m_pPipeRef= 0; } m_pPipeRef= new PipeRef(osl_createPipe(strName.pData, (oslPipeOptions)Options, (oslSecurity)rSecurity)); VOS_POSTCOND(m_pPipeRef != 0, "OPipe(): new failed.\n"); return (*m_pPipeRef)() != 0; } /*****************************************************************************/ // operator= /*****************************************************************************/ OPipe& OPipe::operator= (const OPipe& pipe) { VOS_PRECOND(pipe.m_pPipeRef != 0, "OPipe::operator=: tried to assign an empty/invalid pipe\n"); if (m_pPipeRef == pipe.m_pPipeRef) return *this; // if this was a valid pipe, decrease reference if ((m_pPipeRef) && (m_pPipeRef->release() == 0)) { osl_releasePipe((*m_pPipeRef)()); delete m_pPipeRef; m_pPipeRef= 0; } m_pPipeRef= pipe.m_pPipeRef; m_pPipeRef->acquire(); return *this; } /*****************************************************************************/ // operator oslPipe() /*****************************************************************************/ OPipe::operator oslPipe() const { VOS_ASSERT(m_pPipeRef); return (*m_pPipeRef)(); } /*****************************************************************************/ // isValid() /*****************************************************************************/ sal_Bool OPipe::isValid() const { return m_pPipeRef != 0 && (*m_pPipeRef)() != 0; } /*****************************************************************************/ // close /*****************************************************************************/ void OPipe::close() { if (m_pPipeRef && (m_pPipeRef->release() == 0)) { osl_releasePipe((*m_pPipeRef)()); delete m_pPipeRef; } m_pPipeRef= 0; } /*****************************************************************************/ // accept /*****************************************************************************/ OPipe::TPipeError OPipe::accept(OStreamPipe& Connection) { if ( isValid() ) { Connection = osl_acceptPipe((*m_pPipeRef)()); if(Connection.isValid()) return E_None; } return getError(); } /*****************************************************************************/ // recv /*****************************************************************************/ sal_Int32 OPipe::recv(void* pBuffer, sal_uInt32 BytesToRead) { if ( isValid() ) return osl_receivePipe((*m_pPipeRef)(), pBuffer, BytesToRead); else return -1; } /*****************************************************************************/ // send /*****************************************************************************/ sal_Int32 OPipe::send(const void* pBuffer, sal_uInt32 BytesToSend) { if ( isValid() ) return osl_sendPipe((*m_pPipeRef)(), pBuffer, BytesToSend); else return -1; } /*****************************************************************************/ // getError /*****************************************************************************/ OPipe::TPipeError OPipe::getError() const { if (m_pPipeRef) return (TPipeError)osl_getLastPipeError((*m_pPipeRef)()); else return (TPipeError)osl_getLastPipeError(NULL); } VOS_IMPLEMENT_CLASSINFO(VOS_CLASSNAME(OStreamPipe, vos), VOS_NAMESPACE(OStreamPipe, vos), VOS_NAMESPACE(OPipe, vos), 0); /*****************************************************************************/ // OStreamPipe /*****************************************************************************/ OStreamPipe::OStreamPipe() { } /*****************************************************************************/ // OStreamPipe /*****************************************************************************/ OStreamPipe::OStreamPipe(oslPipe Pipe) : OPipe(Pipe) { } /*****************************************************************************/ // OStreamPipe // copy constructor /*****************************************************************************/ OStreamPipe::OStreamPipe(const OStreamPipe& pipe) : OPipe(), IStream() { VOS_ASSERT(pipe.m_pPipeRef != 0); m_pPipeRef= pipe.m_pPipeRef; m_pPipeRef->acquire(); } /*****************************************************************************/ // ~OStreamPipe /*****************************************************************************/ OStreamPipe::~OStreamPipe() { } /*****************************************************************************/ // operator=(oslPipe) /*****************************************************************************/ OStreamPipe& OStreamPipe::operator=(oslPipe Pipe) { // if this was a valid pipe, decrease reference if (m_pPipeRef && (m_pPipeRef->release() == 0)) { osl_releasePipe((*m_pPipeRef)()); delete m_pPipeRef; m_pPipeRef= 0; } m_pPipeRef= new PipeRef(Pipe); VOS_POSTCOND(m_pPipeRef != 0, "OPipe(): new failed.\n"); return *this; } /*****************************************************************************/ // operator=OPipe /*****************************************************************************/ OStreamPipe& OStreamPipe::operator= (const OPipe& pipe) { OPipe::operator= ( pipe ); return *this; } /*****************************************************************************/ // read /*****************************************************************************/ sal_Int32 OStreamPipe::read(void* pBuffer, sal_uInt32 n) const { VOS_ASSERT(m_pPipeRef && (*m_pPipeRef)()); /* loop until all desired bytes were read or an error occured */ sal_Int32 BytesRead= 0; sal_Int32 BytesToRead= n; while (BytesToRead > 0) { sal_Int32 RetVal; RetVal= osl_receivePipe((*m_pPipeRef)(), pBuffer, BytesToRead); /* error occured? */ if(RetVal <= 0) { break; } BytesToRead -= RetVal; BytesRead += RetVal; pBuffer= (sal_Char*)pBuffer + RetVal; } return BytesRead; } /*****************************************************************************/ // write /*****************************************************************************/ sal_Int32 OStreamPipe::write(const void* pBuffer, sal_uInt32 n) { VOS_ASSERT(m_pPipeRef && (*m_pPipeRef)()); /* loop until all desired bytes were send or an error occured */ sal_Int32 BytesSend= 0; sal_Int32 BytesToSend= n; while (BytesToSend > 0) { sal_Int32 RetVal; RetVal= osl_sendPipe((*m_pPipeRef)(), pBuffer, BytesToSend); /* error occured? */ if(RetVal <= 0) { break; } BytesToSend -= RetVal; BytesSend += RetVal; pBuffer= (sal_Char*)pBuffer + RetVal; } return BytesSend; } sal_Bool OStreamPipe::isEof() const { return isValid(); } <|endoftext|>
<commit_before>/* * Copyright (c) 2010, Joshua Lackey * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "usrp_source.h" #include "fcch_detector.h" #include "util.h" #ifdef _WIN32 inline double round (double x) { return floor (x + 0.5); } #endif static const unsigned int AVG_COUNT = 100; static const unsigned int AVG_THRESHOLD = (AVG_COUNT / 10); static const float OFFSET_MAX = 40e3; extern int g_verbosity; int offset_detect (usrp_source * u) { #define GSM_RATE (1625000.0 / 6.0) unsigned int new_overruns = 0, overruns = 0; int notfound = 0; unsigned int s_len, b_len, consumed, count; float offset = 0.0, min = 0.0, max = 0.0, avg_offset = 0.0, stddev = 0.0, sps, offsets[AVG_COUNT]; double total_ppm; complex *cbuf; fcch_detector *l; circular_buffer *cb; l = new fcch_detector (u->sample_rate ()); /* * We deliberately grab 12 frames and 1 burst. We are guaranteed to * find at least one FCCH burst in this much data. */ sps = u->sample_rate () / GSM_RATE; s_len = (unsigned int) ceil ((12 * 8 * 156.25 + 156.25) * sps); cb = u->get_buffer (); u->start (); u->flush (); count = 0; while (count < AVG_COUNT) { // ensure at least s_len contiguous samples are read from usrp do { if (u->fill (s_len, &new_overruns)) { return -1; } if (new_overruns) { overruns += new_overruns; u->flush (); } } while (new_overruns); // get a pointer to the next samples cbuf = (complex *) cb->peek (&b_len); // search the buffer for a pure tone if (l->scan (cbuf, b_len, &offset, &consumed)) { // FCH is a sine wave at GSM_RATE / 4 offset = offset - GSM_RATE / 4; // sanity check offset if (fabs (offset) < OFFSET_MAX) { offsets[count] = offset; count += 1; if (g_verbosity > 0) { fprintf (stderr, "\toffset %3u: %.2f\n", count, offset); } } } else { ++notfound; } // consume used samples cb->purge (consumed); } u->stop (); delete l; // construct stats sort (offsets, AVG_COUNT); avg_offset = avg (offsets + AVG_THRESHOLD, AVG_COUNT - 2 * AVG_THRESHOLD, &stddev); min = offsets[AVG_THRESHOLD]; max = offsets[AVG_COUNT - AVG_THRESHOLD - 1]; printf ("average\t\t[min, max]\t(range, stddev)\n"); display_freq (avg_offset); printf ("\t\t[%d, %d]\t(%d, %f)\n", (int) round (min), (int) round (max), (int) round (max - min), stddev); printf ("overruns: %u\n", overruns); printf ("not found: %u\n", notfound); total_ppm = u->m_freq_corr - (avg_offset / u->m_center_freq) * 1000000; printf ("average absolute error: %.3f ppm\n", total_ppm); return 0; } <commit_msg>show search progress<commit_after>/* * Copyright (c) 2010, Joshua Lackey * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "usrp_source.h" #include "fcch_detector.h" #include "util.h" #ifdef _WIN32 inline double round (double x) { return floor (x + 0.5); } #endif static const unsigned int AVG_COUNT = 100; static const unsigned int AVG_THRESHOLD = (AVG_COUNT / 10); static const float OFFSET_MAX = 40e3; extern int g_verbosity; int offset_detect (usrp_source * u) { #define GSM_RATE (1625000.0 / 6.0) unsigned int new_overruns = 0, overruns = 0; int notfound = 0; unsigned int s_len, b_len, consumed, count; float offset = 0.0, min = 0.0, max = 0.0, avg_offset = 0.0, stddev = 0.0, sps, offsets[AVG_COUNT]; double total_ppm; complex *cbuf; fcch_detector *l; circular_buffer *cb; l = new fcch_detector (u->sample_rate ()); /* * We deliberately grab 12 frames and 1 burst. We are guaranteed to * find at least one FCCH burst in this much data. */ sps = u->sample_rate () / GSM_RATE; s_len = (unsigned int) ceil ((12 * 8 * 156.25 + 156.25) * sps); cb = u->get_buffer (); u->start (); u->flush (); count = 0; while (count < AVG_COUNT) { // ensure at least s_len contiguous samples are read from usrp do { if (u->fill (s_len, &new_overruns)) { return -1; } if (new_overruns) { overruns += new_overruns; u->flush (); } } while (new_overruns); // get a pointer to the next samples cbuf = (complex *) cb->peek (&b_len); // search the buffer for a pure tone if (l->scan (cbuf, b_len, &offset, &consumed)) { // FCH is a sine wave at GSM_RATE / 4 offset = offset - GSM_RATE / 4; // sanity check offset if (fabs (offset) < OFFSET_MAX) { offsets[count] = offset; count += 1; if (g_verbosity > 0) { fprintf (stderr, "\toffset %3u/%3u: %.2f\n", count, AVG_COUNT, offset); } } } else { ++notfound; } // consume used samples cb->purge (consumed); } u->stop (); delete l; // construct stats sort (offsets, AVG_COUNT); avg_offset = avg (offsets + AVG_THRESHOLD, AVG_COUNT - 2 * AVG_THRESHOLD, &stddev); min = offsets[AVG_THRESHOLD]; max = offsets[AVG_COUNT - AVG_THRESHOLD - 1]; printf ("average\t\t[min, max]\t(range, stddev)\n"); display_freq (avg_offset); printf ("\t\t[%d, %d]\t(%d, %f)\n", (int) round (min), (int) round (max), (int) round (max - min), stddev); printf ("overruns: %u\n", overruns); printf ("not found: %u\n", notfound); total_ppm = u->m_freq_corr - (avg_offset / u->m_center_freq) * 1000000; printf ("average absolute error: %.3f ppm\n", total_ppm); return 0; } <|endoftext|>
<commit_before>/*! * \page CRSTestSuite_cpp Command-Line Test to Demonstrate How To Test the SimCRS Project * \code */ // ////////////////////////////////////////////////////////////////////// // Import section // ////////////////////////////////////////////////////////////////////// // STL #include <sstream> #include <fstream> #include <string> #include <cmath> // Boost Unit Test Framework (UTF) #define BOOST_TEST_DYN_LINK #define BOOST_TEST_MAIN #define BOOST_TEST_MODULE CRSTestSuite #include <boost/test/unit_test.hpp> // StdAir #include <stdair/basic/BasLogParams.hpp> #include <stdair/basic/BasDBParams.hpp> #include <stdair/basic/BasFileMgr.hpp> #include <stdair/bom/TravelSolutionStruct.hpp> #include <stdair/bom/BookingRequestStruct.hpp> #include <stdair/service/Logger.hpp> // SimCRS #include <simcrs/SIMCRS_Service.hpp> #include <simcrs/config/simcrs-paths.hpp> namespace boost_utf = boost::unit_test; // (Boost) Unit Test XML Report std::ofstream utfReportStream ("CRSTestSuite_utfresults.xml"); /** * Configuration for the Boost Unit Test Framework (UTF) */ struct UnitTestConfig { /** Constructor. */ UnitTestConfig() { boost_utf::unit_test_log.set_stream (utfReportStream); boost_utf::unit_test_log.set_format (boost_utf::XML); boost_utf::unit_test_log.set_threshold_level (boost_utf::log_test_units); //boost_utf::unit_test_log.set_threshold_level (boost_utf::log_successful_tests); } /** Destructor. */ ~UnitTestConfig() { } }; // /////////////// Main: Unit Test Suite ////////////// // Set the UTF configuration (re-direct the output to a specific file) BOOST_GLOBAL_FIXTURE (UnitTestConfig); // Start the test suite BOOST_AUTO_TEST_SUITE (master_test_suite) /** * Test a simple simulation */ BOOST_AUTO_TEST_CASE (simcrs_simple_simulation_test) { // CRS code const SIMCRS::CRSCode_T lCRSCode ("1P"); // Schedule input filename const stdair::Filename_T lScheduleInputFilename (STDAIR_SAMPLE_DIR "/rds01/schedule.csv"); // O&D input filename const stdair::Filename_T lOnDInputFilename (STDAIR_SAMPLE_DIR "/ond01.csv"); // Fare input filename const stdair::Filename_T lFareInputFilename (STDAIR_SAMPLE_DIR "/rds01/fare.csv"); // Yield input filename const stdair::Filename_T lYieldInputFilename (STDAIR_SAMPLE_DIR "/rds01/yield.csv"); // Check that the file path given as input corresponds to an actual file bool doesExistAndIsReadable = stdair::BasFileMgr::doesExistAndIsReadable (lScheduleInputFilename); BOOST_CHECK_MESSAGE (doesExistAndIsReadable == true, "The '" << lScheduleInputFilename << "' input file can not be open and read"); // Check that the file path given as input corresponds to an actual file doesExistAndIsReadable = stdair::BasFileMgr::doesExistAndIsReadable (lOnDInputFilename); BOOST_CHECK_MESSAGE (doesExistAndIsReadable == true, "The '" << lOnDInputFilename << "' input file can not be open and read"); // Check that the file path given as input corresponds to an actual file doesExistAndIsReadable = stdair::BasFileMgr::doesExistAndIsReadable (lFareInputFilename); BOOST_CHECK_MESSAGE (doesExistAndIsReadable == true, "The '" << lFareInputFilename << "' input file can not be open and read"); // Check that the file path given as input corresponds to an actual file doesExistAndIsReadable = stdair::BasFileMgr::doesExistAndIsReadable (lYieldInputFilename); BOOST_CHECK_MESSAGE (doesExistAndIsReadable == true, "The '" << lYieldInputFilename << "' input file can not be open and read"); // Output log File const stdair::Filename_T lLogFilename ("CRSTestSuite.log"); // Set the log parameters std::ofstream logOutputFile; // Open and clean the log outputfile logOutputFile.open (lLogFilename.c_str()); logOutputFile.clear(); // Initialise the list of classes/buckets const stdair::BasLogParams lLogParams (stdair::LOG::DEBUG, logOutputFile); SIMCRS::SIMCRS_Service simcrsService (lLogParams, lCRSCode, lScheduleInputFilename, lOnDInputFilename, lFareInputFilename, lYieldInputFilename); // Create an empty booking request structure // TODO: fill the booking request structure from the input parameters const stdair::AirportCode_T lOrigin ("SIN"); const stdair::AirportCode_T lDestination ("BKK"); const stdair::AirportCode_T lPOS ("SIN"); const stdair::Date_T lPreferredDepartureDate(2011, boost::gregorian::Jan, 31); const stdair::Date_T lRequestDate (2011, boost::gregorian::Jan, 22); const stdair::Duration_T lRequestTime (boost::posix_time::hours(10)); const stdair::DateTime_T lRequestDateTime (lRequestDate, lRequestTime); const stdair::CabinCode_T lPreferredCabin ("Eco"); const stdair::PartySize_T lPartySize (3); const stdair::ChannelLabel_T lChannel ("IN"); const stdair::TripType_T lTripType ("RI"); const stdair::DayDuration_T lStayDuration (7); const stdair::FrequentFlyer_T lFrequentFlyerType ("M"); const stdair::Duration_T lPreferredDepartureTime (boost::posix_time::hours(10)); const stdair::WTP_T lWTP (1000.0); const stdair::PriceValue_T lValueOfTime (100.0); const stdair::BookingRequestStruct lBookingRequest (lOrigin, lDestination, lPOS, lPreferredDepartureDate, lRequestDateTime, lPreferredCabin, lPartySize, lChannel, lTripType, lStayDuration, lFrequentFlyerType, lPreferredDepartureTime, lWTP, lValueOfTime); stdair::TravelSolutionList_T lTravelSolutionList = simcrsService.calculateSegmentPathList (lBookingRequest); // Price the travel solution simcrsService.fareQuote (lBookingRequest, lTravelSolutionList); // const unsigned int lNbOfTravelSolutions = lTravelSolutionList.size(); // TODO: change the expected number of travel solutions to the actual number const unsigned int lExpectedNbOfTravelSolutions = 1; // DEBUG STDAIR_LOG_DEBUG ("Number of travel solutions for the booking request '" << lBookingRequest.describe() << "': " << lNbOfTravelSolutions << ". It is expected to be " << lExpectedNbOfTravelSolutions); BOOST_CHECK_EQUAL (lNbOfTravelSolutions, lExpectedNbOfTravelSolutions); BOOST_CHECK_MESSAGE(lNbOfTravelSolutions == lExpectedNbOfTravelSolutions, "The number of travel solutions for the booking request '" << lBookingRequest.describe() << "' is equal to " << lNbOfTravelSolutions << ", but it should be equal to " << lExpectedNbOfTravelSolutions); // stdair::TravelSolutionStruct& lTravelSolution = lTravelSolutionList.front(); // stdair::FareOptionList_T lFareOptionList = lTravelSolution.getFareOptionList (); // stdair::FareOptionStruct lFareOption = lFareOptionList.front(); lTravelSolution.setChosenFareOption (lFareOption); // const unsigned int lExpectedPrice = 160; // DEBUG STDAIR_LOG_DEBUG ("The price given by the fare quoter for '" << lTravelSolution.describe() << "' is: " << lFareOption.getFare() << " Euros, and should be " << lExpectedPrice); BOOST_CHECK_EQUAL (std::floor (lFareOption.getFare() + 0.5), lExpectedPrice); BOOST_CHECK_MESSAGE (std::floor (lFareOption.getFare() + 0.5) == lExpectedPrice, "The price given by the fare quoter for '" << lTravelSolution.describe() << "' is: " << lFareOption.getFare() << " Euros, and should be " << lExpectedPrice); // Make a booking (reminder: party size is 3) const bool isSellSuccessful = simcrsService.sell (lTravelSolution, lPartySize); //BOOST_CHECK_NO_THROW (); // Close the log file logOutputFile.close(); } // End the test suite BOOST_AUTO_TEST_SUITE_END() /*! * \endcode */ <commit_msg>[Test] Modified the expected price according to trip type.<commit_after>/*! * \page CRSTestSuite_cpp Command-Line Test to Demonstrate How To Test the SimCRS Project * \code */ // ////////////////////////////////////////////////////////////////////// // Import section // ////////////////////////////////////////////////////////////////////// // STL #include <sstream> #include <fstream> #include <string> #include <cmath> // Boost Unit Test Framework (UTF) #define BOOST_TEST_DYN_LINK #define BOOST_TEST_MAIN #define BOOST_TEST_MODULE CRSTestSuite #include <boost/test/unit_test.hpp> // StdAir #include <stdair/basic/BasLogParams.hpp> #include <stdair/basic/BasDBParams.hpp> #include <stdair/basic/BasFileMgr.hpp> #include <stdair/bom/TravelSolutionStruct.hpp> #include <stdair/bom/BookingRequestStruct.hpp> #include <stdair/service/Logger.hpp> // SimCRS #include <simcrs/SIMCRS_Service.hpp> #include <simcrs/config/simcrs-paths.hpp> namespace boost_utf = boost::unit_test; // (Boost) Unit Test XML Report std::ofstream utfReportStream ("CRSTestSuite_utfresults.xml"); /** * Configuration for the Boost Unit Test Framework (UTF) */ struct UnitTestConfig { /** Constructor. */ UnitTestConfig() { boost_utf::unit_test_log.set_stream (utfReportStream); boost_utf::unit_test_log.set_format (boost_utf::XML); boost_utf::unit_test_log.set_threshold_level (boost_utf::log_test_units); //boost_utf::unit_test_log.set_threshold_level (boost_utf::log_successful_tests); } /** Destructor. */ ~UnitTestConfig() { } }; // /////////////// Main: Unit Test Suite ////////////// // Set the UTF configuration (re-direct the output to a specific file) BOOST_GLOBAL_FIXTURE (UnitTestConfig); // Start the test suite BOOST_AUTO_TEST_SUITE (master_test_suite) /** * Test a simple simulation */ BOOST_AUTO_TEST_CASE (simcrs_simple_simulation_test) { // CRS code const SIMCRS::CRSCode_T lCRSCode ("1P"); // Schedule input filename const stdair::Filename_T lScheduleInputFilename (STDAIR_SAMPLE_DIR "/rds01/schedule.csv"); // O&D input filename const stdair::Filename_T lOnDInputFilename (STDAIR_SAMPLE_DIR "/ond01.csv"); // Fare input filename const stdair::Filename_T lFareInputFilename (STDAIR_SAMPLE_DIR "/rds01/fare.csv"); // Yield input filename const stdair::Filename_T lYieldInputFilename (STDAIR_SAMPLE_DIR "/rds01/yield.csv"); // Check that the file path given as input corresponds to an actual file bool doesExistAndIsReadable = stdair::BasFileMgr::doesExistAndIsReadable (lScheduleInputFilename); BOOST_CHECK_MESSAGE (doesExistAndIsReadable == true, "The '" << lScheduleInputFilename << "' input file can not be open and read"); // Check that the file path given as input corresponds to an actual file doesExistAndIsReadable = stdair::BasFileMgr::doesExistAndIsReadable (lOnDInputFilename); BOOST_CHECK_MESSAGE (doesExistAndIsReadable == true, "The '" << lOnDInputFilename << "' input file can not be open and read"); // Check that the file path given as input corresponds to an actual file doesExistAndIsReadable = stdair::BasFileMgr::doesExistAndIsReadable (lFareInputFilename); BOOST_CHECK_MESSAGE (doesExistAndIsReadable == true, "The '" << lFareInputFilename << "' input file can not be open and read"); // Check that the file path given as input corresponds to an actual file doesExistAndIsReadable = stdair::BasFileMgr::doesExistAndIsReadable (lYieldInputFilename); BOOST_CHECK_MESSAGE (doesExistAndIsReadable == true, "The '" << lYieldInputFilename << "' input file can not be open and read"); // Output log File const stdair::Filename_T lLogFilename ("CRSTestSuite.log"); // Set the log parameters std::ofstream logOutputFile; // Open and clean the log outputfile logOutputFile.open (lLogFilename.c_str()); logOutputFile.clear(); // Initialise the list of classes/buckets const stdair::BasLogParams lLogParams (stdair::LOG::DEBUG, logOutputFile); SIMCRS::SIMCRS_Service simcrsService (lLogParams, lCRSCode, lScheduleInputFilename, lOnDInputFilename, lFareInputFilename, lYieldInputFilename); // Create an empty booking request structure // TODO: fill the booking request structure from the input parameters const stdair::AirportCode_T lOrigin ("SIN"); const stdair::AirportCode_T lDestination ("BKK"); const stdair::AirportCode_T lPOS ("SIN"); const stdair::Date_T lPreferredDepartureDate(2011, boost::gregorian::Jan, 31); const stdair::Date_T lRequestDate (2011, boost::gregorian::Jan, 22); const stdair::Duration_T lRequestTime (boost::posix_time::hours(10)); const stdair::DateTime_T lRequestDateTime (lRequestDate, lRequestTime); const stdair::CabinCode_T lPreferredCabin ("Eco"); const stdair::PartySize_T lPartySize (3); const stdair::ChannelLabel_T lChannel ("IN"); const stdair::TripType_T lTripType ("RI"); const stdair::DayDuration_T lStayDuration (7); const stdair::FrequentFlyer_T lFrequentFlyerType ("M"); const stdair::Duration_T lPreferredDepartureTime (boost::posix_time::hours(10)); const stdair::WTP_T lWTP (1000.0); const stdair::PriceValue_T lValueOfTime (100.0); const stdair::BookingRequestStruct lBookingRequest (lOrigin, lDestination, lPOS, lPreferredDepartureDate, lRequestDateTime, lPreferredCabin, lPartySize, lChannel, lTripType, lStayDuration, lFrequentFlyerType, lPreferredDepartureTime, lWTP, lValueOfTime); stdair::TravelSolutionList_T lTravelSolutionList = simcrsService.calculateSegmentPathList (lBookingRequest); // Price the travel solution simcrsService.fareQuote (lBookingRequest, lTravelSolutionList); // const unsigned int lNbOfTravelSolutions = lTravelSolutionList.size(); // TODO: change the expected number of travel solutions to the actual number const unsigned int lExpectedNbOfTravelSolutions = 1; // DEBUG STDAIR_LOG_DEBUG ("Number of travel solutions for the booking request '" << lBookingRequest.describe() << "': " << lNbOfTravelSolutions << ". It is expected to be " << lExpectedNbOfTravelSolutions); BOOST_CHECK_EQUAL (lNbOfTravelSolutions, lExpectedNbOfTravelSolutions); BOOST_CHECK_MESSAGE(lNbOfTravelSolutions == lExpectedNbOfTravelSolutions, "The number of travel solutions for the booking request '" << lBookingRequest.describe() << "' is equal to " << lNbOfTravelSolutions << ", but it should be equal to " << lExpectedNbOfTravelSolutions); // stdair::TravelSolutionStruct& lTravelSolution = lTravelSolutionList.front(); // stdair::FareOptionList_T lFareOptionList = lTravelSolution.getFareOptionList (); // stdair::FareOptionStruct lFareOption = lFareOptionList.front(); lTravelSolution.setChosenFareOption (lFareOption); // const unsigned int lExpectedPrice = 320; // DEBUG STDAIR_LOG_DEBUG ("The price given by the fare quoter for '" << lTravelSolution.describe() << "' is: " << lFareOption.getFare() << " Euros, and should be " << lExpectedPrice); BOOST_CHECK_EQUAL (std::floor (lFareOption.getFare() + 0.5), lExpectedPrice); BOOST_CHECK_MESSAGE (std::floor (lFareOption.getFare() + 0.5) == lExpectedPrice, "The price given by the fare quoter for '" << lTravelSolution.describe() << "' is: " << lFareOption.getFare() << " Euros, and should be " << lExpectedPrice); // Make a booking (reminder: party size is 3) const bool isSellSuccessful = simcrsService.sell (lTravelSolution, lPartySize); //BOOST_CHECK_NO_THROW (); // Close the log file logOutputFile.close(); } // End the test suite BOOST_AUTO_TEST_SUITE_END() /*! * \endcode */ <|endoftext|>
<commit_before>#ifndef __test_modelgen__ #define __test_modelgen__ #include <ciri/gfx/IGraphicsDevice.hpp> #include "Model.hpp" namespace modelgen { // width; height; depth; u-scale; v-scale static Model* createCube( float w, float h, float d, float us, float vs, ciri::IGraphicsDevice* device ) { Model* model = new Model(); model->addVertex(Vertex(cc::Vec3f(-0.5f*w, -0.5f*h, 0.5f*d), cc::Vec3f( 1.0f, 0.0f, 0.0f), cc::Vec2f(0.0f * us, 0.0f * vs))); model->addVertex(Vertex(cc::Vec3f( 0.5f*w, -0.5f*h, 0.5f*d), cc::Vec3f( 1.0f, 0.0f, 0.0f), cc::Vec2f(1.0f * us, 0.0f * vs))); model->addVertex(Vertex(cc::Vec3f( 0.5f*w, 0.5f*h, 0.5f*d), cc::Vec3f( 1.0f, 0.0f, 0.0f), cc::Vec2f(1.0f * us, 1.0f * vs))); model->addVertex(Vertex(cc::Vec3f(-0.5f*w, 0.5f*h, 0.5f*d), cc::Vec3f( 1.0f, 0.0f, 0.0f), cc::Vec2f(0.0f * us, 1.0f * vs))); model->addVertex(Vertex(cc::Vec3f(-0.5f*w, -0.5f*h, -0.5f*d), cc::Vec3f(-1.0f, 0.0f, 0.0f), cc::Vec2f(0.0f * us, 0.0f * vs))); model->addVertex(Vertex(cc::Vec3f(-0.5f*w, 0.5f*h, -0.5f*d), cc::Vec3f(-1.0f, 0.0f, 0.0f), cc::Vec2f(1.0f * us, 0.0f * vs))); model->addVertex(Vertex(cc::Vec3f( 0.5f*w, 0.5f*h, -0.5f*d), cc::Vec3f(-1.0f, 0.0f, 0.0f), cc::Vec2f(1.0f * us, 1.0f * vs))); model->addVertex(Vertex(cc::Vec3f( 0.5f*w, -0.5f*h, -0.5f*d), cc::Vec3f(-1.0f, 0.0f, 0.0f), cc::Vec2f(0.0f * us, 1.0f * vs))); model->addVertex(Vertex(cc::Vec3f(-0.5f*w, 0.5f*h, -0.5f*d), cc::Vec3f( 0.0f, 1.0f, 0.0f), cc::Vec2f(0.0f * us, 0.0f * vs))); model->addVertex(Vertex(cc::Vec3f(-0.5f*w, 0.5f*h, 0.5f*d), cc::Vec3f( 0.0f, 1.0f, 0.0f), cc::Vec2f(1.0f * us, 0.0f * vs))); model->addVertex(Vertex(cc::Vec3f( 0.5f*w, 0.5f*h, 0.5f*d), cc::Vec3f( 0.0f, 1.0f, 0.0f), cc::Vec2f(1.0f * us, 1.0f * vs))); model->addVertex(Vertex(cc::Vec3f( 0.5f*w, 0.5f*h, -0.5f*d), cc::Vec3f( 0.0f, 1.0f, 0.0f), cc::Vec2f(0.0f * us, 1.0f * vs))); model->addVertex(Vertex(cc::Vec3f(-0.5f*w, -0.5f*h, -0.5f*d), cc::Vec3f( 0.0f, -1.0f, 0.0f), cc::Vec2f(0.0f * us, 0.0f * vs))); model->addVertex(Vertex(cc::Vec3f( 0.5f*w, -0.5f*h, -0.5f*d), cc::Vec3f( 0.0f, -1.0f, 0.0f), cc::Vec2f(1.0f * us, 0.0f * vs))); model->addVertex(Vertex(cc::Vec3f( 0.5f*w, -0.5f*h, 0.5f*d), cc::Vec3f( 0.0f, -1.0f, 0.0f), cc::Vec2f(1.0f * us, 1.0f * vs))); model->addVertex(Vertex(cc::Vec3f(-0.5f*w, -0.5f*h, 0.5f*d), cc::Vec3f( 0.0f, -1.0f, 0.0f), cc::Vec2f(0.0f * us, 1.0f * vs))); model->addVertex(Vertex(cc::Vec3f( 0.5f*w, -0.5f*h, -0.5f*d), cc::Vec3f( 0.0f, 0.0f, 1.0f), cc::Vec2f(0.0f * us, 0.0f * vs))); model->addVertex(Vertex(cc::Vec3f( 0.5f*w, 0.5f*h, -0.5f*d), cc::Vec3f( 0.0f, 0.0f, 1.0f), cc::Vec2f(1.0f * us, 0.0f * vs))); model->addVertex(Vertex(cc::Vec3f( 0.5f*w, 0.5f*h, 0.5f*d), cc::Vec3f( 0.0f, 0.0f, 1.0f), cc::Vec2f(1.0f * us, 1.0f * vs))); model->addVertex(Vertex(cc::Vec3f( 0.5f*w, -0.5f*h, 0.5f*d), cc::Vec3f( 0.0f, 0.0f, 1.0f), cc::Vec2f(0.0f * us, 1.0f * vs))); model->addVertex(Vertex(cc::Vec3f(-0.5f*w, -0.5f*h, -0.5f*d), cc::Vec3f( 0.0f, 0.0f, -1.0f), cc::Vec2f(0.0f * us, 0.0f * vs))); model->addVertex(Vertex(cc::Vec3f(-0.5f*w, -0.5f*h, 0.5f*d), cc::Vec3f( 0.0f, 0.0f, -1.0f), cc::Vec2f(1.0f * us, 0.0f * vs))); model->addVertex(Vertex(cc::Vec3f(-0.5f*w, 0.5f*h, 0.5f*d), cc::Vec3f( 0.0f, 0.0f, -1.0f), cc::Vec2f(1.0f * us, 1.0f * vs))); model->addVertex(Vertex(cc::Vec3f(-0.5f*w, 0.5f*h, -0.5f*d), cc::Vec3f( 0.0f, 0.0f, -1.0f), cc::Vec2f(0.0f * us, 1.0f * vs))); model->addIndex(0); model->addIndex(1); model->addIndex(2); model->addIndex(0); model->addIndex(2); model->addIndex(3); // +x (right) model->addIndex(4); model->addIndex(5); model->addIndex(6); model->addIndex(4); model->addIndex(6); model->addIndex(7); // -x (left) model->addIndex(8); model->addIndex(9); model->addIndex(10); model->addIndex(8); model->addIndex(10); model->addIndex(11); // +y (top) model->addIndex(12); model->addIndex(13); model->addIndex(14); model->addIndex(12); model->addIndex(14); model->addIndex(15); // -y (bottom) model->addIndex(16); model->addIndex(17); model->addIndex(18); model->addIndex(16); model->addIndex(18); model->addIndex(19); // +z (front) model->addIndex(20); model->addIndex(21); model->addIndex(22); model->addIndex(20); model->addIndex(22); model->addIndex(23); // -z (back) if( !model->build(device) ) { delete model; model = nullptr; return nullptr; } return model; } } #endif /* __test_modelgen__ */ <commit_msg>Added a plane w/ size and subdivs to modelgen.<commit_after>#ifndef __test_modelgen__ #define __test_modelgen__ #include <vector> #include <ciri/gfx/IGraphicsDevice.hpp> #include "Model.hpp" namespace modelgen { // width; height; depth; u-scale; v-scale static Model* createCube( float w, float h, float d, float us, float vs, ciri::IGraphicsDevice* device ) { Model* model = new Model(); model->addVertex(Vertex(cc::Vec3f(-0.5f*w, -0.5f*h, 0.5f*d), cc::Vec3f( 1.0f, 0.0f, 0.0f), cc::Vec2f(0.0f * us, 0.0f * vs))); model->addVertex(Vertex(cc::Vec3f( 0.5f*w, -0.5f*h, 0.5f*d), cc::Vec3f( 1.0f, 0.0f, 0.0f), cc::Vec2f(1.0f * us, 0.0f * vs))); model->addVertex(Vertex(cc::Vec3f( 0.5f*w, 0.5f*h, 0.5f*d), cc::Vec3f( 1.0f, 0.0f, 0.0f), cc::Vec2f(1.0f * us, 1.0f * vs))); model->addVertex(Vertex(cc::Vec3f(-0.5f*w, 0.5f*h, 0.5f*d), cc::Vec3f( 1.0f, 0.0f, 0.0f), cc::Vec2f(0.0f * us, 1.0f * vs))); model->addVertex(Vertex(cc::Vec3f(-0.5f*w, -0.5f*h, -0.5f*d), cc::Vec3f(-1.0f, 0.0f, 0.0f), cc::Vec2f(0.0f * us, 0.0f * vs))); model->addVertex(Vertex(cc::Vec3f(-0.5f*w, 0.5f*h, -0.5f*d), cc::Vec3f(-1.0f, 0.0f, 0.0f), cc::Vec2f(1.0f * us, 0.0f * vs))); model->addVertex(Vertex(cc::Vec3f( 0.5f*w, 0.5f*h, -0.5f*d), cc::Vec3f(-1.0f, 0.0f, 0.0f), cc::Vec2f(1.0f * us, 1.0f * vs))); model->addVertex(Vertex(cc::Vec3f( 0.5f*w, -0.5f*h, -0.5f*d), cc::Vec3f(-1.0f, 0.0f, 0.0f), cc::Vec2f(0.0f * us, 1.0f * vs))); model->addVertex(Vertex(cc::Vec3f(-0.5f*w, 0.5f*h, -0.5f*d), cc::Vec3f( 0.0f, 1.0f, 0.0f), cc::Vec2f(0.0f * us, 0.0f * vs))); model->addVertex(Vertex(cc::Vec3f(-0.5f*w, 0.5f*h, 0.5f*d), cc::Vec3f( 0.0f, 1.0f, 0.0f), cc::Vec2f(1.0f * us, 0.0f * vs))); model->addVertex(Vertex(cc::Vec3f( 0.5f*w, 0.5f*h, 0.5f*d), cc::Vec3f( 0.0f, 1.0f, 0.0f), cc::Vec2f(1.0f * us, 1.0f * vs))); model->addVertex(Vertex(cc::Vec3f( 0.5f*w, 0.5f*h, -0.5f*d), cc::Vec3f( 0.0f, 1.0f, 0.0f), cc::Vec2f(0.0f * us, 1.0f * vs))); model->addVertex(Vertex(cc::Vec3f(-0.5f*w, -0.5f*h, -0.5f*d), cc::Vec3f( 0.0f, -1.0f, 0.0f), cc::Vec2f(0.0f * us, 0.0f * vs))); model->addVertex(Vertex(cc::Vec3f( 0.5f*w, -0.5f*h, -0.5f*d), cc::Vec3f( 0.0f, -1.0f, 0.0f), cc::Vec2f(1.0f * us, 0.0f * vs))); model->addVertex(Vertex(cc::Vec3f( 0.5f*w, -0.5f*h, 0.5f*d), cc::Vec3f( 0.0f, -1.0f, 0.0f), cc::Vec2f(1.0f * us, 1.0f * vs))); model->addVertex(Vertex(cc::Vec3f(-0.5f*w, -0.5f*h, 0.5f*d), cc::Vec3f( 0.0f, -1.0f, 0.0f), cc::Vec2f(0.0f * us, 1.0f * vs))); model->addVertex(Vertex(cc::Vec3f( 0.5f*w, -0.5f*h, -0.5f*d), cc::Vec3f( 0.0f, 0.0f, 1.0f), cc::Vec2f(0.0f * us, 0.0f * vs))); model->addVertex(Vertex(cc::Vec3f( 0.5f*w, 0.5f*h, -0.5f*d), cc::Vec3f( 0.0f, 0.0f, 1.0f), cc::Vec2f(1.0f * us, 0.0f * vs))); model->addVertex(Vertex(cc::Vec3f( 0.5f*w, 0.5f*h, 0.5f*d), cc::Vec3f( 0.0f, 0.0f, 1.0f), cc::Vec2f(1.0f * us, 1.0f * vs))); model->addVertex(Vertex(cc::Vec3f( 0.5f*w, -0.5f*h, 0.5f*d), cc::Vec3f( 0.0f, 0.0f, 1.0f), cc::Vec2f(0.0f * us, 1.0f * vs))); model->addVertex(Vertex(cc::Vec3f(-0.5f*w, -0.5f*h, -0.5f*d), cc::Vec3f( 0.0f, 0.0f, -1.0f), cc::Vec2f(0.0f * us, 0.0f * vs))); model->addVertex(Vertex(cc::Vec3f(-0.5f*w, -0.5f*h, 0.5f*d), cc::Vec3f( 0.0f, 0.0f, -1.0f), cc::Vec2f(1.0f * us, 0.0f * vs))); model->addVertex(Vertex(cc::Vec3f(-0.5f*w, 0.5f*h, 0.5f*d), cc::Vec3f( 0.0f, 0.0f, -1.0f), cc::Vec2f(1.0f * us, 1.0f * vs))); model->addVertex(Vertex(cc::Vec3f(-0.5f*w, 0.5f*h, -0.5f*d), cc::Vec3f( 0.0f, 0.0f, -1.0f), cc::Vec2f(0.0f * us, 1.0f * vs))); model->addIndex(0); model->addIndex(1); model->addIndex(2); model->addIndex(0); model->addIndex(2); model->addIndex(3); // +x (right) model->addIndex(4); model->addIndex(5); model->addIndex(6); model->addIndex(4); model->addIndex(6); model->addIndex(7); // -x (left) model->addIndex(8); model->addIndex(9); model->addIndex(10); model->addIndex(8); model->addIndex(10); model->addIndex(11); // +y (top) model->addIndex(12); model->addIndex(13); model->addIndex(14); model->addIndex(12); model->addIndex(14); model->addIndex(15); // -y (bottom) model->addIndex(16); model->addIndex(17); model->addIndex(18); model->addIndex(16); model->addIndex(18); model->addIndex(19); // +z (front) model->addIndex(20); model->addIndex(21); model->addIndex(22); model->addIndex(20); model->addIndex(22); model->addIndex(23); // -z (back) if( !model->build(device) ) { delete model; model = nullptr; return nullptr; } return model; } static Model* createPlane( float w, float h, int divsX, int divsY, ciri::IGraphicsDevice* device, bool dynamicVertex=false, bool dynamicIndex=false ) { // add 1 such that asking for 1 division will add a split in the middle; asking for 0 returns just a quad divsX += 1; divsY += 1; if( w <= 0.0f || h <= 0.0f || divsX < 1 || divsY < 1 ) { return nullptr; } Model* model = new Model(); model->setDynamicity(dynamicVertex, dynamicIndex); // create and set vertices const int u = divsX+1; const int v = divsY+1; for( int j = 0; j <= divsY; ++j ) { for( int i = 0; i <= divsX; ++i ) { const float x = ((float(i) / (u-1)) * 2.0f - 1.0f) * w * 0.5f; const float y = 0.0f; const float z = ((float(j) / (v-1)) * 2.0f - 1.0f) * h * 0.5f; model->addVertex(Vertex(cc::Vec3f(x, y, z), cc::Vec3f::up(), cc::Vec2f::zero())); } } // create and set indices const int indexCount = divsX * divsY * 2 * 3; std::vector<int> indices(indexCount); int* id = &indices[0]; for( int i = 0; i < divsY; ++i ) { for( int j = 0; j < divsX; ++j ) { const int i0 = i * (divsX+1) + j; const int i1 = i0 + 1; const int i2 = i0 + (divsX+1); const int i3 = i2 + 1; if( (j+2) % 2 ) { *id++= i0; *id++= i2; *id++= i1; *id++= i1; *id++= i2; *id++= i3; } else { *id++= i0; *id++= i2; *id++= i3; *id++= i0; *id++= i3; *id++= i1; } } } for( int i = 0; i < indexCount; ++i ) { model->addIndex(indices[i]); } if( !model->build(device) ) { delete model; model = nullptr; return nullptr; } return model; } } #endif /* __test_modelgen__ */ <|endoftext|>
<commit_before>// Author: Daisuke Kanaizumi // Affiliation: Department of Applied Mathematics, Waseda University // Email: daisuke15@asagi.waseda.jp // Verification program for q-special functions // by using double exponential formula with verified error bounds. // References // Ismail, M. E., & Zhang, R. (2016). // Integral and Series Representations of $ q $-Polynomials and Functions: Part I. // arXiv preprint arXiv:1604.08441. // Okayama, T. (2013). Error Estimates with Explicit Constants for Sinc Quadrature and Sinc Indefinite Integration over Infinite Intervals. arXiv preprint arXiv:1302.1314. // Tanaka, K., Sugihara, M., Murota, K., Mori, M. (2007), Function Classes for Double Exponential Integration Formulas, Numerische Mathematik, 111(4), 631-655. // Okayama, T., Matsuo, T., Sugihara, M. (2013), Error Estimates with Explicit Constants for Sinc Quadrature and Sinc Indefinite Integration. Numerische Mathematik, 124(2), 361-394. // Zhang, R. (2008). Plancherel–Rotach Asymptotics for Certain Basic Hypergeometric Series. Advances in Mathematics, 217(4), 1588-1613. #ifndef QFUNC_DE_HPP #define QFUNC_DE_HPP #include <kv/interval.hpp> #include <kv/rdouble.hpp> #include <kv/constants.hpp> #include <kv/complex.hpp> #include <kv/Pochhammer.hpp> #include <kv/Heine.hpp> #include <cmath> #include <algorithm> namespace kv{ template <class T> complex<interval<T> >Ramanujan_qAiry_DE4(const interval<T>&q, const complex<interval<T> >&z){ // Compute Ramanujan q-Airy function with DE formula complex<interval<T> >res,mid1,mid2,i,int1,int2; interval<T> d,beta,pi,K,C,h,e,Amax,xhat; T rad; int m,N; m=100; while(abs(z)*pow(q,m)/(1-q)>=0.5){ m=m+50; } if (q<=0){ throw std::domain_error("q must be positive"); } i=kv::complex<interval<T> >::i(); pi=kv::constants<interval<T> >::pi(); e=kv::constants<interval<T> >::e(); if(q<=exp(-0.5)){ beta=-1/(2*log(q)); K=qPochhammer(interval<T>(-abs(z)*sqrt(q)*exp(d)),interval<T>(q),int(m))*(1+2*abs(z)*exp(d)*pow(q,m+0.5)/(1-q)); N=100; d=1.; while(2*pi*d*N/beta<e){ N=N+10; } xhat=1.; while(pi/2-d-2*exp(-xhat)*sin(d)<0){ xhat=xhat+1; } interval<T> alpha; alpha=xhat-exp(-xhat); while(alpha<0){ xhat=xhat+1; } Amax=K*std::max(std::max((exp(-exp(-xhat))+1)*(1+exp(xhat))/(exp(xhat)-exp(exp(-xhat)))/exp(-beta/e)*exp(beta),4*exp(beta+1)),4/(1-exp(-alpha))); C=2*Amax/beta*(1+2*exp(-beta)/(1-exp(-beta*e))); h=log(2*pi*N*d/beta)/N; rad=(C*exp(-2*pi*d/h)).upper(); mid1=0.; mid2=0.; for(int k1=-N;k1<=N;k1++){ mid1=mid1+infinite_qPochhammer(complex<interval<T> >(z*sqrt(q)*exp(i*exp(k1*h-exp(-k1*h)))),interval<T>(q)) *exp(-beta*exp(2*k1*h-2*exp(-k1*h))) *(1+exp(k1*h))*exp(-exp(-k1*h)); } mid1=mid1*h; for(int k2=-N;k2<=N;k2++){ mid2=mid2+infinite_qPochhammer(complex<interval<T> >(z*sqrt(q)*exp(-i*exp(k2*h-exp(-k2*h)))),interval<T>(q)) *exp(-beta*exp(2*k2*h-2*exp(-k2*h))) *(1+exp(k2*h))*exp(-exp(-k2*h)); } mid2=mid2*h; int1=complex_nbd(mid1,rad); int2=complex_nbd(mid2,rad); res=(int1+int2)/sqrt(2*pi*log(1/q)); return res; } else{ throw std::domain_error("value of q must be smaller"); } } template <class T> complex<interval<T> >Jackson2_DE4(const complex<interval<T> >&z, const int &nu,const interval<T>&q){ // Compute Jackson's 2nd q-Bessel function with DE formula complex<interval<T> >res,mid1,mid2,i,int1,int2; interval<T> d,beta,pi,K,C,h,e,Amax,xhat; T rad; int m,N; m=100; while(pow(q,m+nu+0.5)/(1-q)>=0.5){ m=m+50; } while(abs(z*z*pow(q,m+nu+0.5)/(1-q)*0.25)>=0.5){ m=m+50; } if (q<=0){ throw std::domain_error("q must be positive"); } if(q<=exp(-0.5)){ beta=-1/(2*log(q)); i=kv::complex<interval<T> >::i(); pi=kv::constants<interval<T> >::pi(); e=kv::constants<interval<T> >::e(); K=qPochhammer(interval<T>(-abs(z*z)*pow(q,nu+0.5)*exp(d)*0.25),interval<T>(q),int(m))*(1+abs(z*z)*pow(q,m+nu+0.5)*exp(d)/(1-q)*0.5) /infinite_qPochhammer(pow(q,nu+0.5)*exp(-d),interval<T>(q))*(1+2*exp(d)*pow(q,m+nu+0.5)/(1-q)); N=1000; d=1.; while(d>=abs((nu+0.5)*log(q))){ d=d*0.5; } while(2*pi*d*N/beta<e){ N=N+10; } xhat=1.; while(pi/2-d-2*exp(-xhat)*sin(d)<0){ xhat=xhat+1; } interval<T> alpha; alpha=xhat-exp(-xhat); while(alpha<0){ xhat=xhat+1; } Amax=K*std::max(std::max((exp(-exp(-xhat))+1)*(1+exp(xhat))/(exp(xhat)-exp(exp(-xhat)))/exp(beta/e)*exp(beta),4*exp(beta+1)),4/(1-exp(-alpha))); C=2*Amax/beta*(1+2*exp(-beta)/(1-exp(-beta*e))); h=log(2*pi*N*d/beta)/N; rad=(C*exp(-2*pi*d/h)).upper(); mid1=0.; mid2=0.; for(int k1=-N;k1<=N;k1++){ mid1=mid1+infinite_qPochhammer(complex<interval<T> >(z*z*pow(q,nu+0.5)*0.25*exp(i*exp(k1*h-exp(-k1*h)))),interval<T>(q)) /infinite_qPochhammer(complex<interval<T> >(-pow(q,nu+0.5)*exp(i*exp(k1*h-exp(-k1*h)))),interval<T>(q)) *exp(-beta*exp(2*k1*h-2*exp(-k1*h))) *(1+exp(k1*h))*exp(-exp(-k1*h)); } mid1=mid1*h; for(int k2=-N;k2<=N;k2++){ mid2=mid2+infinite_qPochhammer(complex<interval<T> >(z*z*pow(q,nu+0.5)*0.25*exp(-i*exp(k2*h-exp(-k2*h)))),interval<T>(q)) /infinite_qPochhammer(complex<interval<T> >(-pow(q,nu+0.5)*exp(-i*exp(k2*h-exp(-k2*h)))),interval<T>(q)) *exp(-beta*exp(2*k2*h-2*exp(-k2*h))) *(1+exp(k2*h))*exp(-exp(-k2*h)); } mid2=mid2*h; int1=complex_nbd(mid1,rad); int2=complex_nbd(mid2,rad); res=(int1+int2)/sqrt(2*pi*log(1/q))/Euler(interval<T>(q))*pow(0.5*z,nu); return res; } else{ throw std::domain_error("value of q must be smaller"); } } template <class T> complex<interval<T> >Jackson2_DE4(const complex<interval<T> >&z, const interval<T> &nu,const interval<T>&q){ // Compute Jackson's 2nd q-Bessel function with DE formula complex<interval<T> >res,mid1,mid2,i,int1,int2; interval<T> d,beta,pi,K,C,h,e,Amax,xhat; T rad; int m,N; m=100; while(pow(q,m+nu+0.5)/(1-q)>=0.5){ m=m+50; } while(abs(z*z*pow(q,m+nu+0.5)/(1-q)*0.25)>=0.5){ m=m+50; } if (q<=0){ throw std::domain_error("q must be positive"); } int floornu; floornu=std::floor(mid(-2*nu)); if(nu<0 && floornu%2==1 && mid(-2*nu)-floornu<=0){ throw std::domain_error("singularity on real axis"); // reject negative half integers } if(q<=exp(-0.5)){ beta=-1/(2*log(q)); i=kv::complex<interval<T> >::i(); pi=kv::constants<interval<T> >::pi(); e=kv::constants<interval<T> >::e(); K=qPochhammer(interval<T>(-abs(z*z)*pow(q,nu+0.5)*exp(d)*0.25),interval<T>(q),int(m))*(1+abs(z*z)*pow(q,m+nu+0.5)*exp(d)/(1-q)*0.5) /infinite_qPochhammer(pow(q,nu+0.5)*exp(-d),interval<T>(q))*(1+2*exp(d)*pow(q,m+nu+0.5)/(1-q)); N=1000; d=1.; while(d>=abs((nu+0.5)*log(q))){ d=d*0.5; } while(2*pi*d*N/beta<e){ N=N+10; } xhat=1.; while(pi/2-d-2*exp(-xhat)*sin(d)<0){ xhat=xhat+1; } interval<T> alpha; alpha=xhat-exp(-xhat); while(alpha<0){ xhat=xhat+1; } Amax=K*std::max(std::max((exp(-exp(-xhat))+1)*(1+exp(xhat))/(exp(xhat)-exp(exp(-xhat)))/exp(beta/e)*exp(beta),4*exp(beta+1)),4/(1-exp(-alpha))); C=2*Amax/beta*(1+2*exp(-beta)/(1-exp(-beta*e))); h=log(2*pi*N*d/beta)/N; rad=(C*exp(-2*pi*d/h)).upper(); mid1=0.; mid2=0.; for(int k1=-N;k1<=N;k1++){ mid1=mid1+infinite_qPochhammer(complex<interval<T> >(z*z*pow(q,nu+0.5)*0.25*exp(i*exp(k1*h-exp(-k1*h)))),interval<T>(q)) /infinite_qPochhammer(complex<interval<T> >(-pow(q,nu+0.5)*exp(i*exp(k1*h-exp(-k1*h)))),interval<T>(q)) *exp(-beta*exp(2*k1*h-2*exp(-k1*h))) *(1+exp(k1*h))*exp(-exp(-k1*h)); } mid1=mid1*h; for(int k2=-N;k2<=N;k2++){ mid2=mid2+infinite_qPochhammer(complex<interval<T> >(z*z*pow(q,nu+0.5)*0.25*exp(-i*exp(k2*h-exp(-k2*h)))),interval<T>(q)) /infinite_qPochhammer(complex<interval<T> >(-pow(q,nu+0.5)*exp(-i*exp(k2*h-exp(-k2*h)))),interval<T>(q)) *exp(-beta*exp(2*k2*h-2*exp(-k2*h))) *(1+exp(k2*h))*exp(-exp(-k2*h)); } mid2=mid2*h; int1=complex_nbd(mid1,rad); int2=complex_nbd(mid2,rad); res=(int1+int2)/sqrt(2*pi*log(1/q))/Euler(interval<T>(q))*pow(0.5*z,nu); return res; } else{ throw std::domain_error("value of q must be smaller"); } } template <class T> complex<interval<T> >Jackson2_DE4(const complex<interval<T> >&z, const complex<interval<T> >&nu,const interval<T>&q){ // Compute Jackson's 2nd q-Bessel function with DE formula and infinite integral representation complex<interval<T> >res,mid1,mid2,i,int1,int2; interval<T> d,beta,pi,K,C,h,e,Amax,xhat; T rad; int m,N; m=100; while(abs(pow(q,m+nu+0.5))/(1-q)>=0.5){ m=m+50; } while(abs(z*z*pow(q,m+nu+0.5)/(1-q)*0.25)>=0.5){ m=m+50; } if (q<=0){ throw std::domain_error("q must be positive"); } int floornu; floornu=std::floor(mid(-2*nu.real())); if(nu.real()<0 && floornu%2==1 && mid(-2*nu.real())-floornu<=0 && nu.imag()==0){ throw std::domain_error("singularity on real axis"); // reject negative half integers } if(q<=exp(-0.5)){ beta=-1/(2*log(q)); i=kv::complex<interval<T> >::i(); pi=kv::constants<interval<T> >::pi(); e=kv::constants<interval<T> >::e(); K=qPochhammer(interval<T>(-abs(z*z*pow(q,nu+0.5))*exp(d)*0.25),interval<T>(q),int(m))*(1+abs(z*z*exp(d)*pow(q,m+nu+0.5))/(1-q)*0.5) /infinite_qPochhammer(abs(pow(q,nu+0.5)*exp(-d)),interval<T>(q))*(1+2*exp(d)*abs(pow(q,m+nu+0.5))/(1-q)); N=1000; d=1.; while(d>=abs((nu.real()+0.5)*log(q))){ d=d*0.5; } while(2*pi*d*N/beta<e){ N=N+10; } xhat=1.; while(pi/2-d-2*exp(-xhat)*sin(d)<0){ xhat=xhat+1; } interval<T> alpha; alpha=xhat-exp(-xhat); while(alpha<0){ xhat=xhat+1; } Amax=K*std::max(std::max((exp(-exp(-xhat))+1)*(1+exp(xhat))/(exp(xhat)-exp(exp(-xhat)))/exp(beta/e)*exp(beta),4*exp(beta+1)),4/(1-exp(-alpha))); C=2*Amax/beta*(1+2*exp(-beta)/(1-exp(-beta*e))); h=log(2*pi*N*d/beta)/N; rad=(C*exp(-2*pi*d/h)).upper(); mid1=0.; mid2=0.; for(int k1=-N;k1<=N;k1++){ mid1=mid1+infinite_qPochhammer(complex<interval<T> >(z*z*pow(q,nu+0.5)*0.25*exp(i*exp(k1*h-exp(-k1*h)))),interval<T>(q)) /infinite_qPochhammer(complex<interval<T> >(-pow(q,nu+0.5)*exp(i*exp(k1*h-exp(-k1*h)))),interval<T>(q)) *exp(-beta*exp(2*k1*h-2*exp(-k1*h))) *(1+exp(k1*h))*exp(-exp(-k1*h)); } mid1=mid1*h; for(int k2=-N;k2<=N;k2++){ mid2=mid2+infinite_qPochhammer(complex<interval<T> >(z*z*pow(q,nu+0.5)*0.25*exp(-i*exp(k2*h-exp(-k2*h)))),interval<T>(q)) /infinite_qPochhammer(complex<interval<T> >(-pow(q,nu+0.5)*exp(-i*exp(k2*h-exp(-k2*h)))),interval<T>(q)) *exp(-beta*exp(2*k2*h-2*exp(-k2*h))) *(1+exp(k2*h))*exp(-exp(-k2*h)); } mid2=mid2*h; int1=complex_nbd(mid1,rad); int2=complex_nbd(mid2,rad); res=(int1+int2)/sqrt(2*pi*log(1/q))/Euler(interval<T>(q))*pow(0.5*z,nu); return res; } else{ throw std::domain_error("value of q must be smaller"); } } } #endif <commit_msg>Delete qfunc_DE.hpp<commit_after><|endoftext|>
<commit_before>#include <cstdint> #include <sys/types.h> #include <thread> #include <vector> #include "raft_c_if.h" #include "raft_shm.h" using boost::interprocess::anonymous_instance; using boost::interprocess::interprocess_mutex; static void start_fsm_worker(RaftFSM* fsm); static void run_fsm_worker(RaftFSM* fsm); static void dispatch_fsm_apply(raft::FSMCallSlot& slot, raft::LogEntry& log); static void dispatch_fsm_apply_cmd(raft::FSMCallSlot& slot, raft::LogEntry& log); static void init_err_msgs(); static RaftFSM* fsm; static std::thread fsm_worker; static std::vector<const char*> err_msgs; const char* raft_err_msg(RaftError err) { if (err < err_msgs.size()) { return err_msgs.at(err); } else { return "Unknown error"; } } bool raft_is_leader() { return raft::scoreboard->is_leader; } RaftError raft_apply(void **res, char* cmd, size_t cmd_len, uint64_t timeout_ns) { raft::SlotHandle<raft::APICall> sh(raft::scoreboard->grab_slot(), std::adopt_lock); raft::RaftCallSlot& slot = sh.slot; std::unique_lock<interprocess_mutex> l(slot.owned); slot.call_type = raft::APICall::Apply; slot.state = raft::CallState::Pending; // manual memory management for now... raft::ApplyCall& call = *raft::shm.construct<raft::ApplyCall>(anonymous_instance)(); fprintf(stderr, "Allocated call buffer at %p.\n", &call); call.cmd_buf = raft::shm.get_handle_from_address(cmd); call.cmd_len = cmd_len; call.timeout_ns = timeout_ns; slot.handle = raft::shm.get_handle_from_address(&call); slot.call_ready = true; slot.call_cond.notify_one(); slot.ret_cond.wait(l, [&] () { return slot.ret_ready; }); if (slot.state == raft::CallState::Success) { assert(slot.error == RAFT_SUCCESS); if (res) *res = (void*) slot.retval; } else if (slot.state == raft::CallState::Error) { assert(slot.error != RAFT_SUCCESS); if (res) *res = nullptr; } else { fprintf(stderr, "Unexpected call state %d!\n", slot.state); abort(); } slot.ret_ready = false; raft::shm.destroy_ptr(&call); return slot.error; } pid_t raft_init(RaftFSM *fsm_) { init_err_msgs(); raft::shm_init("raft", true); fsm = fsm_; pid_t raft_pid = raft::run_raft(); fprintf(stderr, "Started Raft process: pid %d.\n", raft_pid); raft::scoreboard->wait_for_raft(raft_pid); fprintf(stderr, "Raft is running.\n"); start_fsm_worker(fsm); return raft_pid; } void start_fsm_worker(RaftFSM* fsm) { // check that there isn't already one started assert(fsm_worker.get_id() == std::thread::id()); fsm_worker = std::thread(run_fsm_worker, fsm); } void run_fsm_worker(RaftFSM* fsm) { fprintf(stderr, "FSM worker starting.\n"); raft::FSMCallSlot& slot = raft::scoreboard->fsm_slot; for (;;) { // refactor, combine this with the Go side... raft::mutex_lock l(slot.owned); slot.call_cond.wait(l, [&] () { return slot.call_ready; }); assert(slot.state == raft::CallState::Pending); assert(slot.handle); void* call_addr = raft::shm.get_address_from_handle(slot.handle); fprintf(stderr, "Found FSM op buffer at %p.\n", call_addr); switch (slot.call_type) { case raft::FSMOp::Apply: dispatch_fsm_apply(slot, *(raft::LogEntry*)call_addr); break; default: fprintf(stderr, "Unhandled log entry type: %d\n", slot.call_type); abort(); } slot.state = raft::CallState::Success; slot.ret_ready = true; slot.ret_cond.notify_one(); slot.call_ready = false; } } void dispatch_fsm_apply(raft::CallSlot<raft::FSMOp>& slot, raft::LogEntry& log) { switch (log.log_type) { case RAFT_LOG_COMMAND: dispatch_fsm_apply_cmd(slot, log); break; case RAFT_LOG_NOOP: fprintf(stderr, "FSM command: noop\n"); break; case RAFT_LOG_ADD_PEER: fprintf(stderr, "FSM command: add peer\n"); break; case RAFT_LOG_REMOVE_PEER: fprintf(stderr, "FSM command: remove peer\n"); break; case RAFT_LOG_BARRIER: fprintf(stderr, "FSM command: barrier\n"); break; } } void dispatch_fsm_apply_cmd(raft::CallSlot<raft::FSMOp>& slot, raft::LogEntry& log) { assert(log.data_buf); void* data_buf = raft::shm.get_address_from_handle(log.data_buf); fprintf(stderr, "Found command buffer at %p.\n", data_buf); slot.state = raft::CallState::Dispatched; void* response = fsm->apply(log.index, log.term, log.log_type, data_buf, log.data_len); slot.retval = (uintptr_t) response; } void* alloc_raft_buffer(size_t len) { return raft::shm.allocate(len); } void free_raft_buffer(void* buf) { raft::shm.deallocate(buf); } void init_err_msgs() { // TODO: dump these from the Raft code err_msgs = decltype(err_msgs)(N_RAFT_ERRORS); err_msgs[RAFT_SUCCESS] = "success"; err_msgs[RAFT_E_LEADER] = "node is the leader"; err_msgs[RAFT_E_NOT_LEADER] = "node is not the leader"; err_msgs[RAFT_E_LEADERSHIP_LOST] = "leadership lost while committing log"; err_msgs[RAFT_E_SHUTDOWN] = "raft is already shutdown"; err_msgs[RAFT_E_ENQUEUE_TIMEOUT] = "timed out enqueuing operation"; err_msgs[RAFT_E_KNOWN_PEER] = "peer already known"; err_msgs[RAFT_E_UNKNOWN_PEER] = "peer is unknown"; err_msgs[RAFT_E_LOG_NOT_FOUND] = "log not found"; err_msgs[RAFT_E_PIPELINE_REPLICATION_NOT_SUPP] = "pipeline replication not supported"; err_msgs[RAFT_E_TRANSPORT_SHUTDOWN] = "transport shutdown"; err_msgs[RAFT_E_PIPELINE_SHUTDOWN] = "append pipeline closed"; err_msgs[RAFT_E_OTHER] = "undetermined error"; } <commit_msg>Time apply calls.<commit_after>#include <cstdint> #include <sys/types.h> #include <chrono> #include <thread> #include <vector> #include "raft_c_if.h" #include "raft_shm.h" using boost::interprocess::anonymous_instance; using boost::interprocess::interprocess_mutex; static void start_fsm_worker(RaftFSM* fsm); static void run_fsm_worker(RaftFSM* fsm); static void dispatch_fsm_apply(raft::FSMCallSlot& slot, raft::LogEntry& log); static void dispatch_fsm_apply_cmd(raft::FSMCallSlot& slot, raft::LogEntry& log); static void init_err_msgs(); static RaftFSM* fsm; static std::thread fsm_worker; static std::vector<const char*> err_msgs; const char* raft_err_msg(RaftError err) { if (err < err_msgs.size()) { return err_msgs.at(err); } else { return "Unknown error"; } } bool raft_is_leader() { return raft::scoreboard->is_leader; } RaftError raft_apply(void **res, char* cmd, size_t cmd_len, uint64_t timeout_ns) { auto start_t = std::chrono::high_resolution_clock::now(); raft::SlotHandle<raft::APICall> sh(raft::scoreboard->grab_slot(), std::adopt_lock); raft::RaftCallSlot& slot = sh.slot; std::unique_lock<interprocess_mutex> l(slot.owned); slot.call_type = raft::APICall::Apply; slot.state = raft::CallState::Pending; // manual memory management for now... raft::ApplyCall& call = *raft::shm.construct<raft::ApplyCall>(anonymous_instance)(); fprintf(stderr, "Allocated call buffer at %p.\n", &call); call.cmd_buf = raft::shm.get_handle_from_address(cmd); call.cmd_len = cmd_len; call.timeout_ns = timeout_ns; slot.handle = raft::shm.get_handle_from_address(&call); slot.call_ready = true; slot.call_cond.notify_one(); slot.ret_cond.wait(l, [&] () { return slot.ret_ready; }); if (slot.state == raft::CallState::Success) { assert(slot.error == RAFT_SUCCESS); if (res) *res = (void*) slot.retval; } else if (slot.state == raft::CallState::Error) { assert(slot.error != RAFT_SUCCESS); if (res) *res = nullptr; } else { fprintf(stderr, "Unexpected call state %d!\n", slot.state); abort(); } slot.ret_ready = false; raft::shm.destroy_ptr(&call); auto end_t = std::chrono::high_resolution_clock::now(); auto elapsed = std::chrono::duration_cast<std::chrono::microseconds>(end_t - start_t); fprintf(stderr, "Apply call completed in %lld us.\n", elapsed.count()); return slot.error; } pid_t raft_init(RaftFSM *fsm_) { init_err_msgs(); raft::shm_init("raft", true); fsm = fsm_; pid_t raft_pid = raft::run_raft(); fprintf(stderr, "Started Raft process: pid %d.\n", raft_pid); raft::scoreboard->wait_for_raft(raft_pid); fprintf(stderr, "Raft is running.\n"); start_fsm_worker(fsm); return raft_pid; } void start_fsm_worker(RaftFSM* fsm) { // check that there isn't already one started assert(fsm_worker.get_id() == std::thread::id()); fsm_worker = std::thread(run_fsm_worker, fsm); } void run_fsm_worker(RaftFSM* fsm) { fprintf(stderr, "FSM worker starting.\n"); raft::FSMCallSlot& slot = raft::scoreboard->fsm_slot; for (;;) { // refactor, combine this with the Go side... raft::mutex_lock l(slot.owned); slot.call_cond.wait(l, [&] () { return slot.call_ready; }); assert(slot.state == raft::CallState::Pending); assert(slot.handle); void* call_addr = raft::shm.get_address_from_handle(slot.handle); fprintf(stderr, "Found FSM op buffer at %p.\n", call_addr); switch (slot.call_type) { case raft::FSMOp::Apply: dispatch_fsm_apply(slot, *(raft::LogEntry*)call_addr); break; default: fprintf(stderr, "Unhandled log entry type: %d\n", slot.call_type); abort(); } slot.state = raft::CallState::Success; slot.ret_ready = true; slot.ret_cond.notify_one(); slot.call_ready = false; } } void dispatch_fsm_apply(raft::CallSlot<raft::FSMOp>& slot, raft::LogEntry& log) { switch (log.log_type) { case RAFT_LOG_COMMAND: dispatch_fsm_apply_cmd(slot, log); break; case RAFT_LOG_NOOP: fprintf(stderr, "FSM command: noop\n"); break; case RAFT_LOG_ADD_PEER: fprintf(stderr, "FSM command: add peer\n"); break; case RAFT_LOG_REMOVE_PEER: fprintf(stderr, "FSM command: remove peer\n"); break; case RAFT_LOG_BARRIER: fprintf(stderr, "FSM command: barrier\n"); break; } } void dispatch_fsm_apply_cmd(raft::CallSlot<raft::FSMOp>& slot, raft::LogEntry& log) { assert(log.data_buf); void* data_buf = raft::shm.get_address_from_handle(log.data_buf); fprintf(stderr, "Found command buffer at %p.\n", data_buf); slot.state = raft::CallState::Dispatched; void* response = fsm->apply(log.index, log.term, log.log_type, data_buf, log.data_len); slot.retval = (uintptr_t) response; } void* alloc_raft_buffer(size_t len) { return raft::shm.allocate(len); } void free_raft_buffer(void* buf) { raft::shm.deallocate(buf); } void init_err_msgs() { // TODO: dump these from the Raft code err_msgs = decltype(err_msgs)(N_RAFT_ERRORS); err_msgs[RAFT_SUCCESS] = "success"; err_msgs[RAFT_E_LEADER] = "node is the leader"; err_msgs[RAFT_E_NOT_LEADER] = "node is not the leader"; err_msgs[RAFT_E_LEADERSHIP_LOST] = "leadership lost while committing log"; err_msgs[RAFT_E_SHUTDOWN] = "raft is already shutdown"; err_msgs[RAFT_E_ENQUEUE_TIMEOUT] = "timed out enqueuing operation"; err_msgs[RAFT_E_KNOWN_PEER] = "peer already known"; err_msgs[RAFT_E_UNKNOWN_PEER] = "peer is unknown"; err_msgs[RAFT_E_LOG_NOT_FOUND] = "log not found"; err_msgs[RAFT_E_PIPELINE_REPLICATION_NOT_SUPP] = "pipeline replication not supported"; err_msgs[RAFT_E_TRANSPORT_SHUTDOWN] = "transport shutdown"; err_msgs[RAFT_E_PIPELINE_SHUTDOWN] = "append pipeline closed"; err_msgs[RAFT_E_OTHER] = "undetermined error"; } <|endoftext|>
<commit_before>#include <iostream> #include <fstream> #include <cstring> #include <vector> // c++11 sleep #include <thread> #include <chrono> #include "Net.h" #define SHOW_ACKS using namespace std; using namespace net; const unsigned short ServerPort = 30000; const unsigned short ClientPort = 30001; const int ProtocolId = 0x11112222; const float DeltaTime = 0.01f; const chrono::milliseconds DeltaTimeInMs(10); const float TimeOut = 5.0f; const int PacketSize = 10; // const int ServerPort = 30000; // const int ClientPort = 30001; // const int ProtocolId = 0x11112222; // const float DeltaTime = 0.001f; // const float TimeOut = 0.1f; // const uint32_t PacketCount = 100; class FlowControl { public: FlowControl() { printf( "flow control initialized\n" ); Reset(); } void Reset() { mode = Bad; penalty_time = 4.0f; good_conditions_time = 0.0f; penalty_reduction_accumulator = 0.0f; } void Update( float deltaTime, float rtt ) { const float RTT_Threshold = 250.0f; if ( mode == Good ) { if ( rtt > RTT_Threshold ) { printf( "*** dropping to bad mode ***\n" ); mode = Bad; if ( good_conditions_time < 10.0f && penalty_time < 60.0f ) { penalty_time *= 2.0f; if ( penalty_time > 60.0f ) penalty_time = 60.0f; printf( "penalty time increased to %.1f\n", penalty_time ); } good_conditions_time = 0.0f; penalty_reduction_accumulator = 0.0f; return; } good_conditions_time += deltaTime; penalty_reduction_accumulator += deltaTime; if ( penalty_reduction_accumulator > 10.0f && penalty_time > 1.0f ) { penalty_time /= 2.0f; if ( penalty_time < 1.0f ) penalty_time = 1.0f; printf( "penalty time reduced to %.1f\n", penalty_time ); penalty_reduction_accumulator = 0.0f; } } if ( mode == Bad ) { if ( rtt <= RTT_Threshold ) good_conditions_time += deltaTime; else good_conditions_time = 0.0f; if ( good_conditions_time > penalty_time ) { printf( "*** upgrading to good mode ***\n" ); good_conditions_time = 0.0f; penalty_reduction_accumulator = 0.0f; mode = Good; return; } } } float GetSendRate() { return mode == Good ? 30.0f : 10.0f; } private: enum Mode { Good, Bad }; Mode mode; float penalty_time; float good_conditions_time; float penalty_reduction_accumulator; }; // ---------------------------------------------- int main( int argc, char * argv[] ) { // parse command line enum Mode { Client, Server }; Mode mode = Server; Address address; if ( argc >= 2 ) { uchar_t a,b,c,d; if ( sscanf( argv[1], "%hhu.%hhu.%hhu.%hhu", &a, &b, &c, &d ) > 0 ) { mode = Client; address = Address(a,b,c,d,ServerPort); printf("sscanf address ok, address = %hhu,%hhu,%hhu,%hhu\n", a,b,c,d); } else { printf("sscanf error\n"); } } // initialize if ( !InitializeSockets() ) { printf( "failed to initialize sockets\n" ); return 1; } ReliableConnection connection( ProtocolId, TimeOut ); const unsigned short port = mode == Server ? ServerPort : ClientPort; if ( !connection.Start( port ) ) { printf( "could not start connection on port %d\n", port ); return 1; } if ( mode == Client ) connection.Connect( address ); else connection.Listen(); bool connected = false; float sendAccumulator = 0.0f; float statsAccumulator = 0.0f; FlowControl flowControl; while ( true ) { // update flow control if ( connection.IsConnected() ) flowControl.Update( DeltaTime, connection.GetReliabilitySystem().GetRoundTripTime() * 1000.0f ); const float sendRate = flowControl.GetSendRate(); // detect changes in connection state if ( mode == Server && connected && !connection.IsConnected() ) { flowControl.Reset(); printf( "reset flow control\n" ); connected = false; } if ( !connected && connection.IsConnected() ) { printf( "client connected to server\n" ); connected = true; } if ( !connected && connection.ConnectFailed() ) { printf( "connection failed\n" ); break; } // send and receive packets sendAccumulator += DeltaTime; while ( sendAccumulator > 1.0f / sendRate ) { uchar_t packet[PacketSize] = {'a','b','c','d','e','f','g','h','h','i'}; // memset( packet, 0, sizeof( packet ) ); connection.SendPacket( packet, sizeof( packet ) ); sendAccumulator -= 1.0f / sendRate; } while ( true ) { uchar_t packet[256]; int bytes_read = connection.ReceivePacket( packet, sizeof(packet) ); if ( bytes_read == 0 ) break; } // show packets that were acked this frame #ifdef SHOW_ACKS uint32_t * acks = nullptr; uint32_t ack_count = 0; connection.GetReliabilitySystem().GetAcks( &acks, ack_count); if ( ack_count > 0 ) { printf( "acks: %d", acks[0] ); for ( uint32_t i = 1; i < ack_count; ++i ) printf( ",%d", acks[i] ); printf( "\n" ); } #endif // update connection connection.Update( DeltaTime ); // show connection stats statsAccumulator += DeltaTime; while ( statsAccumulator >= 0.25f && connection.IsConnected() ) { float rtt = connection.GetReliabilitySystem().GetRoundTripTime(); uint32_t sent_packets = connection.GetReliabilitySystem().GetSentPackets(); uint32_t acked_packets = connection.GetReliabilitySystem().GetAckedPackets(); uint32_t lost_packets = connection.GetReliabilitySystem().GetLostPackets(); float sent_bandwidth = connection.GetReliabilitySystem().GetSentBandwidth(); float acked_bandwidth = connection.GetReliabilitySystem().GetAckedBandwidth(); printf( "rtt %.1fms, sent %d, acked %d, lost %d (%.1f%%), sent bandwidth = %.1fkbps, acked bandwidth = %.1fkbps\n", rtt * 1000.0f, sent_packets, acked_packets, lost_packets, sent_packets > 0.0f ? static_cast<float>(lost_packets) / static_cast<float>(sent_packets * 100.0f) : 0.0f, sent_bandwidth, acked_bandwidth ); statsAccumulator -= 0.25f; } // c++11 sleep 1 ms this_thread::sleep_for(DeltaTimeInMs); // net::wait( DeltaTime ); } ShutdownSockets(); return 0; } <commit_msg>fix: <iostream> exclude<commit_after>#include <fstream> #include <cstring> #include <vector> // c++11 sleep #include <thread> #include <chrono> #include "Net.h" #define SHOW_ACKS using namespace std; using namespace net; const unsigned short ServerPort = 30000; const unsigned short ClientPort = 30001; const int ProtocolId = 0x11112222; const float DeltaTime = 0.01f; const chrono::milliseconds DeltaTimeInMs(10); const float TimeOut = 5.0f; const int PacketSize = 10; // const int ServerPort = 30000; // const int ClientPort = 30001; // const int ProtocolId = 0x11112222; // const float DeltaTime = 0.001f; // const float TimeOut = 0.1f; // const uint32_t PacketCount = 100; class FlowControl { public: FlowControl() { printf( "flow control initialized\n" ); Reset(); } void Reset() { mode = Bad; penalty_time = 4.0f; good_conditions_time = 0.0f; penalty_reduction_accumulator = 0.0f; } void Update( float deltaTime, float rtt ) { const float RTT_Threshold = 250.0f; if ( mode == Good ) { if ( rtt > RTT_Threshold ) { printf( "*** dropping to bad mode ***\n" ); mode = Bad; if ( good_conditions_time < 10.0f && penalty_time < 60.0f ) { penalty_time *= 2.0f; if ( penalty_time > 60.0f ) penalty_time = 60.0f; printf( "penalty time increased to %.1f\n", penalty_time ); } good_conditions_time = 0.0f; penalty_reduction_accumulator = 0.0f; return; } good_conditions_time += deltaTime; penalty_reduction_accumulator += deltaTime; if ( penalty_reduction_accumulator > 10.0f && penalty_time > 1.0f ) { penalty_time /= 2.0f; if ( penalty_time < 1.0f ) penalty_time = 1.0f; printf( "penalty time reduced to %.1f\n", penalty_time ); penalty_reduction_accumulator = 0.0f; } } if ( mode == Bad ) { if ( rtt <= RTT_Threshold ) good_conditions_time += deltaTime; else good_conditions_time = 0.0f; if ( good_conditions_time > penalty_time ) { printf( "*** upgrading to good mode ***\n" ); good_conditions_time = 0.0f; penalty_reduction_accumulator = 0.0f; mode = Good; return; } } } float GetSendRate() { return mode == Good ? 30.0f : 10.0f; } private: enum Mode { Good, Bad }; Mode mode; float penalty_time; float good_conditions_time; float penalty_reduction_accumulator; }; // ---------------------------------------------- int main( int argc, char * argv[] ) { // parse command line enum Mode { Client, Server }; Mode mode = Server; Address address; if ( argc >= 2 ) { uchar_t a,b,c,d; if ( sscanf( argv[1], "%hhu.%hhu.%hhu.%hhu", &a, &b, &c, &d ) > 0 ) { mode = Client; address = Address(a,b,c,d,ServerPort); printf("sscanf address ok, address = %hhu,%hhu,%hhu,%hhu\n", a,b,c,d); } else { printf("sscanf error\n"); } } // initialize if ( !InitializeSockets() ) { printf( "failed to initialize sockets\n" ); return 1; } ReliableConnection connection( ProtocolId, TimeOut ); const unsigned short port = mode == Server ? ServerPort : ClientPort; if ( !connection.Start( port ) ) { printf( "could not start connection on port %d\n", port ); return 1; } if ( mode == Client ) connection.Connect( address ); else connection.Listen(); bool connected = false; float sendAccumulator = 0.0f; float statsAccumulator = 0.0f; FlowControl flowControl; while ( true ) { // update flow control if ( connection.IsConnected() ) flowControl.Update( DeltaTime, connection.GetReliabilitySystem().GetRoundTripTime() * 1000.0f ); const float sendRate = flowControl.GetSendRate(); // detect changes in connection state if ( mode == Server && connected && !connection.IsConnected() ) { flowControl.Reset(); printf( "reset flow control\n" ); connected = false; } if ( !connected && connection.IsConnected() ) { printf( "client connected to server\n" ); connected = true; } if ( !connected && connection.ConnectFailed() ) { printf( "connection failed\n" ); break; } // send and receive packets sendAccumulator += DeltaTime; while ( sendAccumulator > 1.0f / sendRate ) { uchar_t packet[PacketSize] = {'a','b','c','d','e','f','g','h','h','i'}; // memset( packet, 0, sizeof( packet ) ); connection.SendPacket( packet, sizeof( packet ) ); sendAccumulator -= 1.0f / sendRate; } while ( true ) { uchar_t packet[256]; int bytes_read = connection.ReceivePacket( packet, sizeof(packet) ); if ( bytes_read == 0 ) break; } // show packets that were acked this frame #ifdef SHOW_ACKS uint32_t * acks = nullptr; uint32_t ack_count = 0; connection.GetReliabilitySystem().GetAcks( &acks, ack_count); if ( ack_count > 0 ) { printf( "acks: %d", acks[0] ); for ( uint32_t i = 1; i < ack_count; ++i ) printf( ",%d", acks[i] ); printf( "\n" ); } #endif // update connection connection.Update( DeltaTime ); // show connection stats statsAccumulator += DeltaTime; while ( statsAccumulator >= 0.25f && connection.IsConnected() ) { float rtt = connection.GetReliabilitySystem().GetRoundTripTime(); uint32_t sent_packets = connection.GetReliabilitySystem().GetSentPackets(); uint32_t acked_packets = connection.GetReliabilitySystem().GetAckedPackets(); uint32_t lost_packets = connection.GetReliabilitySystem().GetLostPackets(); float sent_bandwidth = connection.GetReliabilitySystem().GetSentBandwidth(); float acked_bandwidth = connection.GetReliabilitySystem().GetAckedBandwidth(); printf( "rtt %.1fms, sent %d, acked %d, lost %d (%.1f%%), sent bandwidth = %.1fkbps, acked bandwidth = %.1fkbps\n", rtt * 1000.0f, sent_packets, acked_packets, lost_packets, sent_packets > 0.0f ? static_cast<float>(lost_packets) / static_cast<float>(sent_packets * 100.0f) : 0.0f, sent_bandwidth, acked_bandwidth ); statsAccumulator -= 0.25f; } // c++11 sleep 1 ms this_thread::sleep_for(DeltaTimeInMs); // net::wait( DeltaTime ); } ShutdownSockets(); return 0; } <|endoftext|>
<commit_before>#include "responce.h" std::string test(std::string data){ std::string message; message = data; return message; } <commit_msg>Delete responce.cpp<commit_after><|endoftext|>
<commit_before>/** * \file * \brief ContiguousRange template class header. * * \author Copyright (C) 2014 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * 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/. * * \date 2014-11-05 */ #ifndef ESTD_CONTIGUOUSRANGE_HPP_ #define ESTD_CONTIGUOUSRANGE_HPP_ #include <iterator> #include <cstddef> namespace estd { /** * \brief ContiguousRange template class is a pair of iterators to contiguous sequence of elements in memory * * \param T is the type of data in the range */ template<typename T> class ContiguousRange { public: /// value_type type using value_type = T; /// pointer type using pointer = value_type*; /// const_pointer type using const_pointer = const value_type*; /// reference type using reference = value_type&; /// const_reference type using const_reference = const value_type&; /// iterator type using iterator = value_type*; /// const_iterator type using const_iterator = const value_type*; /// size_type type using size_type = std::size_t; /// difference_type type using difference_type = std::ptrdiff_t; /// reverse_iterator type using reverse_iterator = std::reverse_iterator<iterator>; /// const_reverse_iterator type using const_reverse_iterator = std::reverse_iterator<const_iterator>; /** * \brief ContiguousRange's constructor. * * \param [in] beginn is an iterator to first element in the range * \param [in] endd is an iterator to "one past the last" element in the range */ constexpr ContiguousRange(const iterator beginn, const iterator endd) noexcept : begin_{beginn}, end_{endd} { } /** * \brief Empty ContiguousRange's constructor. */ constexpr explicit ContiguousRange() noexcept : ContiguousRange{nullptr, nullptr} { } /** * \brief ContiguousRange's constructor using C-style array. * * \param N is the number of elements in the array * * \param [in] array is the array used to initialize the range */ template<size_t N> constexpr explicit ContiguousRange(T (&array)[N]) noexcept : ContiguousRange{array, array + N} { } /** * \return iterator to first element in the range */ constexpr iterator begin() const noexcept { return begin_; } /** * \return iterator to "one past the last" element in the range */ constexpr iterator end() const noexcept { return end_; } /** * \return number of elements in the range */ constexpr size_type size() const noexcept { return end_ - begin_; } /** * \param [in] i is the index of element that will be accessed * * \return reference to element at given index */ reference operator[](const size_type i) noexcept { return begin_[i]; } /** * \param [in] i is the index of element that will be accessed * * \return const reference to element at given index */ const_reference operator[](const size_type i) const noexcept { return begin_[i]; } private: /// iterator to first element in the range const iterator begin_; /// iterator to "one past the last" element in the range const iterator end_; }; } // namespace estd #endif // ESTD_CONTIGUOUSRANGE_HPP_ <commit_msg>ContiguousRange.hpp: remove unnecessary #include<commit_after>/** * \file * \brief ContiguousRange template class header. * * \author Copyright (C) 2014 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * 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/. * * \date 2014-11-29 */ #ifndef ESTD_CONTIGUOUSRANGE_HPP_ #define ESTD_CONTIGUOUSRANGE_HPP_ #include <iterator> namespace estd { /** * \brief ContiguousRange template class is a pair of iterators to contiguous sequence of elements in memory * * \param T is the type of data in the range */ template<typename T> class ContiguousRange { public: /// value_type type using value_type = T; /// pointer type using pointer = value_type*; /// const_pointer type using const_pointer = const value_type*; /// reference type using reference = value_type&; /// const_reference type using const_reference = const value_type&; /// iterator type using iterator = value_type*; /// const_iterator type using const_iterator = const value_type*; /// size_type type using size_type = std::size_t; /// difference_type type using difference_type = std::ptrdiff_t; /// reverse_iterator type using reverse_iterator = std::reverse_iterator<iterator>; /// const_reverse_iterator type using const_reverse_iterator = std::reverse_iterator<const_iterator>; /** * \brief ContiguousRange's constructor. * * \param [in] beginn is an iterator to first element in the range * \param [in] endd is an iterator to "one past the last" element in the range */ constexpr ContiguousRange(const iterator beginn, const iterator endd) noexcept : begin_{beginn}, end_{endd} { } /** * \brief Empty ContiguousRange's constructor. */ constexpr explicit ContiguousRange() noexcept : ContiguousRange{nullptr, nullptr} { } /** * \brief ContiguousRange's constructor using C-style array. * * \param N is the number of elements in the array * * \param [in] array is the array used to initialize the range */ template<size_t N> constexpr explicit ContiguousRange(T (&array)[N]) noexcept : ContiguousRange{array, array + N} { } /** * \return iterator to first element in the range */ constexpr iterator begin() const noexcept { return begin_; } /** * \return iterator to "one past the last" element in the range */ constexpr iterator end() const noexcept { return end_; } /** * \return number of elements in the range */ constexpr size_type size() const noexcept { return end_ - begin_; } /** * \param [in] i is the index of element that will be accessed * * \return reference to element at given index */ reference operator[](const size_type i) noexcept { return begin_[i]; } /** * \param [in] i is the index of element that will be accessed * * \return const reference to element at given index */ const_reference operator[](const size_type i) const noexcept { return begin_[i]; } private: /// iterator to first element in the range const iterator begin_; /// iterator to "one past the last" element in the range const iterator end_; }; } // namespace estd #endif // ESTD_CONTIGUOUSRANGE_HPP_ <|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2006 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ //$Id$ #ifndef FEATURE_STYLE_PROCESSOR_HPP #define FEATURE_STYLE_PROCESSOR_HPP // mapnik #include <mapnik/box2d.hpp> #include <mapnik/datasource.hpp> #include <mapnik/layer.hpp> #include <mapnik/map.hpp> #include <mapnik/attribute_collector.hpp> #include <mapnik/expression_evaluator.hpp> #include <mapnik/utils.hpp> #include <mapnik/projection.hpp> #include <mapnik/scale_denominator.hpp> #include <mapnik/memory_datasource.hpp> #ifdef MAPNIK_DEBUG //#include <mapnik/wall_clock_timer.hpp> #endif // boost #include <boost/foreach.hpp> //stl #include <vector> namespace mapnik { template <typename Processor> class feature_style_processor { /** Calls the renderer's process function, * \param output Renderer * \param f Feature to process * \param prj_trans Projection * \param sym Symbolizer object */ struct symbol_dispatch : public boost::static_visitor<> { symbol_dispatch (Processor & output, Feature const& f, proj_transform const& prj_trans) : output_(output), f_(f), prj_trans_(prj_trans) {} template <typename T> void operator () (T const& sym) const { output_.process(sym,f_,prj_trans_); } Processor & output_; Feature const& f_; proj_transform const& prj_trans_; }; public: explicit feature_style_processor(Map const& m, double scale_factor = 1.0) : m_(m), scale_factor_(scale_factor) {} /*! * @return apply renderer to all map layers. */ void apply() { #ifdef MAPNIK_DEBUG //mapnik::wall_clock_progress_timer t(std::clog, "map rendering took: "); #endif Processor & p = static_cast<Processor&>(*this); p.start_map_processing(m_); try { projection proj(m_.srs()); start_metawriters(m_,proj); double scale_denom = mapnik::scale_denominator(m_,proj.is_geographic()); scale_denom *= scale_factor_; #ifdef MAPNIK_DEBUG std::clog << "scale denominator = " << scale_denom << "\n"; #endif BOOST_FOREACH ( layer const& lyr, m_.layers() ) { if (lyr.isVisible(scale_denom)) { std::set<std::string> names; apply_to_layer(lyr, p, proj, scale_denom, names); } } stop_metawriters(m_); } catch (proj_init_error& ex) { std::clog << "proj_init_error:" << ex.what() << "\n"; } p.end_map_processing(m_); } /*! * @return apply renderer to a single layer, providing pre-populated set of query attribute names. */ void apply(mapnik::layer const& lyr, std::set<std::string>& names) { Processor & p = static_cast<Processor&>(*this); p.start_map_processing(m_); try { projection proj(m_.srs()); double scale_denom = mapnik::scale_denominator(m_,proj.is_geographic()); scale_denom *= scale_factor_; if (lyr.isVisible(scale_denom)) { apply_to_layer(lyr, p, proj, scale_denom, names); } } catch (proj_init_error& ex) { std::clog << "proj_init_error:" << ex.what() << "\n"; } p.end_map_processing(m_); } private: /*! * @return initialize metawriters for a given map and projection. */ void start_metawriters(Map const& m_, projection const& proj) { Map::const_metawriter_iterator metaItr = m_.begin_metawriters(); Map::const_metawriter_iterator metaItrEnd = m_.end_metawriters(); for (;metaItr!=metaItrEnd; ++metaItr) { metaItr->second->set_size(m_.width(), m_.height()); metaItr->second->set_map_srs(proj); metaItr->second->start(m_.metawriter_output_properties); } } /*! * @return stop metawriters that were previously initialized. */ void stop_metawriters(Map const& m_) { Map::const_metawriter_iterator metaItr = m_.begin_metawriters(); Map::const_metawriter_iterator metaItrEnd = m_.end_metawriters(); for (;metaItr!=metaItrEnd; ++metaItr) { metaItr->second->stop(); } } /*! * @return render a layer given a projection and scale. */ void apply_to_layer(layer const& lay, Processor & p, projection const& proj0, double scale_denom, std::set<std::string>& names) { #ifdef MAPNIK_DEBUG //wall_clock_progress_timer timer(clog, "end layer rendering: "); #endif std::vector<std::string> const& style_names = lay.styles(); unsigned int num_styles = style_names.size(); if (!num_styles) return; mapnik::datasource_ptr ds = lay.datasource(); if (!ds) { std::clog << "WARNING: No datasource for layer '" << lay.name() << "'\n"; return; } p.start_layer_processing(lay); if (ds) { projection proj1(lay.srs()); proj_transform prj_trans(proj0,proj1); // todo: only display raster if src and dest proj are matched // todo: add raster re-projection as an optional feature if (ds->type() == datasource::Raster && !prj_trans.equal()) { std::clog << "WARNING: Map srs does not match layer srs, skipping raster layer '" << lay.name() << "' as raster re-projection is not currently supported (http://trac.mapnik.org/ticket/663)\n" << "map srs: '" << m_.srs() << "'\nlayer srs: '" << lay.srs() << "' \n"; return; } box2d<double> map_ext = m_.get_buffered_extent(); // clip buffered extent by maximum extent, if supplied boost::optional<box2d<double> > const& maximum_extent = m_.maximum_extent(); if (maximum_extent) { map_ext.clip(*maximum_extent); } box2d<double> layer_ext = lay.envelope(); // first, try to forward project map ext into layer srs if (prj_trans.forward(map_ext) && map_ext.intersects(layer_ext)) { layer_ext.clip(map_ext); } // if no intersection and projections are also equal, early return else if (prj_trans.equal()) { return; } // fallback to back projecting layer into map srs else if (prj_trans.backward(layer_ext) && map_ext.intersects(layer_ext)) { layer_ext.clip(map_ext); // forward project layer extent back into native projection if (!prj_trans.forward(layer_ext)) std::clog << "WARNING: layer " << lay.name() << " extent " << layer_ext << " in map projection " << " did not reproject properly back to layer projection\n"; } else { // if no intersection then nothing to do for layer return; } query::resolution_type res(m_.width()/m_.get_current_extent().width(), m_.height()/m_.get_current_extent().height()); query q(layer_ext,res,scale_denom); //BBOX query std::vector<feature_type_style*> active_styles; attribute_collector collector(names); double filt_factor = 1; directive_collector d_collector(&filt_factor); // iterate through all named styles collecting active styles and attribute names BOOST_FOREACH(std::string const& style_name, style_names) { boost::optional<feature_type_style const&> style=m_.find_style(style_name); if (!style) { std::clog << "WARNING: style '" << style_name << "' required for layer '" << lay.name() << "' does not exist.\n"; continue; } const std::vector<rule>& rules=(*style).get_rules(); bool active_rules=false; BOOST_FOREACH(rule const& r, rules) { if (r.active(scale_denom)) { active_rules = true; if (ds->type() == datasource::Vector) { collector(r); } // TODO - in the future rasters should be able to be filtered. } } if (active_rules) { active_styles.push_back(const_cast<feature_type_style*>(&(*style))); } } // push all property names BOOST_FOREACH(std::string const& name, names) { q.add_property_name(name); } memory_datasource cache; bool cache_features = lay.cache_features() && num_styles>1?true:false; bool first = true; BOOST_FOREACH (feature_type_style * style, active_styles) { std::vector<rule*> if_rules; std::vector<rule*> else_rules; std::vector<rule> const& rules=style->get_rules(); BOOST_FOREACH(rule const& r, rules) { if (r.active(scale_denom)) { if (r.has_else_filter()) { else_rules.push_back(const_cast<rule*>(&r)); } else { if_rules.push_back(const_cast<rule*>(&r)); } if ( (ds->type() == datasource::Raster) && (ds->params().get<double>("filter_factor",0.0) == 0.0) ) { rule::symbolizers const& symbols = r.get_symbolizers(); rule::symbolizers::const_iterator symIter = symbols.begin(); rule::symbolizers::const_iterator symEnd = symbols.end(); while (symIter != symEnd) { // if multiple raster symbolizers, last will be respected // should we warn or throw? boost::apply_visitor(d_collector,*symIter++); } q.set_filter_factor(filt_factor); } } } // process features featureset_ptr fs; if (first) { if (cache_features) first = false; fs = ds->features(q); } else { fs = cache.features(q); } if (fs) { feature_ptr feature; while ((feature = fs->next())) { bool do_else=true; if (cache_features) { cache.push(feature); } BOOST_FOREACH(rule * r, if_rules ) { expression_ptr const& expr=r->get_filter(); value_type result = boost::apply_visitor(evaluate<Feature,value_type>(*feature),*expr); if (result.to_bool()) { do_else=false; rule::symbolizers const& symbols = r->get_symbolizers(); // if the underlying renderer is not able to process the complete set of symbolizers, // process one by one. #ifdef SVG_RENDERER if(!p.process(symbols,*feature,prj_trans)) #endif { BOOST_FOREACH (symbolizer const& sym, symbols) { boost::apply_visitor(symbol_dispatch(p,*feature,prj_trans),sym); } } if (style->get_filter_mode() == FILTER_FIRST) { // Stop iterating over rules and proceed with next feature. break; } } } if (do_else) { BOOST_FOREACH( rule * r, else_rules ) { rule::symbolizers const& symbols = r->get_symbolizers(); // if the underlying renderer is not able to process the complete set of symbolizers, // process one by one. #ifdef SVG_RENDERER if(!p.process(symbols,*feature,prj_trans)) #endif { BOOST_FOREACH (symbolizer const& sym, symbols) { boost::apply_visitor(symbol_dispatch(p,*feature,prj_trans),sym); } } } } } } cache_features = false; } } p.end_layer_processing(lay); } Map const& m_; double scale_factor_; }; } #endif //FEATURE_STYLE_PROCESSOR_HPP <commit_msg>improve code comments around transforms and intersection checks<commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2006 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ //$Id$ #ifndef FEATURE_STYLE_PROCESSOR_HPP #define FEATURE_STYLE_PROCESSOR_HPP // mapnik #include <mapnik/box2d.hpp> #include <mapnik/datasource.hpp> #include <mapnik/layer.hpp> #include <mapnik/map.hpp> #include <mapnik/attribute_collector.hpp> #include <mapnik/expression_evaluator.hpp> #include <mapnik/utils.hpp> #include <mapnik/projection.hpp> #include <mapnik/scale_denominator.hpp> #include <mapnik/memory_datasource.hpp> #ifdef MAPNIK_DEBUG //#include <mapnik/wall_clock_timer.hpp> #endif // boost #include <boost/foreach.hpp> //stl #include <vector> namespace mapnik { template <typename Processor> class feature_style_processor { /** Calls the renderer's process function, * \param output Renderer * \param f Feature to process * \param prj_trans Projection * \param sym Symbolizer object */ struct symbol_dispatch : public boost::static_visitor<> { symbol_dispatch (Processor & output, Feature const& f, proj_transform const& prj_trans) : output_(output), f_(f), prj_trans_(prj_trans) {} template <typename T> void operator () (T const& sym) const { output_.process(sym,f_,prj_trans_); } Processor & output_; Feature const& f_; proj_transform const& prj_trans_; }; public: explicit feature_style_processor(Map const& m, double scale_factor = 1.0) : m_(m), scale_factor_(scale_factor) {} /*! * @return apply renderer to all map layers. */ void apply() { #ifdef MAPNIK_DEBUG //mapnik::wall_clock_progress_timer t(std::clog, "map rendering took: "); #endif Processor & p = static_cast<Processor&>(*this); p.start_map_processing(m_); try { projection proj(m_.srs()); start_metawriters(m_,proj); double scale_denom = mapnik::scale_denominator(m_,proj.is_geographic()); scale_denom *= scale_factor_; #ifdef MAPNIK_DEBUG std::clog << "scale denominator = " << scale_denom << "\n"; #endif BOOST_FOREACH ( layer const& lyr, m_.layers() ) { if (lyr.isVisible(scale_denom)) { std::set<std::string> names; apply_to_layer(lyr, p, proj, scale_denom, names); } } stop_metawriters(m_); } catch (proj_init_error& ex) { std::clog << "proj_init_error:" << ex.what() << "\n"; } p.end_map_processing(m_); } /*! * @return apply renderer to a single layer, providing pre-populated set of query attribute names. */ void apply(mapnik::layer const& lyr, std::set<std::string>& names) { Processor & p = static_cast<Processor&>(*this); p.start_map_processing(m_); try { projection proj(m_.srs()); double scale_denom = mapnik::scale_denominator(m_,proj.is_geographic()); scale_denom *= scale_factor_; if (lyr.isVisible(scale_denom)) { apply_to_layer(lyr, p, proj, scale_denom, names); } } catch (proj_init_error& ex) { std::clog << "proj_init_error:" << ex.what() << "\n"; } p.end_map_processing(m_); } private: /*! * @return initialize metawriters for a given map and projection. */ void start_metawriters(Map const& m_, projection const& proj) { Map::const_metawriter_iterator metaItr = m_.begin_metawriters(); Map::const_metawriter_iterator metaItrEnd = m_.end_metawriters(); for (;metaItr!=metaItrEnd; ++metaItr) { metaItr->second->set_size(m_.width(), m_.height()); metaItr->second->set_map_srs(proj); metaItr->second->start(m_.metawriter_output_properties); } } /*! * @return stop metawriters that were previously initialized. */ void stop_metawriters(Map const& m_) { Map::const_metawriter_iterator metaItr = m_.begin_metawriters(); Map::const_metawriter_iterator metaItrEnd = m_.end_metawriters(); for (;metaItr!=metaItrEnd; ++metaItr) { metaItr->second->stop(); } } /*! * @return render a layer given a projection and scale. */ void apply_to_layer(layer const& lay, Processor & p, projection const& proj0, double scale_denom, std::set<std::string>& names) { #ifdef MAPNIK_DEBUG //wall_clock_progress_timer timer(clog, "end layer rendering: "); #endif std::vector<std::string> const& style_names = lay.styles(); unsigned int num_styles = style_names.size(); if (!num_styles) return; mapnik::datasource_ptr ds = lay.datasource(); if (!ds) { std::clog << "WARNING: No datasource for layer '" << lay.name() << "'\n"; return; } p.start_layer_processing(lay); if (ds) { projection proj1(lay.srs()); proj_transform prj_trans(proj0,proj1); // todo: only display raster if src and dest proj are matched // todo: add raster re-projection as an optional feature if (ds->type() == datasource::Raster && !prj_trans.equal()) { std::clog << "WARNING: Map srs does not match layer srs, skipping raster layer '" << lay.name() << "' as raster re-projection is not currently supported (http://trac.mapnik.org/ticket/663)\n" << "map srs: '" << m_.srs() << "'\nlayer srs: '" << lay.srs() << "' \n"; return; } box2d<double> map_ext = m_.get_buffered_extent(); // clip buffered extent by maximum extent, if supplied boost::optional<box2d<double> > const& maximum_extent = m_.maximum_extent(); if (maximum_extent) { map_ext.clip(*maximum_extent); } box2d<double> layer_ext = lay.envelope(); // first, try intersection of map extent forward projected into layer srs if (prj_trans.forward(map_ext) && map_ext.intersects(layer_ext)) { layer_ext.clip(map_ext); } // if no intersection and projections are also equal, early return else if (prj_trans.equal()) { return; } // next try intersection of layer extent back projected into map srs else if (prj_trans.backward(layer_ext) && map_ext.intersects(layer_ext)) { layer_ext.clip(map_ext); // forward project layer extent back into native projection if (!prj_trans.forward(layer_ext)) std::clog << "WARNING: layer " << lay.name() << " extent " << layer_ext << " in map projection " << " did not reproject properly back to layer projection\n"; } else { // if no intersection then nothing to do for layer return; } query::resolution_type res(m_.width()/m_.get_current_extent().width(), m_.height()/m_.get_current_extent().height()); query q(layer_ext,res,scale_denom); //BBOX query std::vector<feature_type_style*> active_styles; attribute_collector collector(names); double filt_factor = 1; directive_collector d_collector(&filt_factor); // iterate through all named styles collecting active styles and attribute names BOOST_FOREACH(std::string const& style_name, style_names) { boost::optional<feature_type_style const&> style=m_.find_style(style_name); if (!style) { std::clog << "WARNING: style '" << style_name << "' required for layer '" << lay.name() << "' does not exist.\n"; continue; } const std::vector<rule>& rules=(*style).get_rules(); bool active_rules=false; BOOST_FOREACH(rule const& r, rules) { if (r.active(scale_denom)) { active_rules = true; if (ds->type() == datasource::Vector) { collector(r); } // TODO - in the future rasters should be able to be filtered. } } if (active_rules) { active_styles.push_back(const_cast<feature_type_style*>(&(*style))); } } // push all property names BOOST_FOREACH(std::string const& name, names) { q.add_property_name(name); } memory_datasource cache; bool cache_features = lay.cache_features() && num_styles>1?true:false; bool first = true; BOOST_FOREACH (feature_type_style * style, active_styles) { std::vector<rule*> if_rules; std::vector<rule*> else_rules; std::vector<rule> const& rules=style->get_rules(); BOOST_FOREACH(rule const& r, rules) { if (r.active(scale_denom)) { if (r.has_else_filter()) { else_rules.push_back(const_cast<rule*>(&r)); } else { if_rules.push_back(const_cast<rule*>(&r)); } if ( (ds->type() == datasource::Raster) && (ds->params().get<double>("filter_factor",0.0) == 0.0) ) { rule::symbolizers const& symbols = r.get_symbolizers(); rule::symbolizers::const_iterator symIter = symbols.begin(); rule::symbolizers::const_iterator symEnd = symbols.end(); while (symIter != symEnd) { // if multiple raster symbolizers, last will be respected // should we warn or throw? boost::apply_visitor(d_collector,*symIter++); } q.set_filter_factor(filt_factor); } } } // process features featureset_ptr fs; if (first) { if (cache_features) first = false; fs = ds->features(q); } else { fs = cache.features(q); } if (fs) { feature_ptr feature; while ((feature = fs->next())) { bool do_else=true; if (cache_features) { cache.push(feature); } BOOST_FOREACH(rule * r, if_rules ) { expression_ptr const& expr=r->get_filter(); value_type result = boost::apply_visitor(evaluate<Feature,value_type>(*feature),*expr); if (result.to_bool()) { do_else=false; rule::symbolizers const& symbols = r->get_symbolizers(); // if the underlying renderer is not able to process the complete set of symbolizers, // process one by one. #ifdef SVG_RENDERER if(!p.process(symbols,*feature,prj_trans)) #endif { BOOST_FOREACH (symbolizer const& sym, symbols) { boost::apply_visitor(symbol_dispatch(p,*feature,prj_trans),sym); } } if (style->get_filter_mode() == FILTER_FIRST) { // Stop iterating over rules and proceed with next feature. break; } } } if (do_else) { BOOST_FOREACH( rule * r, else_rules ) { rule::symbolizers const& symbols = r->get_symbolizers(); // if the underlying renderer is not able to process the complete set of symbolizers, // process one by one. #ifdef SVG_RENDERER if(!p.process(symbols,*feature,prj_trans)) #endif { BOOST_FOREACH (symbolizer const& sym, symbols) { boost::apply_visitor(symbol_dispatch(p,*feature,prj_trans),sym); } } } } } } cache_features = false; } } p.end_layer_processing(lay); } Map const& m_; double scale_factor_; }; } #endif //FEATURE_STYLE_PROCESSOR_HPP <|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2011 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #ifndef MAPNIK_FEATURE_STYLE_PROCESSOR_HPP #define MAPNIK_FEATURE_STYLE_PROCESSOR_HPP // mapnik #include <mapnik/map.hpp> #include <mapnik/projection.hpp> #include <mapnik/memory_datasource.hpp> // stl #include <set> #include <string> #include <vector> namespace mapnik { class Map; class layer; class projection; template <typename Processor> class feature_style_processor { struct symbol_dispatch; public: explicit feature_style_processor(Map const& m, double scale_factor = 1.0); /*! * @return apply renderer to all map layers. */ void apply(); /*! * @return apply renderer to a single layer, providing pre-populated set of query attribute names. */ void apply(mapnik::layer const& lyr, std::set<std::string>& names); private: /*! * @return render a layer given a projection and scale. */ void apply_to_layer(layer const& lay, Processor & p, projection const& proj0, double scale_denom, std::set<std::string>& names); /*! * @return renders a featureset with the given styles. */ void render_style(layer const& lay, Processor & p, feature_type_style* style, std::string const& style_name, featureset_ptr features, proj_transform const& prj_trans, double scale_denom); Map const& m_; double scale_factor_; }; } #endif // MAPNIK_FEATURE_STYLE_PROCESSOR_HPP <commit_msg>fixup includes<commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2011 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #ifndef MAPNIK_FEATURE_STYLE_PROCESSOR_HPP #define MAPNIK_FEATURE_STYLE_PROCESSOR_HPP // mapnik #include <mapnik/map.hpp> #include <mapnik/memory_datasource.hpp> // stl #include <set> #include <string> #include <vector> namespace mapnik { class Map; class layer; class projection; class proj_transform; template <typename Processor> class feature_style_processor { struct symbol_dispatch; public: explicit feature_style_processor(Map const& m, double scale_factor = 1.0); /*! * @return apply renderer to all map layers. */ void apply(); /*! * @return apply renderer to a single layer, providing pre-populated set of query attribute names. */ void apply(mapnik::layer const& lyr, std::set<std::string>& names); private: /*! * @return render a layer given a projection and scale. */ void apply_to_layer(layer const& lay, Processor & p, projection const& proj0, double scale_denom, std::set<std::string>& names); /*! * @return renders a featureset with the given styles. */ void render_style(layer const& lay, Processor & p, feature_type_style* style, std::string const& style_name, featureset_ptr features, proj_transform const& prj_trans, double scale_denom); Map const& m_; double scale_factor_; }; } #endif // MAPNIK_FEATURE_STYLE_PROCESSOR_HPP <|endoftext|>
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE-CHROMIUM file. #include "shell/browser/ui/devtools_ui.h" #include <memory> #include <string> #include <utility> #include "base/memory/ref_counted_memory.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" #include "chrome/common/webui_url_constants.h" #include "content/public/browser/devtools_frontend_host.h" #include "content/public/browser/url_data_source.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_ui.h" namespace electron { namespace { std::string PathWithoutParams(const std::string& path) { return GURL(std::string("devtools://devtools/") + path).path().substr(1); } std::string GetMimeTypeForPath(const std::string& path) { std::string filename = PathWithoutParams(path); if (base::EndsWith(filename, ".html", base::CompareCase::INSENSITIVE_ASCII)) { return "text/html"; } else if (base::EndsWith(filename, ".css", base::CompareCase::INSENSITIVE_ASCII)) { return "text/css"; } else if (base::EndsWith(filename, ".js", base::CompareCase::INSENSITIVE_ASCII)) { return "application/javascript"; } else if (base::EndsWith(filename, ".png", base::CompareCase::INSENSITIVE_ASCII)) { return "image/png"; } else if (base::EndsWith(filename, ".gif", base::CompareCase::INSENSITIVE_ASCII)) { return "image/gif"; } else if (base::EndsWith(filename, ".svg", base::CompareCase::INSENSITIVE_ASCII)) { return "image/svg+xml"; } else if (base::EndsWith(filename, ".manifest", base::CompareCase::INSENSITIVE_ASCII)) { return "text/cache-manifest"; } return "text/html"; } class BundledDataSource : public content::URLDataSource { public: BundledDataSource() = default; ~BundledDataSource() override = default; // content::URLDataSource implementation. std::string GetSource() override { return chrome::kChromeUIDevToolsHost; } void StartDataRequest(const GURL& url, const content::WebContents::Getter& wc_getter, GotDataCallback callback) override { const std::string path = content::URLDataSource::URLToRequestPath(url); // Serve request from local bundle. std::string bundled_path_prefix(chrome::kChromeUIDevToolsBundledPath); bundled_path_prefix += "/"; if (base::StartsWith(path, bundled_path_prefix, base::CompareCase::INSENSITIVE_ASCII)) { StartBundledDataRequest(path.substr(bundled_path_prefix.length()), std::move(callback)); return; } // We do not handle remote and custom requests. std::move(callback).Run(nullptr); } std::string GetMimeType(const std::string& path) override { return GetMimeTypeForPath(path); } bool ShouldAddContentSecurityPolicy() override { return false; } bool ShouldDenyXFrameOptions() override { return false; } bool ShouldServeMimeTypeAsContentTypeHeader() override { return true; } void StartBundledDataRequest(const std::string& path, GotDataCallback callback) { std::string filename = PathWithoutParams(path); scoped_refptr<base::RefCountedMemory> bytes = content::DevToolsFrontendHost::GetFrontendResourceBytes(filename); DLOG_IF(WARNING, !bytes) << "Unable to find dev tool resource: " << filename << ". If you compiled with debug_devtools=1, try running with " "--debug-devtools."; std::move(callback).Run(bytes); } private: DISALLOW_COPY_AND_ASSIGN(BundledDataSource); }; } // namespace DevToolsUI::DevToolsUI(content::BrowserContext* browser_context, content::WebUI* web_ui) : WebUIController(web_ui) { web_ui->SetBindings(0); content::URLDataSource::Add(browser_context, std::make_unique<BundledDataSource>()); } } // namespace electron <commit_msg>fix: sync devtools frontend mime types with upstream (#25780)<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE-CHROMIUM file. #include "shell/browser/ui/devtools_ui.h" #include <memory> #include <string> #include <utility> #include "base/memory/ref_counted_memory.h" #include "base/strings/strcat.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" #include "chrome/common/webui_url_constants.h" #include "content/public/browser/devtools_frontend_host.h" #include "content/public/browser/url_data_source.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_ui.h" namespace electron { namespace { std::string PathWithoutParams(const std::string& path) { return GURL(base::StrCat({content::kChromeDevToolsScheme, url::kStandardSchemeSeparator, chrome::kChromeUIDevToolsHost})) .Resolve(path) .path() .substr(1); } std::string GetMimeTypeForPath(const std::string& path) { std::string filename = PathWithoutParams(path); if (base::EndsWith(filename, ".html", base::CompareCase::INSENSITIVE_ASCII)) { return "text/html"; } else if (base::EndsWith(filename, ".css", base::CompareCase::INSENSITIVE_ASCII)) { return "text/css"; } else if (base::EndsWith(filename, ".js", base::CompareCase::INSENSITIVE_ASCII) || base::EndsWith(filename, ".mjs", base::CompareCase::INSENSITIVE_ASCII)) { return "application/javascript"; } else if (base::EndsWith(filename, ".png", base::CompareCase::INSENSITIVE_ASCII)) { return "image/png"; } else if (base::EndsWith(filename, ".map", base::CompareCase::INSENSITIVE_ASCII)) { return "application/json"; } else if (base::EndsWith(filename, ".ts", base::CompareCase::INSENSITIVE_ASCII)) { return "application/x-typescript"; } else if (base::EndsWith(filename, ".gif", base::CompareCase::INSENSITIVE_ASCII)) { return "image/gif"; } else if (base::EndsWith(filename, ".svg", base::CompareCase::INSENSITIVE_ASCII)) { return "image/svg+xml"; } else if (base::EndsWith(filename, ".manifest", base::CompareCase::INSENSITIVE_ASCII)) { return "text/cache-manifest"; } return "text/html"; } class BundledDataSource : public content::URLDataSource { public: BundledDataSource() = default; ~BundledDataSource() override = default; // content::URLDataSource implementation. std::string GetSource() override { return chrome::kChromeUIDevToolsHost; } void StartDataRequest(const GURL& url, const content::WebContents::Getter& wc_getter, GotDataCallback callback) override { const std::string path = content::URLDataSource::URLToRequestPath(url); // Serve request from local bundle. std::string bundled_path_prefix(chrome::kChromeUIDevToolsBundledPath); bundled_path_prefix += "/"; if (base::StartsWith(path, bundled_path_prefix, base::CompareCase::INSENSITIVE_ASCII)) { StartBundledDataRequest(path.substr(bundled_path_prefix.length()), std::move(callback)); return; } // We do not handle remote and custom requests. std::move(callback).Run(nullptr); } std::string GetMimeType(const std::string& path) override { return GetMimeTypeForPath(path); } bool ShouldAddContentSecurityPolicy() override { return false; } bool ShouldDenyXFrameOptions() override { return false; } bool ShouldServeMimeTypeAsContentTypeHeader() override { return true; } void StartBundledDataRequest(const std::string& path, GotDataCallback callback) { std::string filename = PathWithoutParams(path); scoped_refptr<base::RefCountedMemory> bytes = content::DevToolsFrontendHost::GetFrontendResourceBytes(filename); DLOG_IF(WARNING, !bytes) << "Unable to find dev tool resource: " << filename << ". If you compiled with debug_devtools=1, try running with " "--debug-devtools."; std::move(callback).Run(bytes); } private: DISALLOW_COPY_AND_ASSIGN(BundledDataSource); }; } // namespace DevToolsUI::DevToolsUI(content::BrowserContext* browser_context, content::WebUI* web_ui) : WebUIController(web_ui) { web_ui->SetBindings(0); content::URLDataSource::Add(browser_context, std::make_unique<BundledDataSource>()); } } // namespace electron <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: infotips.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: hr $ $Date: 2006-06-19 14:13:20 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef INFOTIPS_HXX_INCLUDED #define INFOTIPS_HXX_INCLUDED #if defined _MSC_VER #pragma warning(push, 1) #pragma warning(disable:4917) #endif #include <objidl.h> #include <shlobj.h> #if defined _MSC_VER #pragma warning(pop) #endif #include <string> class CInfoTip : public IQueryInfo, public IPersistFile { public: CInfoTip(long RefCnt = 1); virtual ~CInfoTip(); //----------------------------- // IUnknown methods //----------------------------- virtual HRESULT STDMETHODCALLTYPE QueryInterface( REFIID riid, void __RPC_FAR *__RPC_FAR *ppvObject); virtual ULONG STDMETHODCALLTYPE AddRef( void); virtual ULONG STDMETHODCALLTYPE Release( void); //---------------------------- // IQueryInfo methods //---------------------------- virtual HRESULT STDMETHODCALLTYPE GetInfoTip(DWORD dwFlags, wchar_t** ppwszTip); virtual HRESULT STDMETHODCALLTYPE GetInfoFlags(DWORD *pdwFlags); //---------------------------- // IPersist methods //---------------------------- virtual HRESULT STDMETHODCALLTYPE GetClassID(CLSID* pClassID); //---------------------------- // IPersistFile methods //---------------------------- virtual HRESULT STDMETHODCALLTYPE IsDirty(void); virtual HRESULT STDMETHODCALLTYPE Load( /* [in] */ LPCOLESTR pszFileName, /* [in] */ DWORD dwMode); virtual HRESULT STDMETHODCALLTYPE Save( /* [unique][in] */ LPCOLESTR pszFileName, /* [in] */ BOOL fRemember); virtual HRESULT STDMETHODCALLTYPE SaveCompleted( /* [unique][in] */ LPCOLESTR pszFileName); virtual HRESULT STDMETHODCALLTYPE GetCurFile( /* [out] */ LPOLESTR __RPC_FAR *ppszFileName); private: long m_RefCnt; char m_szFileName[MAX_PATH]; std::wstring m_FileNameOnly; }; #endif <commit_msg>INTEGRATION: CWS changefileheader (1.4.154); FILE MERGED 2008/03/31 13:17:04 rt 1.4.154.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: infotips.hxx,v $ * $Revision: 1.5 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef INFOTIPS_HXX_INCLUDED #define INFOTIPS_HXX_INCLUDED #if defined _MSC_VER #pragma warning(push, 1) #pragma warning(disable:4917) #endif #include <objidl.h> #include <shlobj.h> #if defined _MSC_VER #pragma warning(pop) #endif #include <string> class CInfoTip : public IQueryInfo, public IPersistFile { public: CInfoTip(long RefCnt = 1); virtual ~CInfoTip(); //----------------------------- // IUnknown methods //----------------------------- virtual HRESULT STDMETHODCALLTYPE QueryInterface( REFIID riid, void __RPC_FAR *__RPC_FAR *ppvObject); virtual ULONG STDMETHODCALLTYPE AddRef( void); virtual ULONG STDMETHODCALLTYPE Release( void); //---------------------------- // IQueryInfo methods //---------------------------- virtual HRESULT STDMETHODCALLTYPE GetInfoTip(DWORD dwFlags, wchar_t** ppwszTip); virtual HRESULT STDMETHODCALLTYPE GetInfoFlags(DWORD *pdwFlags); //---------------------------- // IPersist methods //---------------------------- virtual HRESULT STDMETHODCALLTYPE GetClassID(CLSID* pClassID); //---------------------------- // IPersistFile methods //---------------------------- virtual HRESULT STDMETHODCALLTYPE IsDirty(void); virtual HRESULT STDMETHODCALLTYPE Load( /* [in] */ LPCOLESTR pszFileName, /* [in] */ DWORD dwMode); virtual HRESULT STDMETHODCALLTYPE Save( /* [unique][in] */ LPCOLESTR pszFileName, /* [in] */ BOOL fRemember); virtual HRESULT STDMETHODCALLTYPE SaveCompleted( /* [unique][in] */ LPCOLESTR pszFileName); virtual HRESULT STDMETHODCALLTYPE GetCurFile( /* [out] */ LPOLESTR __RPC_FAR *ppszFileName); private: long m_RefCnt; char m_szFileName[MAX_PATH]; std::wstring m_FileNameOnly; }; #endif <|endoftext|>
<commit_before>/* * Copyright (c) 2014 Patrick P. Frey * * 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/. */ /// \file textwolf/xmlpathautomatonparse.hpp /// \brief Parser to create a path expression selector automaton from a source (list of path expression in abbreviated syntax of xpath) #ifndef __TEXTWOLF_XML_PATH_AUTOMATON_PARSE_HPP__ #define __TEXTWOLF_XML_PATH_AUTOMATON_PARSE_HPP__ #include "textwolf/xmlpathautomaton.hpp" #include "textwolf/charset.hpp" #include "textwolf/cstringiterator.hpp" #include <limits> #include <string> #include <cstdlib> #include <list> #include <vector> #include <cstring> #include <cstddef> #include <stdexcept> namespace textwolf { ///\class XMLPathSelectAutomatonParser ///\tparam SrcCharSet character set of the automaton definition source ///\tparam AtmCharSet character set of the token defintions of the automaton ///\brief Automaton to define XML path expressions and assign types (int values) to them template <class SrcCharSet=charset::UTF8, class AtmCharSet=charset::UTF8> class XMLPathSelectAutomatonParser :public XMLPathSelectAutomaton<AtmCharSet> { public: typedef XMLPathSelectAutomaton<AtmCharSet> ThisAutomaton; typedef typename ThisAutomaton::PathElement PathElement; typedef XMLPathSelectAutomatonParser This; typedef TextScanner<CStringIterator,SrcCharSet> SrcScanner; public: ///\brief Constructor XMLPathSelectAutomatonParser(){} virtual ~XMLPathSelectAutomatonParser(){} int addExpression( int typeidx, const char* esrc, std::size_t esrcsize) { // Check for namespaces, not supported: char const* xx = (char const*)std::memchr( esrc, ':', esrcsize); while (xx) { std::size_t xpos = xx - esrc; if (xpos + 1 < esrcsize && xx[1] == ':') { return xpos+1; } xx = (char const*)std::memchr( xx+1, ':', esrcsize - (xpos+1)); } // Parse the expression: IdentifierBuf idbuf( &m_atmcharset); CStringIterator itr( esrc, esrcsize); SrcScanner src( m_srccharset, itr); ExprState expr( this); enum State {SelectStart,SelectTag,SelectAttribute,SelectTagId,SelectAttributeId,SelectContent,SelectCondition}; State state = SelectStart; std::vector<const char*> alt; for (; *src; skipSpaces( src)) { switch (*src) { case '@': { if (state != SelectStart && state != SelectTag && state != SelectTagId) return src.getPosition()+1; ++src; state = SelectAttribute; break; } case '/': { if (state != SelectStart && state != SelectCondition && state != SelectTagId) return src.getPosition()+1; ++src; if (*src == '/') { expr.forAllDescendants(); ++src; } state = SelectTag; break; } case '[': { if (state != SelectStart && state != SelectTag && state != SelectTagId && state != SelectCondition) return src.getPosition()+1; ++src; skipSpaces( src); if (*src == '@') { ++src; skipSpaces( src); // Attribute condition: if (!isIdentifierChar( src)) return src.getPosition()+1; const char* attrname = idbuf.parseIdentifier( src); skipSpaces( src); if (*src != '=') return src.getPosition()+1; ++src; skipSpaces( src); const char* attrval = idbuf.parseValue( src); skipSpaces( src); if (!attrval || *src != ']') return src.getPosition()+1; expr.ifAttribute( attrname, attrval); ++src; } else { // Range skipSpaces( src); if (!isIdentifierChar( src)) return src.getPosition()+1; int range_start = parseNum( src); if (range_start < 0) return src.getPosition()+1; skipSpaces( src); if (*src == ',') { ++src; skipSpaces( src); if (*src == ']') { expr.FROM( range_start); ++src; } else { if (!isIdentifierChar( src)) return src.getPosition()+1; int range_end = parseNum( src); if (range_end < 0) return src.getPosition()+1; skipSpaces( src); if (*src != ']') return src.getPosition()+1; expr.RANGE( range_start, range_end); ++src; } } else if (*src == ']') { expr.INDEX( range_start); ++src; } else { return src.getPosition()+1; } } state = SelectCondition; break; } case '(': if (state != SelectStart && state != SelectTag && state != SelectTagId && state != SelectCondition) return src.getPosition()+1; ++src; skipSpaces( src); if (*src != ')') return src.getPosition()+1; ++src; expr.selectContent(); state = SelectContent; break; case '*': if (state != SelectStart && state != SelectTag && state != SelectAttribute) return src.getPosition()+1; ++src; if (state == SelectAttribute) { expr.selectAttribute( 0); state = SelectAttributeId; } else { expr.selectTag( 0); state = SelectTagId; } break; case '{': if (state != SelectStart && state != SelectTag && state != SelectAttribute) return src.getPosition()+1; alt = idbuf.parseIdentifierList( src, '{', '}'); if (alt.empty()) return src.getPosition()+1; expr.selectAttributeAlt( alt); if (state == SelectAttribute) { expr.selectAttributeAlt( alt); state = SelectAttributeId; } else { expr.selectTagAlt( alt); state = SelectTagId; } break; case '~': if (state != SelectTagId) return src.getPosition()+1; ++src; expr.selectCloseTag(); state = SelectContent; break; default: if (state != SelectStart && state != SelectTag && state != SelectAttribute) return src.getPosition()+1; if (!isIdentifierChar( src)) return src.getPosition()+1; if (state == SelectAttribute) { expr.selectAttribute( idbuf.parseIdentifier( src)); state = SelectAttributeId; } else { expr.selectTag( idbuf.parseIdentifier( src)); state = SelectTagId; } break; } } expr.assignType( typeidx); return 0; } private: #define ExprState_FOREACH( EXPR) {typename std::vector<PathElement>::iterator si = statelist.begin(), se = statelist.end(); for (; si != se; ++si) {si->EXPR;}} class ExprState { public: ExprState( XMLPathSelectAutomatonParser* atm) { statelist.push_back(PathElement(atm)); } ExprState( const ExprState& o) :statelist(o.statelist){} void selectTagAlt( std::vector<const char*> alt) { std::vector<PathElement> new_statelist; std::vector<const char*>::const_iterator ai = alt.begin(), ae = alt.end(); for (; ai != ae; ++ai) { ExprState alt_path( *this); alt_path.selectTag( *ai); new_statelist.insert( new_statelist.end(), alt_path.statelist.begin(), alt_path.statelist.end()); } statelist = new_statelist; } void selectAttributeAlt( std::vector<const char*> alt) { std::vector<PathElement> new_statelist; std::vector<const char*>::const_iterator ai = alt.begin(), ae = alt.end(); for (; ai != ae; ++ai) { ExprState alt_path( *this); alt_path.selectAttribute( *ai); new_statelist.insert( new_statelist.end(), alt_path.statelist.begin(), alt_path.statelist.end()); } statelist = new_statelist; } void TO(int idx) ExprState_FOREACH(TO(idx)) void FROM(int idx) ExprState_FOREACH(FROM(idx)) void RANGE(int idx1, int idx2) ExprState_FOREACH(RANGE(idx1,idx2)) void INDEX(int idx) ExprState_FOREACH(INDEX(idx)) void selectAttribute( const char* name) ExprState_FOREACH(selectAttribute(name)) void selectTag( const char* name) ExprState_FOREACH(selectTag(name)) void assignType(int type) ExprState_FOREACH(assignType(type)) void forAllDescendants() ExprState_FOREACH(forAllDescendants()) void selectCloseTag() ExprState_FOREACH(selectCloseTag()) void ifAttribute( const char* name, const char* value) ExprState_FOREACH(ifAttribute(name,value)) void selectContent() ExprState_FOREACH(selectContent()) private: std::vector<PathElement> statelist; }; static void skipSpaces( SrcScanner& src) { for (; src.control() == Space; ++src); } static int parseNum( SrcScanner& src) { std::string num; for (; *src>='0' && *src<='9';++src) num.push_back( *src); if (num.size() == 0 || num.size() > 8) return -1; return std::atoi( num.c_str()); } static bool isIdentifierChar( SrcScanner& src) { if (src.control() == Undef || src.control() == Any) { if (*src == (unsigned char)'*') return false; if (*src == (unsigned char)'~') return false; if (*src == (unsigned char)'/') return false; if (*src == (unsigned char)'(') return false; if (*src == (unsigned char)')') return false; if (*src == (unsigned char)'@') return false; return true; } return false; } class IdentifierBuf { public: explicit IdentifierBuf( const AtmCharSet* atmcharset_) :atmcharset(atmcharset_){} ~IdentifierBuf(){} const char* parseIdentifier( SrcScanner& src) { idlist.push_back( std::string()); for (; isIdentifierChar(src); ++src) { atmcharset->print( *src, idlist.back()); } return idlist.back().c_str(); } const char* parseValue( SrcScanner& src) { idlist.push_back( std::string()); if (*src == '"' || *src == '\'') { unsigned char eb = *src; for (++src; *src && *src != eb; ++src) { atmcharset->print( *src, idlist.back()); } if (*src) ++src; return idlist.back().c_str(); } else if (isIdentifierChar(src)) { return parseIdentifier( src); } else { return NULL; } } std::vector<const char*> parseIdentifierList( SrcScanner& src, char startBracket, char endBracket) { std::vector<const char*> rt; if (*src != startBracket) return std::vector<const char*>(); do { ++src; skipSpaces( src); if (!isIdentifierChar( src)) return std::vector<const char*>(); rt.push_back( parseIdentifier( src)); skipSpaces( src); } while (*src == ','); if (*src != endBracket) return std::vector<const char*>(); ++src; return rt; } private: const AtmCharSet* atmcharset; std::list<std::string> idlist; }; private: AtmCharSet m_atmcharset; SrcCharSet m_srccharset; }; } //namespace #endif <commit_msg>accept '~' as xpath expression (end of document)<commit_after>/* * Copyright (c) 2014 Patrick P. Frey * * 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/. */ /// \file textwolf/xmlpathautomatonparse.hpp /// \brief Parser to create a path expression selector automaton from a source (list of path expression in abbreviated syntax of xpath) #ifndef __TEXTWOLF_XML_PATH_AUTOMATON_PARSE_HPP__ #define __TEXTWOLF_XML_PATH_AUTOMATON_PARSE_HPP__ #include "textwolf/xmlpathautomaton.hpp" #include "textwolf/charset.hpp" #include "textwolf/cstringiterator.hpp" #include <limits> #include <string> #include <cstdlib> #include <list> #include <vector> #include <cstring> #include <cstddef> #include <stdexcept> namespace textwolf { ///\class XMLPathSelectAutomatonParser ///\tparam SrcCharSet character set of the automaton definition source ///\tparam AtmCharSet character set of the token defintions of the automaton ///\brief Automaton to define XML path expressions and assign types (int values) to them template <class SrcCharSet=charset::UTF8, class AtmCharSet=charset::UTF8> class XMLPathSelectAutomatonParser :public XMLPathSelectAutomaton<AtmCharSet> { public: typedef XMLPathSelectAutomaton<AtmCharSet> ThisAutomaton; typedef typename ThisAutomaton::PathElement PathElement; typedef XMLPathSelectAutomatonParser This; typedef TextScanner<CStringIterator,SrcCharSet> SrcScanner; public: ///\brief Constructor XMLPathSelectAutomatonParser(){} virtual ~XMLPathSelectAutomatonParser(){} int addExpression( int typeidx, const char* esrc, std::size_t esrcsize) { // Check for namespaces, not supported: char const* xx = (char const*)std::memchr( esrc, ':', esrcsize); while (xx) { std::size_t xpos = xx - esrc; if (xpos + 1 < esrcsize && xx[1] == ':') { return xpos+1; } xx = (char const*)std::memchr( xx+1, ':', esrcsize - (xpos+1)); } // Parse the expression: IdentifierBuf idbuf( &m_atmcharset); CStringIterator itr( esrc, esrcsize); SrcScanner src( m_srccharset, itr); ExprState expr( this); enum State {SelectStart,SelectTag,SelectAttribute,SelectTagId,SelectAttributeId,SelectContent,SelectCondition}; State state = SelectStart; std::vector<const char*> alt; for (; *src; skipSpaces( src)) { switch (*src) { case '@': { if (state != SelectStart && state != SelectTag && state != SelectTagId) return src.getPosition()+1; ++src; state = SelectAttribute; break; } case '/': { if (state != SelectStart && state != SelectCondition && state != SelectTagId) return src.getPosition()+1; ++src; if (*src == '/') { expr.forAllDescendants(); ++src; } state = SelectTag; break; } case '[': { if (state != SelectStart && state != SelectTag && state != SelectTagId && state != SelectCondition) return src.getPosition()+1; ++src; skipSpaces( src); if (*src == '@') { ++src; skipSpaces( src); // Attribute condition: if (!isIdentifierChar( src)) return src.getPosition()+1; const char* attrname = idbuf.parseIdentifier( src); skipSpaces( src); if (*src != '=') return src.getPosition()+1; ++src; skipSpaces( src); const char* attrval = idbuf.parseValue( src); skipSpaces( src); if (!attrval || *src != ']') return src.getPosition()+1; expr.ifAttribute( attrname, attrval); ++src; } else { // Range skipSpaces( src); if (!isIdentifierChar( src)) return src.getPosition()+1; int range_start = parseNum( src); if (range_start < 0) return src.getPosition()+1; skipSpaces( src); if (*src == ',') { ++src; skipSpaces( src); if (*src == ']') { expr.FROM( range_start); ++src; } else { if (!isIdentifierChar( src)) return src.getPosition()+1; int range_end = parseNum( src); if (range_end < 0) return src.getPosition()+1; skipSpaces( src); if (*src != ']') return src.getPosition()+1; expr.RANGE( range_start, range_end); ++src; } } else if (*src == ']') { expr.INDEX( range_start); ++src; } else { return src.getPosition()+1; } } state = SelectCondition; break; } case '(': if (state != SelectStart && state != SelectTag && state != SelectTagId && state != SelectCondition) return src.getPosition()+1; ++src; skipSpaces( src); if (*src != ')') return src.getPosition()+1; ++src; expr.selectContent(); state = SelectContent; break; case '*': if (state != SelectStart && state != SelectTag && state != SelectAttribute) return src.getPosition()+1; ++src; if (state == SelectAttribute) { expr.selectAttribute( 0); state = SelectAttributeId; } else { expr.selectTag( 0); state = SelectTagId; } break; case '{': if (state != SelectStart && state != SelectTag && state != SelectAttribute) return src.getPosition()+1; alt = idbuf.parseIdentifierList( src, '{', '}'); if (alt.empty()) return src.getPosition()+1; expr.selectAttributeAlt( alt); if (state == SelectAttribute) { expr.selectAttributeAlt( alt); state = SelectAttributeId; } else { expr.selectTagAlt( alt); state = SelectTagId; } break; case '~': if (state != SelectTagId && state != SelectStart) return src.getPosition()+1; ++src; expr.selectCloseTag(); state = SelectContent; break; default: if (state != SelectStart && state != SelectTag && state != SelectAttribute) return src.getPosition()+1; if (!isIdentifierChar( src)) return src.getPosition()+1; if (state == SelectAttribute) { expr.selectAttribute( idbuf.parseIdentifier( src)); state = SelectAttributeId; } else { expr.selectTag( idbuf.parseIdentifier( src)); state = SelectTagId; } break; } } expr.assignType( typeidx); return 0; } private: #define ExprState_FOREACH( EXPR) {typename std::vector<PathElement>::iterator si = statelist.begin(), se = statelist.end(); for (; si != se; ++si) {si->EXPR;}} class ExprState { public: ExprState( XMLPathSelectAutomatonParser* atm) { statelist.push_back(PathElement(atm)); } ExprState( const ExprState& o) :statelist(o.statelist){} void selectTagAlt( std::vector<const char*> alt) { std::vector<PathElement> new_statelist; std::vector<const char*>::const_iterator ai = alt.begin(), ae = alt.end(); for (; ai != ae; ++ai) { ExprState alt_path( *this); alt_path.selectTag( *ai); new_statelist.insert( new_statelist.end(), alt_path.statelist.begin(), alt_path.statelist.end()); } statelist = new_statelist; } void selectAttributeAlt( std::vector<const char*> alt) { std::vector<PathElement> new_statelist; std::vector<const char*>::const_iterator ai = alt.begin(), ae = alt.end(); for (; ai != ae; ++ai) { ExprState alt_path( *this); alt_path.selectAttribute( *ai); new_statelist.insert( new_statelist.end(), alt_path.statelist.begin(), alt_path.statelist.end()); } statelist = new_statelist; } void TO(int idx) ExprState_FOREACH(TO(idx)) void FROM(int idx) ExprState_FOREACH(FROM(idx)) void RANGE(int idx1, int idx2) ExprState_FOREACH(RANGE(idx1,idx2)) void INDEX(int idx) ExprState_FOREACH(INDEX(idx)) void selectAttribute( const char* name) ExprState_FOREACH(selectAttribute(name)) void selectTag( const char* name) ExprState_FOREACH(selectTag(name)) void assignType(int type) ExprState_FOREACH(assignType(type)) void forAllDescendants() ExprState_FOREACH(forAllDescendants()) void selectCloseTag() ExprState_FOREACH(selectCloseTag()) void ifAttribute( const char* name, const char* value) ExprState_FOREACH(ifAttribute(name,value)) void selectContent() ExprState_FOREACH(selectContent()) private: std::vector<PathElement> statelist; }; static void skipSpaces( SrcScanner& src) { for (; src.control() == Space; ++src); } static int parseNum( SrcScanner& src) { std::string num; for (; *src>='0' && *src<='9';++src) num.push_back( *src); if (num.size() == 0 || num.size() > 8) return -1; return std::atoi( num.c_str()); } static bool isIdentifierChar( SrcScanner& src) { if (src.control() == Undef || src.control() == Any) { if (*src == (unsigned char)'*') return false; if (*src == (unsigned char)'~') return false; if (*src == (unsigned char)'/') return false; if (*src == (unsigned char)'(') return false; if (*src == (unsigned char)')') return false; if (*src == (unsigned char)'@') return false; return true; } return false; } class IdentifierBuf { public: explicit IdentifierBuf( const AtmCharSet* atmcharset_) :atmcharset(atmcharset_){} ~IdentifierBuf(){} const char* parseIdentifier( SrcScanner& src) { idlist.push_back( std::string()); for (; isIdentifierChar(src); ++src) { atmcharset->print( *src, idlist.back()); } return idlist.back().c_str(); } const char* parseValue( SrcScanner& src) { idlist.push_back( std::string()); if (*src == '"' || *src == '\'') { unsigned char eb = *src; for (++src; *src && *src != eb; ++src) { atmcharset->print( *src, idlist.back()); } if (*src) ++src; return idlist.back().c_str(); } else if (isIdentifierChar(src)) { return parseIdentifier( src); } else { return NULL; } } std::vector<const char*> parseIdentifierList( SrcScanner& src, char startBracket, char endBracket) { std::vector<const char*> rt; if (*src != startBracket) return std::vector<const char*>(); do { ++src; skipSpaces( src); if (!isIdentifierChar( src)) return std::vector<const char*>(); rt.push_back( parseIdentifier( src)); skipSpaces( src); } while (*src == ','); if (*src != endBracket) return std::vector<const char*>(); ++src; return rt; } private: const AtmCharSet* atmcharset; std::list<std::string> idlist; }; private: AtmCharSet m_atmcharset; SrcCharSet m_srccharset; }; } //namespace #endif <|endoftext|>
<commit_before>#include "APSEthernetPacket.h" APSEthernetPacket::APSEthernetPacket() : header{{}, {}, APS_PROTO, 0, {0}, 0}, payload(0){}; APSEthernetPacket::APSEthernetPacket(const APSCommand_t & command) : header{{}, {}, APS_PROTO, 0, command, 0}, payload(0){}; APSEthernetPacket::APSEthernetPacket(const APSCommand_t & command, const uint32_t & addr) : header{{}, {}, APS_PROTO, 0, command, addr}, payload(0){}; APSEthernetPacket::APSEthernetPacket(const MACAddr & destMAC, const MACAddr & srcMAC, APSCommand_t command, const uint32_t & addr) : header{destMAC, srcMAC, APS_PROTO, 0, command, addr}, payload(0){}; APSEthernetPacket::APSEthernetPacket(const vector<uint8_t> & packetData){ /* Create a packet from a byte array returned by pcap. */ //Helper function to turn two network bytes into a uint16_t or uint32_t assuming big-endian network byte order auto bytes2uint16 = [&packetData](size_t offset) -> uint16_t {return (packetData[offset] << 8) + packetData[offset+1];}; auto bytes2uint32 = [&packetData](size_t offset) -> uint32_t {return (packetData[offset] << 24) + (packetData[offset+1] << 16) + (packetData[offset+2] << 8) + packetData[offset+3] ;}; std::copy(packetData.begin(), packetData.begin()+6, header.dest.addr.begin()); std::copy(packetData.begin()+6, packetData.begin()+12, header.src.addr.begin()); header.frameType = bytes2uint16(12); header.seqNum = bytes2uint16(14); header.command.packed = bytes2uint32(16); size_t myOffset; //not all return packets have an address; if-block on command type if (needs_address(APS_COMMANDS(header.command.cmd))){ header.addr = bytes2uint32(20); myOffset = 24; } else{ myOffset = 20; } payload.clear(); payload.reserve((packetData.size() - myOffset)/4); while(myOffset < packetData.size()){ payload.push_back(bytes2uint32(myOffset)); myOffset += 4; } } vector<uint8_t> APSEthernetPacket::serialize() const { /* * Serialize a packet to a vector of bytes for transmission. * Handle host to network byte ordering here */ vector<uint8_t> outVec; outVec.resize(numBytes()); //Push on the destination and source mac address auto insertPt = outVec.begin(); std::copy(header.dest.addr.begin(), header.dest.addr.end(), insertPt); insertPt += 6; std::copy(header.src.addr.begin(), header.src.addr.end(), insertPt); insertPt += 6; //Push on ethernet protocol uint16_t myuint16; uint8_t * start; start = reinterpret_cast<uint8_t*>(&myuint16); myuint16 = htons(header.frameType); std::copy(start, start+2, insertPt); insertPt += 2; //Sequence number myuint16 = htons(header.seqNum); std::copy(start, start+2, insertPt); insertPt += 2; //Command //TODO: command count field uint32_t myuint32; start = reinterpret_cast<uint8_t*>(&myuint32); myuint32 = htonl(header.command.packed); std::copy(start, start+4, insertPt); insertPt += 4; //Address if (needs_address(APS_COMMANDS(header.command.cmd))){ myuint32 = htonl(header.addr); std::copy(start, start+4, insertPt); insertPt += 4; } //Data for (auto word : payload){ myuint32 = htonl(word); std::copy(start, start+4, insertPt); insertPt += 4; } return outVec; } size_t APSEthernetPacket::numBytes() const{ return needs_address(APS_COMMANDS(header.command.cmd)) ? NUM_HEADER_BYTES + 4*payload.size() : NUM_HEADER_BYTES - 4 + 4*payload.size() ; } APSEthernetPacket APSEthernetPacket::create_broadcast_packet(){ /* * Helper function to put together a broadcast status packet that all APS units should respond to. */ APSEthernetPacket myPacket; //Put the broadcast FF:FF:FF:FF:FF:FF in the MAC destination address std::fill(myPacket.header.dest.addr.begin(), myPacket.header.dest.addr.end(), 0xFF); //Fill out the host register status command myPacket.header.command.ack = 0; myPacket.header.command.r_w = 1; myPacket.header.command.cmd = static_cast<uint32_t>(APS_COMMANDS::STATUS); myPacket.header.command.mode_stat = APS_STATUS_HOST; myPacket.header.command.cnt = 0x10; //minimum length packet return myPacket; } <commit_msg>Enforce minimum Ethernet frame size.<commit_after>#include "APSEthernetPacket.h" APSEthernetPacket::APSEthernetPacket() : header{{}, {}, APS_PROTO, 0, {0}, 0}, payload(0){}; APSEthernetPacket::APSEthernetPacket(const APSCommand_t & command) : header{{}, {}, APS_PROTO, 0, command, 0}, payload(0){}; APSEthernetPacket::APSEthernetPacket(const APSCommand_t & command, const uint32_t & addr) : header{{}, {}, APS_PROTO, 0, command, addr}, payload(0){}; APSEthernetPacket::APSEthernetPacket(const MACAddr & destMAC, const MACAddr & srcMAC, APSCommand_t command, const uint32_t & addr) : header{destMAC, srcMAC, APS_PROTO, 0, command, addr}, payload(0){}; APSEthernetPacket::APSEthernetPacket(const vector<uint8_t> & packetData){ /* Create a packet from a byte array returned by pcap. */ //Helper function to turn two network bytes into a uint16_t or uint32_t assuming big-endian network byte order auto bytes2uint16 = [&packetData](size_t offset) -> uint16_t {return (packetData[offset] << 8) + packetData[offset+1];}; auto bytes2uint32 = [&packetData](size_t offset) -> uint32_t {return (packetData[offset] << 24) + (packetData[offset+1] << 16) + (packetData[offset+2] << 8) + packetData[offset+3] ;}; std::copy(packetData.begin(), packetData.begin()+6, header.dest.addr.begin()); std::copy(packetData.begin()+6, packetData.begin()+12, header.src.addr.begin()); header.frameType = bytes2uint16(12); header.seqNum = bytes2uint16(14); header.command.packed = bytes2uint32(16); size_t myOffset; //not all return packets have an address; if-block on command type if (needs_address(APS_COMMANDS(header.command.cmd))){ header.addr = bytes2uint32(20); myOffset = 24; } else{ myOffset = 20; } payload.clear(); payload.reserve((packetData.size() - myOffset)/4); while(myOffset < packetData.size()){ payload.push_back(bytes2uint32(myOffset)); myOffset += 4; } } vector<uint8_t> APSEthernetPacket::serialize() const { /* * Serialize a packet to a vector of bytes for transmission. * Handle host to network byte ordering here */ vector<uint8_t> outVec; outVec.resize(numBytes(), 0); //Push on the destination and source mac address auto insertPt = outVec.begin(); std::copy(header.dest.addr.begin(), header.dest.addr.end(), insertPt); insertPt += 6; std::copy(header.src.addr.begin(), header.src.addr.end(), insertPt); insertPt += 6; //Push on ethernet protocol uint16_t myuint16; uint8_t * start; start = reinterpret_cast<uint8_t*>(&myuint16); myuint16 = htons(header.frameType); std::copy(start, start+2, insertPt); insertPt += 2; //Sequence number myuint16 = htons(header.seqNum); std::copy(start, start+2, insertPt); insertPt += 2; //Command //TODO: command count field uint32_t myuint32; start = reinterpret_cast<uint8_t*>(&myuint32); myuint32 = htonl(header.command.packed); std::copy(start, start+4, insertPt); insertPt += 4; //Address if (needs_address(APS_COMMANDS(header.command.cmd))){ myuint32 = htonl(header.addr); std::copy(start, start+4, insertPt); insertPt += 4; } //Data for (auto word : payload){ myuint32 = htonl(word); std::copy(start, start+4, insertPt); insertPt += 4; } return outVec; } size_t APSEthernetPacket::numBytes() const{ size_t trueSize = needs_address(APS_COMMANDS(header.command.cmd)) ? NUM_HEADER_BYTES + 4*payload.size() : NUM_HEADER_BYTES - 4 + 4*payload.size() ; return std::max(trueSize, static_cast<size_t>(64)); } APSEthernetPacket APSEthernetPacket::create_broadcast_packet(){ /* * Helper function to put together a broadcast status packet that all APS units should respond to. */ APSEthernetPacket myPacket; //Put the broadcast FF:FF:FF:FF:FF:FF in the MAC destination address std::fill(myPacket.header.dest.addr.begin(), myPacket.header.dest.addr.end(), 0xFF); //Fill out the host register status command myPacket.header.command.ack = 0; myPacket.header.command.r_w = 1; myPacket.header.command.cmd = static_cast<uint32_t>(APS_COMMANDS::STATUS); myPacket.header.command.mode_stat = APS_STATUS_HOST; myPacket.header.command.cnt = 0x00; return myPacket; } <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Library Module: Actor.cc Language: C++ Date: $Date$ Version: $Revision$ This file is part of the Visualization Library. No part of this file or its contents may be copied, reproduced or altered in any way without the express written consent of the authors. Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994 =========================================================================*/ #include <stdlib.h> #include <math.h> #include "Actor.hh" // Description: // Creates an actor with the following defaults: origin(0,0,0) // position=(0,0,0) scale=(1,1,1) visibility=1 pickable=1 dragable=1 // orientation=(0,0,0). IMPORTANT NOTE: Usually the vlRenderWindow // method MakeActor() is used to create a device specific actor. This // has the added benefit that a default device-specific property is // automatically created. Try to use MakeActor() whenever possible. vlActor::vlActor() { this->Mapper = NULL; this->Property = NULL; this->Texture = NULL; this->Origin[0] = 0.0; this->Origin[1] = 0.0; this->Origin[2] = 0.0; this->Position[0] = 0.0; this->Position[1] = 0.0; this->Position[2] = 0.0; this->Orientation[0] = 0.0; this->Orientation[1] = 0.0; this->Orientation[2] = 0.0; this->Scale[0] = 1.0; this->Scale[1] = 1.0; this->Scale[2] = 1.0; this->Visibility = 1; this->Pickable = 1; this->Dragable = 1; } vlActor::~vlActor() { } // Description: // This causes the actor to be rendered. It in turn will render the actor's // property and then mapper. void vlActor::Render(vlRenderer *ren) { /* render the property */ this->Property->Render(ren); /* render the texture */ if (this->Texture) this->Texture->Render(ren); /* send a render to the modeller */ this->Mapper->Render(ren); } // Description: // Change position by increments specified. void vlActor::AddPosition (float deltaX,float deltaY,float deltaZ) { float position[3]; position[0] = this->Position[0] + deltaX; position[1] = this->Position[1] + deltaY; position[2] = this->Position[2] + deltaZ; this->SetPosition(position); } void vlActor::AddPosition (float deltaPosition[3]) { this->AddPosition (deltaPosition[0], deltaPosition[1], deltaPosition[2]); } // Description: // Sets the orientation of the actor. Orientation is specified as // X,Y and Z rotations in that order, but they are performed as // RotateZ, RotateX and finally RotateY. void vlActor::SetOrientation (float x,float y,float z) { // store the coordinates this->Orientation[0] = x; this->Orientation[1] = y; this->Orientation[2] = z; vlDebugMacro(<< " Orientation set to ( " << this->Orientation[0] << ", " << this->Orientation[1] << ", " << this->Orientation[2] << ")\n"); this->Transform.Identity(); this->Transform.RotateZ(this->Orientation[2]); this->Transform.RotateX(this->Orientation[0]); this->Transform.RotateY(this->Orientation[1]); this->Modified(); } void vlActor::SetOrientation(float a[3]) { this->SetOrientation(a[0],a[1],a[2]); } // Description: // Returns the orientation of the actor as s vector of X,Y and Z rotation. // The ordering in which these rotations must be done to generate the // same matrix is RotateZ, RotateX and finally RotateY. See also // SetOrientation. float *vlActor::GetOrientation () { float *orientation; // return the orientation of the transformation matrix orientation = this->Transform.GetOrientation(); this->Orientation[0] = orientation[0]; this->Orientation[1] = orientation[1]; this->Orientation[2] = orientation[2]; vlDebugMacro(<< " Returning Orientation of ( " << this->Orientation[0] << ", " << this->Orientation[1] << ", " << this->Orientation[2] << ")\n"); return this->Orientation; } // vlActor::Getorientation // Description: // Add to the current orientation. See SetOrientation and GetOrientation for // more details. void vlActor::AddOrientation (float a1,float a2,float a3) { float *orient; orient = this->GetOrientation(); this->SetOrientation(orient[0] + a1, orient[1] + a2, orient[2] + a3); } void vlActor::AddOrientation(float a[3]) { this->AddOrientation(a[0],a[1],a[2]); } // Description: // Rotate the actor in degrees about the X axis using the right hand rule. void vlActor::RotateX (float angle) { this->Transform.RotateX(angle); this->Modified(); } // Description: // Rotate the actor in degrees about the Y axis using the right hand rule. void vlActor::RotateY (float angle) { this->Transform.RotateY(angle); this->Modified(); } // Description: // Rotate the actor in degrees about the Z axis using the right hand rule. void vlActor::RotateZ (float angle) { this->Transform.RotateZ(angle); this->Modified(); } // Description: // Rotate the actor in degrees about an arbitrary axis specified by the // last three arguments. void vlActor::RotateWXYZ (float degree, float x, float y, float z) { this->Transform.PostMultiply(); this->Transform.RotateWXYZ(degree,x,y,z); this->Transform.PreMultiply(); this->Modified(); } // Description: // Copy the actor's composite 4x4 matrix into the matrix provided. void vlActor::GetMatrix(vlMatrix4x4& result) { this->GetOrientation(); this->Transform.Push(); this->Transform.Identity(); this->Transform.PreMultiply(); // first translate this->Transform.Translate(this->Position[0], this->Position[1], this->Position[2]); // shift to origin this->Transform.Translate(this->Origin[0], this->Origin[1], this->Origin[2]); // rotate this->Transform.RotateZ(this->Orientation[2]); this->Transform.RotateX(this->Orientation[0]); this->Transform.RotateY(this->Orientation[1]); // scale this->Transform.Scale(this->Scale[0], this->Scale[1], this->Scale[2]); // shift back from origin this->Transform.Translate(-this->Origin[0], -this->Origin[1], -this->Origin[2]); result = this->Transform.GetMatrix(); this->Transform.Pop(); } // Description: // Return a reference to the actor's 4x4 composite matrix. vlMatrix4x4& vlActor::GetMatrix() { static vlMatrix4x4 result; this->GetMatrix(result); return result; } // Description: // Get the bounds for this Actor as (Xmin,Xmax,Ymin,Ymax,Zmin,Zmax). float *vlActor::GetBounds() { int i,n; float *bounds, bbox[24], *fptr; float *result; vlMatrix4x4 matrix; // get the bounds of the Mapper bounds = this->Mapper->GetBounds(); // fill out vertices of a bounding box bbox[ 0] = bounds[1]; bbox[ 1] = bounds[3]; bbox[ 2] = bounds[5]; bbox[ 3] = bounds[1]; bbox[ 4] = bounds[2]; bbox[ 5] = bounds[5]; bbox[ 6] = bounds[0]; bbox[ 7] = bounds[2]; bbox[ 8] = bounds[5]; bbox[ 9] = bounds[0]; bbox[10] = bounds[3]; bbox[11] = bounds[5]; bbox[12] = bounds[1]; bbox[13] = bounds[3]; bbox[14] = bounds[4]; bbox[15] = bounds[1]; bbox[16] = bounds[2]; bbox[17] = bounds[4]; bbox[18] = bounds[0]; bbox[19] = bounds[2]; bbox[20] = bounds[4]; bbox[21] = bounds[0]; bbox[22] = bounds[3]; bbox[23] = bounds[4]; // save the old transform this->Transform.Push(); this->Transform.Identity(); this->GetMatrix(matrix); this->Transform.Concatenate(matrix); // and transform into actors coordinates fptr = bbox; for (n = 0; n < 8; n++) { this->Transform.SetPoint(fptr[0],fptr[1],fptr[2],1.0); // now store the result result = this->Transform.GetPoint(); fptr[0] = result[0]; fptr[1] = result[1]; fptr[2] = result[2]; fptr += 3; } this->Transform.Push(); // now calc the new bounds this->Bounds[0] = this->Bounds[2] = this->Bounds[4] = 1.0e30; this->Bounds[1] = this->Bounds[3] = this->Bounds[5] = -1.0e30; for (i = 0; i < 8; i++) { for (n = 0; n < 3; n++) { if (bbox[i*3+n] < this->Bounds[n*2]) this->Bounds[n*2] = bbox[i*3+n]; if (bbox[i*3+n] > this->Bounds[n*2+1]) this->Bounds[n*2+1] = bbox[i*3+n]; } } return this->Bounds; } // Description: // Get the actors x range in world coordinates. float *vlActor::GetXRange() { this->GetBounds(); return this->Bounds; } // Description: // Get the actors y range in world coordinates. float *vlActor::GetYRange() { this->GetBounds(); return &(this->Bounds[2]); } // Description: // Get the actors z range in world coordinates. float *vlActor::GetZRange() { this->GetBounds(); return &(this->Bounds[4]); } void vlActor::PrintSelf(ostream& os, vlIndent indent) { vlObject::PrintSelf(os,indent); // make sure our bounds are up to date this->GetBounds(); os << indent << "Bounds: (" << this->Bounds[0] << ", " << this->Bounds[1] << ") (" << this->Bounds[2] << ") (" << this->Bounds[3] << ") (" << this->Bounds[4] << ") (" << this->Bounds[5] << ")\n"; os << indent << "Dragable: " << (this->Dragable ? "On\n" : "Off\n"); if ( this->Mapper ) { os << indent << "Mapper:\n"; this->Mapper->PrintSelf(os,indent.GetNextIndent()); } else { os << indent << "Mapper: (none)\n"; } os << indent << "Orientation: (" << this->Orientation[0] << ", " << this->Orientation[1] << ", " << this->Orientation[2] << ")\n"; os << indent << "Origin: (" << this->Origin[0] << ", " << this->Origin[1] << ", " << this->Origin[2] << ")\n"; os << indent << "Pickable: " << (this->Pickable ? "On\n" : "Off\n"); os << indent << "Position: (" << this->Position[0] << ", " << this->Position[1] << ", " << this->Position[2] << ")\n"; if ( this->Property ) { os << indent << "Property:\n"; this->Property->PrintSelf(os,indent.GetNextIndent()); } else { os << indent << "Property: (none)\n"; } os << indent << "Scale: (" << this->Scale[0] << ", " << this->Scale[1] << ", " << this->Scale[2] << ")\n"; os << indent << "Visibility: " << (this->Visibility ? "On\n" : "Off\n"); } <commit_msg>had a Push where needed a pop<commit_after>/*========================================================================= Program: Visualization Library Module: Actor.cc Language: C++ Date: $Date$ Version: $Revision$ This file is part of the Visualization Library. No part of this file or its contents may be copied, reproduced or altered in any way without the express written consent of the authors. Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994 =========================================================================*/ #include <stdlib.h> #include <math.h> #include "Actor.hh" // Description: // Creates an actor with the following defaults: origin(0,0,0) // position=(0,0,0) scale=(1,1,1) visibility=1 pickable=1 dragable=1 // orientation=(0,0,0). IMPORTANT NOTE: Usually the vlRenderWindow // method MakeActor() is used to create a device specific actor. This // has the added benefit that a default device-specific property is // automatically created. Try to use MakeActor() whenever possible. vlActor::vlActor() { this->Mapper = NULL; this->Property = NULL; this->Texture = NULL; this->Origin[0] = 0.0; this->Origin[1] = 0.0; this->Origin[2] = 0.0; this->Position[0] = 0.0; this->Position[1] = 0.0; this->Position[2] = 0.0; this->Orientation[0] = 0.0; this->Orientation[1] = 0.0; this->Orientation[2] = 0.0; this->Scale[0] = 1.0; this->Scale[1] = 1.0; this->Scale[2] = 1.0; this->Visibility = 1; this->Pickable = 1; this->Dragable = 1; } vlActor::~vlActor() { } // Description: // This causes the actor to be rendered. It in turn will render the actor's // property and then mapper. void vlActor::Render(vlRenderer *ren) { /* render the property */ this->Property->Render(ren); /* render the texture */ if (this->Texture) this->Texture->Render(ren); /* send a render to the modeller */ this->Mapper->Render(ren); } // Description: // Change position by increments specified. void vlActor::AddPosition (float deltaX,float deltaY,float deltaZ) { float position[3]; position[0] = this->Position[0] + deltaX; position[1] = this->Position[1] + deltaY; position[2] = this->Position[2] + deltaZ; this->SetPosition(position); } void vlActor::AddPosition (float deltaPosition[3]) { this->AddPosition (deltaPosition[0], deltaPosition[1], deltaPosition[2]); } // Description: // Sets the orientation of the actor. Orientation is specified as // X,Y and Z rotations in that order, but they are performed as // RotateZ, RotateX and finally RotateY. void vlActor::SetOrientation (float x,float y,float z) { // store the coordinates this->Orientation[0] = x; this->Orientation[1] = y; this->Orientation[2] = z; vlDebugMacro(<< " Orientation set to ( " << this->Orientation[0] << ", " << this->Orientation[1] << ", " << this->Orientation[2] << ")\n"); this->Transform.Identity(); this->Transform.RotateZ(this->Orientation[2]); this->Transform.RotateX(this->Orientation[0]); this->Transform.RotateY(this->Orientation[1]); this->Modified(); } void vlActor::SetOrientation(float a[3]) { this->SetOrientation(a[0],a[1],a[2]); } // Description: // Returns the orientation of the actor as s vector of X,Y and Z rotation. // The ordering in which these rotations must be done to generate the // same matrix is RotateZ, RotateX and finally RotateY. See also // SetOrientation. float *vlActor::GetOrientation () { float *orientation; // return the orientation of the transformation matrix orientation = this->Transform.GetOrientation(); this->Orientation[0] = orientation[0]; this->Orientation[1] = orientation[1]; this->Orientation[2] = orientation[2]; vlDebugMacro(<< " Returning Orientation of ( " << this->Orientation[0] << ", " << this->Orientation[1] << ", " << this->Orientation[2] << ")\n"); return this->Orientation; } // vlActor::Getorientation // Description: // Add to the current orientation. See SetOrientation and GetOrientation for // more details. void vlActor::AddOrientation (float a1,float a2,float a3) { float *orient; orient = this->GetOrientation(); this->SetOrientation(orient[0] + a1, orient[1] + a2, orient[2] + a3); } void vlActor::AddOrientation(float a[3]) { this->AddOrientation(a[0],a[1],a[2]); } // Description: // Rotate the actor in degrees about the X axis using the right hand rule. void vlActor::RotateX (float angle) { this->Transform.RotateX(angle); this->Modified(); } // Description: // Rotate the actor in degrees about the Y axis using the right hand rule. void vlActor::RotateY (float angle) { this->Transform.RotateY(angle); this->Modified(); } // Description: // Rotate the actor in degrees about the Z axis using the right hand rule. void vlActor::RotateZ (float angle) { this->Transform.RotateZ(angle); this->Modified(); } // Description: // Rotate the actor in degrees about an arbitrary axis specified by the // last three arguments. void vlActor::RotateWXYZ (float degree, float x, float y, float z) { this->Transform.PostMultiply(); this->Transform.RotateWXYZ(degree,x,y,z); this->Transform.PreMultiply(); this->Modified(); } // Description: // Copy the actor's composite 4x4 matrix into the matrix provided. void vlActor::GetMatrix(vlMatrix4x4& result) { this->GetOrientation(); this->Transform.Push(); this->Transform.Identity(); this->Transform.PreMultiply(); // first translate this->Transform.Translate(this->Position[0], this->Position[1], this->Position[2]); // shift to origin this->Transform.Translate(this->Origin[0], this->Origin[1], this->Origin[2]); // rotate this->Transform.RotateZ(this->Orientation[2]); this->Transform.RotateX(this->Orientation[0]); this->Transform.RotateY(this->Orientation[1]); // scale this->Transform.Scale(this->Scale[0], this->Scale[1], this->Scale[2]); // shift back from origin this->Transform.Translate(-this->Origin[0], -this->Origin[1], -this->Origin[2]); result = this->Transform.GetMatrix(); this->Transform.Pop(); } // Description: // Return a reference to the actor's 4x4 composite matrix. vlMatrix4x4& vlActor::GetMatrix() { static vlMatrix4x4 result; this->GetMatrix(result); return result; } // Description: // Get the bounds for this Actor as (Xmin,Xmax,Ymin,Ymax,Zmin,Zmax). float *vlActor::GetBounds() { int i,n; float *bounds, bbox[24], *fptr; float *result; vlMatrix4x4 matrix; // get the bounds of the Mapper bounds = this->Mapper->GetBounds(); // fill out vertices of a bounding box bbox[ 0] = bounds[1]; bbox[ 1] = bounds[3]; bbox[ 2] = bounds[5]; bbox[ 3] = bounds[1]; bbox[ 4] = bounds[2]; bbox[ 5] = bounds[5]; bbox[ 6] = bounds[0]; bbox[ 7] = bounds[2]; bbox[ 8] = bounds[5]; bbox[ 9] = bounds[0]; bbox[10] = bounds[3]; bbox[11] = bounds[5]; bbox[12] = bounds[1]; bbox[13] = bounds[3]; bbox[14] = bounds[4]; bbox[15] = bounds[1]; bbox[16] = bounds[2]; bbox[17] = bounds[4]; bbox[18] = bounds[0]; bbox[19] = bounds[2]; bbox[20] = bounds[4]; bbox[21] = bounds[0]; bbox[22] = bounds[3]; bbox[23] = bounds[4]; // save the old transform this->Transform.Push(); this->Transform.Identity(); this->GetMatrix(matrix); this->Transform.Concatenate(matrix); // and transform into actors coordinates fptr = bbox; for (n = 0; n < 8; n++) { this->Transform.SetPoint(fptr[0],fptr[1],fptr[2],1.0); // now store the result result = this->Transform.GetPoint(); fptr[0] = result[0]; fptr[1] = result[1]; fptr[2] = result[2]; fptr += 3; } this->Transform.Pop(); // now calc the new bounds this->Bounds[0] = this->Bounds[2] = this->Bounds[4] = 1.0e30; this->Bounds[1] = this->Bounds[3] = this->Bounds[5] = -1.0e30; for (i = 0; i < 8; i++) { for (n = 0; n < 3; n++) { if (bbox[i*3+n] < this->Bounds[n*2]) this->Bounds[n*2] = bbox[i*3+n]; if (bbox[i*3+n] > this->Bounds[n*2+1]) this->Bounds[n*2+1] = bbox[i*3+n]; } } return this->Bounds; } // Description: // Get the actors x range in world coordinates. float *vlActor::GetXRange() { this->GetBounds(); return this->Bounds; } // Description: // Get the actors y range in world coordinates. float *vlActor::GetYRange() { this->GetBounds(); return &(this->Bounds[2]); } // Description: // Get the actors z range in world coordinates. float *vlActor::GetZRange() { this->GetBounds(); return &(this->Bounds[4]); } void vlActor::PrintSelf(ostream& os, vlIndent indent) { vlObject::PrintSelf(os,indent); // make sure our bounds are up to date this->GetBounds(); os << indent << "Bounds: (" << this->Bounds[0] << ", " << this->Bounds[1] << ") (" << this->Bounds[2] << ") (" << this->Bounds[3] << ") (" << this->Bounds[4] << ") (" << this->Bounds[5] << ")\n"; os << indent << "Dragable: " << (this->Dragable ? "On\n" : "Off\n"); if ( this->Mapper ) { os << indent << "Mapper:\n"; this->Mapper->PrintSelf(os,indent.GetNextIndent()); } else { os << indent << "Mapper: (none)\n"; } os << indent << "Orientation: (" << this->Orientation[0] << ", " << this->Orientation[1] << ", " << this->Orientation[2] << ")\n"; os << indent << "Origin: (" << this->Origin[0] << ", " << this->Origin[1] << ", " << this->Origin[2] << ")\n"; os << indent << "Pickable: " << (this->Pickable ? "On\n" : "Off\n"); os << indent << "Position: (" << this->Position[0] << ", " << this->Position[1] << ", " << this->Position[2] << ")\n"; if ( this->Property ) { os << indent << "Property:\n"; this->Property->PrintSelf(os,indent.GetNextIndent()); } else { os << indent << "Property: (none)\n"; } os << indent << "Scale: (" << this->Scale[0] << ", " << this->Scale[1] << ", " << this->Scale[2] << ")\n"; os << indent << "Visibility: " << (this->Visibility ? "On\n" : "Off\n"); } <|endoftext|>
<commit_before>/* * raft_if, Go layer of libraft * Copyright (C) 2015 Clayton Wheeler * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA * */ #include <cinttypes> #include <cstdio> #include <unistd.h> #include <thread> #include <vector> #include "raft_go_if.h" #include "dispatch.h" #include "raft_shm.h" #include "queue.h" using namespace raft; using boost::interprocess::unique_instance; zlog_category_t* go_cat; namespace { std::vector<std::thread> workers; void raft_reply_(BaseSlot& slot, RaftError error); } void raft_ready() { uint32_t n_workers = raft_get_config()->api_workers; if (n_workers == 0) { zlog_warn(go_cat, "Must run more than 0 API workers, defaulting to 4."); n_workers = 4; } workers.reserve(n_workers); for (uint32_t i = 0; i < n_workers; ++i) { workers.push_back(dispatch::start_worker()); } raft::scoreboard->is_raft_running = true; } void raft_reply(raft_call call_p, RaftError error) { auto* slot = (BaseSlot*) call_p; mutex_lock lock(slot->owned); raft_reply_(*slot, error); } void raft_reply_immed(raft_call call_p, RaftError error) { raft_reply_(*(BaseSlot*) call_p, error); } void raft_reply_apply(raft_call call_p, uint64_t retval, RaftError error) { auto* slot = (BaseSlot*) call_p; mutex_lock lock(slot->owned); slot->timings.record("RaftApply return"); assert(slot->tag == CallTag::Apply); if (!error) { slot->reply(retval); } else { zlog_error(go_cat, "Sending error response from RaftApply: %d", error); slot->reply(error); } } namespace { /** * Send reply IFF we already hold the lock on slot! */ void raft_reply_(BaseSlot& slot, RaftError error) { slot.timings.record("Raft call return"); slot.reply(error); } } void raft_reply_value(raft_call call, uint64_t retval) { // TODO: check that this has a return value... auto* slot = (BaseSlot*) call; mutex_lock lock(slot->owned); slot->timings.record("Raft call return"); slot->reply(retval); } uint64_t raft_fsm_apply(uint64_t index, uint64_t term, RaftLogType type, char* cmd_buf, size_t cmd_len) { shm_handle cmd_handle; char* shm_buf = nullptr; if (in_shm_bounds(cmd_buf)) { cmd_handle = raft::shm.get_handle_from_address(cmd_buf); } else { shm_buf = (char*) raft::shm.allocate(cmd_len); assert(shm_buf); zlog_debug(go_cat, "Allocated %lu-byte buffer for log command at %p.", cmd_len, shm_buf); memcpy(shm_buf, cmd_buf, cmd_len); cmd_handle = raft::shm.get_handle_from_address(shm_buf); } auto* slot = send_fsm_request<api::FSMApply>(index, term, type, cmd_handle, cmd_len); slot->wait(); assert(slot->state == raft::CallState::Success); assert(slot->error == RAFT_SUCCESS); zlog_debug(go_cat, "FSM response %#" PRIx64 , slot->retval); if (shm_buf) shm.deallocate(shm_buf); //slot->timings.print(); //fprintf(stderr, "====================\n"); auto rv = slot->retval; slot->dispose(); return rv; } int raft_fsm_snapshot(char *path) { auto* slot = send_fsm_request<api::FSMSnapshot>(path); free(path); slot->wait(); assert(is_terminal(slot->state)); int retval = (slot->state == raft::CallState::Success) ? 0 : 1; slot->dispose(); return retval; } int raft_fsm_restore(char *path) { auto* slot = send_fsm_request<api::FSMRestore>(path); free(path); zlog_info(go_cat, "Sent restore request to FSM."); slot->wait(); assert(is_terminal(slot->state)); int retval = (slot->state == raft::CallState::Success) ? 0 : 1; slot->dispose(); return retval; } void raft_set_leader(bool val) { zlog_info(go_cat, "Leadership state change: %s", val ? "is leader" : "not leader"); raft::scoreboard->is_leader = val; } void* raft_shm_init(const char *shm_path) { raft::shm_init(shm_path, false, nullptr); free((void*) shm_path); go_cat = zlog_get_category("raft_go"); return raft::shm.get_address(); } size_t raft_shm_size() { return raft::shm.get_size(); } uint64_t raft_shm_string(const char *str, size_t len) { char* buf = (char*) raft::shm.allocate(len+1); assert(raft::in_shm_bounds((void*) buf)); memcpy(buf, str, len); free((void*) str); buf[len] = '\0'; return (uint64_t) raft::shm.get_handle_from_address(buf); } RaftConfig* raft_get_config() { return raft::shm.find<RaftConfig>(unique_instance).first; } <commit_msg>Use standard buffer alloc/free calls, for stats.<commit_after>/* * raft_if, Go layer of libraft * Copyright (C) 2015 Clayton Wheeler * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA * */ #include <cinttypes> #include <cstdio> #include <unistd.h> #include <thread> #include <vector> #include "raft_go_if.h" #include "dispatch.h" #include "raft_shm.h" #include "queue.h" using namespace raft; using boost::interprocess::unique_instance; zlog_category_t* go_cat; namespace { std::vector<std::thread> workers; void raft_reply_(BaseSlot& slot, RaftError error); } void raft_ready() { uint32_t n_workers = raft_get_config()->api_workers; if (n_workers == 0) { zlog_warn(go_cat, "Must run more than 0 API workers, defaulting to 4."); n_workers = 4; } workers.reserve(n_workers); for (uint32_t i = 0; i < n_workers; ++i) { workers.push_back(dispatch::start_worker()); } raft::scoreboard->is_raft_running = true; } void raft_reply(raft_call call_p, RaftError error) { auto* slot = (BaseSlot*) call_p; mutex_lock lock(slot->owned); raft_reply_(*slot, error); } void raft_reply_immed(raft_call call_p, RaftError error) { raft_reply_(*(BaseSlot*) call_p, error); } void raft_reply_apply(raft_call call_p, uint64_t retval, RaftError error) { auto* slot = (BaseSlot*) call_p; mutex_lock lock(slot->owned); slot->timings.record("RaftApply return"); assert(slot->tag == CallTag::Apply); if (!error) { slot->reply(retval); } else { zlog_error(go_cat, "Sending error response from RaftApply: %d", error); slot->reply(error); } } namespace { /** * Send reply IFF we already hold the lock on slot! */ void raft_reply_(BaseSlot& slot, RaftError error) { slot.timings.record("Raft call return"); slot.reply(error); } } void raft_reply_value(raft_call call, uint64_t retval) { // TODO: check that this has a return value... auto* slot = (BaseSlot*) call; mutex_lock lock(slot->owned); slot->timings.record("Raft call return"); slot->reply(retval); } uint64_t raft_fsm_apply(uint64_t index, uint64_t term, RaftLogType type, char* cmd_buf, size_t cmd_len) { shm_handle cmd_handle; char* shm_buf = nullptr; if (in_shm_bounds(cmd_buf)) { cmd_handle = raft::shm.get_handle_from_address(cmd_buf); } else { shm_buf = raft::allocate_buf(cmd_len); zlog_debug(go_cat, "Allocated %lu-byte buffer for log command at %p.", cmd_len, shm_buf); memcpy(shm_buf, cmd_buf, cmd_len); cmd_handle = raft::shm.get_handle_from_address(shm_buf); } auto* slot = send_fsm_request<api::FSMApply>(index, term, type, cmd_handle, cmd_len); slot->wait(); assert(slot->state == raft::CallState::Success); assert(slot->error == RAFT_SUCCESS); zlog_debug(go_cat, "FSM response %#" PRIx64 , slot->retval); if (shm_buf) raft::free_buf(shm_buf); //slot->timings.print(); //fprintf(stderr, "====================\n"); auto rv = slot->retval; slot->dispose(); return rv; } int raft_fsm_snapshot(char *path) { auto* slot = send_fsm_request<api::FSMSnapshot>(path); free(path); slot->wait(); assert(is_terminal(slot->state)); int retval = (slot->state == raft::CallState::Success) ? 0 : 1; slot->dispose(); return retval; } int raft_fsm_restore(char *path) { auto* slot = send_fsm_request<api::FSMRestore>(path); free(path); zlog_info(go_cat, "Sent restore request to FSM."); slot->wait(); assert(is_terminal(slot->state)); int retval = (slot->state == raft::CallState::Success) ? 0 : 1; slot->dispose(); return retval; } void raft_set_leader(bool val) { zlog_info(go_cat, "Leadership state change: %s", val ? "is leader" : "not leader"); raft::scoreboard->is_leader = val; } void* raft_shm_init(const char *shm_path) { raft::shm_init(shm_path, false, nullptr); free((void*) shm_path); go_cat = zlog_get_category("raft_go"); return raft::shm.get_address(); } size_t raft_shm_size() { return raft::shm.get_size(); } uint64_t raft_shm_string(const char *str, size_t len) { char* buf = (char*) raft::allocate_buf(len+1); assert(raft::in_shm_bounds((void*) buf)); memcpy(buf, str, len); free((void*) str); buf[len] = '\0'; return (uint64_t) raft::shm.get_handle_from_address(buf); } RaftConfig* raft_get_config() { return raft::shm.find<RaftConfig>(unique_instance).first; } <|endoftext|>